file_id
int64 1
46.7k
| content
stringlengths 14
344k
| repo
stringlengths 7
109
| path
stringlengths 8
171
|
---|---|---|---|
43,262 | package org.apache.lucene.analysis.icu.segmentation;
/*
* 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.
*/
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.BaseTokenStreamTestCase;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.icu.ICUNormalizer2Filter;
import org.apache.lucene.analysis.icu.tokenattributes.ScriptAttribute;
import org.apache.lucene.util.IOUtils;
import com.ibm.icu.lang.UScript;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.Arrays;
import java.util.Random;
public class TestICUTokenizer extends BaseTokenStreamTestCase {
public void testHugeDoc() throws IOException {
StringBuilder sb = new StringBuilder();
char whitespace[] = new char[4094];
Arrays.fill(whitespace, ' ');
sb.append(whitespace);
sb.append("testing 1234");
String input = sb.toString();
ICUTokenizer tokenizer = new ICUTokenizer(new StringReader(input), new DefaultICUTokenizerConfig(false));
assertTokenStreamContents(tokenizer, new String[] { "testing", "1234" });
}
public void testHugeTerm2() throws IOException {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 40960; i++) {
sb.append('a');
}
String input = sb.toString();
ICUTokenizer tokenizer = new ICUTokenizer(new StringReader(input), new DefaultICUTokenizerConfig(false));
char token[] = new char[4096];
Arrays.fill(token, 'a');
String expectedToken = new String(token);
String expected[] = {
expectedToken, expectedToken, expectedToken,
expectedToken, expectedToken, expectedToken,
expectedToken, expectedToken, expectedToken,
expectedToken
};
assertTokenStreamContents(tokenizer, expected);
}
private Analyzer a = new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName,
Reader reader) {
Tokenizer tokenizer = new ICUTokenizer(reader, new DefaultICUTokenizerConfig(false));
TokenFilter filter = new ICUNormalizer2Filter(tokenizer);
return new TokenStreamComponents(tokenizer, filter);
}
};
public void testArmenian() throws Exception {
assertAnalyzesTo(a, "Վիքիպեդիայի 13 միլիոն հոդվածները (4,600` հայերեն վիքիպեդիայում) գրվել են կամավորների կողմից ու համարյա բոլոր հոդվածները կարող է խմբագրել ցանկաց մարդ ով կարող է բացել Վիքիպեդիայի կայքը։",
new String[] { "վիքիպեդիայի", "13", "միլիոն", "հոդվածները", "4,600", "հայերեն", "վիքիպեդիայում", "գրվել", "են", "կամավորների", "կողմից",
"ու", "համարյա", "բոլոր", "հոդվածները", "կարող", "է", "խմբագրել", "ցանկաց", "մարդ", "ով", "կարող", "է", "բացել", "վիքիպեդիայի", "կայքը" } );
}
public void testAmharic() throws Exception {
assertAnalyzesTo(a, "ዊኪፔድያ የባለ ብዙ ቋንቋ የተሟላ ትክክለኛና ነጻ መዝገበ ዕውቀት (ኢንሳይክሎፒዲያ) ነው። ማንኛውም",
new String[] { "ዊኪፔድያ", "የባለ", "ብዙ", "ቋንቋ", "የተሟላ", "ትክክለኛና", "ነጻ", "መዝገበ", "ዕውቀት", "ኢንሳይክሎፒዲያ", "ነው", "ማንኛውም" } );
}
public void testArabic() throws Exception {
assertAnalyzesTo(a, "الفيلم الوثائقي الأول عن ويكيبيديا يسمى \"الحقيقة بالأرقام: قصة ويكيبيديا\" (بالإنجليزية: Truth in Numbers: The Wikipedia Story)، سيتم إطلاقه في 2008.",
new String[] { "الفيلم", "الوثائقي", "الأول", "عن", "ويكيبيديا", "يسمى", "الحقيقة", "بالأرقام", "قصة", "ويكيبيديا",
"بالإنجليزية", "truth", "in", "numbers", "the", "wikipedia", "story", "سيتم", "إطلاقه", "في", "2008" } );
}
public void testAramaic() throws Exception {
assertAnalyzesTo(a, "ܘܝܩܝܦܕܝܐ (ܐܢܓܠܝܐ: Wikipedia) ܗܘ ܐܝܢܣܩܠܘܦܕܝܐ ܚܐܪܬܐ ܕܐܢܛܪܢܛ ܒܠܫܢ̈ܐ ܣܓܝܐ̈ܐ܂ ܫܡܗ ܐܬܐ ܡܢ ܡ̈ܠܬܐ ܕ\"ܘܝܩܝ\" ܘ\"ܐܝܢܣܩܠܘܦܕܝܐ\"܀",
new String[] { "ܘܝܩܝܦܕܝܐ", "ܐܢܓܠܝܐ", "wikipedia", "ܗܘ", "ܐܝܢܣܩܠܘܦܕܝܐ", "ܚܐܪܬܐ", "ܕܐܢܛܪܢܛ", "ܒܠܫܢ̈ܐ", "ܣܓܝܐ̈ܐ", "ܫܡܗ",
"ܐܬܐ", "ܡܢ", "ܡ̈ܠܬܐ", "ܕ", "ܘܝܩܝ", "ܘ", "ܐܝܢܣܩܠܘܦܕܝܐ"});
}
public void testBengali() throws Exception {
assertAnalyzesTo(a, "এই বিশ্বকোষ পরিচালনা করে উইকিমিডিয়া ফাউন্ডেশন (একটি অলাভজনক সংস্থা)। উইকিপিডিয়ার শুরু ১৫ জানুয়ারি, ২০০১ সালে। এখন পর্যন্ত ২০০টিরও বেশী ভাষায় উইকিপিডিয়া রয়েছে।",
new String[] { "এই", "বিশ্বকোষ", "পরিচালনা", "করে", "উইকিমিডিয়া", "ফাউন্ডেশন", "একটি", "অলাভজনক", "সংস্থা", "উইকিপিডিয়ার",
"শুরু", "১৫", "জানুয়ারি", "২০০১", "সালে", "এখন", "পর্যন্ত", "২০০টিরও", "বেশী", "ভাষায়", "উইকিপিডিয়া", "রয়েছে" });
}
public void testFarsi() throws Exception {
assertAnalyzesTo(a, "ویکی پدیای انگلیسی در تاریخ ۲۵ دی ۱۳۷۹ به صورت مکملی برای دانشنامهٔ تخصصی نوپدیا نوشته شد.",
new String[] { "ویکی", "پدیای", "انگلیسی", "در", "تاریخ", "۲۵", "دی", "۱۳۷۹", "به", "صورت", "مکملی",
"برای", "دانشنامهٔ", "تخصصی", "نوپدیا", "نوشته", "شد" });
}
public void testGreek() throws Exception {
assertAnalyzesTo(a, "Γράφεται σε συνεργασία από εθελοντές με το λογισμικό wiki, κάτι που σημαίνει ότι άρθρα μπορεί να προστεθούν ή να αλλάξουν από τον καθένα.",
new String[] { "γράφεται", "σε", "συνεργασία", "από", "εθελοντέσ", "με", "το", "λογισμικό", "wiki", "κάτι", "που",
"σημαίνει", "ότι", "άρθρα", "μπορεί", "να", "προστεθούν", "ή", "να", "αλλάξουν", "από", "τον", "καθένα" });
}
public void testLao() throws Exception {
assertAnalyzesTo(a, "ກວ່າດອກ", new String[] { "ກວ່າ", "ດອກ" });
assertAnalyzesTo(a, "ພາສາລາວ", new String[] { "ພາສາ", "ລາວ"}, new String[] { "<ALPHANUM>", "<ALPHANUM>" });
}
public void testThai() throws Exception {
assertAnalyzesTo(a, "การที่ได้ต้องแสดงว่างานดี. แล้วเธอจะไปไหน? ๑๒๓๔",
new String[] { "การ", "ที่", "ได้", "ต้อง", "แสดง", "ว่า", "งาน", "ดี", "แล้ว", "เธอ", "จะ", "ไป", "ไหน", "๑๒๓๔"});
}
public void testTibetan() throws Exception {
assertAnalyzesTo(a, "སྣོན་མཛོད་དང་ལས་འདིས་བོད་ཡིག་མི་ཉམས་གོང་འཕེལ་དུ་གཏོང་བར་ཧ་ཅང་དགེ་མཚན་མཆིས་སོ། །",
new String[] { "སྣོན", "མཛོད", "དང", "ལས", "འདིས", "བོད", "ཡིག", "མི", "ཉམས", "གོང", "འཕེལ", "དུ", "གཏོང", "བར", "ཧ", "ཅང", "དགེ", "མཚན", "མཆིས", "སོ" });
}
/*
* For chinese, tokenize as char (these can later form bigrams or whatever)
*/
public void testChinese() throws Exception {
assertAnalyzesTo(a, "我是中国人。 1234 Tests ",
new String[] { "我", "是", "中", "国", "人", "1234", "tests"});
}
public void testHebrew() throws Exception {
assertAnalyzesTo(a, "דנקנר תקף את הדו\"ח",
new String[] { "דנקנר", "תקף", "את", "הדו\"ח" });
assertAnalyzesTo(a, "חברת בת של מודי'ס",
new String[] { "חברת", "בת", "של", "מודי'ס" });
}
public void testEmpty() throws Exception {
assertAnalyzesTo(a, "", new String[] {});
assertAnalyzesTo(a, ".", new String[] {});
assertAnalyzesTo(a, " ", new String[] {});
}
/* test various jira issues this analyzer is related to */
public void testLUCENE1545() throws Exception {
/*
* Standard analyzer does not correctly tokenize combining character U+0364 COMBINING LATIN SMALL LETTRE E.
* The word "moͤchte" is incorrectly tokenized into "mo" "chte", the combining character is lost.
* Expected result is only on token "moͤchte".
*/
assertAnalyzesTo(a, "moͤchte", new String[] { "moͤchte" });
}
/* Tests from StandardAnalyzer, just to show behavior is similar */
public void testAlphanumericSA() throws Exception {
// alphanumeric tokens
assertAnalyzesTo(a, "B2B", new String[]{"b2b"});
assertAnalyzesTo(a, "2B", new String[]{"2b"});
}
public void testDelimitersSA() throws Exception {
// other delimiters: "-", "/", ","
assertAnalyzesTo(a, "some-dashed-phrase", new String[]{"some", "dashed", "phrase"});
assertAnalyzesTo(a, "dogs,chase,cats", new String[]{"dogs", "chase", "cats"});
assertAnalyzesTo(a, "ac/dc", new String[]{"ac", "dc"});
}
public void testApostrophesSA() throws Exception {
// internal apostrophes: O'Reilly, you're, O'Reilly's
assertAnalyzesTo(a, "O'Reilly", new String[]{"o'reilly"});
assertAnalyzesTo(a, "you're", new String[]{"you're"});
assertAnalyzesTo(a, "she's", new String[]{"she's"});
assertAnalyzesTo(a, "Jim's", new String[]{"jim's"});
assertAnalyzesTo(a, "don't", new String[]{"don't"});
assertAnalyzesTo(a, "O'Reilly's", new String[]{"o'reilly's"});
}
public void testNumericSA() throws Exception {
// floating point, serial, model numbers, ip addresses, etc.
// every other segment must have at least one digit
assertAnalyzesTo(a, "21.35", new String[]{"21.35"});
assertAnalyzesTo(a, "R2D2 C3PO", new String[]{"r2d2", "c3po"});
assertAnalyzesTo(a, "216.239.63.104", new String[]{"216.239.63.104"});
assertAnalyzesTo(a, "216.239.63.104", new String[]{"216.239.63.104"});
}
public void testTextWithNumbersSA() throws Exception {
// numbers
assertAnalyzesTo(a, "David has 5000 bones", new String[]{"david", "has", "5000", "bones"});
}
public void testVariousTextSA() throws Exception {
// various
assertAnalyzesTo(a, "C embedded developers wanted", new String[]{"c", "embedded", "developers", "wanted"});
assertAnalyzesTo(a, "foo bar FOO BAR", new String[]{"foo", "bar", "foo", "bar"});
assertAnalyzesTo(a, "foo bar . FOO <> BAR", new String[]{"foo", "bar", "foo", "bar"});
assertAnalyzesTo(a, "\"QUOTED\" word", new String[]{"quoted", "word"});
}
public void testKoreanSA() throws Exception {
// Korean words
assertAnalyzesTo(a, "안녕하세요 한글입니다", new String[]{"안녕하세요", "한글입니다"});
}
public void testReusableTokenStream() throws Exception {
assertAnalyzesTo(a, "སྣོན་མཛོད་དང་ལས་འདིས་བོད་ཡིག་མི་ཉམས་གོང་འཕེལ་དུ་གཏོང་བར་ཧ་ཅང་དགེ་མཚན་མཆིས་སོ། །",
new String[] { "སྣོན", "མཛོད", "དང", "ལས", "འདིས", "བོད", "ཡིག", "མི", "ཉམས", "གོང",
"འཕེལ", "དུ", "གཏོང", "བར", "ཧ", "ཅང", "དགེ", "མཚན", "མཆིས", "སོ" });
}
public void testOffsets() throws Exception {
assertAnalyzesTo(a, "David has 5000 bones",
new String[] {"david", "has", "5000", "bones"},
new int[] {0, 6, 10, 15},
new int[] {5, 9, 14, 20});
}
public void testTypes() throws Exception {
assertAnalyzesTo(a, "David has 5000 bones",
new String[] {"david", "has", "5000", "bones"},
new String[] { "<ALPHANUM>", "<ALPHANUM>", "<NUM>", "<ALPHANUM>" });
}
public void testKorean() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "훈민정음",
new String[] { "훈민정음" },
new String[] { "<HANGUL>" });
}
public void testJapanese() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "仮名遣い カタカナ",
new String[] { "仮", "名", "遣", "い", "カタカナ" },
new String[] { "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<HIRAGANA>", "<KATAKANA>" });
}
/** blast some random strings through the analyzer */
public void testRandomStrings() throws Exception {
checkRandomData(random(), a, 1000*RANDOM_MULTIPLIER);
}
/** blast some random large strings through the analyzer */
public void testRandomHugeStrings() throws Exception {
Random random = random();
checkRandomData(random, a, 100*RANDOM_MULTIPLIER, 8192);
}
public void testTokenAttributes() throws Exception {
TokenStream ts = a.tokenStream("dummy", "This is a test");
try {
ScriptAttribute scriptAtt = ts.addAttribute(ScriptAttribute.class);
ts.reset();
while (ts.incrementToken()) {
assertEquals(UScript.LATIN, scriptAtt.getCode());
assertEquals(UScript.getName(UScript.LATIN), scriptAtt.getName());
assertEquals(UScript.getShortName(UScript.LATIN), scriptAtt.getShortName());
assertTrue(ts.reflectAsString(false).contains("script=Latin"));
}
ts.end();
} finally {
IOUtils.closeWhileHandlingException(ts);
}
}
}
| NightOwl888/lucene | lucene/analysis/icu/src/test/org/apache/lucene/analysis/icu/segmentation/TestICUTokenizer.java |
43,266 | package org.apache.lucene.analysis.standard;
/*
* 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.
*/
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.BaseTokenStreamTestCase;
import org.apache.lucene.analysis.standard.UAX29URLEmailAnalyzer;
import java.io.IOException;
import java.util.Arrays;
public class TestUAX29URLEmailAnalyzer extends BaseTokenStreamTestCase {
private Analyzer a = new UAX29URLEmailAnalyzer();
public void testHugeDoc() throws IOException {
StringBuilder sb = new StringBuilder();
char whitespace[] = new char[4094];
Arrays.fill(whitespace, ' ');
sb.append(whitespace);
sb.append("testing 1234");
String input = sb.toString();
BaseTokenStreamTestCase.assertAnalyzesTo(a, input, new String[]{"testing", "1234"}) ;
}
public void testArmenian() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Վիքիպեդիայի 13 միլիոն հոդվածները (4,600` հայերեն վիքիպեդիայում) գրվել են կամավորների կողմից ու համարյա բոլոր հոդվածները կարող է խմբագրել ցանկաց մարդ ով կարող է բացել Վիքիպեդիայի կայքը։",
new String[] { "վիքիպեդիայի", "13", "միլիոն", "հոդվածները", "4,600", "հայերեն", "վիքիպեդիայում", "գրվել", "են", "կամավորների", "կողմից",
"ու", "համարյա", "բոլոր", "հոդվածները", "կարող", "է", "խմբագրել", "ցանկաց", "մարդ", "ով", "կարող", "է", "բացել", "վիքիպեդիայի", "կայքը" } );
}
public void testAmharic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ዊኪፔድያ የባለ ብዙ ቋንቋ የተሟላ ትክክለኛና ነጻ መዝገበ ዕውቀት (ኢንሳይክሎፒዲያ) ነው። ማንኛውም",
new String[] { "ዊኪፔድያ", "የባለ", "ብዙ", "ቋንቋ", "የተሟላ", "ትክክለኛና", "ነጻ", "መዝገበ", "ዕውቀት", "ኢንሳይክሎፒዲያ", "ነው", "ማንኛውም" } );
}
public void testArabic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "الفيلم الوثائقي الأول عن ويكيبيديا يسمى \"الحقيقة بالأرقام: قصة ويكيبيديا\" (بالإنجليزية: Truth in Numbers: The Wikipedia Story)، سيتم إطلاقه في 2008.",
new String[] { "الفيلم", "الوثائقي", "الأول", "عن", "ويكيبيديا", "يسمى", "الحقيقة", "بالأرقام", "قصة", "ويكيبيديا",
"بالإنجليزية", "truth", "numbers", "wikipedia", "story", "سيتم", "إطلاقه", "في", "2008" } );
}
public void testAramaic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ܘܝܩܝܦܕܝܐ (ܐܢܓܠܝܐ: Wikipedia) ܗܘ ܐܝܢܣܩܠܘܦܕܝܐ ܚܐܪܬܐ ܕܐܢܛܪܢܛ ܒܠܫܢ̈ܐ ܣܓܝܐ̈ܐ܂ ܫܡܗ ܐܬܐ ܡܢ ܡ̈ܠܬܐ ܕ\"ܘܝܩܝ\" ܘ\"ܐܝܢܣܩܠܘܦܕܝܐ\"܀",
new String[] { "ܘܝܩܝܦܕܝܐ", "ܐܢܓܠܝܐ", "wikipedia", "ܗܘ", "ܐܝܢܣܩܠܘܦܕܝܐ", "ܚܐܪܬܐ", "ܕܐܢܛܪܢܛ", "ܒܠܫܢ̈ܐ", "ܣܓܝܐ̈ܐ", "ܫܡܗ",
"ܐܬܐ", "ܡܢ", "ܡ̈ܠܬܐ", "ܕ", "ܘܝܩܝ", "ܘ", "ܐܝܢܣܩܠܘܦܕܝܐ"});
}
public void testBengali() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "এই বিশ্বকোষ পরিচালনা করে উইকিমিডিয়া ফাউন্ডেশন (একটি অলাভজনক সংস্থা)। উইকিপিডিয়ার শুরু ১৫ জানুয়ারি, ২০০১ সালে। এখন পর্যন্ত ২০০টিরও বেশী ভাষায় উইকিপিডিয়া রয়েছে।",
new String[] { "এই", "বিশ্বকোষ", "পরিচালনা", "করে", "উইকিমিডিয়া", "ফাউন্ডেশন", "একটি", "অলাভজনক", "সংস্থা", "উইকিপিডিয়ার",
"শুরু", "১৫", "জানুয়ারি", "২০০১", "সালে", "এখন", "পর্যন্ত", "২০০টিরও", "বেশী", "ভাষায়", "উইকিপিডিয়া", "রয়েছে" });
}
public void testFarsi() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ویکی پدیای انگلیسی در تاریخ ۲۵ دی ۱۳۷۹ به صورت مکملی برای دانشنامهٔ تخصصی نوپدیا نوشته شد.",
new String[] { "ویکی", "پدیای", "انگلیسی", "در", "تاریخ", "۲۵", "دی", "۱۳۷۹", "به", "صورت", "مکملی",
"برای", "دانشنامهٔ", "تخصصی", "نوپدیا", "نوشته", "شد" });
}
public void testGreek() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Γράφεται σε συνεργασία από εθελοντές με το λογισμικό wiki, κάτι που σημαίνει ότι άρθρα μπορεί να προστεθούν ή να αλλάξουν από τον καθένα.",
new String[] { "γράφεται", "σε", "συνεργασία", "από", "εθελοντές", "με", "το", "λογισμικό", "wiki", "κάτι", "που",
"σημαίνει", "ότι", "άρθρα", "μπορεί", "να", "προστεθούν", "ή", "να", "αλλάξουν", "από", "τον", "καθένα" });
}
public void testThai() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "การที่ได้ต้องแสดงว่างานดี. แล้วเธอจะไปไหน? ๑๒๓๔",
new String[] { "การที่ได้ต้องแสดงว่างานดี", "แล้วเธอจะไปไหน", "๑๒๓๔" });
}
public void testLao() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ສາທາລະນະລັດ ປະຊາທິປະໄຕ ປະຊາຊົນລາວ",
new String[] { "ສາທາລະນະລັດ", "ປະຊາທິປະໄຕ", "ປະຊາຊົນລາວ" });
}
public void testTibetan() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "སྣོན་མཛོད་དང་ལས་འདིས་བོད་ཡིག་མི་ཉམས་གོང་འཕེལ་དུ་གཏོང་བར་ཧ་ཅང་དགེ་མཚན་མཆིས་སོ། །",
new String[] { "སྣོན", "མཛོད", "དང", "ལས", "འདིས", "བོད", "ཡིག",
"མི", "ཉམས", "གོང", "འཕེལ", "དུ", "གཏོང", "བར",
"ཧ", "ཅང", "དགེ", "མཚན", "མཆིས", "སོ" });
}
/*
* For chinese, tokenize as char (these can later form bigrams or whatever)
*/
public void testChinese() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "我是中国人。 1234 Tests ",
new String[] { "我", "是", "中", "国", "人", "1234", "tests"});
}
public void testEmpty() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "", new String[] {});
BaseTokenStreamTestCase.assertAnalyzesTo(a, ".", new String[] {});
BaseTokenStreamTestCase.assertAnalyzesTo(a, " ", new String[] {});
}
/* test various jira issues this analyzer is related to */
public void testLUCENE1545() throws Exception {
/*
* Standard analyzer does not correctly tokenize combining character U+0364 COMBINING LATIN SMALL LETTER E.
* The word "moͤchte" is incorrectly tokenized into "mo" "chte", the combining character is lost.
* Expected result is only one token "moͤchte".
*/
BaseTokenStreamTestCase.assertAnalyzesTo(a, "moͤchte", new String[] { "moͤchte" });
}
/* Tests from StandardAnalyzer, just to show behavior is similar */
public void testAlphanumericSA() throws Exception {
// alphanumeric tokens
BaseTokenStreamTestCase.assertAnalyzesTo(a, "B2B", new String[]{"b2b"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "2B", new String[]{"2b"});
}
public void testDelimitersSA() throws Exception {
// other delimiters: "-", "/", ","
BaseTokenStreamTestCase.assertAnalyzesTo(a, "some-dashed-phrase", new String[]{"some", "dashed", "phrase"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "dogs,chase,cats", new String[]{"dogs", "chase", "cats"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ac/dc", new String[]{"ac", "dc"});
}
public void testApostrophesSA() throws Exception {
// internal apostrophes: O'Reilly, you're, O'Reilly's
BaseTokenStreamTestCase.assertAnalyzesTo(a, "O'Reilly", new String[]{"o'reilly"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "you're", new String[]{"you're"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "she's", new String[]{"she's"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Jim's", new String[]{"jim's"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "don't", new String[]{"don't"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "O'Reilly's", new String[]{"o'reilly's"});
}
public void testNumericSA() throws Exception {
// floating point, serial, model numbers, ip addresses, etc.
BaseTokenStreamTestCase.assertAnalyzesTo(a, "21.35", new String[]{"21.35"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "R2D2 C3PO", new String[]{"r2d2", "c3po"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "216.239.63.104", new String[]{"216.239.63.104"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "216.239.63.104", new String[]{"216.239.63.104"});
}
public void testTextWithNumbersSA() throws Exception {
// numbers
BaseTokenStreamTestCase.assertAnalyzesTo(a, "David has 5000 bones", new String[]{"david", "has", "5000", "bones"});
}
public void testVariousTextSA() throws Exception {
// various
BaseTokenStreamTestCase.assertAnalyzesTo(a, "C embedded developers wanted", new String[]{"c", "embedded", "developers", "wanted"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "foo bar FOO BAR", new String[]{"foo", "bar", "foo", "bar"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "foo bar . FOO <> BAR", new String[]{"foo", "bar", "foo", "bar"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "\"QUOTED\" word", new String[]{"quoted", "word"});
}
public void testKoreanSA() throws Exception {
// Korean words
BaseTokenStreamTestCase.assertAnalyzesTo(a, "안녕하세요 한글입니다", new String[]{"안녕하세요", "한글입니다"});
}
public void testOffsets() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "David has 5000 bones",
new String[] {"david", "has", "5000", "bones"},
new int[] {0, 6, 10, 15},
new int[] {5, 9, 14, 20});
}
public void testTypes() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "david has 5000 bones",
new String[] {"david", "has", "5000", "bones"},
new String[] { "<ALPHANUM>", "<ALPHANUM>", "<NUM>", "<ALPHANUM>" });
}
public void testSupplementary() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "𩬅艱鍟䇹愯瀛",
new String[] {"𩬅", "艱", "鍟", "䇹", "愯", "瀛"},
new String[] { "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>" });
}
public void testKorean() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "훈민정음",
new String[] { "훈민정음" },
new String[] { "<HANGUL>" });
}
public void testJapanese() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "仮名遣い カタカナ",
new String[] { "仮", "名", "遣", "い", "カタカナ" },
new String[] { "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<HIRAGANA>", "<KATAKANA>" });
}
public void testCombiningMarks() throws Exception {
checkOneTerm(a, "ざ", "ざ"); // hiragana
checkOneTerm(a, "ザ", "ザ"); // katakana
checkOneTerm(a, "壹゙", "壹゙"); // ideographic
checkOneTerm(a, "아゙", "아゙"); // hangul
}
public void testBasicEmails() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a,
"one [email protected] two three [[email protected]] \"ArakaBanassaMassanaBakarA\" <[email protected]>",
new String[] {"one", "[email protected]", "two", "three", "[email protected]", "arakabanassamassanabakara", "[email protected]",},
new String[] { "<ALPHANUM>", "<EMAIL>", "<ALPHANUM>", "<ALPHANUM>", "<EMAIL>", "<ALPHANUM>", "<EMAIL>" });
}
public void testMailtoSchemeEmails () throws Exception {
// See LUCENE-3880
BaseTokenStreamTestCase.assertAnalyzesTo(a, "MAILTO:[email protected]",
new String[] {"mailto", "[email protected]"},
new String[] { "<ALPHANUM>", "<EMAIL>" });
// TODO: Support full mailto: scheme URIs. See RFC 6068: http://tools.ietf.org/html/rfc6068
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "mailto:[email protected],[email protected][email protected]"
+ "&subject=Subjectivity&body=Corpusivity%20or%20something%20like%20that",
new String[] { "mailto",
"[email protected]",
// TODO: recognize ',' address delimiter. Also, see examples of ';' delimiter use at: http://www.mailto.co.uk/
",[email protected]",
"[email protected]", // TODO: split field keys/values
"subject", "subjectivity",
"body", "corpusivity", "20or", "20something","20like", "20that" }, // TODO: Hex decoding + re-tokenization
new String[] { "<ALPHANUM>",
"<EMAIL>",
"<EMAIL>",
"<EMAIL>",
"<ALPHANUM>", "<ALPHANUM>",
"<ALPHANUM>", "<ALPHANUM>", "<ALPHANUM>", "<ALPHANUM>", "<ALPHANUM>", "<ALPHANUM>" });
}
public void testBasicURLs() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a,
"a <HTTPs://example.net/omg/isnt/that/NICE?no=its&n%30t#mntl-E>b-D ftp://www.example.com/ABC.txt file:///C:/path/to/a/FILE.txt C",
new String[] {"https://example.net/omg/isnt/that/nice?no=its&n%30t#mntl-e", "b", "d", "ftp://www.example.com/abc.txt", "file:///c:/path/to/a/file.txt", "c" },
new String[] { "<URL>", "<ALPHANUM>", "<ALPHANUM>", "<URL>", "<URL>", "<ALPHANUM>" });
}
public void testNoSchemeURLs() throws Exception {
// ".ph" is a Top Level Domain
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "<index.ph>", new String[]{"index.ph"}, new String[]{"<URL>"});
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "index.ph", new String[]{"index.ph"}, new String[]{"<URL>"});
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "index.php", new String[]{"index.php"}, new String[]{"<ALPHANUM>"});
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "index.phα", new String[]{"index.phα"}, new String[]{"<ALPHANUM>"});
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "index-h.php", new String[] { "index", "h.php" },
new String[] { "<ALPHANUM>","<ALPHANUM>"});
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "index2.php", new String[] { "index2", "php" },
new String[] { "<ALPHANUM>", "<ALPHANUM>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "index2.ph9,", new String[] { "index2", "ph9" },
new String[] { "<ALPHANUM>", "<ALPHANUM>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com,example.ph,index.php,index2.php,example2.ph",
new String[] { "example.com", "example.ph", "index.php", "index2", "php", "example2.ph" },
new String[] { "<URL>", "<URL>", "<ALPHANUM>", "<ALPHANUM>", "<ALPHANUM>", "<URL>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com:8080 example.com/path/here example.com?query=something example.com#fragment",
new String[] { "example.com:8080", "example.com/path/here", "example.com?query=something", "example.com#fragment" },
new String[] { "<URL>", "<URL>", "<URL>", "<URL>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com:8080/path/here?query=something#fragment",
new String[] { "example.com:8080/path/here?query=something#fragment" },
new String[] { "<URL>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com:8080/path/here?query=something",
new String[] { "example.com:8080/path/here?query=something" },
new String[] { "<URL>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com:8080/path/here#fragment",
new String[] { "example.com:8080/path/here#fragment" },
new String[] { "<URL>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com:8080/path/here",
new String[] { "example.com:8080/path/here" },
new String[] { "<URL>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com:8080?query=something#fragment",
new String[] { "example.com:8080?query=something#fragment" },
new String[] { "<URL>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com:8080?query=something",
new String[] { "example.com:8080?query=something" },
new String[] { "<URL>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com:8080#fragment",
new String[] { "example.com:8080#fragment" },
new String[] { "<URL>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com/path/here?query=something#fragment",
new String[] { "example.com/path/here?query=something#fragment" },
new String[] { "<URL>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com/path/here?query=something",
new String[] { "example.com/path/here?query=something" },
new String[] { "<URL>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com/path/here#fragment",
new String[] { "example.com/path/here#fragment" },
new String[] { "<URL>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com?query=something#fragment",
new String[] { "example.com?query=something#fragment" },
new String[] { "<URL>" });
}
/** blast some random strings through the analyzer */
public void testRandomStrings() throws Exception {
checkRandomData(random(), new UAX29URLEmailAnalyzer(), 1000*RANDOM_MULTIPLIER);
}
}
| Flipkart/lucene-solr | lucene/analysis/common/src/test/org/apache/lucene/analysis/standard/TestUAX29URLEmailAnalyzer.java |
43,267 | /*
* 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.
*/
package org.apache.lucene.analysis.email;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.tokenattributes.TypeAttribute;
import org.apache.lucene.tests.analysis.BaseTokenStreamTestCase;
import org.apache.lucene.tests.analysis.standard.EmojiTokenizationTestUnicode_12_1;
import org.apache.lucene.tests.analysis.standard.WordBreakTestUnicode_12_1_0;
import org.apache.lucene.tests.util.TestUtil;
import org.apache.lucene.util.IOUtils;
public class TestUAX29URLEmailTokenizer extends BaseTokenStreamTestCase {
// LUCENE-5440: extremely slow tokenization of text matching email <local-part> (before the '@')
@Nightly
public void testLongEMAILatomText() throws Exception {
// EMAILatomText = [A-Za-z0-9!#$%&'*+-/=?\^_`{|}~]
char[] emailAtomChars =
"!#$%&'*+,-./0123456789=?ABCDEFGHIJKLMNOPQRSTUVWXYZ^_`abcdefghijklmnopqrstuvwxyz{|}~"
.toCharArray();
StringBuilder builder = new StringBuilder();
int numChars = TestUtil.nextInt(random(), 100 * 1024, 3 * 1024 * 1024);
for (int i = 0; i < numChars; ++i) {
builder.append(emailAtomChars[random().nextInt(emailAtomChars.length)]);
}
int tokenCount = 0;
UAX29URLEmailTokenizer ts = new UAX29URLEmailTokenizer();
String text = builder.toString();
ts.setReader(new StringReader(text));
ts.reset();
while (ts.incrementToken()) {
tokenCount++;
}
ts.end();
ts.close();
assertTrue(tokenCount > 0);
tokenCount = 0;
int newBufferSize = TestUtil.nextInt(random(), 200, 8192);
ts.setMaxTokenLength(newBufferSize);
ts.setReader(new StringReader(text));
ts.reset();
while (ts.incrementToken()) {
tokenCount++;
}
ts.end();
ts.close();
assertTrue(tokenCount > 0);
}
public void testHugeDoc() throws IOException {
StringBuilder sb = new StringBuilder();
char[] whitespace = new char[4094];
Arrays.fill(whitespace, ' ');
sb.append(whitespace);
sb.append("testing 1234");
String input = sb.toString();
UAX29URLEmailTokenizer tokenizer = new UAX29URLEmailTokenizer(newAttributeFactory());
tokenizer.setReader(new StringReader(input));
BaseTokenStreamTestCase.assertTokenStreamContents(tokenizer, new String[] {"testing", "1234"});
}
private Analyzer a, urlAnalyzer, emailAnalyzer;
@Override
public void setUp() throws Exception {
super.setUp();
a =
new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName) {
Tokenizer tokenizer = new UAX29URLEmailTokenizer(newAttributeFactory());
return new TokenStreamComponents(tokenizer);
}
};
urlAnalyzer =
new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName) {
UAX29URLEmailTokenizer tokenizer = new UAX29URLEmailTokenizer(newAttributeFactory());
tokenizer.setMaxTokenLength(
UAX29URLEmailTokenizer.MAX_TOKEN_LENGTH_LIMIT); // Tokenize arbitrary length URLs
TokenFilter filter = new URLFilter(tokenizer);
return new TokenStreamComponents(tokenizer, filter);
}
};
emailAnalyzer =
new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName) {
UAX29URLEmailTokenizer tokenizer = new UAX29URLEmailTokenizer(newAttributeFactory());
TokenFilter filter = new EmailFilter(tokenizer);
return new TokenStreamComponents(tokenizer, filter);
}
};
}
@Override
public void tearDown() throws Exception {
IOUtils.close(a, urlAnalyzer, emailAnalyzer);
super.tearDown();
}
/** Passes through tokens with type "<URL>" and blocks all other types. */
private static class URLFilter extends TokenFilter {
private final TypeAttribute typeAtt = addAttribute(TypeAttribute.class);
public URLFilter(TokenStream in) {
super(in);
}
@Override
public final boolean incrementToken() throws java.io.IOException {
boolean isTokenAvailable = false;
while (input.incrementToken()) {
if (typeAtt.type() == UAX29URLEmailTokenizer.TOKEN_TYPES[UAX29URLEmailTokenizer.URL]) {
isTokenAvailable = true;
break;
}
}
return isTokenAvailable;
}
}
/** Passes through tokens with type "<EMAIL>" and blocks all other types. */
private static class EmailFilter extends TokenFilter {
private final TypeAttribute typeAtt = addAttribute(TypeAttribute.class);
public EmailFilter(TokenStream in) {
super(in);
}
@Override
public final boolean incrementToken() throws java.io.IOException {
boolean isTokenAvailable = false;
while (input.incrementToken()) {
if (typeAtt.type() == UAX29URLEmailTokenizer.TOKEN_TYPES[UAX29URLEmailTokenizer.EMAIL]) {
isTokenAvailable = true;
break;
}
}
return isTokenAvailable;
}
}
public void testArmenian() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"Վիքիպեդիայի 13 միլիոն հոդվածները (4,600` հայերեն վիքիպեդիայում) գրվել են կամավորների կողմից ու համարյա բոլոր հոդվածները կարող է խմբագրել ցանկաց մարդ ով կարող է բացել Վիքիպեդիայի կայքը։",
new String[] {
"Վիքիպեդիայի",
"13",
"միլիոն",
"հոդվածները",
"4,600",
"հայերեն",
"վիքիպեդիայում",
"գրվել",
"են",
"կամավորների",
"կողմից",
"ու",
"համարյա",
"բոլոր",
"հոդվածները",
"կարող",
"է",
"խմբագրել",
"ցանկաց",
"մարդ",
"ով",
"կարող",
"է",
"բացել",
"Վիքիպեդիայի",
"կայքը"
});
}
public void testAmharic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"ዊኪፔድያ የባለ ብዙ ቋንቋ የተሟላ ትክክለኛና ነጻ መዝገበ ዕውቀት (ኢንሳይክሎፒዲያ) ነው። ማንኛውም",
new String[] {
"ዊኪፔድያ",
"የባለ",
"ብዙ",
"ቋንቋ",
"የተሟላ",
"ትክክለኛና",
"ነጻ",
"መዝገበ",
"ዕውቀት",
"ኢንሳይክሎፒዲያ",
"ነው",
"ማንኛውም"
});
}
public void testArabic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"الفيلم الوثائقي الأول عن ويكيبيديا يسمى \"الحقيقة بالأرقام: قصة ويكيبيديا\" (بالإنجليزية: Truth in Numbers: The Wikipedia Story)، سيتم إطلاقه في 2008.",
new String[] {
"الفيلم",
"الوثائقي",
"الأول",
"عن",
"ويكيبيديا",
"يسمى",
"الحقيقة",
"بالأرقام",
"قصة",
"ويكيبيديا",
"بالإنجليزية",
"Truth",
"in",
"Numbers",
"The",
"Wikipedia",
"Story",
"سيتم",
"إطلاقه",
"في",
"2008"
});
}
public void testAramaic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"ܘܝܩܝܦܕܝܐ (ܐܢܓܠܝܐ: Wikipedia) ܗܘ ܐܝܢܣܩܠܘܦܕܝܐ ܚܐܪܬܐ ܕܐܢܛܪܢܛ ܒܠܫܢ̈ܐ ܣܓܝܐ̈ܐ܂ ܫܡܗ ܐܬܐ ܡܢ ܡ̈ܠܬܐ ܕ\"ܘܝܩܝ\" ܘ\"ܐܝܢܣܩܠܘܦܕܝܐ\"܀",
new String[] {
"ܘܝܩܝܦܕܝܐ",
"ܐܢܓܠܝܐ",
"Wikipedia",
"ܗܘ",
"ܐܝܢܣܩܠܘܦܕܝܐ",
"ܚܐܪܬܐ",
"ܕܐܢܛܪܢܛ",
"ܒܠܫܢ̈ܐ",
"ܣܓܝܐ̈ܐ",
"ܫܡܗ",
"ܐܬܐ",
"ܡܢ",
"ܡ̈ܠܬܐ",
"ܕ",
"ܘܝܩܝ",
"ܘ",
"ܐܝܢܣܩܠܘܦܕܝܐ"
});
}
public void testBengali() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"এই বিশ্বকোষ পরিচালনা করে উইকিমিডিয়া ফাউন্ডেশন (একটি অলাভজনক সংস্থা)। উইকিপিডিয়ার শুরু ১৫ জানুয়ারি, ২০০১ সালে। এখন পর্যন্ত ২০০টিরও বেশী ভাষায় উইকিপিডিয়া রয়েছে।",
new String[] {
"এই",
"বিশ্বকোষ",
"পরিচালনা",
"করে",
"উইকিমিডিয়া",
"ফাউন্ডেশন",
"একটি",
"অলাভজনক",
"সংস্থা",
"উইকিপিডিয়ার",
"শুরু",
"১৫",
"জানুয়ারি",
"২০০১",
"সালে",
"এখন",
"পর্যন্ত",
"২০০টিরও",
"বেশী",
"ভাষায়",
"উইকিপিডিয়া",
"রয়েছে"
});
}
public void testFarsi() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"ویکی پدیای انگلیسی در تاریخ ۲۵ دی ۱۳۷۹ به صورت مکملی برای دانشنامهٔ تخصصی نوپدیا نوشته شد.",
new String[] {
"ویکی",
"پدیای",
"انگلیسی",
"در",
"تاریخ",
"۲۵",
"دی",
"۱۳۷۹",
"به",
"صورت",
"مکملی",
"برای",
"دانشنامهٔ",
"تخصصی",
"نوپدیا",
"نوشته",
"شد"
});
}
public void testGreek() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"Γράφεται σε συνεργασία από εθελοντές με το λογισμικό wiki, κάτι που σημαίνει ότι άρθρα μπορεί να προστεθούν ή να αλλάξουν από τον καθένα.",
new String[] {
"Γράφεται",
"σε",
"συνεργασία",
"από",
"εθελοντές",
"με",
"το",
"λογισμικό",
"wiki",
"κάτι",
"που",
"σημαίνει",
"ότι",
"άρθρα",
"μπορεί",
"να",
"προστεθούν",
"ή",
"να",
"αλλάξουν",
"από",
"τον",
"καθένα"
});
}
public void testThai() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"การที่ได้ต้องแสดงว่างานดี. แล้วเธอจะไปไหน? ๑๒๓๔",
new String[] {"การที่ได้ต้องแสดงว่างานดี", "แล้วเธอจะไปไหน", "๑๒๓๔"});
}
public void testLao() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"ສາທາລະນະລັດ ປະຊາທິປະໄຕ ປະຊາຊົນລາວ",
new String[] {"ສາທາລະນະລັດ", "ປະຊາທິປະໄຕ", "ປະຊາຊົນລາວ"});
}
public void testTibetan() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"སྣོན་མཛོད་དང་ལས་འདིས་བོད་ཡིག་མི་ཉམས་གོང་འཕེལ་དུ་གཏོང་བར་ཧ་ཅང་དགེ་མཚན་མཆིས་སོ། །",
new String[] {
"སྣོན", "མཛོད", "དང", "ལས", "འདིས", "བོད", "ཡིག",
"མི", "ཉམས", "གོང", "འཕེལ", "དུ", "གཏོང", "བར",
"ཧ", "ཅང", "དགེ", "མཚན", "མཆིས", "སོ"
});
}
/*
* For chinese, tokenize as char (these can later form bigrams or whatever)
*/
public void testChinese() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a, "我是中国人。 1234 Tests ", new String[] {"我", "是", "中", "国", "人", "1234", "Tests"});
}
public void testEmpty() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "", new String[] {});
BaseTokenStreamTestCase.assertAnalyzesTo(a, ".", new String[] {});
BaseTokenStreamTestCase.assertAnalyzesTo(a, " ", new String[] {});
}
/* test various jira issues this analyzer is related to */
public void testLUCENE1545() throws Exception {
/*
* Standard analyzer does not correctly tokenize combining character U+0364 COMBINING LATIN SMALL LETTRE E.
* The word "moͤchte" is incorrectly tokenized into "mo" "chte", the combining character is lost.
* Expected result is only on token "moͤchte".
*/
BaseTokenStreamTestCase.assertAnalyzesTo(a, "moͤchte", new String[] {"moͤchte"});
}
/* Tests from StandardAnalyzer, just to show behavior is similar */
public void testAlphanumericSA() throws Exception {
// alphanumeric tokens
BaseTokenStreamTestCase.assertAnalyzesTo(a, "B2B", new String[] {"B2B"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "2B", new String[] {"2B"});
}
public void testDelimitersSA() throws Exception {
// other delimiters: "-", "/", ","
BaseTokenStreamTestCase.assertAnalyzesTo(
a, "some-dashed-phrase", new String[] {"some", "dashed", "phrase"});
BaseTokenStreamTestCase.assertAnalyzesTo(
a, "dogs,chase,cats", new String[] {"dogs", "chase", "cats"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ac/dc", new String[] {"ac", "dc"});
}
public void testApostrophesSA() throws Exception {
// internal apostrophes: O'Reilly, you're, O'Reilly's
BaseTokenStreamTestCase.assertAnalyzesTo(a, "O'Reilly", new String[] {"O'Reilly"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "you're", new String[] {"you're"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "she's", new String[] {"she's"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Jim's", new String[] {"Jim's"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "don't", new String[] {"don't"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "O'Reilly's", new String[] {"O'Reilly's"});
}
public void testNumericSA() throws Exception {
// floating point, serial, model numbers, ip addresses, etc.
BaseTokenStreamTestCase.assertAnalyzesTo(a, "21.35", new String[] {"21.35"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "R2D2 C3PO", new String[] {"R2D2", "C3PO"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "216.239.63.104", new String[] {"216.239.63.104"});
}
public void testTextWithNumbersSA() throws Exception {
// numbers
BaseTokenStreamTestCase.assertAnalyzesTo(
a, "David has 5000 bones", new String[] {"David", "has", "5000", "bones"});
}
public void testVariousTextSA() throws Exception {
// various
BaseTokenStreamTestCase.assertAnalyzesTo(
a, "C embedded developers wanted", new String[] {"C", "embedded", "developers", "wanted"});
BaseTokenStreamTestCase.assertAnalyzesTo(
a, "foo bar FOO BAR", new String[] {"foo", "bar", "FOO", "BAR"});
BaseTokenStreamTestCase.assertAnalyzesTo(
a, "foo bar . FOO <> BAR", new String[] {"foo", "bar", "FOO", "BAR"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "\"QUOTED\" word", new String[] {"QUOTED", "word"});
}
public void testKoreanSA() throws Exception {
// Korean words
BaseTokenStreamTestCase.assertAnalyzesTo(a, "안녕하세요 한글입니다", new String[] {"안녕하세요", "한글입니다"});
}
public void testOffsets() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"David has 5000 bones",
new String[] {"David", "has", "5000", "bones"},
new int[] {0, 6, 10, 15},
new int[] {5, 9, 14, 20});
}
public void testTypes() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"David has 5000 bones",
new String[] {"David", "has", "5000", "bones"},
new String[] {"<ALPHANUM>", "<ALPHANUM>", "<NUM>", "<ALPHANUM>"});
}
public void testWikiURLs() throws Exception {
Reader reader = null;
String luceneResourcesWikiPage;
try {
reader =
new InputStreamReader(
getClass().getResourceAsStream("LuceneResourcesWikiPage.html"),
StandardCharsets.UTF_8);
StringBuilder builder = new StringBuilder();
char[] buffer = new char[1024];
int numCharsRead;
while (-1 != (numCharsRead = reader.read(buffer))) {
builder.append(buffer, 0, numCharsRead);
}
luceneResourcesWikiPage = builder.toString();
} finally {
if (null != reader) {
reader.close();
}
}
assertTrue(null != luceneResourcesWikiPage && luceneResourcesWikiPage.length() > 0);
BufferedReader bufferedReader = null;
String[] urls;
try {
List<String> urlList = new ArrayList<>();
bufferedReader =
new BufferedReader(
new InputStreamReader(
getClass().getResourceAsStream("LuceneResourcesWikiPageURLs.txt"),
StandardCharsets.UTF_8));
String line;
while (null != (line = bufferedReader.readLine())) {
line = line.trim();
if (line.length() > 0) {
urlList.add(line);
}
}
urls = urlList.toArray(new String[urlList.size()]);
} finally {
if (null != bufferedReader) {
bufferedReader.close();
}
}
assertTrue(null != urls && urls.length > 0);
BaseTokenStreamTestCase.assertAnalyzesTo(urlAnalyzer, luceneResourcesWikiPage, urls);
}
public void testEmails() throws Exception {
Reader reader = null;
String randomTextWithEmails;
try {
reader =
new InputStreamReader(
getClass().getResourceAsStream("random.text.with.email.addresses.txt"),
StandardCharsets.UTF_8);
StringBuilder builder = new StringBuilder();
char[] buffer = new char[1024];
int numCharsRead;
while (-1 != (numCharsRead = reader.read(buffer))) {
builder.append(buffer, 0, numCharsRead);
}
randomTextWithEmails = builder.toString();
} finally {
if (null != reader) {
reader.close();
}
}
assertTrue(null != randomTextWithEmails && randomTextWithEmails.length() > 0);
BufferedReader bufferedReader = null;
String[] emails;
try {
List<String> emailList = new ArrayList<>();
bufferedReader =
new BufferedReader(
new InputStreamReader(
getClass()
.getResourceAsStream(
"email.addresses.from.random.text.with.email.addresses.txt"),
StandardCharsets.UTF_8));
String line;
while (null != (line = bufferedReader.readLine())) {
line = line.trim();
if (line.length() > 0) {
emailList.add(line);
}
}
emails = emailList.toArray(new String[emailList.size()]);
} finally {
if (null != bufferedReader) {
bufferedReader.close();
}
}
assertTrue(null != emails && emails.length > 0);
BaseTokenStreamTestCase.assertAnalyzesTo(emailAnalyzer, randomTextWithEmails, emails);
}
public void testMailtoSchemeEmails() throws Exception {
// See LUCENE-3880
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"mailto:[email protected]",
new String[] {"mailto", "[email protected]"},
new String[] {"<ALPHANUM>", "<EMAIL>"});
// TODO: Support full mailto: scheme URIs. See RFC 6068: http://tools.ietf.org/html/rfc6068
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"mailto:[email protected],[email protected][email protected]"
+ "&subject=Subjectivity&body=Corpusivity%20or%20something%20like%20that",
new String[] {
"mailto",
"[email protected]",
// TODO: recognize ',' address delimiter. Also, see examples of ';' delimiter use at:
// http://www.mailto.co.uk/
",[email protected]",
"[email protected]", // TODO: split field keys/values
"subject",
"Subjectivity",
"body",
"Corpusivity",
"20or",
"20something",
"20like",
"20that"
}, // TODO: Hex decoding + re-tokenization
new String[] {
"<ALPHANUM>",
"<EMAIL>",
"<EMAIL>",
"<EMAIL>",
"<ALPHANUM>",
"<ALPHANUM>",
"<ALPHANUM>",
"<ALPHANUM>",
"<ALPHANUM>",
"<ALPHANUM>",
"<ALPHANUM>",
"<ALPHANUM>"
});
}
public void testURLs() throws Exception {
Reader reader = null;
String randomTextWithURLs;
try {
reader =
new InputStreamReader(
getClass().getResourceAsStream("random.text.with.urls.txt"), StandardCharsets.UTF_8);
StringBuilder builder = new StringBuilder();
char[] buffer = new char[1024];
int numCharsRead;
while (-1 != (numCharsRead = reader.read(buffer))) {
builder.append(buffer, 0, numCharsRead);
}
randomTextWithURLs = builder.toString();
} finally {
if (null != reader) {
reader.close();
}
}
assertTrue(null != randomTextWithURLs && randomTextWithURLs.length() > 0);
BufferedReader bufferedReader = null;
String[] urls;
try {
List<String> urlList = new ArrayList<>();
bufferedReader =
new BufferedReader(
new InputStreamReader(
getClass().getResourceAsStream("urls.from.random.text.with.urls.txt"),
StandardCharsets.UTF_8));
String line;
while (null != (line = bufferedReader.readLine())) {
line = line.trim();
if (line.length() > 0) {
urlList.add(line);
}
}
urls = urlList.toArray(new String[urlList.size()]);
} finally {
if (null != bufferedReader) {
bufferedReader.close();
}
}
assertTrue(null != urls && urls.length > 0);
BaseTokenStreamTestCase.assertAnalyzesTo(urlAnalyzer, randomTextWithURLs, urls);
}
public void testUnicodeWordBreaks() throws Exception {
WordBreakTestUnicode_12_1_0 wordBreakTest = new WordBreakTestUnicode_12_1_0();
wordBreakTest.test(a);
}
public void testSupplementary() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"𩬅艱鍟䇹愯瀛",
new String[] {"𩬅", "艱", "鍟", "䇹", "愯", "瀛"},
new String[] {
"<IDEOGRAPHIC>",
"<IDEOGRAPHIC>",
"<IDEOGRAPHIC>",
"<IDEOGRAPHIC>",
"<IDEOGRAPHIC>",
"<IDEOGRAPHIC>"
});
}
public void testKorean() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a, "훈민정음", new String[] {"훈민정음"}, new String[] {"<HANGUL>"});
}
public void testJapanese() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"仮名遣い カタカナ",
new String[] {"仮", "名", "遣", "い", "カタカナ"},
new String[] {
"<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<HIRAGANA>", "<KATAKANA>"
});
}
public void testCombiningMarks() throws Exception {
checkOneTerm(a, "ざ", "ざ"); // hiragana
checkOneTerm(a, "ザ", "ザ"); // katakana
checkOneTerm(a, "壹゙", "壹゙"); // ideographic
checkOneTerm(a, "아゙", "아゙"); // hangul
}
/**
* Multiple consecutive chars in \p{Word_Break = MidLetter}, \p{Word_Break = MidNumLet}, and/or
* \p{Word_Break = MidNum} should trigger a token split.
*/
public void testMid() throws Exception {
// ':' is in \p{WB:MidLetter}, which should trigger a split unless there is a Letter char on
// both sides
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A:B", new String[] {"A:B"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A::B", new String[] {"A", "B"});
// '.' is in \p{WB:MidNumLet}, which should trigger a split unless there is a Letter or Numeric
// char on both sides
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1.2", new String[] {"1.2"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A.B", new String[] {"A.B"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1..2", new String[] {"1", "2"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A..B", new String[] {"A", "B"});
// ',' is in \p{WB:MidNum}, which should trigger a split unless there is a Numeric char on both
// sides
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1,2", new String[] {"1,2"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1,,2", new String[] {"1", "2"});
// Mixed consecutive \p{WB:MidLetter} and \p{WB:MidNumLet} should trigger a split
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A.:B", new String[] {"A", "B"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A:.B", new String[] {"A", "B"});
// Mixed consecutive \p{WB:MidNum} and \p{WB:MidNumLet} should trigger a split
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1,.2", new String[] {"1", "2"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1.,2", new String[] {"1", "2"});
// '_' is in \p{WB:ExtendNumLet}
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A:B_A:B", new String[] {"A:B_A:B"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A:B_A::B", new String[] {"A:B_A", "B"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1.2_1.2", new String[] {"1.2_1.2"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A.B_A.B", new String[] {"A.B_A.B"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1.2_1..2", new String[] {"1.2_1", "2"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A.B_A..B", new String[] {"A.B_A", "B"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1,2_1,2", new String[] {"1,2_1,2"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1,2_1,,2", new String[] {"1,2_1", "2"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "C_A.:B", new String[] {"C_A", "B"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "C_A:.B", new String[] {"C_A", "B"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "3_1,.2", new String[] {"3_1", "2"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "3_1.,2", new String[] {"3_1", "2"});
}
/** simple emoji */
public void testEmoji() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"💩 💩💩",
new String[] {"💩", "💩", "💩"},
new String[] {"<EMOJI>", "<EMOJI>", "<EMOJI>"});
}
/** emoji zwj sequence */
public void testEmojiSequence() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a, "👩❤️👩", new String[] {"👩❤️👩"}, new String[] {"<EMOJI>"});
}
/** emoji zwj sequence with fitzpatrick modifier */
public void testEmojiSequenceWithModifier() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a, "👨🏼⚕️", new String[] {"👨🏼⚕️"}, new String[] {"<EMOJI>"});
}
/** regional indicator */
public void testEmojiRegionalIndicator() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a, "🇺🇸🇺🇸", new String[] {"🇺🇸", "🇺🇸"}, new String[] {"<EMOJI>", "<EMOJI>"});
}
/** variation sequence */
public void testEmojiVariationSequence() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a, "#️⃣", new String[] {"#️⃣"}, new String[] {"<EMOJI>"});
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"3️⃣",
new String[] {
"3️⃣",
},
new String[] {"<EMOJI>"});
// text presentation sequences
BaseTokenStreamTestCase.assertAnalyzesTo(a, "#\uFE0E", new String[] {}, new String[] {});
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"3\uFE0E", // \uFE0E is included in \p{WB:Extend}
new String[] {
"3\uFE0E",
},
new String[] {"<NUM>"});
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"\u2B55\uFE0E", // \u2B55 = HEAVY BLACK CIRCLE
new String[] {
"\u2B55",
},
new String[] {"<EMOJI>"});
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"\u2B55\uFE0E\u200D\u2B55\uFE0E",
new String[] {"\u2B55", "\u200D\u2B55"},
new String[] {"<EMOJI>", "<EMOJI>"});
}
public void testEmojiTagSequence() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a, "🏴", new String[] {"🏴"}, new String[] {"<EMOJI>"});
}
public void testEmojiTokenization() throws Exception {
// simple emoji around latin
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"poo💩poo",
new String[] {"poo", "💩", "poo"},
new String[] {"<ALPHANUM>", "<EMOJI>", "<ALPHANUM>"});
// simple emoji around non-latin
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"💩中國💩",
new String[] {"💩", "中", "國", "💩"},
new String[] {"<EMOJI>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<EMOJI>"});
}
public void testUnicodeEmojiTests() throws Exception {
EmojiTokenizationTestUnicode_12_1 emojiTest = new EmojiTokenizationTestUnicode_12_1();
emojiTest.test(a);
}
/** blast some random strings through the analyzer */
public void testRandomStrings() throws Exception {
checkRandomData(random(), a, 200 * RANDOM_MULTIPLIER);
}
/** blast some random large strings through the analyzer */
public void testRandomHugeStrings() throws Exception {
Random random = random();
checkRandomData(random, a, 3 * RANDOM_MULTIPLIER, 8192);
}
public void testExampleURLs() throws Exception {
Stream<String> TLDs;
try (InputStream is = getClass().getResourceAsStream("TLDs.txt")) {
TLDs =
Stream.of(new String(is.readAllBytes(), StandardCharsets.UTF_8).split("\n"))
.filter(line -> !line.trim().startsWith("#") && !line.isBlank());
}
Analyzer analyzer =
new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName) {
return new TokenStreamComponents(new UAX29URLEmailTokenizer(newAttributeFactory()));
}
};
for (String tld : TLDs.collect(Collectors.toList())) {
String URL = "example." + tld;
BaseTokenStreamTestCase.assertAnalyzesTo(
analyzer, URL, new String[] {URL}, new String[] {"<URL>"});
}
}
}
| javanna/lucene | lucene/analysis/common/src/test/org/apache/lucene/analysis/email/TestUAX29URLEmailTokenizer.java |
43,268 | /*
* 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.
*/
package org.apache.lucene.analysis.email;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.BaseTokenStreamTestCase;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.standard.EmojiTokenizationTestUnicode_12_1;
import org.apache.lucene.analysis.standard.WordBreakTestUnicode_12_1_0;
import org.apache.lucene.analysis.tokenattributes.TypeAttribute;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.TestUtil;
public class TestUAX29URLEmailTokenizer extends BaseTokenStreamTestCase {
// LUCENE-5440: extremely slow tokenization of text matching email <local-part> (before the '@')
@Nightly
public void testLongEMAILatomText() throws Exception {
// EMAILatomText = [A-Za-z0-9!#$%&'*+-/=?\^_`{|}~]
char[] emailAtomChars =
"!#$%&'*+,-./0123456789=?ABCDEFGHIJKLMNOPQRSTUVWXYZ^_`abcdefghijklmnopqrstuvwxyz{|}~"
.toCharArray();
StringBuilder builder = new StringBuilder();
int numChars = TestUtil.nextInt(random(), 100 * 1024, 3 * 1024 * 1024);
for (int i = 0; i < numChars; ++i) {
builder.append(emailAtomChars[random().nextInt(emailAtomChars.length)]);
}
int tokenCount = 0;
UAX29URLEmailTokenizer ts = new UAX29URLEmailTokenizer();
String text = builder.toString();
ts.setReader(new StringReader(text));
ts.reset();
while (ts.incrementToken()) {
tokenCount++;
}
ts.end();
ts.close();
assertTrue(tokenCount > 0);
tokenCount = 0;
int newBufferSize = TestUtil.nextInt(random(), 200, 8192);
ts.setMaxTokenLength(newBufferSize);
ts.setReader(new StringReader(text));
ts.reset();
while (ts.incrementToken()) {
tokenCount++;
}
ts.end();
ts.close();
assertTrue(tokenCount > 0);
}
public void testHugeDoc() throws IOException {
StringBuilder sb = new StringBuilder();
char[] whitespace = new char[4094];
Arrays.fill(whitespace, ' ');
sb.append(whitespace);
sb.append("testing 1234");
String input = sb.toString();
UAX29URLEmailTokenizer tokenizer = new UAX29URLEmailTokenizer(newAttributeFactory());
tokenizer.setReader(new StringReader(input));
BaseTokenStreamTestCase.assertTokenStreamContents(tokenizer, new String[] {"testing", "1234"});
}
private Analyzer a, urlAnalyzer, emailAnalyzer;
@Override
public void setUp() throws Exception {
super.setUp();
a =
new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName) {
Tokenizer tokenizer = new UAX29URLEmailTokenizer(newAttributeFactory());
return new TokenStreamComponents(tokenizer);
}
};
urlAnalyzer =
new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName) {
UAX29URLEmailTokenizer tokenizer = new UAX29URLEmailTokenizer(newAttributeFactory());
tokenizer.setMaxTokenLength(
UAX29URLEmailTokenizer.MAX_TOKEN_LENGTH_LIMIT); // Tokenize arbitrary length URLs
TokenFilter filter = new URLFilter(tokenizer);
return new TokenStreamComponents(tokenizer, filter);
}
};
emailAnalyzer =
new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName) {
UAX29URLEmailTokenizer tokenizer = new UAX29URLEmailTokenizer(newAttributeFactory());
TokenFilter filter = new EmailFilter(tokenizer);
return new TokenStreamComponents(tokenizer, filter);
}
};
}
@Override
public void tearDown() throws Exception {
IOUtils.close(a, urlAnalyzer, emailAnalyzer);
super.tearDown();
}
/** Passes through tokens with type "<URL>" and blocks all other types. */
private static class URLFilter extends TokenFilter {
private final TypeAttribute typeAtt = addAttribute(TypeAttribute.class);
public URLFilter(TokenStream in) {
super(in);
}
@Override
public final boolean incrementToken() throws java.io.IOException {
boolean isTokenAvailable = false;
while (input.incrementToken()) {
if (typeAtt.type() == UAX29URLEmailTokenizer.TOKEN_TYPES[UAX29URLEmailTokenizer.URL]) {
isTokenAvailable = true;
break;
}
}
return isTokenAvailable;
}
}
/** Passes through tokens with type "<EMAIL>" and blocks all other types. */
private static class EmailFilter extends TokenFilter {
private final TypeAttribute typeAtt = addAttribute(TypeAttribute.class);
public EmailFilter(TokenStream in) {
super(in);
}
@Override
public final boolean incrementToken() throws java.io.IOException {
boolean isTokenAvailable = false;
while (input.incrementToken()) {
if (typeAtt.type() == UAX29URLEmailTokenizer.TOKEN_TYPES[UAX29URLEmailTokenizer.EMAIL]) {
isTokenAvailable = true;
break;
}
}
return isTokenAvailable;
}
}
public void testArmenian() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"Վիքիպեդիայի 13 միլիոն հոդվածները (4,600` հայերեն վիքիպեդիայում) գրվել են կամավորների կողմից ու համարյա բոլոր հոդվածները կարող է խմբագրել ցանկաց մարդ ով կարող է բացել Վիքիպեդիայի կայքը։",
new String[] {
"Վիքիպեդիայի",
"13",
"միլիոն",
"հոդվածները",
"4,600",
"հայերեն",
"վիքիպեդիայում",
"գրվել",
"են",
"կամավորների",
"կողմից",
"ու",
"համարյա",
"բոլոր",
"հոդվածները",
"կարող",
"է",
"խմբագրել",
"ցանկաց",
"մարդ",
"ով",
"կարող",
"է",
"բացել",
"Վիքիպեդիայի",
"կայքը"
});
}
public void testAmharic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"ዊኪፔድያ የባለ ብዙ ቋንቋ የተሟላ ትክክለኛና ነጻ መዝገበ ዕውቀት (ኢንሳይክሎፒዲያ) ነው። ማንኛውም",
new String[] {
"ዊኪፔድያ",
"የባለ",
"ብዙ",
"ቋንቋ",
"የተሟላ",
"ትክክለኛና",
"ነጻ",
"መዝገበ",
"ዕውቀት",
"ኢንሳይክሎፒዲያ",
"ነው",
"ማንኛውም"
});
}
public void testArabic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"الفيلم الوثائقي الأول عن ويكيبيديا يسمى \"الحقيقة بالأرقام: قصة ويكيبيديا\" (بالإنجليزية: Truth in Numbers: The Wikipedia Story)، سيتم إطلاقه في 2008.",
new String[] {
"الفيلم",
"الوثائقي",
"الأول",
"عن",
"ويكيبيديا",
"يسمى",
"الحقيقة",
"بالأرقام",
"قصة",
"ويكيبيديا",
"بالإنجليزية",
"Truth",
"in",
"Numbers",
"The",
"Wikipedia",
"Story",
"سيتم",
"إطلاقه",
"في",
"2008"
});
}
public void testAramaic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"ܘܝܩܝܦܕܝܐ (ܐܢܓܠܝܐ: Wikipedia) ܗܘ ܐܝܢܣܩܠܘܦܕܝܐ ܚܐܪܬܐ ܕܐܢܛܪܢܛ ܒܠܫܢ̈ܐ ܣܓܝܐ̈ܐ܂ ܫܡܗ ܐܬܐ ܡܢ ܡ̈ܠܬܐ ܕ\"ܘܝܩܝ\" ܘ\"ܐܝܢܣܩܠܘܦܕܝܐ\"܀",
new String[] {
"ܘܝܩܝܦܕܝܐ",
"ܐܢܓܠܝܐ",
"Wikipedia",
"ܗܘ",
"ܐܝܢܣܩܠܘܦܕܝܐ",
"ܚܐܪܬܐ",
"ܕܐܢܛܪܢܛ",
"ܒܠܫܢ̈ܐ",
"ܣܓܝܐ̈ܐ",
"ܫܡܗ",
"ܐܬܐ",
"ܡܢ",
"ܡ̈ܠܬܐ",
"ܕ",
"ܘܝܩܝ",
"ܘ",
"ܐܝܢܣܩܠܘܦܕܝܐ"
});
}
public void testBengali() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"এই বিশ্বকোষ পরিচালনা করে উইকিমিডিয়া ফাউন্ডেশন (একটি অলাভজনক সংস্থা)। উইকিপিডিয়ার শুরু ১৫ জানুয়ারি, ২০০১ সালে। এখন পর্যন্ত ২০০টিরও বেশী ভাষায় উইকিপিডিয়া রয়েছে।",
new String[] {
"এই",
"বিশ্বকোষ",
"পরিচালনা",
"করে",
"উইকিমিডিয়া",
"ফাউন্ডেশন",
"একটি",
"অলাভজনক",
"সংস্থা",
"উইকিপিডিয়ার",
"শুরু",
"১৫",
"জানুয়ারি",
"২০০১",
"সালে",
"এখন",
"পর্যন্ত",
"২০০টিরও",
"বেশী",
"ভাষায়",
"উইকিপিডিয়া",
"রয়েছে"
});
}
public void testFarsi() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"ویکی پدیای انگلیسی در تاریخ ۲۵ دی ۱۳۷۹ به صورت مکملی برای دانشنامهٔ تخصصی نوپدیا نوشته شد.",
new String[] {
"ویکی",
"پدیای",
"انگلیسی",
"در",
"تاریخ",
"۲۵",
"دی",
"۱۳۷۹",
"به",
"صورت",
"مکملی",
"برای",
"دانشنامهٔ",
"تخصصی",
"نوپدیا",
"نوشته",
"شد"
});
}
public void testGreek() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"Γράφεται σε συνεργασία από εθελοντές με το λογισμικό wiki, κάτι που σημαίνει ότι άρθρα μπορεί να προστεθούν ή να αλλάξουν από τον καθένα.",
new String[] {
"Γράφεται",
"σε",
"συνεργασία",
"από",
"εθελοντές",
"με",
"το",
"λογισμικό",
"wiki",
"κάτι",
"που",
"σημαίνει",
"ότι",
"άρθρα",
"μπορεί",
"να",
"προστεθούν",
"ή",
"να",
"αλλάξουν",
"από",
"τον",
"καθένα"
});
}
public void testThai() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"การที่ได้ต้องแสดงว่างานดี. แล้วเธอจะไปไหน? ๑๒๓๔",
new String[] {"การที่ได้ต้องแสดงว่างานดี", "แล้วเธอจะไปไหน", "๑๒๓๔"});
}
public void testLao() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"ສາທາລະນະລັດ ປະຊາທິປະໄຕ ປະຊາຊົນລາວ",
new String[] {"ສາທາລະນະລັດ", "ປະຊາທິປະໄຕ", "ປະຊາຊົນລາວ"});
}
public void testTibetan() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"སྣོན་མཛོད་དང་ལས་འདིས་བོད་ཡིག་མི་ཉམས་གོང་འཕེལ་དུ་གཏོང་བར་ཧ་ཅང་དགེ་མཚན་མཆིས་སོ། །",
new String[] {
"སྣོན", "མཛོད", "དང", "ལས", "འདིས", "བོད", "ཡིག",
"མི", "ཉམས", "གོང", "འཕེལ", "དུ", "གཏོང", "བར",
"ཧ", "ཅང", "དགེ", "མཚན", "མཆིས", "སོ"
});
}
/*
* For chinese, tokenize as char (these can later form bigrams or whatever)
*/
public void testChinese() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a, "我是中国人。 1234 Tests ", new String[] {"我", "是", "中", "国", "人", "1234", "Tests"});
}
public void testEmpty() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "", new String[] {});
BaseTokenStreamTestCase.assertAnalyzesTo(a, ".", new String[] {});
BaseTokenStreamTestCase.assertAnalyzesTo(a, " ", new String[] {});
}
/* test various jira issues this analyzer is related to */
public void testLUCENE1545() throws Exception {
/*
* Standard analyzer does not correctly tokenize combining character U+0364 COMBINING LATIN SMALL LETTRE E.
* The word "moͤchte" is incorrectly tokenized into "mo" "chte", the combining character is lost.
* Expected result is only on token "moͤchte".
*/
BaseTokenStreamTestCase.assertAnalyzesTo(a, "moͤchte", new String[] {"moͤchte"});
}
/* Tests from StandardAnalyzer, just to show behavior is similar */
public void testAlphanumericSA() throws Exception {
// alphanumeric tokens
BaseTokenStreamTestCase.assertAnalyzesTo(a, "B2B", new String[] {"B2B"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "2B", new String[] {"2B"});
}
public void testDelimitersSA() throws Exception {
// other delimiters: "-", "/", ","
BaseTokenStreamTestCase.assertAnalyzesTo(
a, "some-dashed-phrase", new String[] {"some", "dashed", "phrase"});
BaseTokenStreamTestCase.assertAnalyzesTo(
a, "dogs,chase,cats", new String[] {"dogs", "chase", "cats"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ac/dc", new String[] {"ac", "dc"});
}
public void testApostrophesSA() throws Exception {
// internal apostrophes: O'Reilly, you're, O'Reilly's
BaseTokenStreamTestCase.assertAnalyzesTo(a, "O'Reilly", new String[] {"O'Reilly"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "you're", new String[] {"you're"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "she's", new String[] {"she's"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Jim's", new String[] {"Jim's"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "don't", new String[] {"don't"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "O'Reilly's", new String[] {"O'Reilly's"});
}
public void testNumericSA() throws Exception {
// floating point, serial, model numbers, ip addresses, etc.
BaseTokenStreamTestCase.assertAnalyzesTo(a, "21.35", new String[] {"21.35"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "R2D2 C3PO", new String[] {"R2D2", "C3PO"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "216.239.63.104", new String[] {"216.239.63.104"});
}
public void testTextWithNumbersSA() throws Exception {
// numbers
BaseTokenStreamTestCase.assertAnalyzesTo(
a, "David has 5000 bones", new String[] {"David", "has", "5000", "bones"});
}
public void testVariousTextSA() throws Exception {
// various
BaseTokenStreamTestCase.assertAnalyzesTo(
a, "C embedded developers wanted", new String[] {"C", "embedded", "developers", "wanted"});
BaseTokenStreamTestCase.assertAnalyzesTo(
a, "foo bar FOO BAR", new String[] {"foo", "bar", "FOO", "BAR"});
BaseTokenStreamTestCase.assertAnalyzesTo(
a, "foo bar . FOO <> BAR", new String[] {"foo", "bar", "FOO", "BAR"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "\"QUOTED\" word", new String[] {"QUOTED", "word"});
}
public void testKoreanSA() throws Exception {
// Korean words
BaseTokenStreamTestCase.assertAnalyzesTo(a, "안녕하세요 한글입니다", new String[] {"안녕하세요", "한글입니다"});
}
public void testOffsets() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"David has 5000 bones",
new String[] {"David", "has", "5000", "bones"},
new int[] {0, 6, 10, 15},
new int[] {5, 9, 14, 20});
}
public void testTypes() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"David has 5000 bones",
new String[] {"David", "has", "5000", "bones"},
new String[] {"<ALPHANUM>", "<ALPHANUM>", "<NUM>", "<ALPHANUM>"});
}
public void testWikiURLs() throws Exception {
Reader reader = null;
String luceneResourcesWikiPage;
try {
reader =
new InputStreamReader(
getClass().getResourceAsStream("LuceneResourcesWikiPage.html"),
StandardCharsets.UTF_8);
StringBuilder builder = new StringBuilder();
char[] buffer = new char[1024];
int numCharsRead;
while (-1 != (numCharsRead = reader.read(buffer))) {
builder.append(buffer, 0, numCharsRead);
}
luceneResourcesWikiPage = builder.toString();
} finally {
if (null != reader) {
reader.close();
}
}
assertTrue(null != luceneResourcesWikiPage && luceneResourcesWikiPage.length() > 0);
BufferedReader bufferedReader = null;
String[] urls;
try {
List<String> urlList = new ArrayList<>();
bufferedReader =
new BufferedReader(
new InputStreamReader(
getClass().getResourceAsStream("LuceneResourcesWikiPageURLs.txt"),
StandardCharsets.UTF_8));
String line;
while (null != (line = bufferedReader.readLine())) {
line = line.trim();
if (line.length() > 0) {
urlList.add(line);
}
}
urls = urlList.toArray(new String[urlList.size()]);
} finally {
if (null != bufferedReader) {
bufferedReader.close();
}
}
assertTrue(null != urls && urls.length > 0);
BaseTokenStreamTestCase.assertAnalyzesTo(urlAnalyzer, luceneResourcesWikiPage, urls);
}
public void testEmails() throws Exception {
Reader reader = null;
String randomTextWithEmails;
try {
reader =
new InputStreamReader(
getClass().getResourceAsStream("random.text.with.email.addresses.txt"),
StandardCharsets.UTF_8);
StringBuilder builder = new StringBuilder();
char[] buffer = new char[1024];
int numCharsRead;
while (-1 != (numCharsRead = reader.read(buffer))) {
builder.append(buffer, 0, numCharsRead);
}
randomTextWithEmails = builder.toString();
} finally {
if (null != reader) {
reader.close();
}
}
assertTrue(null != randomTextWithEmails && randomTextWithEmails.length() > 0);
BufferedReader bufferedReader = null;
String[] emails;
try {
List<String> emailList = new ArrayList<>();
bufferedReader =
new BufferedReader(
new InputStreamReader(
getClass()
.getResourceAsStream(
"email.addresses.from.random.text.with.email.addresses.txt"),
StandardCharsets.UTF_8));
String line;
while (null != (line = bufferedReader.readLine())) {
line = line.trim();
if (line.length() > 0) {
emailList.add(line);
}
}
emails = emailList.toArray(new String[emailList.size()]);
} finally {
if (null != bufferedReader) {
bufferedReader.close();
}
}
assertTrue(null != emails && emails.length > 0);
BaseTokenStreamTestCase.assertAnalyzesTo(emailAnalyzer, randomTextWithEmails, emails);
}
public void testMailtoSchemeEmails() throws Exception {
// See LUCENE-3880
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"mailto:[email protected]",
new String[] {"mailto", "[email protected]"},
new String[] {"<ALPHANUM>", "<EMAIL>"});
// TODO: Support full mailto: scheme URIs. See RFC 6068: http://tools.ietf.org/html/rfc6068
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"mailto:[email protected],[email protected][email protected]"
+ "&subject=Subjectivity&body=Corpusivity%20or%20something%20like%20that",
new String[] {
"mailto",
"[email protected]",
// TODO: recognize ',' address delimiter. Also, see examples of ';' delimiter use at:
// http://www.mailto.co.uk/
",[email protected]",
"[email protected]", // TODO: split field keys/values
"subject",
"Subjectivity",
"body",
"Corpusivity",
"20or",
"20something",
"20like",
"20that"
}, // TODO: Hex decoding + re-tokenization
new String[] {
"<ALPHANUM>",
"<EMAIL>",
"<EMAIL>",
"<EMAIL>",
"<ALPHANUM>",
"<ALPHANUM>",
"<ALPHANUM>",
"<ALPHANUM>",
"<ALPHANUM>",
"<ALPHANUM>",
"<ALPHANUM>",
"<ALPHANUM>"
});
}
public void testURLs() throws Exception {
Reader reader = null;
String randomTextWithURLs;
try {
reader =
new InputStreamReader(
getClass().getResourceAsStream("random.text.with.urls.txt"), StandardCharsets.UTF_8);
StringBuilder builder = new StringBuilder();
char[] buffer = new char[1024];
int numCharsRead;
while (-1 != (numCharsRead = reader.read(buffer))) {
builder.append(buffer, 0, numCharsRead);
}
randomTextWithURLs = builder.toString();
} finally {
if (null != reader) {
reader.close();
}
}
assertTrue(null != randomTextWithURLs && randomTextWithURLs.length() > 0);
BufferedReader bufferedReader = null;
String[] urls;
try {
List<String> urlList = new ArrayList<>();
bufferedReader =
new BufferedReader(
new InputStreamReader(
getClass().getResourceAsStream("urls.from.random.text.with.urls.txt"),
StandardCharsets.UTF_8));
String line;
while (null != (line = bufferedReader.readLine())) {
line = line.trim();
if (line.length() > 0) {
urlList.add(line);
}
}
urls = urlList.toArray(new String[urlList.size()]);
} finally {
if (null != bufferedReader) {
bufferedReader.close();
}
}
assertTrue(null != urls && urls.length > 0);
BaseTokenStreamTestCase.assertAnalyzesTo(urlAnalyzer, randomTextWithURLs, urls);
}
public void testUnicodeWordBreaks() throws Exception {
WordBreakTestUnicode_12_1_0 wordBreakTest = new WordBreakTestUnicode_12_1_0();
wordBreakTest.test(a);
}
public void testSupplementary() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"𩬅艱鍟䇹愯瀛",
new String[] {"𩬅", "艱", "鍟", "䇹", "愯", "瀛"},
new String[] {
"<IDEOGRAPHIC>",
"<IDEOGRAPHIC>",
"<IDEOGRAPHIC>",
"<IDEOGRAPHIC>",
"<IDEOGRAPHIC>",
"<IDEOGRAPHIC>"
});
}
public void testKorean() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a, "훈민정음", new String[] {"훈민정음"}, new String[] {"<HANGUL>"});
}
public void testJapanese() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"仮名遣い カタカナ",
new String[] {"仮", "名", "遣", "い", "カタカナ"},
new String[] {
"<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<HIRAGANA>", "<KATAKANA>"
});
}
public void testCombiningMarks() throws Exception {
checkOneTerm(a, "ざ", "ざ"); // hiragana
checkOneTerm(a, "ザ", "ザ"); // katakana
checkOneTerm(a, "壹゙", "壹゙"); // ideographic
checkOneTerm(a, "아゙", "아゙"); // hangul
}
/**
* Multiple consecutive chars in \p{Word_Break = MidLetter}, \p{Word_Break = MidNumLet}, and/or
* \p{Word_Break = MidNum} should trigger a token split.
*/
public void testMid() throws Exception {
// ':' is in \p{WB:MidLetter}, which should trigger a split unless there is a Letter char on
// both sides
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A:B", new String[] {"A:B"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A::B", new String[] {"A", "B"});
// '.' is in \p{WB:MidNumLet}, which should trigger a split unless there is a Letter or Numeric
// char on both sides
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1.2", new String[] {"1.2"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A.B", new String[] {"A.B"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1..2", new String[] {"1", "2"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A..B", new String[] {"A", "B"});
// ',' is in \p{WB:MidNum}, which should trigger a split unless there is a Numeric char on both
// sides
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1,2", new String[] {"1,2"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1,,2", new String[] {"1", "2"});
// Mixed consecutive \p{WB:MidLetter} and \p{WB:MidNumLet} should trigger a split
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A.:B", new String[] {"A", "B"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A:.B", new String[] {"A", "B"});
// Mixed consecutive \p{WB:MidNum} and \p{WB:MidNumLet} should trigger a split
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1,.2", new String[] {"1", "2"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1.,2", new String[] {"1", "2"});
// '_' is in \p{WB:ExtendNumLet}
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A:B_A:B", new String[] {"A:B_A:B"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A:B_A::B", new String[] {"A:B_A", "B"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1.2_1.2", new String[] {"1.2_1.2"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A.B_A.B", new String[] {"A.B_A.B"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1.2_1..2", new String[] {"1.2_1", "2"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A.B_A..B", new String[] {"A.B_A", "B"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1,2_1,2", new String[] {"1,2_1,2"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1,2_1,,2", new String[] {"1,2_1", "2"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "C_A.:B", new String[] {"C_A", "B"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "C_A:.B", new String[] {"C_A", "B"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "3_1,.2", new String[] {"3_1", "2"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "3_1.,2", new String[] {"3_1", "2"});
}
/** simple emoji */
public void testEmoji() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"💩 💩💩",
new String[] {"💩", "💩", "💩"},
new String[] {"<EMOJI>", "<EMOJI>", "<EMOJI>"});
}
/** emoji zwj sequence */
public void testEmojiSequence() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a, "👩❤️👩", new String[] {"👩❤️👩"}, new String[] {"<EMOJI>"});
}
/** emoji zwj sequence with fitzpatrick modifier */
public void testEmojiSequenceWithModifier() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a, "👨🏼⚕️", new String[] {"👨🏼⚕️"}, new String[] {"<EMOJI>"});
}
/** regional indicator */
public void testEmojiRegionalIndicator() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a, "🇺🇸🇺🇸", new String[] {"🇺🇸", "🇺🇸"}, new String[] {"<EMOJI>", "<EMOJI>"});
}
/** variation sequence */
public void testEmojiVariationSequence() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a, "#️⃣", new String[] {"#️⃣"}, new String[] {"<EMOJI>"});
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"3️⃣",
new String[] {
"3️⃣",
},
new String[] {"<EMOJI>"});
// text presentation sequences
BaseTokenStreamTestCase.assertAnalyzesTo(a, "#\uFE0E", new String[] {}, new String[] {});
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"3\uFE0E", // \uFE0E is included in \p{WB:Extend}
new String[] {
"3\uFE0E",
},
new String[] {"<NUM>"});
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"\u2B55\uFE0E", // \u2B55 = HEAVY BLACK CIRCLE
new String[] {
"\u2B55",
},
new String[] {"<EMOJI>"});
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"\u2B55\uFE0E\u200D\u2B55\uFE0E",
new String[] {"\u2B55", "\u200D\u2B55"},
new String[] {"<EMOJI>", "<EMOJI>"});
}
public void testEmojiTagSequence() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(
a, "🏴", new String[] {"🏴"}, new String[] {"<EMOJI>"});
}
public void testEmojiTokenization() throws Exception {
// simple emoji around latin
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"poo💩poo",
new String[] {"poo", "💩", "poo"},
new String[] {"<ALPHANUM>", "<EMOJI>", "<ALPHANUM>"});
// simple emoji around non-latin
BaseTokenStreamTestCase.assertAnalyzesTo(
a,
"💩中國💩",
new String[] {"💩", "中", "國", "💩"},
new String[] {"<EMOJI>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<EMOJI>"});
}
public void testUnicodeEmojiTests() throws Exception {
EmojiTokenizationTestUnicode_12_1 emojiTest = new EmojiTokenizationTestUnicode_12_1();
emojiTest.test(a);
}
/** blast some random strings through the analyzer */
public void testRandomStrings() throws Exception {
checkRandomData(random(), a, 200 * RANDOM_MULTIPLIER);
}
/** blast some random large strings through the analyzer */
public void testRandomHugeStrings() throws Exception {
Random random = random();
checkRandomData(random, a, 3 * RANDOM_MULTIPLIER, 8192);
}
public void testExampleURLs() throws Exception {
Stream<String> TLDs;
try (InputStream is = getClass().getResourceAsStream("TLDs.txt")) {
TLDs =
Stream.of(new String(is.readAllBytes(), StandardCharsets.UTF_8).split("\n"))
.filter(line -> !line.trim().startsWith("#") && !line.isBlank());
}
Analyzer analyzer =
new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName) {
return new TokenStreamComponents(new UAX29URLEmailTokenizer(newAttributeFactory()));
}
};
for (String tld : TLDs.collect(Collectors.toList())) {
String URL = "example." + tld;
BaseTokenStreamTestCase.assertAnalyzesTo(
analyzer, URL, new String[] {URL}, new String[] {"<URL>"});
}
}
}
| umeshdangat/lucene | lucene/analysis/common/src/test/org/apache/lucene/analysis/email/TestUAX29URLEmailTokenizer.java |
43,271 | /*
* 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.
*/
package org.apache.lucene.analysis.standard;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.BaseTokenStreamTestCase;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.standard.UAX29URLEmailTokenizer;
import org.apache.lucene.analysis.standard.WordBreakTestUnicode_6_3_0;
import org.apache.lucene.analysis.tokenattributes.TypeAttribute;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.TestUtil;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
public class TestUAX29URLEmailTokenizer extends BaseTokenStreamTestCase {
// LUCENE-5440: extremely slow tokenization of text matching email <local-part> (before the '@')
@Slow
public void testLongEMAILatomText() throws Exception {
// EMAILatomText = [A-Za-z0-9!#$%&'*+-/=?\^_`{|}~]
char[] emailAtomChars
= "!#$%&'*+,-./0123456789=?ABCDEFGHIJKLMNOPQRSTUVWXYZ^_`abcdefghijklmnopqrstuvwxyz{|}~".toCharArray();
StringBuilder builder = new StringBuilder();
int numChars = TestUtil.nextInt(random(), 100 * 1024, 3 * 1024 * 1024);
for (int i = 0 ; i < numChars ; ++i) {
builder.append(emailAtomChars[random().nextInt(emailAtomChars.length)]);
}
int tokenCount = 0;
UAX29URLEmailTokenizer ts = new UAX29URLEmailTokenizer();
String text = builder.toString();
ts.setReader(new StringReader(text));
ts.reset();
while (ts.incrementToken()) {
tokenCount++;
}
ts.end();
ts.close();
assertTrue(tokenCount > 0);
tokenCount = 0;
int newBufferSize = TestUtil.nextInt(random(), 200, 8192);
ts.setMaxTokenLength(newBufferSize);
ts.setReader(new StringReader(text));
ts.reset();
while (ts.incrementToken()) {
tokenCount++;
}
ts.end();
ts.close();
assertTrue(tokenCount > 0);
}
public void testHugeDoc() throws IOException {
StringBuilder sb = new StringBuilder();
char whitespace[] = new char[4094];
Arrays.fill(whitespace, ' ');
sb.append(whitespace);
sb.append("testing 1234");
String input = sb.toString();
UAX29URLEmailTokenizer tokenizer = new UAX29URLEmailTokenizer(newAttributeFactory());
tokenizer.setReader(new StringReader(input));
BaseTokenStreamTestCase.assertTokenStreamContents(tokenizer, new String[] { "testing", "1234" });
}
private Analyzer a, urlAnalyzer, emailAnalyzer;
@Override
public void setUp() throws Exception {
super.setUp();
a = new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName) {
Tokenizer tokenizer = new UAX29URLEmailTokenizer(newAttributeFactory());
return new TokenStreamComponents(tokenizer);
}
};
urlAnalyzer = new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName) {
UAX29URLEmailTokenizer tokenizer = new UAX29URLEmailTokenizer(newAttributeFactory());
tokenizer.setMaxTokenLength(UAX29URLEmailTokenizer.MAX_TOKEN_LENGTH_LIMIT); // Tokenize arbitrary length URLs
TokenFilter filter = new URLFilter(tokenizer);
return new TokenStreamComponents(tokenizer, filter);
}
};
emailAnalyzer = new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName) {
UAX29URLEmailTokenizer tokenizer = new UAX29URLEmailTokenizer(newAttributeFactory());
TokenFilter filter = new EmailFilter(tokenizer);
return new TokenStreamComponents(tokenizer, filter);
}
};
}
@Override
public void tearDown() throws Exception {
IOUtils.close(a, urlAnalyzer, emailAnalyzer);
super.tearDown();
}
/** Passes through tokens with type "<URL>" and blocks all other types. */
private static class URLFilter extends TokenFilter {
private final TypeAttribute typeAtt = addAttribute(TypeAttribute.class);
public URLFilter(TokenStream in) {
super(in);
}
@Override
public final boolean incrementToken() throws java.io.IOException {
boolean isTokenAvailable = false;
while (input.incrementToken()) {
if (typeAtt.type() == UAX29URLEmailTokenizer.TOKEN_TYPES[UAX29URLEmailTokenizer.URL]) {
isTokenAvailable = true;
break;
}
}
return isTokenAvailable;
}
}
/** Passes through tokens with type "<EMAIL>" and blocks all other types. */
private static class EmailFilter extends TokenFilter {
private final TypeAttribute typeAtt = addAttribute(TypeAttribute.class);
public EmailFilter(TokenStream in) {
super(in);
}
@Override
public final boolean incrementToken() throws java.io.IOException {
boolean isTokenAvailable = false;
while (input.incrementToken()) {
if (typeAtt.type() == UAX29URLEmailTokenizer.TOKEN_TYPES[UAX29URLEmailTokenizer.EMAIL]) {
isTokenAvailable = true;
break;
}
}
return isTokenAvailable;
}
}
public void testArmenian() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Վիքիպեդիայի 13 միլիոն հոդվածները (4,600` հայերեն վիքիպեդիայում) գրվել են կամավորների կողմից ու համարյա բոլոր հոդվածները կարող է խմբագրել ցանկաց մարդ ով կարող է բացել Վիքիպեդիայի կայքը։",
new String[] { "Վիքիպեդիայի", "13", "միլիոն", "հոդվածները", "4,600", "հայերեն", "վիքիպեդիայում", "գրվել", "են", "կամավորների", "կողմից",
"ու", "համարյա", "բոլոր", "հոդվածները", "կարող", "է", "խմբագրել", "ցանկաց", "մարդ", "ով", "կարող", "է", "բացել", "Վիքիպեդիայի", "կայքը" } );
}
public void testAmharic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ዊኪፔድያ የባለ ብዙ ቋንቋ የተሟላ ትክክለኛና ነጻ መዝገበ ዕውቀት (ኢንሳይክሎፒዲያ) ነው። ማንኛውም",
new String[] { "ዊኪፔድያ", "የባለ", "ብዙ", "ቋንቋ", "የተሟላ", "ትክክለኛና", "ነጻ", "መዝገበ", "ዕውቀት", "ኢንሳይክሎፒዲያ", "ነው", "ማንኛውም" } );
}
public void testArabic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "الفيلم الوثائقي الأول عن ويكيبيديا يسمى \"الحقيقة بالأرقام: قصة ويكيبيديا\" (بالإنجليزية: Truth in Numbers: The Wikipedia Story)، سيتم إطلاقه في 2008.",
new String[] { "الفيلم", "الوثائقي", "الأول", "عن", "ويكيبيديا", "يسمى", "الحقيقة", "بالأرقام", "قصة", "ويكيبيديا",
"بالإنجليزية", "Truth", "in", "Numbers", "The", "Wikipedia", "Story", "سيتم", "إطلاقه", "في", "2008" } );
}
public void testAramaic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ܘܝܩܝܦܕܝܐ (ܐܢܓܠܝܐ: Wikipedia) ܗܘ ܐܝܢܣܩܠܘܦܕܝܐ ܚܐܪܬܐ ܕܐܢܛܪܢܛ ܒܠܫܢ̈ܐ ܣܓܝܐ̈ܐ܂ ܫܡܗ ܐܬܐ ܡܢ ܡ̈ܠܬܐ ܕ\"ܘܝܩܝ\" ܘ\"ܐܝܢܣܩܠܘܦܕܝܐ\"܀",
new String[] { "ܘܝܩܝܦܕܝܐ", "ܐܢܓܠܝܐ", "Wikipedia", "ܗܘ", "ܐܝܢܣܩܠܘܦܕܝܐ", "ܚܐܪܬܐ", "ܕܐܢܛܪܢܛ", "ܒܠܫܢ̈ܐ", "ܣܓܝܐ̈ܐ", "ܫܡܗ",
"ܐܬܐ", "ܡܢ", "ܡ̈ܠܬܐ", "ܕ", "ܘܝܩܝ", "ܘ", "ܐܝܢܣܩܠܘܦܕܝܐ"});
}
public void testBengali() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "এই বিশ্বকোষ পরিচালনা করে উইকিমিডিয়া ফাউন্ডেশন (একটি অলাভজনক সংস্থা)। উইকিপিডিয়ার শুরু ১৫ জানুয়ারি, ২০০১ সালে। এখন পর্যন্ত ২০০টিরও বেশী ভাষায় উইকিপিডিয়া রয়েছে।",
new String[] { "এই", "বিশ্বকোষ", "পরিচালনা", "করে", "উইকিমিডিয়া", "ফাউন্ডেশন", "একটি", "অলাভজনক", "সংস্থা", "উইকিপিডিয়ার",
"শুরু", "১৫", "জানুয়ারি", "২০০১", "সালে", "এখন", "পর্যন্ত", "২০০টিরও", "বেশী", "ভাষায়", "উইকিপিডিয়া", "রয়েছে" });
}
public void testFarsi() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ویکی پدیای انگلیسی در تاریخ ۲۵ دی ۱۳۷۹ به صورت مکملی برای دانشنامهٔ تخصصی نوپدیا نوشته شد.",
new String[] { "ویکی", "پدیای", "انگلیسی", "در", "تاریخ", "۲۵", "دی", "۱۳۷۹", "به", "صورت", "مکملی",
"برای", "دانشنامهٔ", "تخصصی", "نوپدیا", "نوشته", "شد" });
}
public void testGreek() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Γράφεται σε συνεργασία από εθελοντές με το λογισμικό wiki, κάτι που σημαίνει ότι άρθρα μπορεί να προστεθούν ή να αλλάξουν από τον καθένα.",
new String[] { "Γράφεται", "σε", "συνεργασία", "από", "εθελοντές", "με", "το", "λογισμικό", "wiki", "κάτι", "που",
"σημαίνει", "ότι", "άρθρα", "μπορεί", "να", "προστεθούν", "ή", "να", "αλλάξουν", "από", "τον", "καθένα" });
}
public void testThai() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "การที่ได้ต้องแสดงว่างานดี. แล้วเธอจะไปไหน? ๑๒๓๔",
new String[] { "การที่ได้ต้องแสดงว่างานดี", "แล้วเธอจะไปไหน", "๑๒๓๔" });
}
public void testLao() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ສາທາລະນະລັດ ປະຊາທິປະໄຕ ປະຊາຊົນລາວ",
new String[] { "ສາທາລະນະລັດ", "ປະຊາທິປະໄຕ", "ປະຊາຊົນລາວ" });
}
public void testTibetan() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "སྣོན་མཛོད་དང་ལས་འདིས་བོད་ཡིག་མི་ཉམས་གོང་འཕེལ་དུ་གཏོང་བར་ཧ་ཅང་དགེ་མཚན་མཆིས་སོ། །",
new String[] { "སྣོན", "མཛོད", "དང", "ལས", "འདིས", "བོད", "ཡིག",
"མི", "ཉམས", "གོང", "འཕེལ", "དུ", "གཏོང", "བར",
"ཧ", "ཅང", "དགེ", "མཚན", "མཆིས", "སོ" });
}
/*
* For chinese, tokenize as char (these can later form bigrams or whatever)
*/
public void testChinese() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "我是中国人。 1234 Tests ",
new String[] { "我", "是", "中", "国", "人", "1234", "Tests"});
}
public void testEmpty() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "", new String[] {});
BaseTokenStreamTestCase.assertAnalyzesTo(a, ".", new String[] {});
BaseTokenStreamTestCase.assertAnalyzesTo(a, " ", new String[] {});
}
/* test various jira issues this analyzer is related to */
public void testLUCENE1545() throws Exception {
/*
* Standard analyzer does not correctly tokenize combining character U+0364 COMBINING LATIN SMALL LETTRE E.
* The word "moͤchte" is incorrectly tokenized into "mo" "chte", the combining character is lost.
* Expected result is only on token "moͤchte".
*/
BaseTokenStreamTestCase.assertAnalyzesTo(a, "moͤchte", new String[] { "moͤchte" });
}
/* Tests from StandardAnalyzer, just to show behavior is similar */
public void testAlphanumericSA() throws Exception {
// alphanumeric tokens
BaseTokenStreamTestCase.assertAnalyzesTo(a, "B2B", new String[]{"B2B"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "2B", new String[]{"2B"});
}
public void testDelimitersSA() throws Exception {
// other delimiters: "-", "/", ","
BaseTokenStreamTestCase.assertAnalyzesTo(a, "some-dashed-phrase", new String[]{"some", "dashed", "phrase"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "dogs,chase,cats", new String[]{"dogs", "chase", "cats"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ac/dc", new String[]{"ac", "dc"});
}
public void testApostrophesSA() throws Exception {
// internal apostrophes: O'Reilly, you're, O'Reilly's
BaseTokenStreamTestCase.assertAnalyzesTo(a, "O'Reilly", new String[]{"O'Reilly"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "you're", new String[]{"you're"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "she's", new String[]{"she's"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Jim's", new String[]{"Jim's"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "don't", new String[]{"don't"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "O'Reilly's", new String[]{"O'Reilly's"});
}
public void testNumericSA() throws Exception {
// floating point, serial, model numbers, ip addresses, etc.
BaseTokenStreamTestCase.assertAnalyzesTo(a, "21.35", new String[]{"21.35"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "R2D2 C3PO", new String[]{"R2D2", "C3PO"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "216.239.63.104", new String[]{"216.239.63.104"});
}
public void testTextWithNumbersSA() throws Exception {
// numbers
BaseTokenStreamTestCase.assertAnalyzesTo(a, "David has 5000 bones", new String[]{"David", "has", "5000", "bones"});
}
public void testVariousTextSA() throws Exception {
// various
BaseTokenStreamTestCase.assertAnalyzesTo(a, "C embedded developers wanted", new String[]{"C", "embedded", "developers", "wanted"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "foo bar FOO BAR", new String[]{"foo", "bar", "FOO", "BAR"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "foo bar . FOO <> BAR", new String[]{"foo", "bar", "FOO", "BAR"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "\"QUOTED\" word", new String[]{"QUOTED", "word"});
}
public void testKoreanSA() throws Exception {
// Korean words
BaseTokenStreamTestCase.assertAnalyzesTo(a, "안녕하세요 한글입니다", new String[]{"안녕하세요", "한글입니다"});
}
public void testOffsets() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "David has 5000 bones",
new String[] {"David", "has", "5000", "bones"},
new int[] {0, 6, 10, 15},
new int[] {5, 9, 14, 20});
}
public void testTypes() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "David has 5000 bones",
new String[] {"David", "has", "5000", "bones"},
new String[] { "<ALPHANUM>", "<ALPHANUM>", "<NUM>", "<ALPHANUM>" });
}
public void testWikiURLs() throws Exception {
Reader reader = null;
String luceneResourcesWikiPage;
try {
reader = new InputStreamReader(getClass().getResourceAsStream
("LuceneResourcesWikiPage.html"), StandardCharsets.UTF_8);
StringBuilder builder = new StringBuilder();
char[] buffer = new char[1024];
int numCharsRead;
while (-1 != (numCharsRead = reader.read(buffer))) {
builder.append(buffer, 0, numCharsRead);
}
luceneResourcesWikiPage = builder.toString();
} finally {
if (null != reader) {
reader.close();
}
}
assertTrue(null != luceneResourcesWikiPage
&& luceneResourcesWikiPage.length() > 0);
BufferedReader bufferedReader = null;
String[] urls;
try {
List<String> urlList = new ArrayList<>();
bufferedReader = new BufferedReader(new InputStreamReader
(getClass().getResourceAsStream("LuceneResourcesWikiPageURLs.txt"), StandardCharsets.UTF_8));
String line;
while (null != (line = bufferedReader.readLine())) {
line = line.trim();
if (line.length() > 0) {
urlList.add(line);
}
}
urls = urlList.toArray(new String[urlList.size()]);
} finally {
if (null != bufferedReader) {
bufferedReader.close();
}
}
assertTrue(null != urls && urls.length > 0);
BaseTokenStreamTestCase.assertAnalyzesTo
(urlAnalyzer, luceneResourcesWikiPage, urls);
}
public void testEmails() throws Exception {
Reader reader = null;
String randomTextWithEmails;
try {
reader = new InputStreamReader(getClass().getResourceAsStream
("random.text.with.email.addresses.txt"), StandardCharsets.UTF_8);
StringBuilder builder = new StringBuilder();
char[] buffer = new char[1024];
int numCharsRead;
while (-1 != (numCharsRead = reader.read(buffer))) {
builder.append(buffer, 0, numCharsRead);
}
randomTextWithEmails = builder.toString();
} finally {
if (null != reader) {
reader.close();
}
}
assertTrue(null != randomTextWithEmails
&& randomTextWithEmails.length() > 0);
BufferedReader bufferedReader = null;
String[] emails;
try {
List<String> emailList = new ArrayList<>();
bufferedReader = new BufferedReader(new InputStreamReader
(getClass().getResourceAsStream
("email.addresses.from.random.text.with.email.addresses.txt"), StandardCharsets.UTF_8));
String line;
while (null != (line = bufferedReader.readLine())) {
line = line.trim();
if (line.length() > 0) {
emailList.add(line);
}
}
emails = emailList.toArray(new String[emailList.size()]);
} finally {
if (null != bufferedReader) {
bufferedReader.close();
}
}
assertTrue(null != emails && emails.length > 0);
BaseTokenStreamTestCase.assertAnalyzesTo
(emailAnalyzer, randomTextWithEmails, emails);
}
public void testMailtoSchemeEmails () throws Exception {
// See LUCENE-3880
BaseTokenStreamTestCase.assertAnalyzesTo(a, "mailto:[email protected]",
new String[] {"mailto", "[email protected]"},
new String[] { "<ALPHANUM>", "<EMAIL>" });
// TODO: Support full mailto: scheme URIs. See RFC 6068: http://tools.ietf.org/html/rfc6068
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "mailto:[email protected],[email protected][email protected]"
+ "&subject=Subjectivity&body=Corpusivity%20or%20something%20like%20that",
new String[] { "mailto",
"[email protected]",
// TODO: recognize ',' address delimiter. Also, see examples of ';' delimiter use at: http://www.mailto.co.uk/
",[email protected]",
"[email protected]", // TODO: split field keys/values
"subject", "Subjectivity",
"body", "Corpusivity", "20or", "20something","20like", "20that" }, // TODO: Hex decoding + re-tokenization
new String[] { "<ALPHANUM>",
"<EMAIL>",
"<EMAIL>",
"<EMAIL>",
"<ALPHANUM>", "<ALPHANUM>",
"<ALPHANUM>", "<ALPHANUM>", "<ALPHANUM>", "<ALPHANUM>", "<ALPHANUM>", "<ALPHANUM>" });
}
public void testURLs() throws Exception {
Reader reader = null;
String randomTextWithURLs;
try {
reader = new InputStreamReader(getClass().getResourceAsStream
("random.text.with.urls.txt"), StandardCharsets.UTF_8);
StringBuilder builder = new StringBuilder();
char[] buffer = new char[1024];
int numCharsRead;
while (-1 != (numCharsRead = reader.read(buffer))) {
builder.append(buffer, 0, numCharsRead);
}
randomTextWithURLs = builder.toString();
} finally {
if (null != reader) {
reader.close();
}
}
assertTrue(null != randomTextWithURLs
&& randomTextWithURLs.length() > 0);
BufferedReader bufferedReader = null;
String[] urls;
try {
List<String> urlList = new ArrayList<>();
bufferedReader = new BufferedReader(new InputStreamReader
(getClass().getResourceAsStream
("urls.from.random.text.with.urls.txt"), StandardCharsets.UTF_8));
String line;
while (null != (line = bufferedReader.readLine())) {
line = line.trim();
if (line.length() > 0) {
urlList.add(line);
}
}
urls = urlList.toArray(new String[urlList.size()]);
} finally {
if (null != bufferedReader) {
bufferedReader.close();
}
}
assertTrue(null != urls && urls.length > 0);
BaseTokenStreamTestCase.assertAnalyzesTo
(urlAnalyzer, randomTextWithURLs, urls);
}
public void testUnicodeWordBreaks() throws Exception {
WordBreakTestUnicode_6_3_0 wordBreakTest = new WordBreakTestUnicode_6_3_0();
wordBreakTest.test(a);
}
public void testSupplementary() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "𩬅艱鍟䇹愯瀛",
new String[] {"𩬅", "艱", "鍟", "䇹", "愯", "瀛"},
new String[] { "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>" });
}
public void testKorean() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "훈민정음",
new String[] { "훈민정음" },
new String[] { "<HANGUL>" });
}
public void testJapanese() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "仮名遣い カタカナ",
new String[] { "仮", "名", "遣", "い", "カタカナ" },
new String[] { "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<HIRAGANA>", "<KATAKANA>" });
}
public void testCombiningMarks() throws Exception {
checkOneTerm(a, "ざ", "ざ"); // hiragana
checkOneTerm(a, "ザ", "ザ"); // katakana
checkOneTerm(a, "壹゙", "壹゙"); // ideographic
checkOneTerm(a, "아゙", "아゙"); // hangul
}
/**
* Multiple consecutive chars in \p{Word_Break = MidLetter},
* \p{Word_Break = MidNumLet}, and/or \p{Word_Break = MidNum}
* should trigger a token split.
*/
public void testMid() throws Exception {
// ':' is in \p{WB:MidLetter}, which should trigger a split unless there is a Letter char on both sides
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A:B", new String[] { "A:B" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A::B", new String[] { "A", "B" });
// '.' is in \p{WB:MidNumLet}, which should trigger a split unless there is a Letter or Numeric char on both sides
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1.2", new String[] { "1.2" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A.B", new String[] { "A.B" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1..2", new String[] { "1", "2" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A..B", new String[] { "A", "B" });
// ',' is in \p{WB:MidNum}, which should trigger a split unless there is a Numeric char on both sides
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1,2", new String[] { "1,2" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1,,2", new String[] { "1", "2" });
// Mixed consecutive \p{WB:MidLetter} and \p{WB:MidNumLet} should trigger a split
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A.:B", new String[] { "A", "B" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A:.B", new String[] { "A", "B" });
// Mixed consecutive \p{WB:MidNum} and \p{WB:MidNumLet} should trigger a split
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1,.2", new String[] { "1", "2" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1.,2", new String[] { "1", "2" });
// '_' is in \p{WB:ExtendNumLet}
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A:B_A:B", new String[] { "A:B_A:B" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A:B_A::B", new String[] { "A:B_A", "B" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1.2_1.2", new String[] { "1.2_1.2" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A.B_A.B", new String[] { "A.B_A.B" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1.2_1..2", new String[] { "1.2_1", "2" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A.B_A..B", new String[] { "A.B_A", "B" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1,2_1,2", new String[] { "1,2_1,2" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1,2_1,,2", new String[] { "1,2_1", "2" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "C_A.:B", new String[] { "C_A", "B" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "C_A:.B", new String[] { "C_A", "B" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "3_1,.2", new String[] { "3_1", "2" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "3_1.,2", new String[] { "3_1", "2" });
}
/** blast some random strings through the analyzer */
public void testRandomStrings() throws Exception {
checkRandomData(random(), a, 1000*RANDOM_MULTIPLIER);
}
/** blast some random large strings through the analyzer */
public void testRandomHugeStrings() throws Exception {
Random random = random();
checkRandomData(random, a, 100*RANDOM_MULTIPLIER, 8192);
}
}
| janhoy/lucene-solr | lucene/analysis/common/src/test/org/apache/lucene/analysis/standard/TestUAX29URLEmailTokenizer.java |
43,272 | package org.apache.lucene.analysis.core;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.BaseTokenStreamTestCase;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.analysis.standard.UAX29URLEmailTokenizer;
import org.apache.lucene.analysis.tokenattributes.TypeAttribute;
import org.apache.lucene.util.Version;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
/**
* 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.
*/
public class TestUAX29URLEmailTokenizer extends BaseTokenStreamTestCase {
public void testHugeDoc() throws IOException {
StringBuilder sb = new StringBuilder();
char whitespace[] = new char[4094];
Arrays.fill(whitespace, ' ');
sb.append(whitespace);
sb.append("testing 1234");
String input = sb.toString();
UAX29URLEmailTokenizer tokenizer = new UAX29URLEmailTokenizer(TEST_VERSION_CURRENT, new StringReader(input));
BaseTokenStreamTestCase.assertTokenStreamContents(tokenizer, new String[] { "testing", "1234" });
}
private Analyzer a = new Analyzer() {
@Override
protected TokenStreamComponents createComponents
(String fieldName, Reader reader) {
Tokenizer tokenizer = new UAX29URLEmailTokenizer(TEST_VERSION_CURRENT, reader);
return new TokenStreamComponents(tokenizer);
}
};
/** Passes through tokens with type "<URL>" and blocks all other types. */
private class URLFilter extends TokenFilter {
private final TypeAttribute typeAtt = addAttribute(TypeAttribute.class);
public URLFilter(TokenStream in) {
super(in);
}
@Override
public final boolean incrementToken() throws java.io.IOException {
boolean isTokenAvailable = false;
while (input.incrementToken()) {
if (typeAtt.type() == UAX29URLEmailTokenizer.TOKEN_TYPES[UAX29URLEmailTokenizer.URL]) {
isTokenAvailable = true;
break;
}
}
return isTokenAvailable;
}
}
/** Passes through tokens with type "<EMAIL>" and blocks all other types. */
private class EmailFilter extends TokenFilter {
private final TypeAttribute typeAtt = addAttribute(TypeAttribute.class);
public EmailFilter(TokenStream in) {
super(in);
}
@Override
public final boolean incrementToken() throws java.io.IOException {
boolean isTokenAvailable = false;
while (input.incrementToken()) {
if (typeAtt.type() == UAX29URLEmailTokenizer.TOKEN_TYPES[UAX29URLEmailTokenizer.EMAIL]) {
isTokenAvailable = true;
break;
}
}
return isTokenAvailable;
}
}
private Analyzer urlAnalyzer = new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
UAX29URLEmailTokenizer tokenizer = new UAX29URLEmailTokenizer(TEST_VERSION_CURRENT, reader);
tokenizer.setMaxTokenLength(Integer.MAX_VALUE); // Tokenize arbitrary length URLs
TokenFilter filter = new URLFilter(tokenizer);
return new TokenStreamComponents(tokenizer, filter);
}
};
private Analyzer emailAnalyzer = new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
UAX29URLEmailTokenizer tokenizer = new UAX29URLEmailTokenizer(TEST_VERSION_CURRENT, reader);
TokenFilter filter = new EmailFilter(tokenizer);
return new TokenStreamComponents(tokenizer, filter);
}
};
public void testArmenian() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Վիքիպեդիայի 13 միլիոն հոդվածները (4,600` հայերեն վիքիպեդիայում) գրվել են կամավորների կողմից ու համարյա բոլոր հոդվածները կարող է խմբագրել ցանկաց մարդ ով կարող է բացել Վիքիպեդիայի կայքը։",
new String[] { "Վիքիպեդիայի", "13", "միլիոն", "հոդվածները", "4,600", "հայերեն", "վիքիպեդիայում", "գրվել", "են", "կամավորների", "կողմից",
"ու", "համարյա", "բոլոր", "հոդվածները", "կարող", "է", "խմբագրել", "ցանկաց", "մարդ", "ով", "կարող", "է", "բացել", "Վիքիպեդիայի", "կայքը" } );
}
public void testAmharic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ዊኪፔድያ የባለ ብዙ ቋንቋ የተሟላ ትክክለኛና ነጻ መዝገበ ዕውቀት (ኢንሳይክሎፒዲያ) ነው። ማንኛውም",
new String[] { "ዊኪፔድያ", "የባለ", "ብዙ", "ቋንቋ", "የተሟላ", "ትክክለኛና", "ነጻ", "መዝገበ", "ዕውቀት", "ኢንሳይክሎፒዲያ", "ነው", "ማንኛውም" } );
}
public void testArabic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "الفيلم الوثائقي الأول عن ويكيبيديا يسمى \"الحقيقة بالأرقام: قصة ويكيبيديا\" (بالإنجليزية: Truth in Numbers: The Wikipedia Story)، سيتم إطلاقه في 2008.",
new String[] { "الفيلم", "الوثائقي", "الأول", "عن", "ويكيبيديا", "يسمى", "الحقيقة", "بالأرقام", "قصة", "ويكيبيديا",
"بالإنجليزية", "Truth", "in", "Numbers", "The", "Wikipedia", "Story", "سيتم", "إطلاقه", "في", "2008" } );
}
public void testAramaic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ܘܝܩܝܦܕܝܐ (ܐܢܓܠܝܐ: Wikipedia) ܗܘ ܐܝܢܣܩܠܘܦܕܝܐ ܚܐܪܬܐ ܕܐܢܛܪܢܛ ܒܠܫܢ̈ܐ ܣܓܝܐ̈ܐ܂ ܫܡܗ ܐܬܐ ܡܢ ܡ̈ܠܬܐ ܕ\"ܘܝܩܝ\" ܘ\"ܐܝܢܣܩܠܘܦܕܝܐ\"܀",
new String[] { "ܘܝܩܝܦܕܝܐ", "ܐܢܓܠܝܐ", "Wikipedia", "ܗܘ", "ܐܝܢܣܩܠܘܦܕܝܐ", "ܚܐܪܬܐ", "ܕܐܢܛܪܢܛ", "ܒܠܫܢ̈ܐ", "ܣܓܝܐ̈ܐ", "ܫܡܗ",
"ܐܬܐ", "ܡܢ", "ܡ̈ܠܬܐ", "ܕ", "ܘܝܩܝ", "ܘ", "ܐܝܢܣܩܠܘܦܕܝܐ"});
}
public void testBengali() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "এই বিশ্বকোষ পরিচালনা করে উইকিমিডিয়া ফাউন্ডেশন (একটি অলাভজনক সংস্থা)। উইকিপিডিয়ার শুরু ১৫ জানুয়ারি, ২০০১ সালে। এখন পর্যন্ত ২০০টিরও বেশী ভাষায় উইকিপিডিয়া রয়েছে।",
new String[] { "এই", "বিশ্বকোষ", "পরিচালনা", "করে", "উইকিমিডিয়া", "ফাউন্ডেশন", "একটি", "অলাভজনক", "সংস্থা", "উইকিপিডিয়ার",
"শুরু", "১৫", "জানুয়ারি", "২০০১", "সালে", "এখন", "পর্যন্ত", "২০০টিরও", "বেশী", "ভাষায়", "উইকিপিডিয়া", "রয়েছে" });
}
public void testFarsi() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ویکی پدیای انگلیسی در تاریخ ۲۵ دی ۱۳۷۹ به صورت مکملی برای دانشنامهٔ تخصصی نوپدیا نوشته شد.",
new String[] { "ویکی", "پدیای", "انگلیسی", "در", "تاریخ", "۲۵", "دی", "۱۳۷۹", "به", "صورت", "مکملی",
"برای", "دانشنامهٔ", "تخصصی", "نوپدیا", "نوشته", "شد" });
}
public void testGreek() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Γράφεται σε συνεργασία από εθελοντές με το λογισμικό wiki, κάτι που σημαίνει ότι άρθρα μπορεί να προστεθούν ή να αλλάξουν από τον καθένα.",
new String[] { "Γράφεται", "σε", "συνεργασία", "από", "εθελοντές", "με", "το", "λογισμικό", "wiki", "κάτι", "που",
"σημαίνει", "ότι", "άρθρα", "μπορεί", "να", "προστεθούν", "ή", "να", "αλλάξουν", "από", "τον", "καθένα" });
}
public void testThai() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "การที่ได้ต้องแสดงว่างานดี. แล้วเธอจะไปไหน? ๑๒๓๔",
new String[] { "การที่ได้ต้องแสดงว่างานดี", "แล้วเธอจะไปไหน", "๑๒๓๔" });
}
public void testLao() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ສາທາລະນະລັດ ປະຊາທິປະໄຕ ປະຊາຊົນລາວ",
new String[] { "ສາທາລະນະລັດ", "ປະຊາທິປະໄຕ", "ປະຊາຊົນລາວ" });
}
public void testTibetan() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "སྣོན་མཛོད་དང་ལས་འདིས་བོད་ཡིག་མི་ཉམས་གོང་འཕེལ་དུ་གཏོང་བར་ཧ་ཅང་དགེ་མཚན་མཆིས་སོ། །",
new String[] { "སྣོན", "མཛོད", "དང", "ལས", "འདིས", "བོད", "ཡིག",
"མི", "ཉམས", "གོང", "འཕེལ", "དུ", "གཏོང", "བར",
"ཧ", "ཅང", "དགེ", "མཚན", "མཆིས", "སོ" });
}
/*
* For chinese, tokenize as char (these can later form bigrams or whatever)
*/
public void testChinese() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "我是中国人。 1234 Tests ",
new String[] { "我", "是", "中", "国", "人", "1234", "Tests"});
}
public void testEmpty() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "", new String[] {});
BaseTokenStreamTestCase.assertAnalyzesTo(a, ".", new String[] {});
BaseTokenStreamTestCase.assertAnalyzesTo(a, " ", new String[] {});
}
/* test various jira issues this analyzer is related to */
public void testLUCENE1545() throws Exception {
/*
* Standard analyzer does not correctly tokenize combining character U+0364 COMBINING LATIN SMALL LETTRE E.
* The word "moͤchte" is incorrectly tokenized into "mo" "chte", the combining character is lost.
* Expected result is only on token "moͤchte".
*/
BaseTokenStreamTestCase.assertAnalyzesTo(a, "moͤchte", new String[] { "moͤchte" });
}
/* Tests from StandardAnalyzer, just to show behavior is similar */
public void testAlphanumericSA() throws Exception {
// alphanumeric tokens
BaseTokenStreamTestCase.assertAnalyzesTo(a, "B2B", new String[]{"B2B"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "2B", new String[]{"2B"});
}
public void testDelimitersSA() throws Exception {
// other delimiters: "-", "/", ","
BaseTokenStreamTestCase.assertAnalyzesTo(a, "some-dashed-phrase", new String[]{"some", "dashed", "phrase"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "dogs,chase,cats", new String[]{"dogs", "chase", "cats"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ac/dc", new String[]{"ac", "dc"});
}
public void testApostrophesSA() throws Exception {
// internal apostrophes: O'Reilly, you're, O'Reilly's
BaseTokenStreamTestCase.assertAnalyzesTo(a, "O'Reilly", new String[]{"O'Reilly"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "you're", new String[]{"you're"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "she's", new String[]{"she's"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Jim's", new String[]{"Jim's"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "don't", new String[]{"don't"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "O'Reilly's", new String[]{"O'Reilly's"});
}
public void testNumericSA() throws Exception {
// floating point, serial, model numbers, ip addresses, etc.
BaseTokenStreamTestCase.assertAnalyzesTo(a, "21.35", new String[]{"21.35"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "R2D2 C3PO", new String[]{"R2D2", "C3PO"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "216.239.63.104", new String[]{"216.239.63.104"});
}
public void testTextWithNumbersSA() throws Exception {
// numbers
BaseTokenStreamTestCase.assertAnalyzesTo(a, "David has 5000 bones", new String[]{"David", "has", "5000", "bones"});
}
public void testVariousTextSA() throws Exception {
// various
BaseTokenStreamTestCase.assertAnalyzesTo(a, "C embedded developers wanted", new String[]{"C", "embedded", "developers", "wanted"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "foo bar FOO BAR", new String[]{"foo", "bar", "FOO", "BAR"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "foo bar . FOO <> BAR", new String[]{"foo", "bar", "FOO", "BAR"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "\"QUOTED\" word", new String[]{"QUOTED", "word"});
}
public void testKoreanSA() throws Exception {
// Korean words
BaseTokenStreamTestCase.assertAnalyzesTo(a, "안녕하세요 한글입니다", new String[]{"안녕하세요", "한글입니다"});
}
public void testOffsets() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "David has 5000 bones",
new String[] {"David", "has", "5000", "bones"},
new int[] {0, 6, 10, 15},
new int[] {5, 9, 14, 20});
}
public void testTypes() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "David has 5000 bones",
new String[] {"David", "has", "5000", "bones"},
new String[] { "<ALPHANUM>", "<ALPHANUM>", "<NUM>", "<ALPHANUM>" });
}
public void testWikiURLs() throws Exception {
Reader reader = null;
String luceneResourcesWikiPage;
try {
reader = new InputStreamReader(getClass().getResourceAsStream
("LuceneResourcesWikiPage.html"), "UTF-8");
StringBuilder builder = new StringBuilder();
char[] buffer = new char[1024];
int numCharsRead;
while (-1 != (numCharsRead = reader.read(buffer))) {
builder.append(buffer, 0, numCharsRead);
}
luceneResourcesWikiPage = builder.toString();
} finally {
if (null != reader) {
reader.close();
}
}
assertTrue(null != luceneResourcesWikiPage
&& luceneResourcesWikiPage.length() > 0);
BufferedReader bufferedReader = null;
String[] urls;
try {
List<String> urlList = new ArrayList<String>();
bufferedReader = new BufferedReader(new InputStreamReader
(getClass().getResourceAsStream("LuceneResourcesWikiPageURLs.txt"), "UTF-8"));
String line;
while (null != (line = bufferedReader.readLine())) {
line = line.trim();
if (line.length() > 0) {
urlList.add(line);
}
}
urls = urlList.toArray(new String[urlList.size()]);
} finally {
if (null != bufferedReader) {
bufferedReader.close();
}
}
assertTrue(null != urls && urls.length > 0);
BaseTokenStreamTestCase.assertAnalyzesTo
(urlAnalyzer, luceneResourcesWikiPage, urls);
}
public void testEmails() throws Exception {
Reader reader = null;
String randomTextWithEmails;
try {
reader = new InputStreamReader(getClass().getResourceAsStream
("random.text.with.email.addresses.txt"), "UTF-8");
StringBuilder builder = new StringBuilder();
char[] buffer = new char[1024];
int numCharsRead;
while (-1 != (numCharsRead = reader.read(buffer))) {
builder.append(buffer, 0, numCharsRead);
}
randomTextWithEmails = builder.toString();
} finally {
if (null != reader) {
reader.close();
}
}
assertTrue(null != randomTextWithEmails
&& randomTextWithEmails.length() > 0);
BufferedReader bufferedReader = null;
String[] emails;
try {
List<String> emailList = new ArrayList<String>();
bufferedReader = new BufferedReader(new InputStreamReader
(getClass().getResourceAsStream
("email.addresses.from.random.text.with.email.addresses.txt"), "UTF-8"));
String line;
while (null != (line = bufferedReader.readLine())) {
line = line.trim();
if (line.length() > 0) {
emailList.add(line);
}
}
emails = emailList.toArray(new String[emailList.size()]);
} finally {
if (null != bufferedReader) {
bufferedReader.close();
}
}
assertTrue(null != emails && emails.length > 0);
BaseTokenStreamTestCase.assertAnalyzesTo
(emailAnalyzer, randomTextWithEmails, emails);
}
public void testMailtoSchemeEmails () throws Exception {
// See LUCENE-3880
BaseTokenStreamTestCase.assertAnalyzesTo(a, "mailto:[email protected]",
new String[] {"mailto", "[email protected]"},
new String[] { "<ALPHANUM>", "<EMAIL>" });
// TODO: Support full mailto: scheme URIs. See RFC 6068: http://tools.ietf.org/html/rfc6068
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "mailto:[email protected],[email protected][email protected]"
+ "&subject=Subjectivity&body=Corpusivity%20or%20something%20like%20that",
new String[] { "mailto",
"[email protected]",
// TODO: recognize ',' address delimiter. Also, see examples of ';' delimiter use at: http://www.mailto.co.uk/
",[email protected]",
"[email protected]", // TODO: split field keys/values
"subject", "Subjectivity",
"body", "Corpusivity", "20or", "20something","20like", "20that" }, // TODO: Hex decoding + re-tokenization
new String[] { "<ALPHANUM>",
"<EMAIL>",
"<EMAIL>",
"<EMAIL>",
"<ALPHANUM>", "<ALPHANUM>",
"<ALPHANUM>", "<ALPHANUM>", "<ALPHANUM>", "<ALPHANUM>", "<ALPHANUM>", "<ALPHANUM>" });
}
public void testURLs() throws Exception {
Reader reader = null;
String randomTextWithURLs;
try {
reader = new InputStreamReader(getClass().getResourceAsStream
("random.text.with.urls.txt"), "UTF-8");
StringBuilder builder = new StringBuilder();
char[] buffer = new char[1024];
int numCharsRead;
while (-1 != (numCharsRead = reader.read(buffer))) {
builder.append(buffer, 0, numCharsRead);
}
randomTextWithURLs = builder.toString();
} finally {
if (null != reader) {
reader.close();
}
}
assertTrue(null != randomTextWithURLs
&& randomTextWithURLs.length() > 0);
BufferedReader bufferedReader = null;
String[] urls;
try {
List<String> urlList = new ArrayList<String>();
bufferedReader = new BufferedReader(new InputStreamReader
(getClass().getResourceAsStream
("urls.from.random.text.with.urls.txt"), "UTF-8"));
String line;
while (null != (line = bufferedReader.readLine())) {
line = line.trim();
if (line.length() > 0) {
urlList.add(line);
}
}
urls = urlList.toArray(new String[urlList.size()]);
} finally {
if (null != bufferedReader) {
bufferedReader.close();
}
}
assertTrue(null != urls && urls.length > 0);
BaseTokenStreamTestCase.assertAnalyzesTo
(urlAnalyzer, randomTextWithURLs, urls);
}
public void testUnicodeWordBreaks() throws Exception {
WordBreakTestUnicode_6_0_0 wordBreakTest = new WordBreakTestUnicode_6_0_0();
wordBreakTest.test(a);
}
public void testSupplementary() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "𩬅艱鍟䇹愯瀛",
new String[] {"𩬅", "艱", "鍟", "䇹", "愯", "瀛"},
new String[] { "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>" });
}
public void testKorean() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "훈민정음",
new String[] { "훈민정음" },
new String[] { "<HANGUL>" });
}
public void testJapanese() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "仮名遣い カタカナ",
new String[] { "仮", "名", "遣", "い", "カタカナ" },
new String[] { "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<HIRAGANA>", "<KATAKANA>" });
}
public void testCombiningMarks() throws Exception {
checkOneTerm(a, "ざ", "ざ"); // hiragana
checkOneTerm(a, "ザ", "ザ"); // katakana
checkOneTerm(a, "壹゙", "壹゙"); // ideographic
checkOneTerm(a, "아゙", "아゙"); // hangul
}
/** blast some random strings through the analyzer */
public void testRandomStrings() throws Exception {
checkRandomData(random(), a, 10000*RANDOM_MULTIPLIER);
}
/** blast some random large strings through the analyzer */
public void testRandomHugeStrings() throws Exception {
Random random = random();
checkRandomData(random, a, 200*RANDOM_MULTIPLIER, 8192);
}
}
| mumrah/lucene-solr | lucene/analysis/common/src/test/org/apache/lucene/analysis/core/TestUAX29URLEmailTokenizer.java |
43,275 | package org.apache.lucene.analysis;
import org.apache.lucene.analysis.standard.UAX29URLEmailTokenizer;
import org.apache.lucene.analysis.tokenattributes.TypeAttribute;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 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.
*/
public class TestUAX29URLEmailTokenizer extends BaseTokenStreamTestCase {
public void testHugeDoc() throws IOException {
StringBuilder sb = new StringBuilder();
char whitespace[] = new char[4094];
Arrays.fill(whitespace, ' ');
sb.append(whitespace);
sb.append("testing 1234");
String input = sb.toString();
UAX29URLEmailTokenizer tokenizer = new UAX29URLEmailTokenizer(new StringReader(input));
BaseTokenStreamTestCase.assertTokenStreamContents(tokenizer, new String[] { "testing", "1234" });
}
private Analyzer a = new ReusableAnalyzerBase() {
@Override
protected TokenStreamComponents createComponents
(String fieldName, Reader reader) {
Tokenizer tokenizer = new UAX29URLEmailTokenizer(reader);
return new TokenStreamComponents(tokenizer);
}
};
/** Passes through tokens with type "<URL>" and blocks all other types. */
private class URLFilter extends TokenFilter {
private final TypeAttribute typeAtt = addAttribute(TypeAttribute.class);
public URLFilter(TokenStream in) {
super(in);
}
@Override
public final boolean incrementToken() throws java.io.IOException {
boolean isTokenAvailable = false;
while (input.incrementToken()) {
if (typeAtt.type() == UAX29URLEmailTokenizer.URL_TYPE) {
isTokenAvailable = true;
break;
}
}
return isTokenAvailable;
}
}
/** Passes through tokens with type "<EMAIL>" and blocks all other types. */
private class EmailFilter extends TokenFilter {
private final TypeAttribute typeAtt = addAttribute(TypeAttribute.class);
public EmailFilter(TokenStream in) {
super(in);
}
@Override
public final boolean incrementToken() throws java.io.IOException {
boolean isTokenAvailable = false;
while (input.incrementToken()) {
if (typeAtt.type() == UAX29URLEmailTokenizer.EMAIL_TYPE) {
isTokenAvailable = true;
break;
}
}
return isTokenAvailable;
}
}
private Analyzer urlAnalyzer = new ReusableAnalyzerBase() {
@Override
protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
UAX29URLEmailTokenizer tokenizer = new UAX29URLEmailTokenizer(reader);
tokenizer.setMaxTokenLength(Integer.MAX_VALUE); // Tokenize arbitrary length URLs
TokenFilter filter = new URLFilter(tokenizer);
return new TokenStreamComponents(tokenizer, filter);
}
};
private Analyzer emailAnalyzer = new ReusableAnalyzerBase() {
@Override
protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
UAX29URLEmailTokenizer tokenizer = new UAX29URLEmailTokenizer(reader);
TokenFilter filter = new EmailFilter(tokenizer);
return new TokenStreamComponents(tokenizer, filter);
}
};
public void testArmenian() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Վիքիպեդիայի 13 միլիոն հոդվածները (4,600` հայերեն վիքիպեդիայում) գրվել են կամավորների կողմից ու համարյա բոլոր հոդվածները կարող է խմբագրել ցանկաց մարդ ով կարող է բացել Վիքիպեդիայի կայքը։",
new String[] { "Վիքիպեդիայի", "13", "միլիոն", "հոդվածները", "4,600", "հայերեն", "վիքիպեդիայում", "գրվել", "են", "կամավորների", "կողմից",
"ու", "համարյա", "բոլոր", "հոդվածները", "կարող", "է", "խմբագրել", "ցանկաց", "մարդ", "ով", "կարող", "է", "բացել", "Վիքիպեդիայի", "կայքը" } );
}
public void testAmharic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ዊኪፔድያ የባለ ብዙ ቋንቋ የተሟላ ትክክለኛና ነጻ መዝገበ ዕውቀት (ኢንሳይክሎፒዲያ) ነው። ማንኛውም",
new String[] { "ዊኪፔድያ", "የባለ", "ብዙ", "ቋንቋ", "የተሟላ", "ትክክለኛና", "ነጻ", "መዝገበ", "ዕውቀት", "ኢንሳይክሎፒዲያ", "ነው", "ማንኛውም" } );
}
public void testArabic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "الفيلم الوثائقي الأول عن ويكيبيديا يسمى \"الحقيقة بالأرقام: قصة ويكيبيديا\" (بالإنجليزية: Truth in Numbers: The Wikipedia Story)، سيتم إطلاقه في 2008.",
new String[] { "الفيلم", "الوثائقي", "الأول", "عن", "ويكيبيديا", "يسمى", "الحقيقة", "بالأرقام", "قصة", "ويكيبيديا",
"بالإنجليزية", "Truth", "in", "Numbers", "The", "Wikipedia", "Story", "سيتم", "إطلاقه", "في", "2008" } );
}
public void testAramaic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ܘܝܩܝܦܕܝܐ (ܐܢܓܠܝܐ: Wikipedia) ܗܘ ܐܝܢܣܩܠܘܦܕܝܐ ܚܐܪܬܐ ܕܐܢܛܪܢܛ ܒܠܫܢ̈ܐ ܣܓܝܐ̈ܐ܂ ܫܡܗ ܐܬܐ ܡܢ ܡ̈ܠܬܐ ܕ\"ܘܝܩܝ\" ܘ\"ܐܝܢܣܩܠܘܦܕܝܐ\"܀",
new String[] { "ܘܝܩܝܦܕܝܐ", "ܐܢܓܠܝܐ", "Wikipedia", "ܗܘ", "ܐܝܢܣܩܠܘܦܕܝܐ", "ܚܐܪܬܐ", "ܕܐܢܛܪܢܛ", "ܒܠܫܢ̈ܐ", "ܣܓܝܐ̈ܐ", "ܫܡܗ",
"ܐܬܐ", "ܡܢ", "ܡ̈ܠܬܐ", "ܕ", "ܘܝܩܝ", "ܘ", "ܐܝܢܣܩܠܘܦܕܝܐ"});
}
public void testBengali() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "এই বিশ্বকোষ পরিচালনা করে উইকিমিডিয়া ফাউন্ডেশন (একটি অলাভজনক সংস্থা)। উইকিপিডিয়ার শুরু ১৫ জানুয়ারি, ২০০১ সালে। এখন পর্যন্ত ২০০টিরও বেশী ভাষায় উইকিপিডিয়া রয়েছে।",
new String[] { "এই", "বিশ্বকোষ", "পরিচালনা", "করে", "উইকিমিডিয়া", "ফাউন্ডেশন", "একটি", "অলাভজনক", "সংস্থা", "উইকিপিডিয়ার",
"শুরু", "১৫", "জানুয়ারি", "২০০১", "সালে", "এখন", "পর্যন্ত", "২০০টিরও", "বেশী", "ভাষায়", "উইকিপিডিয়া", "রয়েছে" });
}
public void testFarsi() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ویکی پدیای انگلیسی در تاریخ ۲۵ دی ۱۳۷۹ به صورت مکملی برای دانشنامهٔ تخصصی نوپدیا نوشته شد.",
new String[] { "ویکی", "پدیای", "انگلیسی", "در", "تاریخ", "۲۵", "دی", "۱۳۷۹", "به", "صورت", "مکملی",
"برای", "دانشنامهٔ", "تخصصی", "نوپدیا", "نوشته", "شد" });
}
public void testGreek() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Γράφεται σε συνεργασία από εθελοντές με το λογισμικό wiki, κάτι που σημαίνει ότι άρθρα μπορεί να προστεθούν ή να αλλάξουν από τον καθένα.",
new String[] { "Γράφεται", "σε", "συνεργασία", "από", "εθελοντές", "με", "το", "λογισμικό", "wiki", "κάτι", "που",
"σημαίνει", "ότι", "άρθρα", "μπορεί", "να", "προστεθούν", "ή", "να", "αλλάξουν", "από", "τον", "καθένα" });
}
public void testThai() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "การที่ได้ต้องแสดงว่างานดี. แล้วเธอจะไปไหน? ๑๒๓๔",
new String[] { "การที่ได้ต้องแสดงว่างานดี", "แล้วเธอจะไปไหน", "๑๒๓๔" });
}
public void testLao() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ສາທາລະນະລັດ ປະຊາທິປະໄຕ ປະຊາຊົນລາວ",
new String[] { "ສາທາລະນະລັດ", "ປະຊາທິປະໄຕ", "ປະຊາຊົນລາວ" });
}
public void testTibetan() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "སྣོན་མཛོད་དང་ལས་འདིས་བོད་ཡིག་མི་ཉམས་གོང་འཕེལ་དུ་གཏོང་བར་ཧ་ཅང་དགེ་མཚན་མཆིས་སོ། །",
new String[] { "སྣོན", "མཛོད", "དང", "ལས", "འདིས", "བོད", "ཡིག",
"མི", "ཉམས", "གོང", "འཕེལ", "དུ", "གཏོང", "བར",
"ཧ", "ཅང", "དགེ", "མཚན", "མཆིས", "སོ" });
}
/*
* For chinese, tokenize as char (these can later form bigrams or whatever)
*/
public void testChinese() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "我是中国人。 1234 Tests ",
new String[] { "我", "是", "中", "国", "人", "1234", "Tests"});
}
public void testEmpty() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "", new String[] {});
BaseTokenStreamTestCase.assertAnalyzesTo(a, ".", new String[] {});
BaseTokenStreamTestCase.assertAnalyzesTo(a, " ", new String[] {});
}
/* test various jira issues this analyzer is related to */
public void testLUCENE1545() throws Exception {
/*
* Standard analyzer does not correctly tokenize combining character U+0364 COMBINING LATIN SMALL LETTRE E.
* The word "moͤchte" is incorrectly tokenized into "mo" "chte", the combining character is lost.
* Expected result is only on token "moͤchte".
*/
BaseTokenStreamTestCase.assertAnalyzesTo(a, "moͤchte", new String[] { "moͤchte" });
}
/* Tests from StandardAnalyzer, just to show behavior is similar */
public void testAlphanumericSA() throws Exception {
// alphanumeric tokens
BaseTokenStreamTestCase.assertAnalyzesTo(a, "B2B", new String[]{"B2B"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "2B", new String[]{"2B"});
}
public void testDelimitersSA() throws Exception {
// other delimiters: "-", "/", ","
BaseTokenStreamTestCase.assertAnalyzesTo(a, "some-dashed-phrase", new String[]{"some", "dashed", "phrase"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "dogs,chase,cats", new String[]{"dogs", "chase", "cats"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ac/dc", new String[]{"ac", "dc"});
}
public void testApostrophesSA() throws Exception {
// internal apostrophes: O'Reilly, you're, O'Reilly's
BaseTokenStreamTestCase.assertAnalyzesTo(a, "O'Reilly", new String[]{"O'Reilly"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "you're", new String[]{"you're"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "she's", new String[]{"she's"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Jim's", new String[]{"Jim's"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "don't", new String[]{"don't"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "O'Reilly's", new String[]{"O'Reilly's"});
}
public void testNumericSA() throws Exception {
// floating point, serial, model numbers, ip addresses, etc.
BaseTokenStreamTestCase.assertAnalyzesTo(a, "21.35", new String[]{"21.35"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "R2D2 C3PO", new String[]{"R2D2", "C3PO"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "216.239.63.104", new String[]{"216.239.63.104"});
}
public void testTextWithNumbersSA() throws Exception {
// numbers
BaseTokenStreamTestCase.assertAnalyzesTo(a, "David has 5000 bones", new String[]{"David", "has", "5000", "bones"});
}
public void testVariousTextSA() throws Exception {
// various
BaseTokenStreamTestCase.assertAnalyzesTo(a, "C embedded developers wanted", new String[]{"C", "embedded", "developers", "wanted"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "foo bar FOO BAR", new String[]{"foo", "bar", "FOO", "BAR"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "foo bar . FOO <> BAR", new String[]{"foo", "bar", "FOO", "BAR"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "\"QUOTED\" word", new String[]{"QUOTED", "word"});
}
public void testKoreanSA() throws Exception {
// Korean words
BaseTokenStreamTestCase.assertAnalyzesTo(a, "안녕하세요 한글입니다", new String[]{"안녕하세요", "한글입니다"});
}
public void testOffsets() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "David has 5000 bones",
new String[] {"David", "has", "5000", "bones"},
new int[] {0, 6, 10, 15},
new int[] {5, 9, 14, 20});
}
public void testTypes() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "David has 5000 bones",
new String[] {"David", "has", "5000", "bones"},
new String[] { "<ALPHANUM>", "<ALPHANUM>", "<NUM>", "<ALPHANUM>" });
}
public void testWikiURLs() throws Exception {
Reader reader = null;
String luceneResourcesWikiPage;
try {
reader = new InputStreamReader(getClass().getResourceAsStream
("LuceneResourcesWikiPage.html"), "UTF-8");
StringBuilder builder = new StringBuilder();
char[] buffer = new char[1024];
int numCharsRead;
while (-1 != (numCharsRead = reader.read(buffer))) {
builder.append(buffer, 0, numCharsRead);
}
luceneResourcesWikiPage = builder.toString();
} finally {
if (null != reader) {
reader.close();
}
}
assertTrue(null != luceneResourcesWikiPage
&& luceneResourcesWikiPage.length() > 0);
BufferedReader bufferedReader = null;
String[] urls;
try {
List<String> urlList = new ArrayList<String>();
bufferedReader = new BufferedReader(new InputStreamReader
(getClass().getResourceAsStream("LuceneResourcesWikiPageURLs.txt"), "UTF-8"));
String line;
while (null != (line = bufferedReader.readLine())) {
line = line.trim();
if (line.length() > 0) {
urlList.add(line);
}
}
urls = urlList.toArray(new String[urlList.size()]);
} finally {
if (null != bufferedReader) {
bufferedReader.close();
}
}
assertTrue(null != urls && urls.length > 0);
BaseTokenStreamTestCase.assertAnalyzesTo
(urlAnalyzer, luceneResourcesWikiPage, urls);
}
public void testEmails() throws Exception {
Reader reader = null;
String randomTextWithEmails;
try {
reader = new InputStreamReader(getClass().getResourceAsStream
("random.text.with.email.addresses.txt"), "UTF-8");
StringBuilder builder = new StringBuilder();
char[] buffer = new char[1024];
int numCharsRead;
while (-1 != (numCharsRead = reader.read(buffer))) {
builder.append(buffer, 0, numCharsRead);
}
randomTextWithEmails = builder.toString();
} finally {
if (null != reader) {
reader.close();
}
}
assertTrue(null != randomTextWithEmails
&& randomTextWithEmails.length() > 0);
BufferedReader bufferedReader = null;
String[] emails;
try {
List<String> emailList = new ArrayList<String>();
bufferedReader = new BufferedReader(new InputStreamReader
(getClass().getResourceAsStream
("email.addresses.from.random.text.with.email.addresses.txt"), "UTF-8"));
String line;
while (null != (line = bufferedReader.readLine())) {
line = line.trim();
if (line.length() > 0) {
emailList.add(line);
}
}
emails = emailList.toArray(new String[emailList.size()]);
} finally {
if (null != bufferedReader) {
bufferedReader.close();
}
}
assertTrue(null != emails && emails.length > 0);
BaseTokenStreamTestCase.assertAnalyzesTo
(emailAnalyzer, randomTextWithEmails, emails);
}
public void testURLs() throws Exception {
Reader reader = null;
String randomTextWithURLs;
try {
reader = new InputStreamReader(getClass().getResourceAsStream
("random.text.with.urls.txt"), "UTF-8");
StringBuilder builder = new StringBuilder();
char[] buffer = new char[1024];
int numCharsRead;
while (-1 != (numCharsRead = reader.read(buffer))) {
builder.append(buffer, 0, numCharsRead);
}
randomTextWithURLs = builder.toString();
} finally {
if (null != reader) {
reader.close();
}
}
assertTrue(null != randomTextWithURLs
&& randomTextWithURLs.length() > 0);
BufferedReader bufferedReader = null;
String[] urls;
try {
List<String> urlList = new ArrayList<String>();
bufferedReader = new BufferedReader(new InputStreamReader
(getClass().getResourceAsStream
("urls.from.random.text.with.urls.txt"), "UTF-8"));
String line;
while (null != (line = bufferedReader.readLine())) {
line = line.trim();
if (line.length() > 0) {
urlList.add(line);
}
}
urls = urlList.toArray(new String[urlList.size()]);
} finally {
if (null != bufferedReader) {
bufferedReader.close();
}
}
assertTrue(null != urls && urls.length > 0);
BaseTokenStreamTestCase.assertAnalyzesTo
(urlAnalyzer, randomTextWithURLs, urls);
}
public void testUnicodeWordBreaks() throws Exception {
WordBreakTestUnicode_6_0_0 wordBreakTest = new WordBreakTestUnicode_6_0_0();
wordBreakTest.test(a);
}
}
| tdurieux/pattern-detector-experiment | benchmark/icse15/1055904/buggy-version/lucene/dev/branches/branch_3x/lucene/src/test/org/apache/lucene/analysis/TestUAX29URLEmailTokenizer.java |
43,277 | package org.apache.lucene.analysis.core;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.BaseTokenStreamTestCase;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.analysis.standard.UAX29URLEmailTokenizer;
import org.apache.lucene.analysis.tokenattributes.TypeAttribute;
import org.apache.lucene.util.Version;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
/*
* 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.
*/
public class TestUAX29URLEmailTokenizer extends BaseTokenStreamTestCase {
public void testHugeDoc() throws IOException {
StringBuilder sb = new StringBuilder();
char whitespace[] = new char[4094];
Arrays.fill(whitespace, ' ');
sb.append(whitespace);
sb.append("testing 1234");
String input = sb.toString();
UAX29URLEmailTokenizer tokenizer = new UAX29URLEmailTokenizer(TEST_VERSION_CURRENT);
tokenizer.setReader(new StringReader(input));
BaseTokenStreamTestCase.assertTokenStreamContents(tokenizer, new String[] { "testing", "1234" });
}
private Analyzer a = new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName) {
Tokenizer tokenizer = new UAX29URLEmailTokenizer(TEST_VERSION_CURRENT);
return new TokenStreamComponents(tokenizer);
}
};
/** Passes through tokens with type "<URL>" and blocks all other types. */
private class URLFilter extends TokenFilter {
private final TypeAttribute typeAtt = addAttribute(TypeAttribute.class);
public URLFilter(TokenStream in) {
super(in);
}
@Override
public final boolean incrementToken() throws java.io.IOException {
boolean isTokenAvailable = false;
while (input.incrementToken()) {
if (typeAtt.type() == UAX29URLEmailTokenizer.TOKEN_TYPES[UAX29URLEmailTokenizer.URL]) {
isTokenAvailable = true;
break;
}
}
return isTokenAvailable;
}
}
/** Passes through tokens with type "<EMAIL>" and blocks all other types. */
private class EmailFilter extends TokenFilter {
private final TypeAttribute typeAtt = addAttribute(TypeAttribute.class);
public EmailFilter(TokenStream in) {
super(in);
}
@Override
public final boolean incrementToken() throws java.io.IOException {
boolean isTokenAvailable = false;
while (input.incrementToken()) {
if (typeAtt.type() == UAX29URLEmailTokenizer.TOKEN_TYPES[UAX29URLEmailTokenizer.EMAIL]) {
isTokenAvailable = true;
break;
}
}
return isTokenAvailable;
}
}
private Analyzer urlAnalyzer = new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName) {
UAX29URLEmailTokenizer tokenizer = new UAX29URLEmailTokenizer(TEST_VERSION_CURRENT);
tokenizer.setMaxTokenLength(Integer.MAX_VALUE); // Tokenize arbitrary length URLs
TokenFilter filter = new URLFilter(tokenizer);
return new TokenStreamComponents(tokenizer, filter);
}
};
private Analyzer emailAnalyzer = new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName) {
UAX29URLEmailTokenizer tokenizer = new UAX29URLEmailTokenizer(TEST_VERSION_CURRENT);
TokenFilter filter = new EmailFilter(tokenizer);
return new TokenStreamComponents(tokenizer, filter);
}
};
public void testArmenian() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Վիքիպեդիայի 13 միլիոն հոդվածները (4,600` հայերեն վիքիպեդիայում) գրվել են կամավորների կողմից ու համարյա բոլոր հոդվածները կարող է խմբագրել ցանկաց մարդ ով կարող է բացել Վիքիպեդիայի կայքը։",
new String[] { "Վիքիպեդիայի", "13", "միլիոն", "հոդվածները", "4,600", "հայերեն", "վիքիպեդիայում", "գրվել", "են", "կամավորների", "կողմից",
"ու", "համարյա", "բոլոր", "հոդվածները", "կարող", "է", "խմբագրել", "ցանկաց", "մարդ", "ով", "կարող", "է", "բացել", "Վիքիպեդիայի", "կայքը" } );
}
public void testAmharic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ዊኪፔድያ የባለ ብዙ ቋንቋ የተሟላ ትክክለኛና ነጻ መዝገበ ዕውቀት (ኢንሳይክሎፒዲያ) ነው። ማንኛውም",
new String[] { "ዊኪፔድያ", "የባለ", "ብዙ", "ቋንቋ", "የተሟላ", "ትክክለኛና", "ነጻ", "መዝገበ", "ዕውቀት", "ኢንሳይክሎፒዲያ", "ነው", "ማንኛውም" } );
}
public void testArabic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "الفيلم الوثائقي الأول عن ويكيبيديا يسمى \"الحقيقة بالأرقام: قصة ويكيبيديا\" (بالإنجليزية: Truth in Numbers: The Wikipedia Story)، سيتم إطلاقه في 2008.",
new String[] { "الفيلم", "الوثائقي", "الأول", "عن", "ويكيبيديا", "يسمى", "الحقيقة", "بالأرقام", "قصة", "ويكيبيديا",
"بالإنجليزية", "Truth", "in", "Numbers", "The", "Wikipedia", "Story", "سيتم", "إطلاقه", "في", "2008" } );
}
public void testAramaic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ܘܝܩܝܦܕܝܐ (ܐܢܓܠܝܐ: Wikipedia) ܗܘ ܐܝܢܣܩܠܘܦܕܝܐ ܚܐܪܬܐ ܕܐܢܛܪܢܛ ܒܠܫܢ̈ܐ ܣܓܝܐ̈ܐ܂ ܫܡܗ ܐܬܐ ܡܢ ܡ̈ܠܬܐ ܕ\"ܘܝܩܝ\" ܘ\"ܐܝܢܣܩܠܘܦܕܝܐ\"܀",
new String[] { "ܘܝܩܝܦܕܝܐ", "ܐܢܓܠܝܐ", "Wikipedia", "ܗܘ", "ܐܝܢܣܩܠܘܦܕܝܐ", "ܚܐܪܬܐ", "ܕܐܢܛܪܢܛ", "ܒܠܫܢ̈ܐ", "ܣܓܝܐ̈ܐ", "ܫܡܗ",
"ܐܬܐ", "ܡܢ", "ܡ̈ܠܬܐ", "ܕ", "ܘܝܩܝ", "ܘ", "ܐܝܢܣܩܠܘܦܕܝܐ"});
}
public void testBengali() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "এই বিশ্বকোষ পরিচালনা করে উইকিমিডিয়া ফাউন্ডেশন (একটি অলাভজনক সংস্থা)। উইকিপিডিয়ার শুরু ১৫ জানুয়ারি, ২০০১ সালে। এখন পর্যন্ত ২০০টিরও বেশী ভাষায় উইকিপিডিয়া রয়েছে।",
new String[] { "এই", "বিশ্বকোষ", "পরিচালনা", "করে", "উইকিমিডিয়া", "ফাউন্ডেশন", "একটি", "অলাভজনক", "সংস্থা", "উইকিপিডিয়ার",
"শুরু", "১৫", "জানুয়ারি", "২০০১", "সালে", "এখন", "পর্যন্ত", "২০০টিরও", "বেশী", "ভাষায়", "উইকিপিডিয়া", "রয়েছে" });
}
public void testFarsi() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ویکی پدیای انگلیسی در تاریخ ۲۵ دی ۱۳۷۹ به صورت مکملی برای دانشنامهٔ تخصصی نوپدیا نوشته شد.",
new String[] { "ویکی", "پدیای", "انگلیسی", "در", "تاریخ", "۲۵", "دی", "۱۳۷۹", "به", "صورت", "مکملی",
"برای", "دانشنامهٔ", "تخصصی", "نوپدیا", "نوشته", "شد" });
}
public void testGreek() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Γράφεται σε συνεργασία από εθελοντές με το λογισμικό wiki, κάτι που σημαίνει ότι άρθρα μπορεί να προστεθούν ή να αλλάξουν από τον καθένα.",
new String[] { "Γράφεται", "σε", "συνεργασία", "από", "εθελοντές", "με", "το", "λογισμικό", "wiki", "κάτι", "που",
"σημαίνει", "ότι", "άρθρα", "μπορεί", "να", "προστεθούν", "ή", "να", "αλλάξουν", "από", "τον", "καθένα" });
}
public void testThai() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "การที่ได้ต้องแสดงว่างานดี. แล้วเธอจะไปไหน? ๑๒๓๔",
new String[] { "การที่ได้ต้องแสดงว่างานดี", "แล้วเธอจะไปไหน", "๑๒๓๔" });
}
public void testLao() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ສາທາລະນະລັດ ປະຊາທິປະໄຕ ປະຊາຊົນລາວ",
new String[] { "ສາທາລະນະລັດ", "ປະຊາທິປະໄຕ", "ປະຊາຊົນລາວ" });
}
public void testTibetan() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "སྣོན་མཛོད་དང་ལས་འདིས་བོད་ཡིག་མི་ཉམས་གོང་འཕེལ་དུ་གཏོང་བར་ཧ་ཅང་དགེ་མཚན་མཆིས་སོ། །",
new String[] { "སྣོན", "མཛོད", "དང", "ལས", "འདིས", "བོད", "ཡིག",
"མི", "ཉམས", "གོང", "འཕེལ", "དུ", "གཏོང", "བར",
"ཧ", "ཅང", "དགེ", "མཚན", "མཆིས", "སོ" });
}
/*
* For chinese, tokenize as char (these can later form bigrams or whatever)
*/
public void testChinese() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "我是中国人。 1234 Tests ",
new String[] { "我", "是", "中", "国", "人", "1234", "Tests"});
}
public void testEmpty() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "", new String[] {});
BaseTokenStreamTestCase.assertAnalyzesTo(a, ".", new String[] {});
BaseTokenStreamTestCase.assertAnalyzesTo(a, " ", new String[] {});
}
/* test various jira issues this analyzer is related to */
public void testLUCENE1545() throws Exception {
/*
* Standard analyzer does not correctly tokenize combining character U+0364 COMBINING LATIN SMALL LETTRE E.
* The word "moͤchte" is incorrectly tokenized into "mo" "chte", the combining character is lost.
* Expected result is only on token "moͤchte".
*/
BaseTokenStreamTestCase.assertAnalyzesTo(a, "moͤchte", new String[] { "moͤchte" });
}
/* Tests from StandardAnalyzer, just to show behavior is similar */
public void testAlphanumericSA() throws Exception {
// alphanumeric tokens
BaseTokenStreamTestCase.assertAnalyzesTo(a, "B2B", new String[]{"B2B"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "2B", new String[]{"2B"});
}
public void testDelimitersSA() throws Exception {
// other delimiters: "-", "/", ","
BaseTokenStreamTestCase.assertAnalyzesTo(a, "some-dashed-phrase", new String[]{"some", "dashed", "phrase"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "dogs,chase,cats", new String[]{"dogs", "chase", "cats"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ac/dc", new String[]{"ac", "dc"});
}
public void testApostrophesSA() throws Exception {
// internal apostrophes: O'Reilly, you're, O'Reilly's
BaseTokenStreamTestCase.assertAnalyzesTo(a, "O'Reilly", new String[]{"O'Reilly"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "you're", new String[]{"you're"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "she's", new String[]{"she's"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Jim's", new String[]{"Jim's"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "don't", new String[]{"don't"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "O'Reilly's", new String[]{"O'Reilly's"});
}
public void testNumericSA() throws Exception {
// floating point, serial, model numbers, ip addresses, etc.
BaseTokenStreamTestCase.assertAnalyzesTo(a, "21.35", new String[]{"21.35"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "R2D2 C3PO", new String[]{"R2D2", "C3PO"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "216.239.63.104", new String[]{"216.239.63.104"});
}
public void testTextWithNumbersSA() throws Exception {
// numbers
BaseTokenStreamTestCase.assertAnalyzesTo(a, "David has 5000 bones", new String[]{"David", "has", "5000", "bones"});
}
public void testVariousTextSA() throws Exception {
// various
BaseTokenStreamTestCase.assertAnalyzesTo(a, "C embedded developers wanted", new String[]{"C", "embedded", "developers", "wanted"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "foo bar FOO BAR", new String[]{"foo", "bar", "FOO", "BAR"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "foo bar . FOO <> BAR", new String[]{"foo", "bar", "FOO", "BAR"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "\"QUOTED\" word", new String[]{"QUOTED", "word"});
}
public void testKoreanSA() throws Exception {
// Korean words
BaseTokenStreamTestCase.assertAnalyzesTo(a, "안녕하세요 한글입니다", new String[]{"안녕하세요", "한글입니다"});
}
public void testOffsets() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "David has 5000 bones",
new String[] {"David", "has", "5000", "bones"},
new int[] {0, 6, 10, 15},
new int[] {5, 9, 14, 20});
}
public void testTypes() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "David has 5000 bones",
new String[] {"David", "has", "5000", "bones"},
new String[] { "<ALPHANUM>", "<ALPHANUM>", "<NUM>", "<ALPHANUM>" });
}
public void testWikiURLs() throws Exception {
Reader reader = null;
String luceneResourcesWikiPage;
try {
reader = new InputStreamReader(getClass().getResourceAsStream
("LuceneResourcesWikiPage.html"), "UTF-8");
StringBuilder builder = new StringBuilder();
char[] buffer = new char[1024];
int numCharsRead;
while (-1 != (numCharsRead = reader.read(buffer))) {
builder.append(buffer, 0, numCharsRead);
}
luceneResourcesWikiPage = builder.toString();
} finally {
if (null != reader) {
reader.close();
}
}
assertTrue(null != luceneResourcesWikiPage
&& luceneResourcesWikiPage.length() > 0);
BufferedReader bufferedReader = null;
String[] urls;
try {
List<String> urlList = new ArrayList<String>();
bufferedReader = new BufferedReader(new InputStreamReader
(getClass().getResourceAsStream("LuceneResourcesWikiPageURLs.txt"), "UTF-8"));
String line;
while (null != (line = bufferedReader.readLine())) {
line = line.trim();
if (line.length() > 0) {
urlList.add(line);
}
}
urls = urlList.toArray(new String[urlList.size()]);
} finally {
if (null != bufferedReader) {
bufferedReader.close();
}
}
assertTrue(null != urls && urls.length > 0);
BaseTokenStreamTestCase.assertAnalyzesTo
(urlAnalyzer, luceneResourcesWikiPage, urls);
}
public void testEmails() throws Exception {
Reader reader = null;
String randomTextWithEmails;
try {
reader = new InputStreamReader(getClass().getResourceAsStream
("random.text.with.email.addresses.txt"), "UTF-8");
StringBuilder builder = new StringBuilder();
char[] buffer = new char[1024];
int numCharsRead;
while (-1 != (numCharsRead = reader.read(buffer))) {
builder.append(buffer, 0, numCharsRead);
}
randomTextWithEmails = builder.toString();
} finally {
if (null != reader) {
reader.close();
}
}
assertTrue(null != randomTextWithEmails
&& randomTextWithEmails.length() > 0);
BufferedReader bufferedReader = null;
String[] emails;
try {
List<String> emailList = new ArrayList<String>();
bufferedReader = new BufferedReader(new InputStreamReader
(getClass().getResourceAsStream
("email.addresses.from.random.text.with.email.addresses.txt"), "UTF-8"));
String line;
while (null != (line = bufferedReader.readLine())) {
line = line.trim();
if (line.length() > 0) {
emailList.add(line);
}
}
emails = emailList.toArray(new String[emailList.size()]);
} finally {
if (null != bufferedReader) {
bufferedReader.close();
}
}
assertTrue(null != emails && emails.length > 0);
BaseTokenStreamTestCase.assertAnalyzesTo
(emailAnalyzer, randomTextWithEmails, emails);
}
public void testMailtoSchemeEmails () throws Exception {
// See LUCENE-3880
BaseTokenStreamTestCase.assertAnalyzesTo(a, "mailto:[email protected]",
new String[] {"mailto", "[email protected]"},
new String[] { "<ALPHANUM>", "<EMAIL>" });
// TODO: Support full mailto: scheme URIs. See RFC 6068: http://tools.ietf.org/html/rfc6068
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "mailto:[email protected],[email protected][email protected]"
+ "&subject=Subjectivity&body=Corpusivity%20or%20something%20like%20that",
new String[] { "mailto",
"[email protected]",
// TODO: recognize ',' address delimiter. Also, see examples of ';' delimiter use at: http://www.mailto.co.uk/
",[email protected]",
"[email protected]", // TODO: split field keys/values
"subject", "Subjectivity",
"body", "Corpusivity", "20or", "20something","20like", "20that" }, // TODO: Hex decoding + re-tokenization
new String[] { "<ALPHANUM>",
"<EMAIL>",
"<EMAIL>",
"<EMAIL>",
"<ALPHANUM>", "<ALPHANUM>",
"<ALPHANUM>", "<ALPHANUM>", "<ALPHANUM>", "<ALPHANUM>", "<ALPHANUM>", "<ALPHANUM>" });
}
public void testURLs() throws Exception {
Reader reader = null;
String randomTextWithURLs;
try {
reader = new InputStreamReader(getClass().getResourceAsStream
("random.text.with.urls.txt"), "UTF-8");
StringBuilder builder = new StringBuilder();
char[] buffer = new char[1024];
int numCharsRead;
while (-1 != (numCharsRead = reader.read(buffer))) {
builder.append(buffer, 0, numCharsRead);
}
randomTextWithURLs = builder.toString();
} finally {
if (null != reader) {
reader.close();
}
}
assertTrue(null != randomTextWithURLs
&& randomTextWithURLs.length() > 0);
BufferedReader bufferedReader = null;
String[] urls;
try {
List<String> urlList = new ArrayList<String>();
bufferedReader = new BufferedReader(new InputStreamReader
(getClass().getResourceAsStream
("urls.from.random.text.with.urls.txt"), "UTF-8"));
String line;
while (null != (line = bufferedReader.readLine())) {
line = line.trim();
if (line.length() > 0) {
urlList.add(line);
}
}
urls = urlList.toArray(new String[urlList.size()]);
} finally {
if (null != bufferedReader) {
bufferedReader.close();
}
}
assertTrue(null != urls && urls.length > 0);
BaseTokenStreamTestCase.assertAnalyzesTo
(urlAnalyzer, randomTextWithURLs, urls);
}
public void testUnicodeWordBreaks() throws Exception {
WordBreakTestUnicode_6_3_0 wordBreakTest = new WordBreakTestUnicode_6_3_0();
wordBreakTest.test(a);
}
public void testSupplementary() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "𩬅艱鍟䇹愯瀛",
new String[] {"𩬅", "艱", "鍟", "䇹", "愯", "瀛"},
new String[] { "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>" });
}
public void testKorean() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "훈민정음",
new String[] { "훈민정음" },
new String[] { "<HANGUL>" });
}
public void testJapanese() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "仮名遣い カタカナ",
new String[] { "仮", "名", "遣", "い", "カタカナ" },
new String[] { "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<HIRAGANA>", "<KATAKANA>" });
}
public void testCombiningMarks() throws Exception {
checkOneTerm(a, "ざ", "ざ"); // hiragana
checkOneTerm(a, "ザ", "ザ"); // katakana
checkOneTerm(a, "壹゙", "壹゙"); // ideographic
checkOneTerm(a, "아゙", "아゙"); // hangul
}
/**
* Multiple consecutive chars in \p{Word_Break = MidLetter},
* \p{Word_Break = MidNumLet}, and/or \p{Word_Break = MidNum}
* should trigger a token split.
*/
public void testMid() throws Exception {
// ':' is in \p{WB:MidLetter}, which should trigger a split unless there is a Letter char on both sides
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A:B", new String[] { "A:B" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A::B", new String[] { "A", "B" });
// '.' is in \p{WB:MidNumLet}, which should trigger a split unless there is a Letter or Numeric char on both sides
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1.2", new String[] { "1.2" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A.B", new String[] { "A.B" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1..2", new String[] { "1", "2" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A..B", new String[] { "A", "B" });
// ',' is in \p{WB:MidNum}, which should trigger a split unless there is a Numeric char on both sides
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1,2", new String[] { "1,2" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1,,2", new String[] { "1", "2" });
// Mixed consecutive \p{WB:MidLetter} and \p{WB:MidNumLet} should trigger a split
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A.:B", new String[] { "A", "B" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A:.B", new String[] { "A", "B" });
// Mixed consecutive \p{WB:MidNum} and \p{WB:MidNumLet} should trigger a split
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1,.2", new String[] { "1", "2" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1.,2", new String[] { "1", "2" });
}
/** blast some random strings through the analyzer */
public void testRandomStrings() throws Exception {
checkRandomData(random(), a, 1000*RANDOM_MULTIPLIER);
}
/** blast some random large strings through the analyzer */
public void testRandomHugeStrings() throws Exception {
Random random = random();
checkRandomData(random, a, 100*RANDOM_MULTIPLIER, 8192);
}
}
| tdurieux/pattern-detector-experiment | benchmark/icse15/1569831/buggy-version/lucene/dev/trunk/lucene/analysis/common/src/test/org/apache/lucene/analysis/core/TestUAX29URLEmailTokenizer.java |
43,281 | package org.apache.lucene.analysis.core;
/*
* 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.
*/
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.Arrays;
import java.util.Random;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.BaseTokenStreamTestCase;
import org.apache.lucene.analysis.MockGraphTokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.analysis.standard.StandardTokenizer;
import org.apache.lucene.util.Version;
public class TestStandardAnalyzer extends BaseTokenStreamTestCase {
public void testHugeDoc() throws IOException {
StringBuilder sb = new StringBuilder();
char whitespace[] = new char[4094];
Arrays.fill(whitespace, ' ');
sb.append(whitespace);
sb.append("testing 1234");
String input = sb.toString();
StandardTokenizer tokenizer = new StandardTokenizer(TEST_VERSION_CURRENT);
tokenizer.setReader(new StringReader(input));
BaseTokenStreamTestCase.assertTokenStreamContents(tokenizer, new String[] { "testing", "1234" });
}
private Analyzer a = new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName) {
Tokenizer tokenizer = new StandardTokenizer(TEST_VERSION_CURRENT);
return new TokenStreamComponents(tokenizer);
}
};
public void testArmenian() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Վիքիպեդիայի 13 միլիոն հոդվածները (4,600` հայերեն վիքիպեդիայում) գրվել են կամավորների կողմից ու համարյա բոլոր հոդվածները կարող է խմբագրել ցանկաց մարդ ով կարող է բացել Վիքիպեդիայի կայքը։",
new String[] { "Վիքիպեդիայի", "13", "միլիոն", "հոդվածները", "4,600", "հայերեն", "վիքիպեդիայում", "գրվել", "են", "կամավորների", "կողմից",
"ու", "համարյա", "բոլոր", "հոդվածները", "կարող", "է", "խմբագրել", "ցանկաց", "մարդ", "ով", "կարող", "է", "բացել", "Վիքիպեդիայի", "կայքը" } );
}
public void testAmharic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ዊኪፔድያ የባለ ብዙ ቋንቋ የተሟላ ትክክለኛና ነጻ መዝገበ ዕውቀት (ኢንሳይክሎፒዲያ) ነው። ማንኛውም",
new String[] { "ዊኪፔድያ", "የባለ", "ብዙ", "ቋንቋ", "የተሟላ", "ትክክለኛና", "ነጻ", "መዝገበ", "ዕውቀት", "ኢንሳይክሎፒዲያ", "ነው", "ማንኛውም" } );
}
public void testArabic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "الفيلم الوثائقي الأول عن ويكيبيديا يسمى \"الحقيقة بالأرقام: قصة ويكيبيديا\" (بالإنجليزية: Truth in Numbers: The Wikipedia Story)، سيتم إطلاقه في 2008.",
new String[] { "الفيلم", "الوثائقي", "الأول", "عن", "ويكيبيديا", "يسمى", "الحقيقة", "بالأرقام", "قصة", "ويكيبيديا",
"بالإنجليزية", "Truth", "in", "Numbers", "The", "Wikipedia", "Story", "سيتم", "إطلاقه", "في", "2008" } );
}
public void testAramaic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ܘܝܩܝܦܕܝܐ (ܐܢܓܠܝܐ: Wikipedia) ܗܘ ܐܝܢܣܩܠܘܦܕܝܐ ܚܐܪܬܐ ܕܐܢܛܪܢܛ ܒܠܫܢ̈ܐ ܣܓܝܐ̈ܐ܂ ܫܡܗ ܐܬܐ ܡܢ ܡ̈ܠܬܐ ܕ\"ܘܝܩܝ\" ܘ\"ܐܝܢܣܩܠܘܦܕܝܐ\"܀",
new String[] { "ܘܝܩܝܦܕܝܐ", "ܐܢܓܠܝܐ", "Wikipedia", "ܗܘ", "ܐܝܢܣܩܠܘܦܕܝܐ", "ܚܐܪܬܐ", "ܕܐܢܛܪܢܛ", "ܒܠܫܢ̈ܐ", "ܣܓܝܐ̈ܐ", "ܫܡܗ",
"ܐܬܐ", "ܡܢ", "ܡ̈ܠܬܐ", "ܕ", "ܘܝܩܝ", "ܘ", "ܐܝܢܣܩܠܘܦܕܝܐ"});
}
public void testBengali() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "এই বিশ্বকোষ পরিচালনা করে উইকিমিডিয়া ফাউন্ডেশন (একটি অলাভজনক সংস্থা)। উইকিপিডিয়ার শুরু ১৫ জানুয়ারি, ২০০১ সালে। এখন পর্যন্ত ২০০টিরও বেশী ভাষায় উইকিপিডিয়া রয়েছে।",
new String[] { "এই", "বিশ্বকোষ", "পরিচালনা", "করে", "উইকিমিডিয়া", "ফাউন্ডেশন", "একটি", "অলাভজনক", "সংস্থা", "উইকিপিডিয়ার",
"শুরু", "১৫", "জানুয়ারি", "২০০১", "সালে", "এখন", "পর্যন্ত", "২০০টিরও", "বেশী", "ভাষায়", "উইকিপিডিয়া", "রয়েছে" });
}
public void testFarsi() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ویکی پدیای انگلیسی در تاریخ ۲۵ دی ۱۳۷۹ به صورت مکملی برای دانشنامهٔ تخصصی نوپدیا نوشته شد.",
new String[] { "ویکی", "پدیای", "انگلیسی", "در", "تاریخ", "۲۵", "دی", "۱۳۷۹", "به", "صورت", "مکملی",
"برای", "دانشنامهٔ", "تخصصی", "نوپدیا", "نوشته", "شد" });
}
public void testGreek() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Γράφεται σε συνεργασία από εθελοντές με το λογισμικό wiki, κάτι που σημαίνει ότι άρθρα μπορεί να προστεθούν ή να αλλάξουν από τον καθένα.",
new String[] { "Γράφεται", "σε", "συνεργασία", "από", "εθελοντές", "με", "το", "λογισμικό", "wiki", "κάτι", "που",
"σημαίνει", "ότι", "άρθρα", "μπορεί", "να", "προστεθούν", "ή", "να", "αλλάξουν", "από", "τον", "καθένα" });
}
public void testThai() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "การที่ได้ต้องแสดงว่างานดี. แล้วเธอจะไปไหน? ๑๒๓๔",
new String[] { "การที่ได้ต้องแสดงว่างานดี", "แล้วเธอจะไปไหน", "๑๒๓๔" });
}
public void testLao() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ສາທາລະນະລັດ ປະຊາທິປະໄຕ ປະຊາຊົນລາວ",
new String[] { "ສາທາລະນະລັດ", "ປະຊາທິປະໄຕ", "ປະຊາຊົນລາວ" });
}
public void testTibetan() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "སྣོན་མཛོད་དང་ལས་འདིས་བོད་ཡིག་མི་ཉམས་གོང་འཕེལ་དུ་གཏོང་བར་ཧ་ཅང་དགེ་མཚན་མཆིས་སོ། །",
new String[] { "སྣོན", "མཛོད", "དང", "ལས", "འདིས", "བོད", "ཡིག",
"མི", "ཉམས", "གོང", "འཕེལ", "དུ", "གཏོང", "བར",
"ཧ", "ཅང", "དགེ", "མཚན", "མཆིས", "སོ" });
}
/*
* For chinese, tokenize as char (these can later form bigrams or whatever)
*/
public void testChinese() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "我是中国人。 1234 Tests ",
new String[] { "我", "是", "中", "国", "人", "1234", "Tests"});
}
public void testEmpty() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "", new String[] {});
BaseTokenStreamTestCase.assertAnalyzesTo(a, ".", new String[] {});
BaseTokenStreamTestCase.assertAnalyzesTo(a, " ", new String[] {});
}
/* test various jira issues this analyzer is related to */
public void testLUCENE1545() throws Exception {
/*
* Standard analyzer does not correctly tokenize combining character U+0364 COMBINING LATIN SMALL LETTRE E.
* The word "moͤchte" is incorrectly tokenized into "mo" "chte", the combining character is lost.
* Expected result is only on token "moͤchte".
*/
BaseTokenStreamTestCase.assertAnalyzesTo(a, "moͤchte", new String[] { "moͤchte" });
}
/* Tests from StandardAnalyzer, just to show behavior is similar */
public void testAlphanumericSA() throws Exception {
// alphanumeric tokens
BaseTokenStreamTestCase.assertAnalyzesTo(a, "B2B", new String[]{"B2B"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "2B", new String[]{"2B"});
}
public void testDelimitersSA() throws Exception {
// other delimiters: "-", "/", ","
BaseTokenStreamTestCase.assertAnalyzesTo(a, "some-dashed-phrase", new String[]{"some", "dashed", "phrase"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "dogs,chase,cats", new String[]{"dogs", "chase", "cats"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ac/dc", new String[]{"ac", "dc"});
}
public void testApostrophesSA() throws Exception {
// internal apostrophes: O'Reilly, you're, O'Reilly's
BaseTokenStreamTestCase.assertAnalyzesTo(a, "O'Reilly", new String[]{"O'Reilly"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "you're", new String[]{"you're"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "she's", new String[]{"she's"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Jim's", new String[]{"Jim's"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "don't", new String[]{"don't"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "O'Reilly's", new String[]{"O'Reilly's"});
}
public void testNumericSA() throws Exception {
// floating point, serial, model numbers, ip addresses, etc.
BaseTokenStreamTestCase.assertAnalyzesTo(a, "21.35", new String[]{"21.35"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "R2D2 C3PO", new String[]{"R2D2", "C3PO"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "216.239.63.104", new String[]{"216.239.63.104"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "216.239.63.104", new String[]{"216.239.63.104"});
}
public void testTextWithNumbersSA() throws Exception {
// numbers
BaseTokenStreamTestCase.assertAnalyzesTo(a, "David has 5000 bones", new String[]{"David", "has", "5000", "bones"});
}
public void testVariousTextSA() throws Exception {
// various
BaseTokenStreamTestCase.assertAnalyzesTo(a, "C embedded developers wanted", new String[]{"C", "embedded", "developers", "wanted"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "foo bar FOO BAR", new String[]{"foo", "bar", "FOO", "BAR"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "foo bar . FOO <> BAR", new String[]{"foo", "bar", "FOO", "BAR"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "\"QUOTED\" word", new String[]{"QUOTED", "word"});
}
public void testKoreanSA() throws Exception {
// Korean words
BaseTokenStreamTestCase.assertAnalyzesTo(a, "안녕하세요 한글입니다", new String[]{"안녕하세요", "한글입니다"});
}
public void testOffsets() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "David has 5000 bones",
new String[] {"David", "has", "5000", "bones"},
new int[] {0, 6, 10, 15},
new int[] {5, 9, 14, 20});
}
public void testTypes() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "David has 5000 bones",
new String[] {"David", "has", "5000", "bones"},
new String[] { "<ALPHANUM>", "<ALPHANUM>", "<NUM>", "<ALPHANUM>" });
}
public void testUnicodeWordBreaks() throws Exception {
WordBreakTestUnicode_6_3_0 wordBreakTest = new WordBreakTestUnicode_6_3_0();
wordBreakTest.test(a);
}
public void testSupplementary() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "𩬅艱鍟䇹愯瀛",
new String[] {"𩬅", "艱", "鍟", "䇹", "愯", "瀛"},
new String[] { "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>" });
}
public void testKorean() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "훈민정음",
new String[] { "훈민정음" },
new String[] { "<HANGUL>" });
}
public void testJapanese() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "仮名遣い カタカナ",
new String[] { "仮", "名", "遣", "い", "カタカナ" },
new String[] { "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<HIRAGANA>", "<KATAKANA>" });
}
public void testCombiningMarks() throws Exception {
checkOneTerm(a, "ざ", "ざ"); // hiragana
checkOneTerm(a, "ザ", "ザ"); // katakana
checkOneTerm(a, "壹゙", "壹゙"); // ideographic
checkOneTerm(a, "아゙", "아゙"); // hangul
}
/**
* Multiple consecutive chars in \p{WB:MidLetter}, \p{WB:MidNumLet},
* and/or \p{MidNum} should trigger a token split.
*/
public void testMid() throws Exception {
// ':' is in \p{WB:MidLetter}, which should trigger a split unless there is a Letter char on both sides
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A:B", new String[] { "A:B" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A::B", new String[] { "A", "B" });
// '.' is in \p{WB:MidNumLet}, which should trigger a split unless there is a Letter or Numeric char on both sides
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1.2", new String[] { "1.2" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A.B", new String[] { "A.B" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1..2", new String[] { "1", "2" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A..B", new String[] { "A", "B" });
// ',' is in \p{WB:MidNum}, which should trigger a split unless there is a Numeric char on both sides
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1,2", new String[] { "1,2" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1,,2", new String[] { "1", "2" });
// Mixed consecutive \p{WB:MidLetter} and \p{WB:MidNumLet} should trigger a split
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A.:B", new String[] { "A", "B" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A:.B", new String[] { "A", "B" });
// Mixed consecutive \p{WB:MidNum} and \p{WB:MidNumLet} should trigger a split
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1,.2", new String[] { "1", "2" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1.,2", new String[] { "1", "2" });
}
/** blast some random strings through the analyzer */
public void testRandomStrings() throws Exception {
checkRandomData(random(), new StandardAnalyzer(TEST_VERSION_CURRENT), 1000*RANDOM_MULTIPLIER);
}
/** blast some random large strings through the analyzer */
public void testRandomHugeStrings() throws Exception {
Random random = random();
checkRandomData(random, new StandardAnalyzer(TEST_VERSION_CURRENT), 100*RANDOM_MULTIPLIER, 8192);
}
// Adds random graph after:
public void testRandomHugeStringsGraphAfter() throws Exception {
Random random = random();
checkRandomData(random,
new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName) {
Tokenizer tokenizer = new StandardTokenizer(TEST_VERSION_CURRENT);
TokenStream tokenStream = new MockGraphTokenFilter(random(), tokenizer);
return new TokenStreamComponents(tokenizer, tokenStream);
}
},
100*RANDOM_MULTIPLIER, 8192);
}
}
| tdurieux/pattern-detector-experiment | benchmark/icse15/1569831/buggy-version/lucene/dev/trunk/lucene/analysis/common/src/test/org/apache/lucene/analysis/core/TestStandardAnalyzer.java |
43,282 | package org.apache.lucene.analysis.core;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.BaseTokenStreamTestCase;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.standard.StandardTokenizer;
import org.apache.lucene.analysis.tokenattributes.TypeAttribute;
import org.apache.lucene.analysis.util.ReusableAnalyzerBase;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 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.
*/
public class TestStandardAnalyzer extends BaseTokenStreamTestCase {
public void testHugeDoc() throws IOException {
StringBuilder sb = new StringBuilder();
char whitespace[] = new char[4094];
Arrays.fill(whitespace, ' ');
sb.append(whitespace);
sb.append("testing 1234");
String input = sb.toString();
StandardTokenizer tokenizer = new StandardTokenizer(TEST_VERSION_CURRENT, new StringReader(input));
BaseTokenStreamTestCase.assertTokenStreamContents(tokenizer, new String[] { "testing", "1234" });
}
private Analyzer a = new ReusableAnalyzerBase() {
@Override
protected TokenStreamComponents createComponents
(String fieldName, Reader reader) {
Tokenizer tokenizer = new StandardTokenizer(TEST_VERSION_CURRENT, reader);
return new TokenStreamComponents(tokenizer);
}
};
/** Passes through tokens with type "<URL>" and blocks all other types. */
private class URLFilter extends TokenFilter {
private final TypeAttribute typeAtt = addAttribute(TypeAttribute.class);
public URLFilter(TokenStream in) {
super(in);
}
@Override
public final boolean incrementToken() throws java.io.IOException {
boolean isTokenAvailable = false;
while (input.incrementToken()) {
if (typeAtt.type() == StandardTokenizer.TOKEN_TYPES[StandardTokenizer.URL]) {
isTokenAvailable = true;
break;
}
}
return isTokenAvailable;
}
}
/** Passes through tokens with type "<EMAIL>" and blocks all other types. */
private class EmailFilter extends TokenFilter {
private final TypeAttribute typeAtt = addAttribute(TypeAttribute.class);
public EmailFilter(TokenStream in) {
super(in);
}
@Override
public final boolean incrementToken() throws java.io.IOException {
boolean isTokenAvailable = false;
while (input.incrementToken()) {
if (typeAtt.type() == StandardTokenizer.TOKEN_TYPES[StandardTokenizer.EMAIL]) {
isTokenAvailable = true;
break;
}
}
return isTokenAvailable;
}
}
private Analyzer urlAnalyzer = new ReusableAnalyzerBase() {
@Override
protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
StandardTokenizer tokenizer = new StandardTokenizer(TEST_VERSION_CURRENT, reader);
tokenizer.setMaxTokenLength(Integer.MAX_VALUE); // Tokenize arbitrary length URLs
TokenFilter filter = new URLFilter(tokenizer);
return new TokenStreamComponents(tokenizer, filter);
}
};
private Analyzer emailAnalyzer = new ReusableAnalyzerBase() {
@Override
protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
Tokenizer tokenizer = new StandardTokenizer(TEST_VERSION_CURRENT, reader);
TokenFilter filter = new EmailFilter(tokenizer);
return new TokenStreamComponents(tokenizer, filter);
}
};
public void testArmenian() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Վիքիպեդիայի 13 միլիոն հոդվածները (4,600` հայերեն վիքիպեդիայում) գրվել են կամավորների կողմից ու համարյա բոլոր հոդվածները կարող է խմբագրել ցանկաց մարդ ով կարող է բացել Վիքիպեդիայի կայքը։",
new String[] { "Վիքիպեդիայի", "13", "միլիոն", "հոդվածները", "4,600", "հայերեն", "վիքիպեդիայում", "գրվել", "են", "կամավորների", "կողմից",
"ու", "համարյա", "բոլոր", "հոդվածները", "կարող", "է", "խմբագրել", "ցանկաց", "մարդ", "ով", "կարող", "է", "բացել", "Վիքիպեդիայի", "կայքը" } );
}
public void testAmharic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ዊኪፔድያ የባለ ብዙ ቋንቋ የተሟላ ትክክለኛና ነጻ መዝገበ ዕውቀት (ኢንሳይክሎፒዲያ) ነው። ማንኛውም",
new String[] { "ዊኪፔድያ", "የባለ", "ብዙ", "ቋንቋ", "የተሟላ", "ትክክለኛና", "ነጻ", "መዝገበ", "ዕውቀት", "ኢንሳይክሎፒዲያ", "ነው", "ማንኛውም" } );
}
public void testArabic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "الفيلم الوثائقي الأول عن ويكيبيديا يسمى \"الحقيقة بالأرقام: قصة ويكيبيديا\" (بالإنجليزية: Truth in Numbers: The Wikipedia Story)، سيتم إطلاقه في 2008.",
new String[] { "الفيلم", "الوثائقي", "الأول", "عن", "ويكيبيديا", "يسمى", "الحقيقة", "بالأرقام", "قصة", "ويكيبيديا",
"بالإنجليزية", "Truth", "in", "Numbers", "The", "Wikipedia", "Story", "سيتم", "إطلاقه", "في", "2008" } );
}
public void testAramaic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ܘܝܩܝܦܕܝܐ (ܐܢܓܠܝܐ: Wikipedia) ܗܘ ܐܝܢܣܩܠܘܦܕܝܐ ܚܐܪܬܐ ܕܐܢܛܪܢܛ ܒܠܫܢ̈ܐ ܣܓܝܐ̈ܐ܂ ܫܡܗ ܐܬܐ ܡܢ ܡ̈ܠܬܐ ܕ\"ܘܝܩܝ\" ܘ\"ܐܝܢܣܩܠܘܦܕܝܐ\"܀",
new String[] { "ܘܝܩܝܦܕܝܐ", "ܐܢܓܠܝܐ", "Wikipedia", "ܗܘ", "ܐܝܢܣܩܠܘܦܕܝܐ", "ܚܐܪܬܐ", "ܕܐܢܛܪܢܛ", "ܒܠܫܢ̈ܐ", "ܣܓܝܐ̈ܐ", "ܫܡܗ",
"ܐܬܐ", "ܡܢ", "ܡ̈ܠܬܐ", "ܕ", "ܘܝܩܝ", "ܘ", "ܐܝܢܣܩܠܘܦܕܝܐ"});
}
public void testBengali() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "এই বিশ্বকোষ পরিচালনা করে উইকিমিডিয়া ফাউন্ডেশন (একটি অলাভজনক সংস্থা)। উইকিপিডিয়ার শুরু ১৫ জানুয়ারি, ২০০১ সালে। এখন পর্যন্ত ২০০টিরও বেশী ভাষায় উইকিপিডিয়া রয়েছে।",
new String[] { "এই", "বিশ্বকোষ", "পরিচালনা", "করে", "উইকিমিডিয়া", "ফাউন্ডেশন", "একটি", "অলাভজনক", "সংস্থা", "উইকিপিডিয়ার",
"শুরু", "১৫", "জানুয়ারি", "২০০১", "সালে", "এখন", "পর্যন্ত", "২০০টিরও", "বেশী", "ভাষায়", "উইকিপিডিয়া", "রয়েছে" });
}
public void testFarsi() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ویکی پدیای انگلیسی در تاریخ ۲۵ دی ۱۳۷۹ به صورت مکملی برای دانشنامهٔ تخصصی نوپدیا نوشته شد.",
new String[] { "ویکی", "پدیای", "انگلیسی", "در", "تاریخ", "۲۵", "دی", "۱۳۷۹", "به", "صورت", "مکملی",
"برای", "دانشنامهٔ", "تخصصی", "نوپدیا", "نوشته", "شد" });
}
public void testGreek() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Γράφεται σε συνεργασία από εθελοντές με το λογισμικό wiki, κάτι που σημαίνει ότι άρθρα μπορεί να προστεθούν ή να αλλάξουν από τον καθένα.",
new String[] { "Γράφεται", "σε", "συνεργασία", "από", "εθελοντές", "με", "το", "λογισμικό", "wiki", "κάτι", "που",
"σημαίνει", "ότι", "άρθρα", "μπορεί", "να", "προστεθούν", "ή", "να", "αλλάξουν", "από", "τον", "καθένα" });
}
public void testThai() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "การที่ได้ต้องแสดงว่างานดี. แล้วเธอจะไปไหน? ๑๒๓๔",
new String[] { "การที่ได้ต้องแสดงว่างานดี", "แล้วเธอจะไปไหน", "๑๒๓๔" });
}
public void testLao() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ສາທາລະນະລັດ ປະຊາທິປະໄຕ ປະຊາຊົນລາວ",
new String[] { "ສາທາລະນະລັດ", "ປະຊາທິປະໄຕ", "ປະຊາຊົນລາວ" });
}
public void testTibetan() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "སྣོན་མཛོད་དང་ལས་འདིས་བོད་ཡིག་མི་ཉམས་གོང་འཕེལ་དུ་གཏོང་བར་ཧ་ཅང་དགེ་མཚན་མཆིས་སོ། །",
new String[] { "སྣོན", "མཛོད", "དང", "ལས", "འདིས", "བོད", "ཡིག",
"མི", "ཉམས", "གོང", "འཕེལ", "དུ", "གཏོང", "བར",
"ཧ", "ཅང", "དགེ", "མཚན", "མཆིས", "སོ" });
}
/*
* For chinese, tokenize as char (these can later form bigrams or whatever)
*/
public void testChinese() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "我是中国人。 1234 Tests ",
new String[] { "我", "是", "中", "国", "人", "1234", "Tests"});
}
public void testEmpty() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "", new String[] {});
BaseTokenStreamTestCase.assertAnalyzesTo(a, ".", new String[] {});
BaseTokenStreamTestCase.assertAnalyzesTo(a, " ", new String[] {});
}
/* test various jira issues this analyzer is related to */
public void testLUCENE1545() throws Exception {
/*
* Standard analyzer does not correctly tokenize combining character U+0364 COMBINING LATIN SMALL LETTRE E.
* The word "moͤchte" is incorrectly tokenized into "mo" "chte", the combining character is lost.
* Expected result is only on token "moͤchte".
*/
BaseTokenStreamTestCase.assertAnalyzesTo(a, "moͤchte", new String[] { "moͤchte" });
}
/* Tests from StandardAnalyzer, just to show behavior is similar */
public void testAlphanumericSA() throws Exception {
// alphanumeric tokens
BaseTokenStreamTestCase.assertAnalyzesTo(a, "B2B", new String[]{"B2B"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "2B", new String[]{"2B"});
}
public void testDelimitersSA() throws Exception {
// other delimiters: "-", "/", ","
BaseTokenStreamTestCase.assertAnalyzesTo(a, "some-dashed-phrase", new String[]{"some", "dashed", "phrase"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "dogs,chase,cats", new String[]{"dogs", "chase", "cats"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ac/dc", new String[]{"ac", "dc"});
}
public void testApostrophesSA() throws Exception {
// internal apostrophes: O'Reilly, you're, O'Reilly's
BaseTokenStreamTestCase.assertAnalyzesTo(a, "O'Reilly", new String[]{"O'Reilly"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "you're", new String[]{"you're"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "she's", new String[]{"she's"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Jim's", new String[]{"Jim's"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "don't", new String[]{"don't"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "O'Reilly's", new String[]{"O'Reilly's"});
}
public void testNumericSA() throws Exception {
// floating point, serial, model numbers, ip addresses, etc.
BaseTokenStreamTestCase.assertAnalyzesTo(a, "21.35", new String[]{"21.35"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "R2D2 C3PO", new String[]{"R2D2", "C3PO"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "216.239.63.104", new String[]{"216.239.63.104"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "216.239.63.104", new String[]{"216.239.63.104"});
}
public void testTextWithNumbersSA() throws Exception {
// numbers
BaseTokenStreamTestCase.assertAnalyzesTo(a, "David has 5000 bones", new String[]{"David", "has", "5000", "bones"});
}
public void testVariousTextSA() throws Exception {
// various
BaseTokenStreamTestCase.assertAnalyzesTo(a, "C embedded developers wanted", new String[]{"C", "embedded", "developers", "wanted"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "foo bar FOO BAR", new String[]{"foo", "bar", "FOO", "BAR"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "foo bar . FOO <> BAR", new String[]{"foo", "bar", "FOO", "BAR"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "\"QUOTED\" word", new String[]{"QUOTED", "word"});
}
public void testKoreanSA() throws Exception {
// Korean words
BaseTokenStreamTestCase.assertAnalyzesTo(a, "안녕하세요 한글입니다", new String[]{"안녕하세요", "한글입니다"});
}
public void testOffsets() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "David has 5000 bones",
new String[] {"David", "has", "5000", "bones"},
new int[] {0, 6, 10, 15},
new int[] {5, 9, 14, 20});
}
public void testTypes() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "David has 5000 bones",
new String[] {"David", "has", "5000", "bones"},
new String[] { "<ALPHANUM>", "<ALPHANUM>", "<NUM>", "<ALPHANUM>" });
}
public void testWikiURLs() throws Exception {
Reader reader = null;
String luceneResourcesWikiPage;
try {
reader = new InputStreamReader
(getClass().getResourceAsStream("LuceneResourcesWikiPage.html"), "UTF-8");
StringBuilder builder = new StringBuilder();
char[] buffer = new char[1024];
int numCharsRead;
while (-1 != (numCharsRead = reader.read(buffer))) {
builder.append(buffer, 0, numCharsRead);
}
luceneResourcesWikiPage = builder.toString();
} finally {
if (null != reader) {
reader.close();
}
}
assertTrue(null != luceneResourcesWikiPage
&& luceneResourcesWikiPage.length() > 0);
BufferedReader bufferedReader = null;
String[] urls;
try {
List<String> urlList = new ArrayList<String>();
bufferedReader = new BufferedReader(new InputStreamReader
(getClass().getResourceAsStream("LuceneResourcesWikiPageURLs.txt"), "UTF-8"));
String line;
while (null != (line = bufferedReader.readLine())) {
line = line.trim();
if (line.length() > 0) {
urlList.add(line);
}
}
urls = urlList.toArray(new String[urlList.size()]);
} finally {
if (null != bufferedReader) {
bufferedReader.close();
}
}
assertTrue(null != urls && urls.length > 0);
BaseTokenStreamTestCase.assertAnalyzesTo
(urlAnalyzer, luceneResourcesWikiPage, urls);
}
public void testEmails() throws Exception {
Reader reader = null;
String randomTextWithEmails;
try {
reader = new InputStreamReader
(getClass().getResourceAsStream("random.text.with.email.addresses.txt"), "UTF-8");
StringBuilder builder = new StringBuilder();
char[] buffer = new char[1024];
int numCharsRead;
while (-1 != (numCharsRead = reader.read(buffer))) {
builder.append(buffer, 0, numCharsRead);
}
randomTextWithEmails = builder.toString();
} finally {
if (null != reader) {
reader.close();
}
}
assertTrue(null != randomTextWithEmails
&& randomTextWithEmails.length() > 0);
BufferedReader bufferedReader = null;
String[] emails;
try {
List<String> emailList = new ArrayList<String>();
bufferedReader = new BufferedReader(new InputStreamReader
(getClass().getResourceAsStream("email.addresses.from.random.text.with.email.addresses.txt"), "UTF-8"));
String line;
while (null != (line = bufferedReader.readLine())) {
line = line.trim();
if (line.length() > 0) {
emailList.add(line);
}
}
emails = emailList.toArray(new String[emailList.size()]);
} finally {
if (null != bufferedReader) {
bufferedReader.close();
}
}
assertTrue(null != emails && emails.length > 0);
BaseTokenStreamTestCase.assertAnalyzesTo
(emailAnalyzer, randomTextWithEmails, emails);
}
public void testURLs() throws Exception {
Reader reader = null;
String randomTextWithURLs;
try {
reader = new InputStreamReader
(getClass().getResourceAsStream("random.text.with.urls.txt"), "UTF-8");
StringBuilder builder = new StringBuilder();
char[] buffer = new char[1024];
int numCharsRead;
while (-1 != (numCharsRead = reader.read(buffer))) {
builder.append(buffer, 0, numCharsRead);
}
randomTextWithURLs = builder.toString();
} finally {
if (null != reader) {
reader.close();
}
}
assertTrue(null != randomTextWithURLs
&& randomTextWithURLs.length() > 0);
BufferedReader bufferedReader = null;
String[] urls;
try {
List<String> urlList = new ArrayList<String>();
bufferedReader = new BufferedReader(new InputStreamReader
(getClass().getResourceAsStream("urls.from.random.text.with.urls.txt"), "UTF-8"));
String line;
while (null != (line = bufferedReader.readLine())) {
line = line.trim();
if (line.length() > 0) {
urlList.add(line);
}
}
urls = urlList.toArray(new String[urlList.size()]);
} finally {
if (null != bufferedReader) {
bufferedReader.close();
}
}
assertTrue(null != urls && urls.length > 0);
BaseTokenStreamTestCase.assertAnalyzesTo
(urlAnalyzer, randomTextWithURLs, urls);
}
public void testUnicodeWordBreaks() throws Exception {
WordBreakTestUnicode_6_0_0 wordBreakTest = new WordBreakTestUnicode_6_0_0();
wordBreakTest.test(a);
}
}
| erikhatcher/lucene-solr-svn | modules/analysis/common/src/test/org/apache/lucene/analysis/core/TestStandardAnalyzer.java |
43,285 | /*
* 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.
*/
package org.apache.lucene.analysis.icu.segmentation;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.BaseTokenStreamTestCase;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.icu.tokenattributes.ScriptAttribute;
import com.ibm.icu.lang.UScript;
import java.io.IOException;
import java.io.StringReader;
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
public class TestICUTokenizer extends BaseTokenStreamTestCase {
public void testHugeDoc() throws IOException {
StringBuilder sb = new StringBuilder();
char whitespace[] = new char[4094];
Arrays.fill(whitespace, ' ');
sb.append(whitespace);
sb.append("testing 1234");
String input = sb.toString();
ICUTokenizer tokenizer = new ICUTokenizer(newAttributeFactory(), new DefaultICUTokenizerConfig(false, true));
tokenizer.setReader(new StringReader(input));
assertTokenStreamContents(tokenizer, new String[] { "testing", "1234" });
}
public void testHugeTerm2() throws IOException {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 40960; i++) {
sb.append('a');
}
String input = sb.toString();
ICUTokenizer tokenizer = new ICUTokenizer(newAttributeFactory(), new DefaultICUTokenizerConfig(false, true));
tokenizer.setReader(new StringReader(input));
char token[] = new char[4096];
Arrays.fill(token, 'a');
String expectedToken = new String(token);
String expected[] = {
expectedToken, expectedToken, expectedToken,
expectedToken, expectedToken, expectedToken,
expectedToken, expectedToken, expectedToken,
expectedToken
};
assertTokenStreamContents(tokenizer, expected);
}
private Analyzer a;
@Override
public void setUp() throws Exception {
super.setUp();
a = new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName) {
Tokenizer tokenizer = new ICUTokenizer(newAttributeFactory(), new DefaultICUTokenizerConfig(false, true));
return new TokenStreamComponents(tokenizer);
}
};
}
@Override
public void tearDown() throws Exception {
a.close();
super.tearDown();
}
public void testArmenian() throws Exception {
assertAnalyzesTo(a, "Վիքիպեդիայի 13 միլիոն հոդվածները (4,600` հայերեն վիքիպեդիայում) գրվել են կամավորների կողմից ու համարյա բոլոր հոդվածները կարող է խմբագրել ցանկաց մարդ ով կարող է բացել Վիքիպեդիայի կայքը։",
new String[] { "Վիքիպեդիայի", "13", "միլիոն", "հոդվածները", "4,600", "հայերեն", "վիքիպեդիայում", "գրվել", "են", "կամավորների", "կողմից",
"ու", "համարյա", "բոլոր", "հոդվածները", "կարող", "է", "խմբագրել", "ցանկաց", "մարդ", "ով", "կարող", "է", "բացել", "Վիքիպեդիայի", "կայքը" } );
}
public void testAmharic() throws Exception {
assertAnalyzesTo(a, "ዊኪፔድያ የባለ ብዙ ቋንቋ የተሟላ ትክክለኛና ነጻ መዝገበ ዕውቀት (ኢንሳይክሎፒዲያ) ነው። ማንኛውም",
new String[] { "ዊኪፔድያ", "የባለ", "ብዙ", "ቋንቋ", "የተሟላ", "ትክክለኛና", "ነጻ", "መዝገበ", "ዕውቀት", "ኢንሳይክሎፒዲያ", "ነው", "ማንኛውም" } );
}
public void testArabic() throws Exception {
assertAnalyzesTo(a, "الفيلم الوثائقي الأول عن ويكيبيديا يسمى \"الحقيقة بالأرقام: قصة ويكيبيديا\" (بالإنجليزية: Truth in Numbers: The Wikipedia Story)، سيتم إطلاقه في 2008.",
new String[] { "الفيلم", "الوثائقي", "الأول", "عن", "ويكيبيديا", "يسمى", "الحقيقة", "بالأرقام", "قصة", "ويكيبيديا",
"بالإنجليزية", "Truth", "in", "Numbers", "The", "Wikipedia", "Story", "سيتم", "إطلاقه", "في", "2008" } );
}
public void testAramaic() throws Exception {
assertAnalyzesTo(a, "ܘܝܩܝܦܕܝܐ (ܐܢܓܠܝܐ: Wikipedia) ܗܘ ܐܝܢܣܩܠܘܦܕܝܐ ܚܐܪܬܐ ܕܐܢܛܪܢܛ ܒܠܫܢ̈ܐ ܣܓܝܐ̈ܐ܂ ܫܡܗ ܐܬܐ ܡܢ ܡ̈ܠܬܐ ܕ\"ܘܝܩܝ\" ܘ\"ܐܝܢܣܩܠܘܦܕܝܐ\"܀",
new String[] { "ܘܝܩܝܦܕܝܐ", "ܐܢܓܠܝܐ", "Wikipedia", "ܗܘ", "ܐܝܢܣܩܠܘܦܕܝܐ", "ܚܐܪܬܐ", "ܕܐܢܛܪܢܛ", "ܒܠܫܢ̈ܐ", "ܣܓܝܐ̈ܐ", "ܫܡܗ",
"ܐܬܐ", "ܡܢ", "ܡ̈ܠܬܐ", "ܕ", "ܘܝܩܝ", "ܘ", "ܐܝܢܣܩܠܘܦܕܝܐ"});
}
public void testBengali() throws Exception {
assertAnalyzesTo(a, "এই বিশ্বকোষ পরিচালনা করে উইকিমিডিয়া ফাউন্ডেশন (একটি অলাভজনক সংস্থা)। উইকিপিডিয়ার শুরু ১৫ জানুয়ারি, ২০০১ সালে। এখন পর্যন্ত ২০০টিরও বেশী ভাষায় উইকিপিডিয়া রয়েছে।",
new String[] { "এই", "বিশ্বকোষ", "পরিচালনা", "করে", "উইকিমিডিয়া", "ফাউন্ডেশন", "একটি", "অলাভজনক", "সংস্থা", "উইকিপিডিয়ার",
"শুরু", "১৫", "জানুয়ারি", "২০০১", "সালে", "এখন", "পর্যন্ত", "২০০টিরও", "বেশী", "ভাষায়", "উইকিপিডিয়া", "রয়েছে" });
}
public void testFarsi() throws Exception {
assertAnalyzesTo(a, "ویکی پدیای انگلیسی در تاریخ ۲۵ دی ۱۳۷۹ به صورت مکملی برای دانشنامهٔ تخصصی نوپدیا نوشته شد.",
new String[] { "ویکی", "پدیای", "انگلیسی", "در", "تاریخ", "۲۵", "دی", "۱۳۷۹", "به", "صورت", "مکملی",
"برای", "دانشنامهٔ", "تخصصی", "نوپدیا", "نوشته", "شد" });
}
public void testGreek() throws Exception {
assertAnalyzesTo(a, "Γράφεται σε συνεργασία από εθελοντές με το λογισμικό wiki, κάτι που σημαίνει ότι άρθρα μπορεί να προστεθούν ή να αλλάξουν από τον καθένα.",
new String[] { "Γράφεται", "σε", "συνεργασία", "από", "εθελοντές", "με", "το", "λογισμικό", "wiki", "κάτι", "που",
"σημαίνει", "ότι", "άρθρα", "μπορεί", "να", "προστεθούν", "ή", "να", "αλλάξουν", "από", "τον", "καθένα" });
}
public void testKhmer() throws Exception {
assertAnalyzesTo(a, "ផ្ទះស្កឹមស្កៃបីបួនខ្នងនេះ", new String[] { "ផ្ទះ", "ស្កឹមស្កៃ", "បី", "បួន", "ខ្នង", "នេះ" });
}
public void testLao() throws Exception {
assertAnalyzesTo(a, "ກວ່າດອກ", new String[] { "ກວ່າ", "ດອກ" });
assertAnalyzesTo(a, "ພາສາລາວ", new String[] { "ພາສາ", "ລາວ"}, new String[] { "<ALPHANUM>", "<ALPHANUM>" });
}
public void testMyanmar() throws Exception {
assertAnalyzesTo(a, "သက်ဝင်လှုပ်ရှားစေပြီး", new String[] { "သက်ဝင်", "လှုပ်ရှား", "စေ", "ပြီး" });
}
public void testThai() throws Exception {
assertAnalyzesTo(a, "การที่ได้ต้องแสดงว่างานดี. แล้วเธอจะไปไหน? ๑๒๓๔",
new String[] { "การ", "ที่", "ได้", "ต้อง", "แสดง", "ว่า", "งาน", "ดี", "แล้ว", "เธอ", "จะ", "ไป", "ไหน", "๑๒๓๔"});
}
public void testTibetan() throws Exception {
assertAnalyzesTo(a, "སྣོན་མཛོད་དང་ལས་འདིས་བོད་ཡིག་མི་ཉམས་གོང་འཕེལ་དུ་གཏོང་བར་ཧ་ཅང་དགེ་མཚན་མཆིས་སོ། །",
new String[] { "སྣོན", "མཛོད", "དང", "ལས", "འདིས", "བོད", "ཡིག", "མི", "ཉམས", "གོང", "འཕེལ", "དུ", "གཏོང", "བར", "ཧ", "ཅང", "དགེ", "མཚན", "མཆིས", "སོ" });
}
/*
* For chinese, tokenize as char (these can later form bigrams or whatever)
*/
public void testChinese() throws Exception {
assertAnalyzesTo(a, "我是中国人。 1234 Tests ",
new String[] { "我", "是", "中", "国", "人", "1234", "Tests"});
}
public void testHebrew() throws Exception {
assertAnalyzesTo(a, "דנקנר תקף את הדו\"ח",
new String[] { "דנקנר", "תקף", "את", "הדו\"ח" });
assertAnalyzesTo(a, "חברת בת של מודי'ס",
new String[] { "חברת", "בת", "של", "מודי'ס" });
}
public void testEmpty() throws Exception {
assertAnalyzesTo(a, "", new String[] {});
assertAnalyzesTo(a, ".", new String[] {});
assertAnalyzesTo(a, " ", new String[] {});
}
/* test various jira issues this analyzer is related to */
public void testLUCENE1545() throws Exception {
/*
* Standard analyzer does not correctly tokenize combining character U+0364 COMBINING LATIN SMALL LETTRE E.
* The word "moͤchte" is incorrectly tokenized into "mo" "chte", the combining character is lost.
* Expected result is only on token "moͤchte".
*/
assertAnalyzesTo(a, "moͤchte", new String[] { "moͤchte" });
}
/* Tests from StandardAnalyzer, just to show behavior is similar */
public void testAlphanumericSA() throws Exception {
// alphanumeric tokens
assertAnalyzesTo(a, "B2B", new String[]{"B2B"});
assertAnalyzesTo(a, "2B", new String[]{"2B"});
}
public void testDelimitersSA() throws Exception {
// other delimiters: "-", "/", ","
assertAnalyzesTo(a, "some-dashed-phrase", new String[]{"some", "dashed", "phrase"});
assertAnalyzesTo(a, "dogs,chase,cats", new String[]{"dogs", "chase", "cats"});
assertAnalyzesTo(a, "ac/dc", new String[]{"ac", "dc"});
}
public void testApostrophesSA() throws Exception {
// internal apostrophes: O'Reilly, you're, O'Reilly's
assertAnalyzesTo(a, "O'Reilly", new String[]{"O'Reilly"});
assertAnalyzesTo(a, "you're", new String[]{"you're"});
assertAnalyzesTo(a, "she's", new String[]{"she's"});
assertAnalyzesTo(a, "Jim's", new String[]{"Jim's"});
assertAnalyzesTo(a, "don't", new String[]{"don't"});
assertAnalyzesTo(a, "O'Reilly's", new String[]{"O'Reilly's"});
}
public void testNumericSA() throws Exception {
// floating point, serial, model numbers, ip addresses, etc.
// every other segment must have at least one digit
assertAnalyzesTo(a, "21.35", new String[]{"21.35"});
assertAnalyzesTo(a, "R2D2 C3PO", new String[]{"R2D2", "C3PO"});
assertAnalyzesTo(a, "216.239.63.104", new String[]{"216.239.63.104"});
assertAnalyzesTo(a, "216.239.63.104", new String[]{"216.239.63.104"});
}
public void testTextWithNumbersSA() throws Exception {
// numbers
assertAnalyzesTo(a, "David has 5000 bones", new String[]{"David", "has", "5000", "bones"});
}
public void testVariousTextSA() throws Exception {
// various
assertAnalyzesTo(a, "C embedded developers wanted", new String[]{"C", "embedded", "developers", "wanted"});
assertAnalyzesTo(a, "foo bar FOO BAR", new String[]{"foo", "bar", "FOO", "BAR"});
assertAnalyzesTo(a, "foo bar . FOO <> BAR", new String[]{"foo", "bar", "FOO", "BAR"});
assertAnalyzesTo(a, "\"QUOTED\" word", new String[]{"QUOTED", "word"});
}
public void testKoreanSA() throws Exception {
// Korean words
assertAnalyzesTo(a, "안녕하세요 한글입니다", new String[]{"안녕하세요", "한글입니다"});
}
public void testReusableTokenStream() throws Exception {
assertAnalyzesTo(a, "སྣོན་མཛོད་དང་ལས་འདིས་བོད་ཡིག་མི་ཉམས་གོང་འཕེལ་དུ་གཏོང་བར་ཧ་ཅང་དགེ་མཚན་མཆིས་སོ། །",
new String[] { "སྣོན", "མཛོད", "དང", "ལས", "འདིས", "བོད", "ཡིག", "མི", "ཉམས", "གོང",
"འཕེལ", "དུ", "གཏོང", "བར", "ཧ", "ཅང", "དགེ", "མཚན", "མཆིས", "སོ" });
}
public void testOffsets() throws Exception {
assertAnalyzesTo(a, "David has 5000 bones",
new String[] {"David", "has", "5000", "bones"},
new int[] {0, 6, 10, 15},
new int[] {5, 9, 14, 20});
}
public void testTypes() throws Exception {
assertAnalyzesTo(a, "David has 5000 bones",
new String[] {"David", "has", "5000", "bones"},
new String[] { "<ALPHANUM>", "<ALPHANUM>", "<NUM>", "<ALPHANUM>" });
}
public void testKorean() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "훈민정음",
new String[] { "훈민정음" },
new String[] { "<HANGUL>" });
}
public void testJapanese() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "仮名遣い カタカナ",
new String[] { "仮", "名", "遣", "い", "カタカナ" },
new String[] { "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<HIRAGANA>", "<KATAKANA>" });
}
/** simple emoji */
public void testEmoji() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "💩 💩💩",
new String[] { "💩", "💩", "💩" },
new String[] { "<EMOJI>", "<EMOJI>", "<EMOJI>" });
}
/** emoji zwj sequence */
public void testEmojiSequence() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "👩❤️👩",
new String[] { "👩❤️👩" },
new String[] { "<EMOJI>" });
}
/** emoji zwj sequence with fitzpatrick modifier */
public void testEmojiSequenceWithModifier() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "👨🏼⚕️",
new String[] { "👨🏼⚕️" },
new String[] { "<EMOJI>" });
}
/** regional indicator */
public void testEmojiRegionalIndicator() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "🇺🇸🇺🇸",
new String[] { "🇺🇸", "🇺🇸" },
new String[] { "<EMOJI>", "<EMOJI>" });
}
/** variation sequence */
public void testEmojiVariationSequence() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "#️⃣",
new String[] { "#️⃣" },
new String[] { "<EMOJI>" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "3️⃣",
new String[] { "3️⃣",},
new String[] { "<EMOJI>" });
}
public void testEmojiTagSequence() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "🏴",
new String[] { "🏴" },
new String[] { "<EMOJI>" });
}
public void testEmojiTokenization() throws Exception {
// simple emoji around latin
BaseTokenStreamTestCase.assertAnalyzesTo(a, "poo💩poo",
new String[] { "poo", "💩", "poo" },
new String[] { "<ALPHANUM>", "<EMOJI>", "<ALPHANUM>" });
// simple emoji around non-latin
BaseTokenStreamTestCase.assertAnalyzesTo(a, "💩中國💩",
new String[] { "💩", "中", "國", "💩" },
new String[] { "<EMOJI>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<EMOJI>" });
}
/** blast some random strings through the analyzer */
public void testRandomStrings() throws Exception {
checkRandomData(random(), a, 1000*RANDOM_MULTIPLIER);
}
/** blast some random large strings through the analyzer */
public void testRandomHugeStrings() throws Exception {
Random random = random();
checkRandomData(random, a, 100*RANDOM_MULTIPLIER, 8192);
}
public void testTokenAttributes() throws Exception {
try (TokenStream ts = a.tokenStream("dummy", "This is a test")) {
ScriptAttribute scriptAtt = ts.addAttribute(ScriptAttribute.class);
ts.reset();
while (ts.incrementToken()) {
assertEquals(UScript.LATIN, scriptAtt.getCode());
assertEquals(UScript.getName(UScript.LATIN), scriptAtt.getName());
assertEquals(UScript.getShortName(UScript.LATIN), scriptAtt.getShortName());
assertTrue(ts.reflectAsString(false).contains("script=Latin"));
}
ts.end();
}
}
/** test for bugs like http://bugs.icu-project.org/trac/ticket/10767 */
public void testICUConcurrency() throws Exception {
int numThreads = 8;
final CountDownLatch startingGun = new CountDownLatch(1);
Thread threads[] = new Thread[numThreads];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread() {
@Override
public void run() {
try {
startingGun.await();
long tokenCount = 0;
final String contents = "英 เบียร์ ビール ເບຍ abc";
for (int i = 0; i < 1000; i++) {
try (Tokenizer tokenizer = new ICUTokenizer()) {
tokenizer.setReader(new StringReader(contents));
tokenizer.reset();
while (tokenizer.incrementToken()) {
tokenCount++;
}
tokenizer.end();
}
}
if (VERBOSE) {
System.out.println(tokenCount);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
};
threads[i].start();
}
startingGun.countDown();
for (int i = 0; i < threads.length; i++) {
threads[i].join();
}
}
}
| janhoy/lucene-solr | lucene/analysis/icu/src/test/org/apache/lucene/analysis/icu/segmentation/TestICUTokenizer.java |
43,289 | package org.apache.lucene.analysis.standard;
/*
* 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.
*/
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.BaseTokenStreamTestCase;
import org.apache.lucene.util.Version;
import java.io.IOException;
import java.util.Arrays;
public class TestUAX29URLEmailAnalyzer extends BaseTokenStreamTestCase {
private Analyzer a;
@Override
public void setUp() throws Exception {
super.setUp();
a = new UAX29URLEmailAnalyzer();
}
@Override
public void tearDown() throws Exception {
a.close();
super.tearDown();
}
public void testHugeDoc() throws IOException {
StringBuilder sb = new StringBuilder();
char whitespace[] = new char[4094];
Arrays.fill(whitespace, ' ');
sb.append(whitespace);
sb.append("testing 1234");
String input = sb.toString();
BaseTokenStreamTestCase.assertAnalyzesTo(a, input, new String[]{"testing", "1234"}) ;
}
public void testArmenian() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Վիքիպեդիայի 13 միլիոն հոդվածները (4,600` հայերեն վիքիպեդիայում) գրվել են կամավորների կողմից ու համարյա բոլոր հոդվածները կարող է խմբագրել ցանկաց մարդ ով կարող է բացել Վիքիպեդիայի կայքը։",
new String[] { "վիքիպեդիայի", "13", "միլիոն", "հոդվածները", "4,600", "հայերեն", "վիքիպեդիայում", "գրվել", "են", "կամավորների", "կողմից",
"ու", "համարյա", "բոլոր", "հոդվածները", "կարող", "է", "խմբագրել", "ցանկաց", "մարդ", "ով", "կարող", "է", "բացել", "վիքիպեդիայի", "կայքը" } );
}
public void testAmharic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ዊኪፔድያ የባለ ብዙ ቋንቋ የተሟላ ትክክለኛና ነጻ መዝገበ ዕውቀት (ኢንሳይክሎፒዲያ) ነው። ማንኛውም",
new String[] { "ዊኪፔድያ", "የባለ", "ብዙ", "ቋንቋ", "የተሟላ", "ትክክለኛና", "ነጻ", "መዝገበ", "ዕውቀት", "ኢንሳይክሎፒዲያ", "ነው", "ማንኛውም" } );
}
public void testArabic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "الفيلم الوثائقي الأول عن ويكيبيديا يسمى \"الحقيقة بالأرقام: قصة ويكيبيديا\" (بالإنجليزية: Truth in Numbers: The Wikipedia Story)، سيتم إطلاقه في 2008.",
new String[] { "الفيلم", "الوثائقي", "الأول", "عن", "ويكيبيديا", "يسمى", "الحقيقة", "بالأرقام", "قصة", "ويكيبيديا",
"بالإنجليزية", "truth", "numbers", "wikipedia", "story", "سيتم", "إطلاقه", "في", "2008" } );
}
public void testAramaic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ܘܝܩܝܦܕܝܐ (ܐܢܓܠܝܐ: Wikipedia) ܗܘ ܐܝܢܣܩܠܘܦܕܝܐ ܚܐܪܬܐ ܕܐܢܛܪܢܛ ܒܠܫܢ̈ܐ ܣܓܝܐ̈ܐ܂ ܫܡܗ ܐܬܐ ܡܢ ܡ̈ܠܬܐ ܕ\"ܘܝܩܝ\" ܘ\"ܐܝܢܣܩܠܘܦܕܝܐ\"܀",
new String[] { "ܘܝܩܝܦܕܝܐ", "ܐܢܓܠܝܐ", "wikipedia", "ܗܘ", "ܐܝܢܣܩܠܘܦܕܝܐ", "ܚܐܪܬܐ", "ܕܐܢܛܪܢܛ", "ܒܠܫܢ̈ܐ", "ܣܓܝܐ̈ܐ", "ܫܡܗ",
"ܐܬܐ", "ܡܢ", "ܡ̈ܠܬܐ", "ܕ", "ܘܝܩܝ", "ܘ", "ܐܝܢܣܩܠܘܦܕܝܐ"});
}
public void testBengali() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "এই বিশ্বকোষ পরিচালনা করে উইকিমিডিয়া ফাউন্ডেশন (একটি অলাভজনক সংস্থা)। উইকিপিডিয়ার শুরু ১৫ জানুয়ারি, ২০০১ সালে। এখন পর্যন্ত ২০০টিরও বেশী ভাষায় উইকিপিডিয়া রয়েছে।",
new String[] { "এই", "বিশ্বকোষ", "পরিচালনা", "করে", "উইকিমিডিয়া", "ফাউন্ডেশন", "একটি", "অলাভজনক", "সংস্থা", "উইকিপিডিয়ার",
"শুরু", "১৫", "জানুয়ারি", "২০০১", "সালে", "এখন", "পর্যন্ত", "২০০টিরও", "বেশী", "ভাষায়", "উইকিপিডিয়া", "রয়েছে" });
}
public void testFarsi() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ویکی پدیای انگلیسی در تاریخ ۲۵ دی ۱۳۷۹ به صورت مکملی برای دانشنامهٔ تخصصی نوپدیا نوشته شد.",
new String[] { "ویکی", "پدیای", "انگلیسی", "در", "تاریخ", "۲۵", "دی", "۱۳۷۹", "به", "صورت", "مکملی",
"برای", "دانشنامهٔ", "تخصصی", "نوپدیا", "نوشته", "شد" });
}
public void testGreek() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Γράφεται σε συνεργασία από εθελοντές με το λογισμικό wiki, κάτι που σημαίνει ότι άρθρα μπορεί να προστεθούν ή να αλλάξουν από τον καθένα.",
new String[] { "γράφεται", "σε", "συνεργασία", "από", "εθελοντές", "με", "το", "λογισμικό", "wiki", "κάτι", "που",
"σημαίνει", "ότι", "άρθρα", "μπορεί", "να", "προστεθούν", "ή", "να", "αλλάξουν", "από", "τον", "καθένα" });
}
public void testThai() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "การที่ได้ต้องแสดงว่างานดี. แล้วเธอจะไปไหน? ๑๒๓๔",
new String[] { "การที่ได้ต้องแสดงว่างานดี", "แล้วเธอจะไปไหน", "๑๒๓๔" });
}
public void testLao() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ສາທາລະນະລັດ ປະຊາທິປະໄຕ ປະຊາຊົນລາວ",
new String[] { "ສາທາລະນະລັດ", "ປະຊາທິປະໄຕ", "ປະຊາຊົນລາວ" });
}
public void testTibetan() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "སྣོན་མཛོད་དང་ལས་འདིས་བོད་ཡིག་མི་ཉམས་གོང་འཕེལ་དུ་གཏོང་བར་ཧ་ཅང་དགེ་མཚན་མཆིས་སོ། །",
new String[] { "སྣོན", "མཛོད", "དང", "ལས", "འདིས", "བོད", "ཡིག",
"མི", "ཉམས", "གོང", "འཕེལ", "དུ", "གཏོང", "བར",
"ཧ", "ཅང", "དགེ", "མཚན", "མཆིས", "སོ" });
}
/*
* For chinese, tokenize as char (these can later form bigrams or whatever)
*/
public void testChinese() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "我是中国人。 1234 Tests ",
new String[] { "我", "是", "中", "国", "人", "1234", "tests"});
}
public void testEmpty() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "", new String[] {});
BaseTokenStreamTestCase.assertAnalyzesTo(a, ".", new String[] {});
BaseTokenStreamTestCase.assertAnalyzesTo(a, " ", new String[] {});
}
/* test various jira issues this analyzer is related to */
public void testLUCENE1545() throws Exception {
/*
* Standard analyzer does not correctly tokenize combining character U+0364 COMBINING LATIN SMALL LETTER E.
* The word "moͤchte" is incorrectly tokenized into "mo" "chte", the combining character is lost.
* Expected result is only one token "moͤchte".
*/
BaseTokenStreamTestCase.assertAnalyzesTo(a, "moͤchte", new String[] { "moͤchte" });
}
/* Tests from StandardAnalyzer, just to show behavior is similar */
public void testAlphanumericSA() throws Exception {
// alphanumeric tokens
BaseTokenStreamTestCase.assertAnalyzesTo(a, "B2B", new String[]{"b2b"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "2B", new String[]{"2b"});
}
public void testDelimitersSA() throws Exception {
// other delimiters: "-", "/", ","
BaseTokenStreamTestCase.assertAnalyzesTo(a, "some-dashed-phrase", new String[]{"some", "dashed", "phrase"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "dogs,chase,cats", new String[]{"dogs", "chase", "cats"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ac/dc", new String[]{"ac", "dc"});
}
public void testApostrophesSA() throws Exception {
// internal apostrophes: O'Reilly, you're, O'Reilly's
BaseTokenStreamTestCase.assertAnalyzesTo(a, "O'Reilly", new String[]{"o'reilly"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "you're", new String[]{"you're"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "she's", new String[]{"she's"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Jim's", new String[]{"jim's"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "don't", new String[]{"don't"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "O'Reilly's", new String[]{"o'reilly's"});
}
public void testNumericSA() throws Exception {
// floating point, serial, model numbers, ip addresses, etc.
BaseTokenStreamTestCase.assertAnalyzesTo(a, "21.35", new String[]{"21.35"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "R2D2 C3PO", new String[]{"r2d2", "c3po"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "216.239.63.104", new String[]{"216.239.63.104"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "216.239.63.104", new String[]{"216.239.63.104"});
}
public void testTextWithNumbersSA() throws Exception {
// numbers
BaseTokenStreamTestCase.assertAnalyzesTo(a, "David has 5000 bones", new String[]{"david", "has", "5000", "bones"});
}
public void testVariousTextSA() throws Exception {
// various
BaseTokenStreamTestCase.assertAnalyzesTo(a, "C embedded developers wanted", new String[]{"c", "embedded", "developers", "wanted"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "foo bar FOO BAR", new String[]{"foo", "bar", "foo", "bar"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "foo bar . FOO <> BAR", new String[]{"foo", "bar", "foo", "bar"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "\"QUOTED\" word", new String[]{"quoted", "word"});
}
public void testKoreanSA() throws Exception {
// Korean words
BaseTokenStreamTestCase.assertAnalyzesTo(a, "안녕하세요 한글입니다", new String[]{"안녕하세요", "한글입니다"});
}
public void testOffsets() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "David has 5000 bones",
new String[] {"david", "has", "5000", "bones"},
new int[] {0, 6, 10, 15},
new int[] {5, 9, 14, 20});
}
public void testTypes() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "david has 5000 bones",
new String[] {"david", "has", "5000", "bones"},
new String[] { "<ALPHANUM>", "<ALPHANUM>", "<NUM>", "<ALPHANUM>" });
}
public void testSupplementary() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "𩬅艱鍟䇹愯瀛",
new String[] {"𩬅", "艱", "鍟", "䇹", "愯", "瀛"},
new String[] { "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>" });
}
public void testKorean() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "훈민정음",
new String[] { "훈민정음" },
new String[] { "<HANGUL>" });
}
public void testJapanese() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "仮名遣い カタカナ",
new String[] { "仮", "名", "遣", "い", "カタカナ" },
new String[] { "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<HIRAGANA>", "<KATAKANA>" });
}
public void testCombiningMarks() throws Exception {
checkOneTerm(a, "ざ", "ざ"); // hiragana
checkOneTerm(a, "ザ", "ザ"); // katakana
checkOneTerm(a, "壹゙", "壹゙"); // ideographic
checkOneTerm(a, "아゙", "아゙"); // hangul
}
public void testBasicEmails() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a,
"one [email protected] two three [[email protected]] \"ArakaBanassaMassanaBakarA\" <[email protected]>",
new String[] {"one", "[email protected]", "two", "three", "[email protected]", "arakabanassamassanabakara", "[email protected]",},
new String[] { "<ALPHANUM>", "<EMAIL>", "<ALPHANUM>", "<ALPHANUM>", "<EMAIL>", "<ALPHANUM>", "<EMAIL>" });
}
public void testMailtoSchemeEmails () throws Exception {
// See LUCENE-3880
BaseTokenStreamTestCase.assertAnalyzesTo(a, "MAILTO:[email protected]",
new String[] {"mailto", "[email protected]"},
new String[] { "<ALPHANUM>", "<EMAIL>" });
// TODO: Support full mailto: scheme URIs. See RFC 6068: http://tools.ietf.org/html/rfc6068
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "mailto:[email protected],[email protected][email protected]"
+ "&subject=Subjectivity&body=Corpusivity%20or%20something%20like%20that",
new String[] { "mailto",
"[email protected]",
// TODO: recognize ',' address delimiter. Also, see examples of ';' delimiter use at: http://www.mailto.co.uk/
",[email protected]",
"[email protected]", // TODO: split field keys/values
"subject", "subjectivity",
"body", "corpusivity", "20or", "20something","20like", "20that" }, // TODO: Hex decoding + re-tokenization
new String[] { "<ALPHANUM>",
"<EMAIL>",
"<EMAIL>",
"<EMAIL>",
"<ALPHANUM>", "<ALPHANUM>",
"<ALPHANUM>", "<ALPHANUM>", "<ALPHANUM>", "<ALPHANUM>", "<ALPHANUM>", "<ALPHANUM>" });
}
public void testBasicURLs() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a,
"a <HTTPs://example.net/omg/isnt/that/NICE?no=its&n%30t#mntl-E>b-D ftp://www.example.com/ABC.txt file:///C:/path/to/a/FILE.txt C",
new String[] {"https://example.net/omg/isnt/that/nice?no=its&n%30t#mntl-e", "b", "d", "ftp://www.example.com/abc.txt", "file:///c:/path/to/a/file.txt", "c" },
new String[] { "<URL>", "<ALPHANUM>", "<ALPHANUM>", "<URL>", "<URL>", "<ALPHANUM>" });
}
public void testNoSchemeURLs() throws Exception {
// ".ph" is a Top Level Domain
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "<index.ph>", new String[]{"index.ph"}, new String[]{"<URL>"});
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "index.ph", new String[]{"index.ph"}, new String[]{"<URL>"});
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "index.php", new String[]{"index.php"}, new String[]{"<ALPHANUM>"});
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "index.phα", new String[]{"index.phα"}, new String[]{"<ALPHANUM>"});
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "index-h.php", new String[] { "index", "h.php" },
new String[] { "<ALPHANUM>","<ALPHANUM>"});
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "index2.php", new String[] { "index2", "php" },
new String[] { "<ALPHANUM>", "<ALPHANUM>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "index2.ph9,", new String[] { "index2", "ph9" },
new String[] { "<ALPHANUM>", "<ALPHANUM>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com,example.ph,index.php,index2.php,example2.ph",
new String[] { "example.com", "example.ph", "index.php", "index2", "php", "example2.ph" },
new String[] { "<URL>", "<URL>", "<ALPHANUM>", "<ALPHANUM>", "<ALPHANUM>", "<URL>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com:8080 example.com/path/here example.com?query=something example.com#fragment",
new String[] { "example.com:8080", "example.com/path/here", "example.com?query=something", "example.com#fragment" },
new String[] { "<URL>", "<URL>", "<URL>", "<URL>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com:8080/path/here?query=something#fragment",
new String[] { "example.com:8080/path/here?query=something#fragment" },
new String[] { "<URL>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com:8080/path/here?query=something",
new String[] { "example.com:8080/path/here?query=something" },
new String[] { "<URL>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com:8080/path/here#fragment",
new String[] { "example.com:8080/path/here#fragment" },
new String[] { "<URL>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com:8080/path/here",
new String[] { "example.com:8080/path/here" },
new String[] { "<URL>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com:8080?query=something#fragment",
new String[] { "example.com:8080?query=something#fragment" },
new String[] { "<URL>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com:8080?query=something",
new String[] { "example.com:8080?query=something" },
new String[] { "<URL>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com:8080#fragment",
new String[] { "example.com:8080#fragment" },
new String[] { "<URL>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com/path/here?query=something#fragment",
new String[] { "example.com/path/here?query=something#fragment" },
new String[] { "<URL>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com/path/here?query=something",
new String[] { "example.com/path/here?query=something" },
new String[] { "<URL>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com/path/here#fragment",
new String[] { "example.com/path/here#fragment" },
new String[] { "<URL>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com?query=something#fragment",
new String[] { "example.com?query=something#fragment" },
new String[] { "<URL>" });
}
/** blast some random strings through the analyzer */
public void testRandomStrings() throws Exception {
checkRandomData(random(), a, 1000*RANDOM_MULTIPLIER);
}
public void testBackcompat40() throws IOException {
UAX29URLEmailAnalyzer a = new UAX29URLEmailAnalyzer();
a.setVersion(Version.LUCENE_4_6_1);
// this is just a test to see the correct unicode version is being used, not actually testing hebrew
assertAnalyzesTo(a, "א\"א", new String[] {"א", "א"});
}
}
| sindicetech/lucene-solr | lucene/analysis/common/src/test/org/apache/lucene/analysis/standard/TestUAX29URLEmailAnalyzer.java |
43,292 | package org.apache.lucene.analysis.core;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.BaseTokenStreamTestCase;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.standard.UAX29URLEmailTokenizer;
import org.apache.lucene.analysis.tokenattributes.TypeAttribute;
import org.apache.lucene.util.TestUtil;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.regex.Pattern;
/*
* 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.
*/
public class TestUAX29URLEmailTokenizer extends BaseTokenStreamTestCase {
// LUCENE-5440: extremely slow tokenization of text matching email <local-part> (before the '@')
public void testLongEMAILatomText() throws Exception {
// EMAILatomText = [A-Za-z0-9!#$%&'*+-/=?\^_`{|}~]
char[] emailAtomChars
= "!#$%&'*+,-./0123456789=?ABCDEFGHIJKLMNOPQRSTUVWXYZ^_`abcdefghijklmnopqrstuvwxyz{|}~".toCharArray();
StringBuilder builder = new StringBuilder();
int numChars = TestUtil.nextInt(random(), 100 * 1024, 3 * 1024 * 1024);
for (int i = 0 ; i < numChars ; ++i) {
builder.append(emailAtomChars[random().nextInt(emailAtomChars.length)]);
}
int tokenCount = 0;
UAX29URLEmailTokenizer ts = new UAX29URLEmailTokenizer();
String text = builder.toString();
ts.setReader(new StringReader(text));
ts.reset();
while (ts.incrementToken()) {
tokenCount++;
}
ts.end();
ts.close();
assertTrue(tokenCount > 0);
tokenCount = 0;
int newBufferSize = TestUtil.nextInt(random(), 200, 8192);
ts.setMaxTokenLength(newBufferSize);
ts.setReader(new StringReader(text));
ts.reset();
while (ts.incrementToken()) {
tokenCount++;
}
ts.end();
ts.close();
assertTrue(tokenCount > 0);
}
public void testHugeDoc() throws IOException {
StringBuilder sb = new StringBuilder();
char whitespace[] = new char[4094];
Arrays.fill(whitespace, ' ');
sb.append(whitespace);
sb.append("testing 1234");
String input = sb.toString();
UAX29URLEmailTokenizer tokenizer = new UAX29URLEmailTokenizer(newAttributeFactory());
tokenizer.setReader(new StringReader(input));
BaseTokenStreamTestCase.assertTokenStreamContents(tokenizer, new String[] { "testing", "1234" });
}
private Analyzer a = new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName) {
Tokenizer tokenizer = new UAX29URLEmailTokenizer(newAttributeFactory());
return new TokenStreamComponents(tokenizer);
}
};
/** Passes through tokens with type "<URL>" and blocks all other types. */
private class URLFilter extends TokenFilter {
private final TypeAttribute typeAtt = addAttribute(TypeAttribute.class);
public URLFilter(TokenStream in) {
super(in);
}
@Override
public final boolean incrementToken() throws java.io.IOException {
boolean isTokenAvailable = false;
while (input.incrementToken()) {
if (typeAtt.type() == UAX29URLEmailTokenizer.TOKEN_TYPES[UAX29URLEmailTokenizer.URL]) {
isTokenAvailable = true;
break;
}
}
return isTokenAvailable;
}
}
/** Passes through tokens with type "<EMAIL>" and blocks all other types. */
private class EmailFilter extends TokenFilter {
private final TypeAttribute typeAtt = addAttribute(TypeAttribute.class);
public EmailFilter(TokenStream in) {
super(in);
}
@Override
public final boolean incrementToken() throws java.io.IOException {
boolean isTokenAvailable = false;
while (input.incrementToken()) {
if (typeAtt.type() == UAX29URLEmailTokenizer.TOKEN_TYPES[UAX29URLEmailTokenizer.EMAIL]) {
isTokenAvailable = true;
break;
}
}
return isTokenAvailable;
}
}
private Analyzer urlAnalyzer = new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName) {
UAX29URLEmailTokenizer tokenizer = new UAX29URLEmailTokenizer(newAttributeFactory());
tokenizer.setMaxTokenLength(Integer.MAX_VALUE); // Tokenize arbitrary length URLs
TokenFilter filter = new URLFilter(tokenizer);
return new TokenStreamComponents(tokenizer, filter);
}
};
private Analyzer emailAnalyzer = new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName) {
UAX29URLEmailTokenizer tokenizer = new UAX29URLEmailTokenizer(newAttributeFactory());
TokenFilter filter = new EmailFilter(tokenizer);
return new TokenStreamComponents(tokenizer, filter);
}
};
public void testArmenian() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Վիքիպեդիայի 13 միլիոն հոդվածները (4,600` հայերեն վիքիպեդիայում) գրվել են կամավորների կողմից ու համարյա բոլոր հոդվածները կարող է խմբագրել ցանկաց մարդ ով կարող է բացել Վիքիպեդիայի կայքը։",
new String[] { "Վիքիպեդիայի", "13", "միլիոն", "հոդվածները", "4,600", "հայերեն", "վիքիպեդիայում", "գրվել", "են", "կամավորների", "կողմից",
"ու", "համարյա", "բոլոր", "հոդվածները", "կարող", "է", "խմբագրել", "ցանկաց", "մարդ", "ով", "կարող", "է", "բացել", "Վիքիպեդիայի", "կայքը" } );
}
public void testAmharic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ዊኪፔድያ የባለ ብዙ ቋንቋ የተሟላ ትክክለኛና ነጻ መዝገበ ዕውቀት (ኢንሳይክሎፒዲያ) ነው። ማንኛውም",
new String[] { "ዊኪፔድያ", "የባለ", "ብዙ", "ቋንቋ", "የተሟላ", "ትክክለኛና", "ነጻ", "መዝገበ", "ዕውቀት", "ኢንሳይክሎፒዲያ", "ነው", "ማንኛውም" } );
}
public void testArabic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "الفيلم الوثائقي الأول عن ويكيبيديا يسمى \"الحقيقة بالأرقام: قصة ويكيبيديا\" (بالإنجليزية: Truth in Numbers: The Wikipedia Story)، سيتم إطلاقه في 2008.",
new String[] { "الفيلم", "الوثائقي", "الأول", "عن", "ويكيبيديا", "يسمى", "الحقيقة", "بالأرقام", "قصة", "ويكيبيديا",
"بالإنجليزية", "Truth", "in", "Numbers", "The", "Wikipedia", "Story", "سيتم", "إطلاقه", "في", "2008" } );
}
public void testAramaic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ܘܝܩܝܦܕܝܐ (ܐܢܓܠܝܐ: Wikipedia) ܗܘ ܐܝܢܣܩܠܘܦܕܝܐ ܚܐܪܬܐ ܕܐܢܛܪܢܛ ܒܠܫܢ̈ܐ ܣܓܝܐ̈ܐ܂ ܫܡܗ ܐܬܐ ܡܢ ܡ̈ܠܬܐ ܕ\"ܘܝܩܝ\" ܘ\"ܐܝܢܣܩܠܘܦܕܝܐ\"܀",
new String[] { "ܘܝܩܝܦܕܝܐ", "ܐܢܓܠܝܐ", "Wikipedia", "ܗܘ", "ܐܝܢܣܩܠܘܦܕܝܐ", "ܚܐܪܬܐ", "ܕܐܢܛܪܢܛ", "ܒܠܫܢ̈ܐ", "ܣܓܝܐ̈ܐ", "ܫܡܗ",
"ܐܬܐ", "ܡܢ", "ܡ̈ܠܬܐ", "ܕ", "ܘܝܩܝ", "ܘ", "ܐܝܢܣܩܠܘܦܕܝܐ"});
}
public void testBengali() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "এই বিশ্বকোষ পরিচালনা করে উইকিমিডিয়া ফাউন্ডেশন (একটি অলাভজনক সংস্থা)। উইকিপিডিয়ার শুরু ১৫ জানুয়ারি, ২০০১ সালে। এখন পর্যন্ত ২০০টিরও বেশী ভাষায় উইকিপিডিয়া রয়েছে।",
new String[] { "এই", "বিশ্বকোষ", "পরিচালনা", "করে", "উইকিমিডিয়া", "ফাউন্ডেশন", "একটি", "অলাভজনক", "সংস্থা", "উইকিপিডিয়ার",
"শুরু", "১৫", "জানুয়ারি", "২০০১", "সালে", "এখন", "পর্যন্ত", "২০০টিরও", "বেশী", "ভাষায়", "উইকিপিডিয়া", "রয়েছে" });
}
public void testFarsi() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ویکی پدیای انگلیسی در تاریخ ۲۵ دی ۱۳۷۹ به صورت مکملی برای دانشنامهٔ تخصصی نوپدیا نوشته شد.",
new String[] { "ویکی", "پدیای", "انگلیسی", "در", "تاریخ", "۲۵", "دی", "۱۳۷۹", "به", "صورت", "مکملی",
"برای", "دانشنامهٔ", "تخصصی", "نوپدیا", "نوشته", "شد" });
}
public void testGreek() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Γράφεται σε συνεργασία από εθελοντές με το λογισμικό wiki, κάτι που σημαίνει ότι άρθρα μπορεί να προστεθούν ή να αλλάξουν από τον καθένα.",
new String[] { "Γράφεται", "σε", "συνεργασία", "από", "εθελοντές", "με", "το", "λογισμικό", "wiki", "κάτι", "που",
"σημαίνει", "ότι", "άρθρα", "μπορεί", "να", "προστεθούν", "ή", "να", "αλλάξουν", "από", "τον", "καθένα" });
}
public void testThai() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "การที่ได้ต้องแสดงว่างานดี. แล้วเธอจะไปไหน? ๑๒๓๔",
new String[] { "การที่ได้ต้องแสดงว่างานดี", "แล้วเธอจะไปไหน", "๑๒๓๔" });
}
public void testLao() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ສາທາລະນະລັດ ປະຊາທິປະໄຕ ປະຊາຊົນລາວ",
new String[] { "ສາທາລະນະລັດ", "ປະຊາທິປະໄຕ", "ປະຊາຊົນລາວ" });
}
public void testTibetan() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "སྣོན་མཛོད་དང་ལས་འདིས་བོད་ཡིག་མི་ཉམས་གོང་འཕེལ་དུ་གཏོང་བར་ཧ་ཅང་དགེ་མཚན་མཆིས་སོ། །",
new String[] { "སྣོན", "མཛོད", "དང", "ལས", "འདིས", "བོད", "ཡིག",
"མི", "ཉམས", "གོང", "འཕེལ", "དུ", "གཏོང", "བར",
"ཧ", "ཅང", "དགེ", "མཚན", "མཆིས", "སོ" });
}
/*
* For chinese, tokenize as char (these can later form bigrams or whatever)
*/
public void testChinese() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "我是中国人。 1234 Tests ",
new String[] { "我", "是", "中", "国", "人", "1234", "Tests"});
}
public void testEmpty() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "", new String[] {});
BaseTokenStreamTestCase.assertAnalyzesTo(a, ".", new String[] {});
BaseTokenStreamTestCase.assertAnalyzesTo(a, " ", new String[] {});
}
/* test various jira issues this analyzer is related to */
public void testLUCENE1545() throws Exception {
/*
* Standard analyzer does not correctly tokenize combining character U+0364 COMBINING LATIN SMALL LETTRE E.
* The word "moͤchte" is incorrectly tokenized into "mo" "chte", the combining character is lost.
* Expected result is only on token "moͤchte".
*/
BaseTokenStreamTestCase.assertAnalyzesTo(a, "moͤchte", new String[] { "moͤchte" });
}
/* Tests from StandardAnalyzer, just to show behavior is similar */
public void testAlphanumericSA() throws Exception {
// alphanumeric tokens
BaseTokenStreamTestCase.assertAnalyzesTo(a, "B2B", new String[]{"B2B"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "2B", new String[]{"2B"});
}
public void testDelimitersSA() throws Exception {
// other delimiters: "-", "/", ","
BaseTokenStreamTestCase.assertAnalyzesTo(a, "some-dashed-phrase", new String[]{"some", "dashed", "phrase"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "dogs,chase,cats", new String[]{"dogs", "chase", "cats"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ac/dc", new String[]{"ac", "dc"});
}
public void testApostrophesSA() throws Exception {
// internal apostrophes: O'Reilly, you're, O'Reilly's
BaseTokenStreamTestCase.assertAnalyzesTo(a, "O'Reilly", new String[]{"O'Reilly"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "you're", new String[]{"you're"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "she's", new String[]{"she's"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Jim's", new String[]{"Jim's"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "don't", new String[]{"don't"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "O'Reilly's", new String[]{"O'Reilly's"});
}
public void testNumericSA() throws Exception {
// floating point, serial, model numbers, ip addresses, etc.
BaseTokenStreamTestCase.assertAnalyzesTo(a, "21.35", new String[]{"21.35"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "R2D2 C3PO", new String[]{"R2D2", "C3PO"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "216.239.63.104", new String[]{"216.239.63.104"});
}
public void testTextWithNumbersSA() throws Exception {
// numbers
BaseTokenStreamTestCase.assertAnalyzesTo(a, "David has 5000 bones", new String[]{"David", "has", "5000", "bones"});
}
public void testVariousTextSA() throws Exception {
// various
BaseTokenStreamTestCase.assertAnalyzesTo(a, "C embedded developers wanted", new String[]{"C", "embedded", "developers", "wanted"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "foo bar FOO BAR", new String[]{"foo", "bar", "FOO", "BAR"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "foo bar . FOO <> BAR", new String[]{"foo", "bar", "FOO", "BAR"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "\"QUOTED\" word", new String[]{"QUOTED", "word"});
}
public void testKoreanSA() throws Exception {
// Korean words
BaseTokenStreamTestCase.assertAnalyzesTo(a, "안녕하세요 한글입니다", new String[]{"안녕하세요", "한글입니다"});
}
public void testOffsets() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "David has 5000 bones",
new String[] {"David", "has", "5000", "bones"},
new int[] {0, 6, 10, 15},
new int[] {5, 9, 14, 20});
}
public void testTypes() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "David has 5000 bones",
new String[] {"David", "has", "5000", "bones"},
new String[] { "<ALPHANUM>", "<ALPHANUM>", "<NUM>", "<ALPHANUM>" });
}
public void testWikiURLs() throws Exception {
Reader reader = null;
String luceneResourcesWikiPage;
try {
reader = new InputStreamReader(getClass().getResourceAsStream
("LuceneResourcesWikiPage.html"), StandardCharsets.UTF_8);
StringBuilder builder = new StringBuilder();
char[] buffer = new char[1024];
int numCharsRead;
while (-1 != (numCharsRead = reader.read(buffer))) {
builder.append(buffer, 0, numCharsRead);
}
luceneResourcesWikiPage = builder.toString();
} finally {
if (null != reader) {
reader.close();
}
}
assertTrue(null != luceneResourcesWikiPage
&& luceneResourcesWikiPage.length() > 0);
BufferedReader bufferedReader = null;
String[] urls;
try {
List<String> urlList = new ArrayList<>();
bufferedReader = new BufferedReader(new InputStreamReader
(getClass().getResourceAsStream("LuceneResourcesWikiPageURLs.txt"), StandardCharsets.UTF_8));
String line;
while (null != (line = bufferedReader.readLine())) {
line = line.trim();
if (line.length() > 0) {
urlList.add(line);
}
}
urls = urlList.toArray(new String[urlList.size()]);
} finally {
if (null != bufferedReader) {
bufferedReader.close();
}
}
assertTrue(null != urls && urls.length > 0);
BaseTokenStreamTestCase.assertAnalyzesTo
(urlAnalyzer, luceneResourcesWikiPage, urls);
}
public void testEmails() throws Exception {
Reader reader = null;
String randomTextWithEmails;
try {
reader = new InputStreamReader(getClass().getResourceAsStream
("random.text.with.email.addresses.txt"), StandardCharsets.UTF_8);
StringBuilder builder = new StringBuilder();
char[] buffer = new char[1024];
int numCharsRead;
while (-1 != (numCharsRead = reader.read(buffer))) {
builder.append(buffer, 0, numCharsRead);
}
randomTextWithEmails = builder.toString();
} finally {
if (null != reader) {
reader.close();
}
}
assertTrue(null != randomTextWithEmails
&& randomTextWithEmails.length() > 0);
BufferedReader bufferedReader = null;
String[] emails;
try {
List<String> emailList = new ArrayList<>();
bufferedReader = new BufferedReader(new InputStreamReader
(getClass().getResourceAsStream
("email.addresses.from.random.text.with.email.addresses.txt"), StandardCharsets.UTF_8));
String line;
while (null != (line = bufferedReader.readLine())) {
line = line.trim();
if (line.length() > 0) {
emailList.add(line);
}
}
emails = emailList.toArray(new String[emailList.size()]);
} finally {
if (null != bufferedReader) {
bufferedReader.close();
}
}
assertTrue(null != emails && emails.length > 0);
BaseTokenStreamTestCase.assertAnalyzesTo
(emailAnalyzer, randomTextWithEmails, emails);
}
public void testMailtoSchemeEmails () throws Exception {
// See LUCENE-3880
BaseTokenStreamTestCase.assertAnalyzesTo(a, "mailto:[email protected]",
new String[] {"mailto", "[email protected]"},
new String[] { "<ALPHANUM>", "<EMAIL>" });
// TODO: Support full mailto: scheme URIs. See RFC 6068: http://tools.ietf.org/html/rfc6068
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "mailto:[email protected],[email protected][email protected]"
+ "&subject=Subjectivity&body=Corpusivity%20or%20something%20like%20that",
new String[] { "mailto",
"[email protected]",
// TODO: recognize ',' address delimiter. Also, see examples of ';' delimiter use at: http://www.mailto.co.uk/
",[email protected]",
"[email protected]", // TODO: split field keys/values
"subject", "Subjectivity",
"body", "Corpusivity", "20or", "20something","20like", "20that" }, // TODO: Hex decoding + re-tokenization
new String[] { "<ALPHANUM>",
"<EMAIL>",
"<EMAIL>",
"<EMAIL>",
"<ALPHANUM>", "<ALPHANUM>",
"<ALPHANUM>", "<ALPHANUM>", "<ALPHANUM>", "<ALPHANUM>", "<ALPHANUM>", "<ALPHANUM>" });
}
public void testURLs() throws Exception {
Reader reader = null;
String randomTextWithURLs;
try {
reader = new InputStreamReader(getClass().getResourceAsStream
("random.text.with.urls.txt"), StandardCharsets.UTF_8);
StringBuilder builder = new StringBuilder();
char[] buffer = new char[1024];
int numCharsRead;
while (-1 != (numCharsRead = reader.read(buffer))) {
builder.append(buffer, 0, numCharsRead);
}
randomTextWithURLs = builder.toString();
} finally {
if (null != reader) {
reader.close();
}
}
assertTrue(null != randomTextWithURLs
&& randomTextWithURLs.length() > 0);
BufferedReader bufferedReader = null;
String[] urls;
try {
List<String> urlList = new ArrayList<>();
bufferedReader = new BufferedReader(new InputStreamReader
(getClass().getResourceAsStream
("urls.from.random.text.with.urls.txt"), StandardCharsets.UTF_8));
String line;
while (null != (line = bufferedReader.readLine())) {
line = line.trim();
if (line.length() > 0) {
urlList.add(line);
}
}
urls = urlList.toArray(new String[urlList.size()]);
} finally {
if (null != bufferedReader) {
bufferedReader.close();
}
}
assertTrue(null != urls && urls.length > 0);
BaseTokenStreamTestCase.assertAnalyzesTo
(urlAnalyzer, randomTextWithURLs, urls);
}
public void testUnicodeWordBreaks() throws Exception {
WordBreakTestUnicode_6_3_0 wordBreakTest = new WordBreakTestUnicode_6_3_0();
wordBreakTest.test(a);
}
public void testSupplementary() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "𩬅艱鍟䇹愯瀛",
new String[] {"𩬅", "艱", "鍟", "䇹", "愯", "瀛"},
new String[] { "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>" });
}
public void testKorean() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "훈민정음",
new String[] { "훈민정음" },
new String[] { "<HANGUL>" });
}
public void testJapanese() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "仮名遣い カタカナ",
new String[] { "仮", "名", "遣", "い", "カタカナ" },
new String[] { "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<HIRAGANA>", "<KATAKANA>" });
}
public void testCombiningMarks() throws Exception {
checkOneTerm(a, "ざ", "ざ"); // hiragana
checkOneTerm(a, "ザ", "ザ"); // katakana
checkOneTerm(a, "壹゙", "壹゙"); // ideographic
checkOneTerm(a, "아゙", "아゙"); // hangul
}
/**
* Multiple consecutive chars in \p{Word_Break = MidLetter},
* \p{Word_Break = MidNumLet}, and/or \p{Word_Break = MidNum}
* should trigger a token split.
*/
public void testMid() throws Exception {
// ':' is in \p{WB:MidLetter}, which should trigger a split unless there is a Letter char on both sides
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A:B", new String[] { "A:B" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A::B", new String[] { "A", "B" });
// '.' is in \p{WB:MidNumLet}, which should trigger a split unless there is a Letter or Numeric char on both sides
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1.2", new String[] { "1.2" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A.B", new String[] { "A.B" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1..2", new String[] { "1", "2" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A..B", new String[] { "A", "B" });
// ',' is in \p{WB:MidNum}, which should trigger a split unless there is a Numeric char on both sides
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1,2", new String[] { "1,2" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1,,2", new String[] { "1", "2" });
// Mixed consecutive \p{WB:MidLetter} and \p{WB:MidNumLet} should trigger a split
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A.:B", new String[] { "A", "B" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A:.B", new String[] { "A", "B" });
// Mixed consecutive \p{WB:MidNum} and \p{WB:MidNumLet} should trigger a split
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1,.2", new String[] { "1", "2" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1.,2", new String[] { "1", "2" });
// '_' is in \p{WB:ExtendNumLet}
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A:B_A:B", new String[] { "A:B_A:B" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A:B_A::B", new String[] { "A:B_A", "B" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1.2_1.2", new String[] { "1.2_1.2" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A.B_A.B", new String[] { "A.B_A.B" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1.2_1..2", new String[] { "1.2_1", "2" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "A.B_A..B", new String[] { "A.B_A", "B" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1,2_1,2", new String[] { "1,2_1,2" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "1,2_1,,2", new String[] { "1,2_1", "2" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "C_A.:B", new String[] { "C_A", "B" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "C_A:.B", new String[] { "C_A", "B" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "3_1,.2", new String[] { "3_1", "2" });
BaseTokenStreamTestCase.assertAnalyzesTo(a, "3_1.,2", new String[] { "3_1", "2" });
}
/** blast some random strings through the analyzer */
public void testRandomStrings() throws Exception {
checkRandomData(random(), a, 1000*RANDOM_MULTIPLIER);
}
/** blast some random large strings through the analyzer */
public void testRandomHugeStrings() throws Exception {
Random random = random();
checkRandomData(random, a, 100*RANDOM_MULTIPLIER, 8192);
}
}
| mdodsworth/lucene-solr | lucene/analysis/common/src/test/org/apache/lucene/analysis/core/TestUAX29URLEmailTokenizer.java |
43,294 | /*
* 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.
*/
package org.apache.lucene.analysis.email;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.BaseTokenStreamTestCase;
import java.io.IOException;
import java.util.Arrays;
public class TestUAX29URLEmailAnalyzer extends BaseTokenStreamTestCase {
private Analyzer a;
@Override
public void setUp() throws Exception {
super.setUp();
a = new UAX29URLEmailAnalyzer();
}
@Override
public void tearDown() throws Exception {
a.close();
super.tearDown();
}
public void testHugeDoc() throws IOException {
StringBuilder sb = new StringBuilder();
char whitespace[] = new char[4094];
Arrays.fill(whitespace, ' ');
sb.append(whitespace);
sb.append("testing 1234");
String input = sb.toString();
BaseTokenStreamTestCase.assertAnalyzesTo(a, input, new String[]{"testing", "1234"}) ;
}
public void testArmenian() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Վիքիպեդիայի 13 միլիոն հոդվածները (4,600` հայերեն վիքիպեդիայում) գրվել են կամավորների կողմից ու համարյա բոլոր հոդվածները կարող է խմբագրել ցանկաց մարդ ով կարող է բացել Վիքիպեդիայի կայքը։",
new String[] { "վիքիպեդիայի", "13", "միլիոն", "հոդվածները", "4,600", "հայերեն", "վիքիպեդիայում", "գրվել", "են", "կամավորների", "կողմից",
"ու", "համարյա", "բոլոր", "հոդվածները", "կարող", "է", "խմբագրել", "ցանկաց", "մարդ", "ով", "կարող", "է", "բացել", "վիքիպեդիայի", "կայքը" } );
}
public void testAmharic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ዊኪፔድያ የባለ ብዙ ቋንቋ የተሟላ ትክክለኛና ነጻ መዝገበ ዕውቀት (ኢንሳይክሎፒዲያ) ነው። ማንኛውም",
new String[] { "ዊኪፔድያ", "የባለ", "ብዙ", "ቋንቋ", "የተሟላ", "ትክክለኛና", "ነጻ", "መዝገበ", "ዕውቀት", "ኢንሳይክሎፒዲያ", "ነው", "ማንኛውም" } );
}
public void testArabic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "الفيلم الوثائقي الأول عن ويكيبيديا يسمى \"الحقيقة بالأرقام: قصة ويكيبيديا\" (بالإنجليزية: Truth in Numbers: The Wikipedia Story)، سيتم إطلاقه في 2008.",
new String[] { "الفيلم", "الوثائقي", "الأول", "عن", "ويكيبيديا", "يسمى", "الحقيقة", "بالأرقام", "قصة", "ويكيبيديا",
"بالإنجليزية", "truth", "numbers", "wikipedia", "story", "سيتم", "إطلاقه", "في", "2008" } );
}
public void testAramaic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ܘܝܩܝܦܕܝܐ (ܐܢܓܠܝܐ: Wikipedia) ܗܘ ܐܝܢܣܩܠܘܦܕܝܐ ܚܐܪܬܐ ܕܐܢܛܪܢܛ ܒܠܫܢ̈ܐ ܣܓܝܐ̈ܐ܂ ܫܡܗ ܐܬܐ ܡܢ ܡ̈ܠܬܐ ܕ\"ܘܝܩܝ\" ܘ\"ܐܝܢܣܩܠܘܦܕܝܐ\"܀",
new String[] { "ܘܝܩܝܦܕܝܐ", "ܐܢܓܠܝܐ", "wikipedia", "ܗܘ", "ܐܝܢܣܩܠܘܦܕܝܐ", "ܚܐܪܬܐ", "ܕܐܢܛܪܢܛ", "ܒܠܫܢ̈ܐ", "ܣܓܝܐ̈ܐ", "ܫܡܗ",
"ܐܬܐ", "ܡܢ", "ܡ̈ܠܬܐ", "ܕ", "ܘܝܩܝ", "ܘ", "ܐܝܢܣܩܠܘܦܕܝܐ"});
}
public void testBengali() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "এই বিশ্বকোষ পরিচালনা করে উইকিমিডিয়া ফাউন্ডেশন (একটি অলাভজনক সংস্থা)। উইকিপিডিয়ার শুরু ১৫ জানুয়ারি, ২০০১ সালে। এখন পর্যন্ত ২০০টিরও বেশী ভাষায় উইকিপিডিয়া রয়েছে।",
new String[] { "এই", "বিশ্বকোষ", "পরিচালনা", "করে", "উইকিমিডিয়া", "ফাউন্ডেশন", "একটি", "অলাভজনক", "সংস্থা", "উইকিপিডিয়ার",
"শুরু", "১৫", "জানুয়ারি", "২০০১", "সালে", "এখন", "পর্যন্ত", "২০০টিরও", "বেশী", "ভাষায়", "উইকিপিডিয়া", "রয়েছে" });
}
public void testFarsi() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ویکی پدیای انگلیسی در تاریخ ۲۵ دی ۱۳۷۹ به صورت مکملی برای دانشنامهٔ تخصصی نوپدیا نوشته شد.",
new String[] { "ویکی", "پدیای", "انگلیسی", "در", "تاریخ", "۲۵", "دی", "۱۳۷۹", "به", "صورت", "مکملی",
"برای", "دانشنامهٔ", "تخصصی", "نوپدیا", "نوشته", "شد" });
}
public void testGreek() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Γράφεται σε συνεργασία από εθελοντές με το λογισμικό wiki, κάτι που σημαίνει ότι άρθρα μπορεί να προστεθούν ή να αλλάξουν από τον καθένα.",
new String[] { "γράφεται", "σε", "συνεργασία", "από", "εθελοντές", "με", "το", "λογισμικό", "wiki", "κάτι", "που",
"σημαίνει", "ότι", "άρθρα", "μπορεί", "να", "προστεθούν", "ή", "να", "αλλάξουν", "από", "τον", "καθένα" });
}
public void testThai() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "การที่ได้ต้องแสดงว่างานดี. แล้วเธอจะไปไหน? ๑๒๓๔",
new String[] { "การที่ได้ต้องแสดงว่างานดี", "แล้วเธอจะไปไหน", "๑๒๓๔" });
}
public void testLao() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ສາທາລະນະລັດ ປະຊາທິປະໄຕ ປະຊາຊົນລາວ",
new String[] { "ສາທາລະນະລັດ", "ປະຊາທິປະໄຕ", "ປະຊາຊົນລາວ" });
}
public void testTibetan() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "སྣོན་མཛོད་དང་ལས་འདིས་བོད་ཡིག་མི་ཉམས་གོང་འཕེལ་དུ་གཏོང་བར་ཧ་ཅང་དགེ་མཚན་མཆིས་སོ། །",
new String[] { "སྣོན", "མཛོད", "དང", "ལས", "འདིས", "བོད", "ཡིག",
"མི", "ཉམས", "གོང", "འཕེལ", "དུ", "གཏོང", "བར",
"ཧ", "ཅང", "དགེ", "མཚན", "མཆིས", "སོ" });
}
/*
* For chinese, tokenize as char (these can later form bigrams or whatever)
*/
public void testChinese() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "我是中国人。 1234 Tests ",
new String[] { "我", "是", "中", "国", "人", "1234", "tests"});
}
public void testEmpty() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "", new String[] {});
BaseTokenStreamTestCase.assertAnalyzesTo(a, ".", new String[] {});
BaseTokenStreamTestCase.assertAnalyzesTo(a, " ", new String[] {});
}
/* test various jira issues this analyzer is related to */
public void testLUCENE1545() throws Exception {
/*
* Standard analyzer does not correctly tokenize combining character U+0364 COMBINING LATIN SMALL LETTER E.
* The word "moͤchte" is incorrectly tokenized into "mo" "chte", the combining character is lost.
* Expected result is only one token "moͤchte".
*/
BaseTokenStreamTestCase.assertAnalyzesTo(a, "moͤchte", new String[] { "moͤchte" });
}
/* Tests from StandardAnalyzer, just to show behavior is similar */
public void testAlphanumericSA() throws Exception {
// alphanumeric tokens
BaseTokenStreamTestCase.assertAnalyzesTo(a, "B2B", new String[]{"b2b"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "2B", new String[]{"2b"});
}
public void testDelimitersSA() throws Exception {
// other delimiters: "-", "/", ","
BaseTokenStreamTestCase.assertAnalyzesTo(a, "some-dashed-phrase", new String[]{"some", "dashed", "phrase"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "dogs,chase,cats", new String[]{"dogs", "chase", "cats"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ac/dc", new String[]{"ac", "dc"});
}
public void testApostrophesSA() throws Exception {
// internal apostrophes: O'Reilly, you're, O'Reilly's
BaseTokenStreamTestCase.assertAnalyzesTo(a, "O'Reilly", new String[]{"o'reilly"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "you're", new String[]{"you're"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "she's", new String[]{"she's"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Jim's", new String[]{"jim's"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "don't", new String[]{"don't"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "O'Reilly's", new String[]{"o'reilly's"});
}
public void testNumericSA() throws Exception {
// floating point, serial, model numbers, ip addresses, etc.
BaseTokenStreamTestCase.assertAnalyzesTo(a, "21.35", new String[]{"21.35"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "R2D2 C3PO", new String[]{"r2d2", "c3po"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "216.239.63.104", new String[]{"216.239.63.104"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "216.239.63.104", new String[]{"216.239.63.104"});
}
public void testTextWithNumbersSA() throws Exception {
// numbers
BaseTokenStreamTestCase.assertAnalyzesTo(a, "David has 5000 bones", new String[]{"david", "has", "5000", "bones"});
}
public void testVariousTextSA() throws Exception {
// various
BaseTokenStreamTestCase.assertAnalyzesTo(a, "C embedded developers wanted", new String[]{"c", "embedded", "developers", "wanted"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "foo bar FOO BAR", new String[]{"foo", "bar", "foo", "bar"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "foo bar . FOO <> BAR", new String[]{"foo", "bar", "foo", "bar"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "\"QUOTED\" word", new String[]{"quoted", "word"});
}
public void testKoreanSA() throws Exception {
// Korean words
BaseTokenStreamTestCase.assertAnalyzesTo(a, "안녕하세요 한글입니다", new String[]{"안녕하세요", "한글입니다"});
}
public void testOffsets() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "David has 5000 bones",
new String[] {"david", "has", "5000", "bones"},
new int[] {0, 6, 10, 15},
new int[] {5, 9, 14, 20});
}
public void testTypes() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "david has 5000 bones",
new String[] {"david", "has", "5000", "bones"},
new String[] { "<ALPHANUM>", "<ALPHANUM>", "<NUM>", "<ALPHANUM>" });
}
public void testSupplementary() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "𩬅艱鍟䇹愯瀛",
new String[] {"𩬅", "艱", "鍟", "䇹", "愯", "瀛"},
new String[] { "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>" });
}
public void testKorean() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "훈민정음",
new String[] { "훈민정음" },
new String[] { "<HANGUL>" });
}
public void testJapanese() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "仮名遣い カタカナ",
new String[] { "仮", "名", "遣", "い", "カタカナ" },
new String[] { "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<HIRAGANA>", "<KATAKANA>" });
}
public void testCombiningMarks() throws Exception {
checkOneTerm(a, "ざ", "ざ"); // hiragana
checkOneTerm(a, "ザ", "ザ"); // katakana
checkOneTerm(a, "壹゙", "壹゙"); // ideographic
checkOneTerm(a, "아゙", "아゙"); // hangul
}
public void testBasicEmails() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a,
"one [email protected] two three [[email protected]] \"ArakaBanassaMassanaBakarA\" <[email protected]>",
new String[] {"one", "[email protected]", "two", "three", "[email protected]", "arakabanassamassanabakara", "[email protected]",},
new String[] { "<ALPHANUM>", "<EMAIL>", "<ALPHANUM>", "<ALPHANUM>", "<EMAIL>", "<ALPHANUM>", "<EMAIL>" });
}
public void testMailtoSchemeEmails () throws Exception {
// See LUCENE-3880
BaseTokenStreamTestCase.assertAnalyzesTo(a, "MAILTO:[email protected]",
new String[] {"mailto", "[email protected]"},
new String[] { "<ALPHANUM>", "<EMAIL>" });
// TODO: Support full mailto: scheme URIs. See RFC 6068: http://tools.ietf.org/html/rfc6068
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "mailto:[email protected],[email protected][email protected]"
+ "&subject=Subjectivity&body=Corpusivity%20or%20something%20like%20that",
new String[] { "mailto",
"[email protected]",
// TODO: recognize ',' address delimiter. Also, see examples of ';' delimiter use at: http://www.mailto.co.uk/
",[email protected]",
"[email protected]", // TODO: split field keys/values
"subject", "subjectivity",
"body", "corpusivity", "20or", "20something","20like", "20that" }, // TODO: Hex decoding + re-tokenization
new String[] { "<ALPHANUM>",
"<EMAIL>",
"<EMAIL>",
"<EMAIL>",
"<ALPHANUM>", "<ALPHANUM>",
"<ALPHANUM>", "<ALPHANUM>", "<ALPHANUM>", "<ALPHANUM>", "<ALPHANUM>", "<ALPHANUM>" });
}
public void testBasicURLs() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a,
"a <HTTPs://example.net/omg/isnt/that/NICE?no=its&n%30t#mntl-E>b-D ftp://www.example.com/ABC.txt file:///C:/path/to/a/FILE.txt C",
new String[] {"https://example.net/omg/isnt/that/nice?no=its&n%30t#mntl-e", "b", "d", "ftp://www.example.com/abc.txt", "file:///c:/path/to/a/file.txt", "c" },
new String[] { "<URL>", "<ALPHANUM>", "<ALPHANUM>", "<URL>", "<URL>", "<ALPHANUM>" });
}
public void testNoSchemeURLs() throws Exception {
// ".ph" is a Top Level Domain
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "<index.ph>", new String[]{"index.ph"}, new String[]{"<URL>"});
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "index.ph", new String[]{"index.ph"}, new String[]{"<URL>"});
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "index.php", new String[]{"index.php"}, new String[]{"<ALPHANUM>"});
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "index.phα", new String[]{"index.phα"}, new String[]{"<ALPHANUM>"});
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "index-h.php", new String[] { "index", "h.php" },
new String[] { "<ALPHANUM>","<ALPHANUM>"});
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "index2.php", new String[] { "index2", "php" },
new String[] { "<ALPHANUM>", "<ALPHANUM>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "index2.ph9,", new String[] { "index2", "ph9" },
new String[] { "<ALPHANUM>", "<ALPHANUM>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com,example.ph,index.php,index2.php,example2.ph",
new String[] { "example.com", "example.ph", "index.php", "index2", "php", "example2.ph" },
new String[] { "<URL>", "<URL>", "<ALPHANUM>", "<ALPHANUM>", "<ALPHANUM>", "<URL>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com:8080 example.com/path/here example.com?query=something example.com#fragment",
new String[] { "example.com:8080", "example.com/path/here", "example.com?query=something", "example.com#fragment" },
new String[] { "<URL>", "<URL>", "<URL>", "<URL>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com:8080/path/here?query=something#fragment",
new String[] { "example.com:8080/path/here?query=something#fragment" },
new String[] { "<URL>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com:8080/path/here?query=something",
new String[] { "example.com:8080/path/here?query=something" },
new String[] { "<URL>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com:8080/path/here#fragment",
new String[] { "example.com:8080/path/here#fragment" },
new String[] { "<URL>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com:8080/path/here",
new String[] { "example.com:8080/path/here" },
new String[] { "<URL>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com:8080?query=something#fragment",
new String[] { "example.com:8080?query=something#fragment" },
new String[] { "<URL>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com:8080?query=something",
new String[] { "example.com:8080?query=something" },
new String[] { "<URL>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com:8080#fragment",
new String[] { "example.com:8080#fragment" },
new String[] { "<URL>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com/path/here?query=something#fragment",
new String[] { "example.com/path/here?query=something#fragment" },
new String[] { "<URL>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com/path/here?query=something",
new String[] { "example.com/path/here?query=something" },
new String[] { "<URL>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com/path/here#fragment",
new String[] { "example.com/path/here#fragment" },
new String[] { "<URL>" });
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "example.com?query=something#fragment",
new String[] { "example.com?query=something#fragment" },
new String[] { "<URL>" });
}
/** blast some random strings through the analyzer */
public void testRandomStrings() throws Exception {
checkRandomData(random(), a, 200 * RANDOM_MULTIPLIER);
}
public void testMaxTokenLengthDefault() throws Exception {
StringBuilder bToken = new StringBuilder();
// exact max length:
for(int i=0;i<UAX29URLEmailAnalyzer.DEFAULT_MAX_TOKEN_LENGTH;i++) {
bToken.append('b');
}
String bString = bToken.toString();
// first bString is exact max default length; next one is 1 too long
String input = "x " + bString + " " + bString + "b";
assertAnalyzesTo(a, input, new String[] {"x", bString, bString, "b"});
a.close();
}
public void testMaxTokenLengthNonDefault() throws Exception {
UAX29URLEmailAnalyzer a = new UAX29URLEmailAnalyzer();
a.setMaxTokenLength(5);
assertAnalyzesTo(a, "ab cd toolong xy z", new String[]{"ab", "cd", "toolo", "ng", "xy", "z"});
a.close();
}
}
| CAFxX/lucene-solr | lucene/analysis/common/src/test/org/apache/lucene/analysis/email/TestUAX29URLEmailAnalyzer.java |
43,299 | package org.apache.lucene.analysis;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.analysis.standard.StandardTokenizer;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.Arrays;
/**
* 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.
*/
public class TestStandardAnalyzer extends BaseTokenStreamTestCase {
public void testHugeDoc() throws IOException {
StringBuilder sb = new StringBuilder();
char whitespace[] = new char[4094];
Arrays.fill(whitespace, ' ');
sb.append(whitespace);
sb.append("testing 1234");
String input = sb.toString();
StandardTokenizer tokenizer = new StandardTokenizer(TEST_VERSION_CURRENT, new StringReader(input));
BaseTokenStreamTestCase.assertTokenStreamContents(tokenizer, new String[] { "testing", "1234" });
}
private Analyzer a = new ReusableAnalyzerBase() {
@Override
protected TokenStreamComponents createComponents
(String fieldName, Reader reader) {
Tokenizer tokenizer = new StandardTokenizer(TEST_VERSION_CURRENT, reader);
return new TokenStreamComponents(tokenizer);
}
};
public void testArmenian() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Վիքիպեդիայի 13 միլիոն հոդվածները (4,600` հայերեն վիքիպեդիայում) գրվել են կամավորների կողմից ու համարյա բոլոր հոդվածները կարող է խմբագրել ցանկաց մարդ ով կարող է բացել Վիքիպեդիայի կայքը։",
new String[] { "Վիքիպեդիայի", "13", "միլիոն", "հոդվածները", "4,600", "հայերեն", "վիքիպեդիայում", "գրվել", "են", "կամավորների", "կողմից",
"ու", "համարյա", "բոլոր", "հոդվածները", "կարող", "է", "խմբագրել", "ցանկաց", "մարդ", "ով", "կարող", "է", "բացել", "Վիքիպեդիայի", "կայքը" } );
}
public void testAmharic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ዊኪፔድያ የባለ ብዙ ቋንቋ የተሟላ ትክክለኛና ነጻ መዝገበ ዕውቀት (ኢንሳይክሎፒዲያ) ነው። ማንኛውም",
new String[] { "ዊኪፔድያ", "የባለ", "ብዙ", "ቋንቋ", "የተሟላ", "ትክክለኛና", "ነጻ", "መዝገበ", "ዕውቀት", "ኢንሳይክሎፒዲያ", "ነው", "ማንኛውም" } );
}
public void testArabic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "الفيلم الوثائقي الأول عن ويكيبيديا يسمى \"الحقيقة بالأرقام: قصة ويكيبيديا\" (بالإنجليزية: Truth in Numbers: The Wikipedia Story)، سيتم إطلاقه في 2008.",
new String[] { "الفيلم", "الوثائقي", "الأول", "عن", "ويكيبيديا", "يسمى", "الحقيقة", "بالأرقام", "قصة", "ويكيبيديا",
"بالإنجليزية", "Truth", "in", "Numbers", "The", "Wikipedia", "Story", "سيتم", "إطلاقه", "في", "2008" } );
}
public void testAramaic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ܘܝܩܝܦܕܝܐ (ܐܢܓܠܝܐ: Wikipedia) ܗܘ ܐܝܢܣܩܠܘܦܕܝܐ ܚܐܪܬܐ ܕܐܢܛܪܢܛ ܒܠܫܢ̈ܐ ܣܓܝܐ̈ܐ܂ ܫܡܗ ܐܬܐ ܡܢ ܡ̈ܠܬܐ ܕ\"ܘܝܩܝ\" ܘ\"ܐܝܢܣܩܠܘܦܕܝܐ\"܀",
new String[] { "ܘܝܩܝܦܕܝܐ", "ܐܢܓܠܝܐ", "Wikipedia", "ܗܘ", "ܐܝܢܣܩܠܘܦܕܝܐ", "ܚܐܪܬܐ", "ܕܐܢܛܪܢܛ", "ܒܠܫܢ̈ܐ", "ܣܓܝܐ̈ܐ", "ܫܡܗ",
"ܐܬܐ", "ܡܢ", "ܡ̈ܠܬܐ", "ܕ", "ܘܝܩܝ", "ܘ", "ܐܝܢܣܩܠܘܦܕܝܐ"});
}
public void testBengali() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "এই বিশ্বকোষ পরিচালনা করে উইকিমিডিয়া ফাউন্ডেশন (একটি অলাভজনক সংস্থা)। উইকিপিডিয়ার শুরু ১৫ জানুয়ারি, ২০০১ সালে। এখন পর্যন্ত ২০০টিরও বেশী ভাষায় উইকিপিডিয়া রয়েছে।",
new String[] { "এই", "বিশ্বকোষ", "পরিচালনা", "করে", "উইকিমিডিয়া", "ফাউন্ডেশন", "একটি", "অলাভজনক", "সংস্থা", "উইকিপিডিয়ার",
"শুরু", "১৫", "জানুয়ারি", "২০০১", "সালে", "এখন", "পর্যন্ত", "২০০টিরও", "বেশী", "ভাষায়", "উইকিপিডিয়া", "রয়েছে" });
}
public void testFarsi() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ویکی پدیای انگلیسی در تاریخ ۲۵ دی ۱۳۷۹ به صورت مکملی برای دانشنامهٔ تخصصی نوپدیا نوشته شد.",
new String[] { "ویکی", "پدیای", "انگلیسی", "در", "تاریخ", "۲۵", "دی", "۱۳۷۹", "به", "صورت", "مکملی",
"برای", "دانشنامهٔ", "تخصصی", "نوپدیا", "نوشته", "شد" });
}
public void testGreek() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Γράφεται σε συνεργασία από εθελοντές με το λογισμικό wiki, κάτι που σημαίνει ότι άρθρα μπορεί να προστεθούν ή να αλλάξουν από τον καθένα.",
new String[] { "Γράφεται", "σε", "συνεργασία", "από", "εθελοντές", "με", "το", "λογισμικό", "wiki", "κάτι", "που",
"σημαίνει", "ότι", "άρθρα", "μπορεί", "να", "προστεθούν", "ή", "να", "αλλάξουν", "από", "τον", "καθένα" });
}
public void testThai() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "การที่ได้ต้องแสดงว่างานดี. แล้วเธอจะไปไหน? ๑๒๓๔",
new String[] { "การที่ได้ต้องแสดงว่างานดี", "แล้วเธอจะไปไหน", "๑๒๓๔" });
}
public void testLao() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ສາທາລະນະລັດ ປະຊາທິປະໄຕ ປະຊາຊົນລາວ",
new String[] { "ສາທາລະນະລັດ", "ປະຊາທິປະໄຕ", "ປະຊາຊົນລາວ" });
}
public void testTibetan() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "སྣོན་མཛོད་དང་ལས་འདིས་བོད་ཡིག་མི་ཉམས་གོང་འཕེལ་དུ་གཏོང་བར་ཧ་ཅང་དགེ་མཚན་མཆིས་སོ། །",
new String[] { "སྣོན", "མཛོད", "དང", "ལས", "འདིས", "བོད", "ཡིག",
"མི", "ཉམས", "གོང", "འཕེལ", "དུ", "གཏོང", "བར",
"ཧ", "ཅང", "དགེ", "མཚན", "མཆིས", "སོ" });
}
/*
* For chinese, tokenize as char (these can later form bigrams or whatever)
*/
public void testChinese() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "我是中国人。 1234 Tests ",
new String[] { "我", "是", "中", "国", "人", "1234", "Tests"});
}
public void testEmpty() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "", new String[] {});
BaseTokenStreamTestCase.assertAnalyzesTo(a, ".", new String[] {});
BaseTokenStreamTestCase.assertAnalyzesTo(a, " ", new String[] {});
}
/* test various jira issues this analyzer is related to */
public void testLUCENE1545() throws Exception {
/*
* Standard analyzer does not correctly tokenize combining character U+0364 COMBINING LATIN SMALL LETTRE E.
* The word "moͤchte" is incorrectly tokenized into "mo" "chte", the combining character is lost.
* Expected result is only on token "moͤchte".
*/
BaseTokenStreamTestCase.assertAnalyzesTo(a, "moͤchte", new String[] { "moͤchte" });
}
/* Tests from StandardAnalyzer, just to show behavior is similar */
public void testAlphanumericSA() throws Exception {
// alphanumeric tokens
BaseTokenStreamTestCase.assertAnalyzesTo(a, "B2B", new String[]{"B2B"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "2B", new String[]{"2B"});
}
public void testDelimitersSA() throws Exception {
// other delimiters: "-", "/", ","
BaseTokenStreamTestCase.assertAnalyzesTo(a, "some-dashed-phrase", new String[]{"some", "dashed", "phrase"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "dogs,chase,cats", new String[]{"dogs", "chase", "cats"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ac/dc", new String[]{"ac", "dc"});
}
public void testApostrophesSA() throws Exception {
// internal apostrophes: O'Reilly, you're, O'Reilly's
BaseTokenStreamTestCase.assertAnalyzesTo(a, "O'Reilly", new String[]{"O'Reilly"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "you're", new String[]{"you're"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "she's", new String[]{"she's"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Jim's", new String[]{"Jim's"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "don't", new String[]{"don't"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "O'Reilly's", new String[]{"O'Reilly's"});
}
public void testNumericSA() throws Exception {
// floating point, serial, model numbers, ip addresses, etc.
BaseTokenStreamTestCase.assertAnalyzesTo(a, "21.35", new String[]{"21.35"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "R2D2 C3PO", new String[]{"R2D2", "C3PO"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "216.239.63.104", new String[]{"216.239.63.104"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "216.239.63.104", new String[]{"216.239.63.104"});
}
public void testTextWithNumbersSA() throws Exception {
// numbers
BaseTokenStreamTestCase.assertAnalyzesTo(a, "David has 5000 bones", new String[]{"David", "has", "5000", "bones"});
}
public void testVariousTextSA() throws Exception {
// various
BaseTokenStreamTestCase.assertAnalyzesTo(a, "C embedded developers wanted", new String[]{"C", "embedded", "developers", "wanted"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "foo bar FOO BAR", new String[]{"foo", "bar", "FOO", "BAR"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "foo bar . FOO <> BAR", new String[]{"foo", "bar", "FOO", "BAR"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "\"QUOTED\" word", new String[]{"QUOTED", "word"});
}
public void testKoreanSA() throws Exception {
// Korean words
BaseTokenStreamTestCase.assertAnalyzesTo(a, "안녕하세요 한글입니다", new String[]{"안녕하세요", "한글입니다"});
}
public void testOffsets() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "David has 5000 bones",
new String[] {"David", "has", "5000", "bones"},
new int[] {0, 6, 10, 15},
new int[] {5, 9, 14, 20});
}
public void testTypes() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "David has 5000 bones",
new String[] {"David", "has", "5000", "bones"},
new String[] { "<ALPHANUM>", "<ALPHANUM>", "<NUM>", "<ALPHANUM>" });
}
public void testUnicodeWordBreaks() throws Exception {
WordBreakTestUnicode_6_0_0 wordBreakTest = new WordBreakTestUnicode_6_0_0();
wordBreakTest.test(a);
}
public void testSupplementary() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "𩬅艱鍟䇹愯瀛",
new String[] {"𩬅", "艱", "鍟", "䇹", "愯", "瀛"},
new String[] { "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>" });
}
public void testKorean() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "훈민정음",
new String[] { "훈민정음" },
new String[] { "<HANGUL>" });
}
public void testJapanese() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "仮名遣い カタカナ",
new String[] { "仮", "名", "遣", "い", "カタカナ" },
new String[] { "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<HIRAGANA>", "<KATAKANA>" });
}
/** blast some random strings through the analyzer */
public void testRandomStrings() throws Exception {
checkRandomData(random, new StandardAnalyzer(TEST_VERSION_CURRENT), 10000*RANDOM_MULTIPLIER);
}
}
| fluidinfo/solr-packaging | lucene/backwards/src/test/org/apache/lucene/analysis/TestStandardAnalyzer.java |
43,304 | package org.apache.lucene.analysis.core;
/**
* 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.
*/
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.Arrays;
import java.util.Random;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.BaseTokenStreamTestCase;
import org.apache.lucene.analysis.MockGraphTokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.analysis.standard.StandardTokenizer;
import org.apache.lucene.util.Version;
public class TestStandardAnalyzer extends BaseTokenStreamTestCase {
public void testHugeDoc() throws IOException {
StringBuilder sb = new StringBuilder();
char whitespace[] = new char[4094];
Arrays.fill(whitespace, ' ');
sb.append(whitespace);
sb.append("testing 1234");
String input = sb.toString();
StandardTokenizer tokenizer = new StandardTokenizer(TEST_VERSION_CURRENT, new StringReader(input));
BaseTokenStreamTestCase.assertTokenStreamContents(tokenizer, new String[] { "testing", "1234" });
}
private Analyzer a = new Analyzer() {
@Override
protected TokenStreamComponents createComponents
(String fieldName, Reader reader) {
Tokenizer tokenizer = new StandardTokenizer(TEST_VERSION_CURRENT, reader);
return new TokenStreamComponents(tokenizer);
}
};
public void testArmenian() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Վիքիպեդիայի 13 միլիոն հոդվածները (4,600` հայերեն վիքիպեդիայում) գրվել են կամավորների կողմից ու համարյա բոլոր հոդվածները կարող է խմբագրել ցանկաց մարդ ով կարող է բացել Վիքիպեդիայի կայքը։",
new String[] { "Վիքիպեդիայի", "13", "միլիոն", "հոդվածները", "4,600", "հայերեն", "վիքիպեդիայում", "գրվել", "են", "կամավորների", "կողմից",
"ու", "համարյա", "բոլոր", "հոդվածները", "կարող", "է", "խմբագրել", "ցանկաց", "մարդ", "ով", "կարող", "է", "բացել", "Վիքիպեդիայի", "կայքը" } );
}
public void testAmharic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ዊኪፔድያ የባለ ብዙ ቋንቋ የተሟላ ትክክለኛና ነጻ መዝገበ ዕውቀት (ኢንሳይክሎፒዲያ) ነው። ማንኛውም",
new String[] { "ዊኪፔድያ", "የባለ", "ብዙ", "ቋንቋ", "የተሟላ", "ትክክለኛና", "ነጻ", "መዝገበ", "ዕውቀት", "ኢንሳይክሎፒዲያ", "ነው", "ማንኛውም" } );
}
public void testArabic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "الفيلم الوثائقي الأول عن ويكيبيديا يسمى \"الحقيقة بالأرقام: قصة ويكيبيديا\" (بالإنجليزية: Truth in Numbers: The Wikipedia Story)، سيتم إطلاقه في 2008.",
new String[] { "الفيلم", "الوثائقي", "الأول", "عن", "ويكيبيديا", "يسمى", "الحقيقة", "بالأرقام", "قصة", "ويكيبيديا",
"بالإنجليزية", "Truth", "in", "Numbers", "The", "Wikipedia", "Story", "سيتم", "إطلاقه", "في", "2008" } );
}
public void testAramaic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ܘܝܩܝܦܕܝܐ (ܐܢܓܠܝܐ: Wikipedia) ܗܘ ܐܝܢܣܩܠܘܦܕܝܐ ܚܐܪܬܐ ܕܐܢܛܪܢܛ ܒܠܫܢ̈ܐ ܣܓܝܐ̈ܐ܂ ܫܡܗ ܐܬܐ ܡܢ ܡ̈ܠܬܐ ܕ\"ܘܝܩܝ\" ܘ\"ܐܝܢܣܩܠܘܦܕܝܐ\"܀",
new String[] { "ܘܝܩܝܦܕܝܐ", "ܐܢܓܠܝܐ", "Wikipedia", "ܗܘ", "ܐܝܢܣܩܠܘܦܕܝܐ", "ܚܐܪܬܐ", "ܕܐܢܛܪܢܛ", "ܒܠܫܢ̈ܐ", "ܣܓܝܐ̈ܐ", "ܫܡܗ",
"ܐܬܐ", "ܡܢ", "ܡ̈ܠܬܐ", "ܕ", "ܘܝܩܝ", "ܘ", "ܐܝܢܣܩܠܘܦܕܝܐ"});
}
public void testBengali() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "এই বিশ্বকোষ পরিচালনা করে উইকিমিডিয়া ফাউন্ডেশন (একটি অলাভজনক সংস্থা)। উইকিপিডিয়ার শুরু ১৫ জানুয়ারি, ২০০১ সালে। এখন পর্যন্ত ২০০টিরও বেশী ভাষায় উইকিপিডিয়া রয়েছে।",
new String[] { "এই", "বিশ্বকোষ", "পরিচালনা", "করে", "উইকিমিডিয়া", "ফাউন্ডেশন", "একটি", "অলাভজনক", "সংস্থা", "উইকিপিডিয়ার",
"শুরু", "১৫", "জানুয়ারি", "২০০১", "সালে", "এখন", "পর্যন্ত", "২০০টিরও", "বেশী", "ভাষায়", "উইকিপিডিয়া", "রয়েছে" });
}
public void testFarsi() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ویکی پدیای انگلیسی در تاریخ ۲۵ دی ۱۳۷۹ به صورت مکملی برای دانشنامهٔ تخصصی نوپدیا نوشته شد.",
new String[] { "ویکی", "پدیای", "انگلیسی", "در", "تاریخ", "۲۵", "دی", "۱۳۷۹", "به", "صورت", "مکملی",
"برای", "دانشنامهٔ", "تخصصی", "نوپدیا", "نوشته", "شد" });
}
public void testGreek() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Γράφεται σε συνεργασία από εθελοντές με το λογισμικό wiki, κάτι που σημαίνει ότι άρθρα μπορεί να προστεθούν ή να αλλάξουν από τον καθένα.",
new String[] { "Γράφεται", "σε", "συνεργασία", "από", "εθελοντές", "με", "το", "λογισμικό", "wiki", "κάτι", "που",
"σημαίνει", "ότι", "άρθρα", "μπορεί", "να", "προστεθούν", "ή", "να", "αλλάξουν", "από", "τον", "καθένα" });
}
public void testThai() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "การที่ได้ต้องแสดงว่างานดี. แล้วเธอจะไปไหน? ๑๒๓๔",
new String[] { "การที่ได้ต้องแสดงว่างานดี", "แล้วเธอจะไปไหน", "๑๒๓๔" });
}
public void testLao() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ສາທາລະນະລັດ ປະຊາທິປະໄຕ ປະຊາຊົນລາວ",
new String[] { "ສາທາລະນະລັດ", "ປະຊາທິປະໄຕ", "ປະຊາຊົນລາວ" });
}
public void testTibetan() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "སྣོན་མཛོད་དང་ལས་འདིས་བོད་ཡིག་མི་ཉམས་གོང་འཕེལ་དུ་གཏོང་བར་ཧ་ཅང་དགེ་མཚན་མཆིས་སོ། །",
new String[] { "སྣོན", "མཛོད", "དང", "ལས", "འདིས", "བོད", "ཡིག",
"མི", "ཉམས", "གོང", "འཕེལ", "དུ", "གཏོང", "བར",
"ཧ", "ཅང", "དགེ", "མཚན", "མཆིས", "སོ" });
}
/*
* For chinese, tokenize as char (these can later form bigrams or whatever)
*/
public void testChinese() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "我是中国人。 1234 Tests ",
new String[] { "我", "是", "中", "国", "人", "1234", "Tests"});
}
public void testEmpty() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "", new String[] {});
BaseTokenStreamTestCase.assertAnalyzesTo(a, ".", new String[] {});
BaseTokenStreamTestCase.assertAnalyzesTo(a, " ", new String[] {});
}
/* test various jira issues this analyzer is related to */
public void testLUCENE1545() throws Exception {
/*
* Standard analyzer does not correctly tokenize combining character U+0364 COMBINING LATIN SMALL LETTRE E.
* The word "moͤchte" is incorrectly tokenized into "mo" "chte", the combining character is lost.
* Expected result is only on token "moͤchte".
*/
BaseTokenStreamTestCase.assertAnalyzesTo(a, "moͤchte", new String[] { "moͤchte" });
}
/* Tests from StandardAnalyzer, just to show behavior is similar */
public void testAlphanumericSA() throws Exception {
// alphanumeric tokens
BaseTokenStreamTestCase.assertAnalyzesTo(a, "B2B", new String[]{"B2B"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "2B", new String[]{"2B"});
}
public void testDelimitersSA() throws Exception {
// other delimiters: "-", "/", ","
BaseTokenStreamTestCase.assertAnalyzesTo(a, "some-dashed-phrase", new String[]{"some", "dashed", "phrase"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "dogs,chase,cats", new String[]{"dogs", "chase", "cats"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ac/dc", new String[]{"ac", "dc"});
}
public void testApostrophesSA() throws Exception {
// internal apostrophes: O'Reilly, you're, O'Reilly's
BaseTokenStreamTestCase.assertAnalyzesTo(a, "O'Reilly", new String[]{"O'Reilly"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "you're", new String[]{"you're"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "she's", new String[]{"she's"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Jim's", new String[]{"Jim's"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "don't", new String[]{"don't"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "O'Reilly's", new String[]{"O'Reilly's"});
}
public void testNumericSA() throws Exception {
// floating point, serial, model numbers, ip addresses, etc.
BaseTokenStreamTestCase.assertAnalyzesTo(a, "21.35", new String[]{"21.35"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "R2D2 C3PO", new String[]{"R2D2", "C3PO"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "216.239.63.104", new String[]{"216.239.63.104"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "216.239.63.104", new String[]{"216.239.63.104"});
}
public void testTextWithNumbersSA() throws Exception {
// numbers
BaseTokenStreamTestCase.assertAnalyzesTo(a, "David has 5000 bones", new String[]{"David", "has", "5000", "bones"});
}
public void testVariousTextSA() throws Exception {
// various
BaseTokenStreamTestCase.assertAnalyzesTo(a, "C embedded developers wanted", new String[]{"C", "embedded", "developers", "wanted"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "foo bar FOO BAR", new String[]{"foo", "bar", "FOO", "BAR"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "foo bar . FOO <> BAR", new String[]{"foo", "bar", "FOO", "BAR"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "\"QUOTED\" word", new String[]{"QUOTED", "word"});
}
public void testKoreanSA() throws Exception {
// Korean words
BaseTokenStreamTestCase.assertAnalyzesTo(a, "안녕하세요 한글입니다", new String[]{"안녕하세요", "한글입니다"});
}
public void testOffsets() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "David has 5000 bones",
new String[] {"David", "has", "5000", "bones"},
new int[] {0, 6, 10, 15},
new int[] {5, 9, 14, 20});
}
public void testTypes() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "David has 5000 bones",
new String[] {"David", "has", "5000", "bones"},
new String[] { "<ALPHANUM>", "<ALPHANUM>", "<NUM>", "<ALPHANUM>" });
}
public void testUnicodeWordBreaks() throws Exception {
WordBreakTestUnicode_6_0_0 wordBreakTest = new WordBreakTestUnicode_6_0_0();
wordBreakTest.test(a);
}
public void testSupplementary() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "𩬅艱鍟䇹愯瀛",
new String[] {"𩬅", "艱", "鍟", "䇹", "愯", "瀛"},
new String[] { "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>" });
}
public void testKorean() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "훈민정음",
new String[] { "훈민정음" },
new String[] { "<HANGUL>" });
}
public void testJapanese() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "仮名遣い カタカナ",
new String[] { "仮", "名", "遣", "い", "カタカナ" },
new String[] { "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<HIRAGANA>", "<KATAKANA>" });
}
public void testCombiningMarks() throws Exception {
checkOneTerm(a, "ざ", "ざ"); // hiragana
checkOneTerm(a, "ザ", "ザ"); // katakana
checkOneTerm(a, "壹゙", "壹゙"); // ideographic
checkOneTerm(a, "아゙", "아゙"); // hangul
}
/** @deprecated remove this and sophisticated backwards layer in 5.0 */
@Deprecated
public void testCombiningMarksBackwards() throws Exception {
Analyzer a = new StandardAnalyzer(Version.LUCENE_33);
checkOneTerm(a, "ざ", "さ"); // hiragana Bug
checkOneTerm(a, "ザ", "ザ"); // katakana Works
checkOneTerm(a, "壹゙", "壹"); // ideographic Bug
checkOneTerm(a, "아゙", "아゙"); // hangul Works
}
/** blast some random strings through the analyzer */
public void testRandomStrings() throws Exception {
checkRandomData(random(), new StandardAnalyzer(TEST_VERSION_CURRENT), 10000*RANDOM_MULTIPLIER);
}
/** blast some random large strings through the analyzer */
public void testRandomHugeStrings() throws Exception {
Random random = random();
checkRandomData(random, new StandardAnalyzer(TEST_VERSION_CURRENT), 200*RANDOM_MULTIPLIER, 8192);
}
// Adds random graph after:
public void testRandomHugeStringsGraphAfter() throws Exception {
Random random = random();
checkRandomData(random,
new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
Tokenizer tokenizer = new StandardTokenizer(TEST_VERSION_CURRENT, reader);
TokenStream tokenStream = new MockGraphTokenFilter(random(), tokenizer);
return new TokenStreamComponents(tokenizer, tokenStream);
}
},
200*RANDOM_MULTIPLIER, 8192);
}
}
| sudarshang/lucene-solr | lucene/analysis/common/src/test/org/apache/lucene/analysis/core/TestStandardAnalyzer.java |
43,305 | package org.apache.lucene.analysis.icu.segmentation;
/*
* 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.
*/
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.BaseTokenStreamTestCase;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.icu.ICUNormalizer2Filter;
import org.apache.lucene.analysis.icu.tokenattributes.ScriptAttribute;
import com.ibm.icu.lang.UScript;
import java.io.IOException;
import java.io.StringReader;
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
public class TestICUTokenizer extends BaseTokenStreamTestCase {
public void testHugeDoc() throws IOException {
StringBuilder sb = new StringBuilder();
char whitespace[] = new char[4094];
Arrays.fill(whitespace, ' ');
sb.append(whitespace);
sb.append("testing 1234");
String input = sb.toString();
ICUTokenizer tokenizer = new ICUTokenizer(newAttributeFactory(), new DefaultICUTokenizerConfig(false));
tokenizer.setReader(new StringReader(input));
assertTokenStreamContents(tokenizer, new String[] { "testing", "1234" });
}
public void testHugeTerm2() throws IOException {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 40960; i++) {
sb.append('a');
}
String input = sb.toString();
ICUTokenizer tokenizer = new ICUTokenizer(newAttributeFactory(), new DefaultICUTokenizerConfig(false));
tokenizer.setReader(new StringReader(input));
char token[] = new char[4096];
Arrays.fill(token, 'a');
String expectedToken = new String(token);
String expected[] = {
expectedToken, expectedToken, expectedToken,
expectedToken, expectedToken, expectedToken,
expectedToken, expectedToken, expectedToken,
expectedToken
};
assertTokenStreamContents(tokenizer, expected);
}
private Analyzer a = new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName) {
Tokenizer tokenizer = new ICUTokenizer(newAttributeFactory(), new DefaultICUTokenizerConfig(false));
TokenFilter filter = new ICUNormalizer2Filter(tokenizer);
return new TokenStreamComponents(tokenizer, filter);
}
};
public void testArmenian() throws Exception {
assertAnalyzesTo(a, "Վիքիպեդիայի 13 միլիոն հոդվածները (4,600` հայերեն վիքիպեդիայում) գրվել են կամավորների կողմից ու համարյա բոլոր հոդվածները կարող է խմբագրել ցանկաց մարդ ով կարող է բացել Վիքիպեդիայի կայքը։",
new String[] { "վիքիպեդիայի", "13", "միլիոն", "հոդվածները", "4,600", "հայերեն", "վիքիպեդիայում", "գրվել", "են", "կամավորների", "կողմից",
"ու", "համարյա", "բոլոր", "հոդվածները", "կարող", "է", "խմբագրել", "ցանկաց", "մարդ", "ով", "կարող", "է", "բացել", "վիքիպեդիայի", "կայքը" } );
}
public void testAmharic() throws Exception {
assertAnalyzesTo(a, "ዊኪፔድያ የባለ ብዙ ቋንቋ የተሟላ ትክክለኛና ነጻ መዝገበ ዕውቀት (ኢንሳይክሎፒዲያ) ነው። ማንኛውም",
new String[] { "ዊኪፔድያ", "የባለ", "ብዙ", "ቋንቋ", "የተሟላ", "ትክክለኛና", "ነጻ", "መዝገበ", "ዕውቀት", "ኢንሳይክሎፒዲያ", "ነው", "ማንኛውም" } );
}
public void testArabic() throws Exception {
assertAnalyzesTo(a, "الفيلم الوثائقي الأول عن ويكيبيديا يسمى \"الحقيقة بالأرقام: قصة ويكيبيديا\" (بالإنجليزية: Truth in Numbers: The Wikipedia Story)، سيتم إطلاقه في 2008.",
new String[] { "الفيلم", "الوثائقي", "الأول", "عن", "ويكيبيديا", "يسمى", "الحقيقة", "بالأرقام", "قصة", "ويكيبيديا",
"بالإنجليزية", "truth", "in", "numbers", "the", "wikipedia", "story", "سيتم", "إطلاقه", "في", "2008" } );
}
public void testAramaic() throws Exception {
assertAnalyzesTo(a, "ܘܝܩܝܦܕܝܐ (ܐܢܓܠܝܐ: Wikipedia) ܗܘ ܐܝܢܣܩܠܘܦܕܝܐ ܚܐܪܬܐ ܕܐܢܛܪܢܛ ܒܠܫܢ̈ܐ ܣܓܝܐ̈ܐ܂ ܫܡܗ ܐܬܐ ܡܢ ܡ̈ܠܬܐ ܕ\"ܘܝܩܝ\" ܘ\"ܐܝܢܣܩܠܘܦܕܝܐ\"܀",
new String[] { "ܘܝܩܝܦܕܝܐ", "ܐܢܓܠܝܐ", "wikipedia", "ܗܘ", "ܐܝܢܣܩܠܘܦܕܝܐ", "ܚܐܪܬܐ", "ܕܐܢܛܪܢܛ", "ܒܠܫܢ̈ܐ", "ܣܓܝܐ̈ܐ", "ܫܡܗ",
"ܐܬܐ", "ܡܢ", "ܡ̈ܠܬܐ", "ܕ", "ܘܝܩܝ", "ܘ", "ܐܝܢܣܩܠܘܦܕܝܐ"});
}
public void testBengali() throws Exception {
assertAnalyzesTo(a, "এই বিশ্বকোষ পরিচালনা করে উইকিমিডিয়া ফাউন্ডেশন (একটি অলাভজনক সংস্থা)। উইকিপিডিয়ার শুরু ১৫ জানুয়ারি, ২০০১ সালে। এখন পর্যন্ত ২০০টিরও বেশী ভাষায় উইকিপিডিয়া রয়েছে।",
new String[] { "এই", "বিশ্বকোষ", "পরিচালনা", "করে", "উইকিমিডিয়া", "ফাউন্ডেশন", "একটি", "অলাভজনক", "সংস্থা", "উইকিপিডিয়ার",
"শুরু", "১৫", "জানুয়ারি", "২০০১", "সালে", "এখন", "পর্যন্ত", "২০০টিরও", "বেশী", "ভাষায়", "উইকিপিডিয়া", "রয়েছে" });
}
public void testFarsi() throws Exception {
assertAnalyzesTo(a, "ویکی پدیای انگلیسی در تاریخ ۲۵ دی ۱۳۷۹ به صورت مکملی برای دانشنامهٔ تخصصی نوپدیا نوشته شد.",
new String[] { "ویکی", "پدیای", "انگلیسی", "در", "تاریخ", "۲۵", "دی", "۱۳۷۹", "به", "صورت", "مکملی",
"برای", "دانشنامهٔ", "تخصصی", "نوپدیا", "نوشته", "شد" });
}
public void testGreek() throws Exception {
assertAnalyzesTo(a, "Γράφεται σε συνεργασία από εθελοντές με το λογισμικό wiki, κάτι που σημαίνει ότι άρθρα μπορεί να προστεθούν ή να αλλάξουν από τον καθένα.",
new String[] { "γράφεται", "σε", "συνεργασία", "από", "εθελοντέσ", "με", "το", "λογισμικό", "wiki", "κάτι", "που",
"σημαίνει", "ότι", "άρθρα", "μπορεί", "να", "προστεθούν", "ή", "να", "αλλάξουν", "από", "τον", "καθένα" });
}
public void testLao() throws Exception {
assertAnalyzesTo(a, "ກວ່າດອກ", new String[] { "ກວ່າ", "ດອກ" });
assertAnalyzesTo(a, "ພາສາລາວ", new String[] { "ພາສາ", "ລາວ"}, new String[] { "<ALPHANUM>", "<ALPHANUM>" });
}
public void testMyanmar() throws Exception {
assertAnalyzesTo(a, "သက်ဝင်လှုပ်ရှားစေပြီး", new String[] { "သက်ဝင်", "လှုပ်ရှား", "စေ", "ပြီး" });
}
public void testThai() throws Exception {
assertAnalyzesTo(a, "การที่ได้ต้องแสดงว่างานดี. แล้วเธอจะไปไหน? ๑๒๓๔",
new String[] { "การ", "ที่", "ได้", "ต้อง", "แสดง", "ว่า", "งาน", "ดี", "แล้ว", "เธอ", "จะ", "ไป", "ไหน", "๑๒๓๔"});
}
public void testTibetan() throws Exception {
assertAnalyzesTo(a, "སྣོན་མཛོད་དང་ལས་འདིས་བོད་ཡིག་མི་ཉམས་གོང་འཕེལ་དུ་གཏོང་བར་ཧ་ཅང་དགེ་མཚན་མཆིས་སོ། །",
new String[] { "སྣོན", "མཛོད", "དང", "ལས", "འདིས", "བོད", "ཡིག", "མི", "ཉམས", "གོང", "འཕེལ", "དུ", "གཏོང", "བར", "ཧ", "ཅང", "དགེ", "མཚན", "མཆིས", "སོ" });
}
/*
* For chinese, tokenize as char (these can later form bigrams or whatever)
*/
public void testChinese() throws Exception {
assertAnalyzesTo(a, "我是中国人。 1234 Tests ",
new String[] { "我", "是", "中", "国", "人", "1234", "tests"});
}
public void testHebrew() throws Exception {
assertAnalyzesTo(a, "דנקנר תקף את הדו\"ח",
new String[] { "דנקנר", "תקף", "את", "הדו\"ח" });
assertAnalyzesTo(a, "חברת בת של מודי'ס",
new String[] { "חברת", "בת", "של", "מודי'ס" });
}
public void testEmpty() throws Exception {
assertAnalyzesTo(a, "", new String[] {});
assertAnalyzesTo(a, ".", new String[] {});
assertAnalyzesTo(a, " ", new String[] {});
}
/* test various jira issues this analyzer is related to */
public void testLUCENE1545() throws Exception {
/*
* Standard analyzer does not correctly tokenize combining character U+0364 COMBINING LATIN SMALL LETTRE E.
* The word "moͤchte" is incorrectly tokenized into "mo" "chte", the combining character is lost.
* Expected result is only on token "moͤchte".
*/
assertAnalyzesTo(a, "moͤchte", new String[] { "moͤchte" });
}
/* Tests from StandardAnalyzer, just to show behavior is similar */
public void testAlphanumericSA() throws Exception {
// alphanumeric tokens
assertAnalyzesTo(a, "B2B", new String[]{"b2b"});
assertAnalyzesTo(a, "2B", new String[]{"2b"});
}
public void testDelimitersSA() throws Exception {
// other delimiters: "-", "/", ","
assertAnalyzesTo(a, "some-dashed-phrase", new String[]{"some", "dashed", "phrase"});
assertAnalyzesTo(a, "dogs,chase,cats", new String[]{"dogs", "chase", "cats"});
assertAnalyzesTo(a, "ac/dc", new String[]{"ac", "dc"});
}
public void testApostrophesSA() throws Exception {
// internal apostrophes: O'Reilly, you're, O'Reilly's
assertAnalyzesTo(a, "O'Reilly", new String[]{"o'reilly"});
assertAnalyzesTo(a, "you're", new String[]{"you're"});
assertAnalyzesTo(a, "she's", new String[]{"she's"});
assertAnalyzesTo(a, "Jim's", new String[]{"jim's"});
assertAnalyzesTo(a, "don't", new String[]{"don't"});
assertAnalyzesTo(a, "O'Reilly's", new String[]{"o'reilly's"});
}
public void testNumericSA() throws Exception {
// floating point, serial, model numbers, ip addresses, etc.
// every other segment must have at least one digit
assertAnalyzesTo(a, "21.35", new String[]{"21.35"});
assertAnalyzesTo(a, "R2D2 C3PO", new String[]{"r2d2", "c3po"});
assertAnalyzesTo(a, "216.239.63.104", new String[]{"216.239.63.104"});
assertAnalyzesTo(a, "216.239.63.104", new String[]{"216.239.63.104"});
}
public void testTextWithNumbersSA() throws Exception {
// numbers
assertAnalyzesTo(a, "David has 5000 bones", new String[]{"david", "has", "5000", "bones"});
}
public void testVariousTextSA() throws Exception {
// various
assertAnalyzesTo(a, "C embedded developers wanted", new String[]{"c", "embedded", "developers", "wanted"});
assertAnalyzesTo(a, "foo bar FOO BAR", new String[]{"foo", "bar", "foo", "bar"});
assertAnalyzesTo(a, "foo bar . FOO <> BAR", new String[]{"foo", "bar", "foo", "bar"});
assertAnalyzesTo(a, "\"QUOTED\" word", new String[]{"quoted", "word"});
}
public void testKoreanSA() throws Exception {
// Korean words
assertAnalyzesTo(a, "안녕하세요 한글입니다", new String[]{"안녕하세요", "한글입니다"});
}
public void testReusableTokenStream() throws Exception {
assertAnalyzesTo(a, "སྣོན་མཛོད་དང་ལས་འདིས་བོད་ཡིག་མི་ཉམས་གོང་འཕེལ་དུ་གཏོང་བར་ཧ་ཅང་དགེ་མཚན་མཆིས་སོ། །",
new String[] { "སྣོན", "མཛོད", "དང", "ལས", "འདིས", "བོད", "ཡིག", "མི", "ཉམས", "གོང",
"འཕེལ", "དུ", "གཏོང", "བར", "ཧ", "ཅང", "དགེ", "མཚན", "མཆིས", "སོ" });
}
public void testOffsets() throws Exception {
assertAnalyzesTo(a, "David has 5000 bones",
new String[] {"david", "has", "5000", "bones"},
new int[] {0, 6, 10, 15},
new int[] {5, 9, 14, 20});
}
public void testTypes() throws Exception {
assertAnalyzesTo(a, "David has 5000 bones",
new String[] {"david", "has", "5000", "bones"},
new String[] { "<ALPHANUM>", "<ALPHANUM>", "<NUM>", "<ALPHANUM>" });
}
public void testKorean() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "훈민정음",
new String[] { "훈민정음" },
new String[] { "<HANGUL>" });
}
public void testJapanese() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "仮名遣い カタカナ",
new String[] { "仮", "名", "遣", "い", "カタカナ" },
new String[] { "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<HIRAGANA>", "<KATAKANA>" });
}
/** blast some random strings through the analyzer */
public void testRandomStrings() throws Exception {
checkRandomData(random(), a, 1000*RANDOM_MULTIPLIER);
}
/** blast some random large strings through the analyzer */
public void testRandomHugeStrings() throws Exception {
Random random = random();
checkRandomData(random, a, 100*RANDOM_MULTIPLIER, 8192);
}
public void testTokenAttributes() throws Exception {
try (TokenStream ts = a.tokenStream("dummy", "This is a test")) {
ScriptAttribute scriptAtt = ts.addAttribute(ScriptAttribute.class);
ts.reset();
while (ts.incrementToken()) {
assertEquals(UScript.LATIN, scriptAtt.getCode());
assertEquals(UScript.getName(UScript.LATIN), scriptAtt.getName());
assertEquals(UScript.getShortName(UScript.LATIN), scriptAtt.getShortName());
assertTrue(ts.reflectAsString(false).contains("script=Latin"));
}
ts.end();
}
}
/** test for bugs like http://bugs.icu-project.org/trac/ticket/10767 */
public void testICUConcurrency() throws Exception {
int numThreads = 8;
final CountDownLatch startingGun = new CountDownLatch(1);
Thread threads[] = new Thread[numThreads];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread() {
@Override
public void run() {
try {
startingGun.await();
long tokenCount = 0;
final String contents = "英 เบียร์ ビール ເບຍ abc";
for (int i = 0; i < 1000; i++) {
try (Tokenizer tokenizer = new ICUTokenizer()) {
tokenizer.setReader(new StringReader(contents));
tokenizer.reset();
while (tokenizer.incrementToken()) {
tokenCount++;
}
tokenizer.end();
}
}
if (VERBOSE) {
System.out.println(tokenCount);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
};
threads[i].start();
}
startingGun.countDown();
for (int i = 0; i < threads.length; i++) {
threads[i].join();
}
}
}
| Flipkart/lucene-solr | lucene/analysis/icu/src/test/org/apache/lucene/analysis/icu/segmentation/TestICUTokenizer.java |
43,306 | package org.apache.lucene.analysis.core;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.BaseTokenStreamTestCase;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.analysis.standard.UAX29URLEmailTokenizer;
import org.apache.lucene.analysis.tokenattributes.TypeAttribute;
import org.apache.lucene.util.Version;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
/*
* 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.
*/
public class TestUAX29URLEmailTokenizer extends BaseTokenStreamTestCase {
public void testHugeDoc() throws IOException {
StringBuilder sb = new StringBuilder();
char whitespace[] = new char[4094];
Arrays.fill(whitespace, ' ');
sb.append(whitespace);
sb.append("testing 1234");
String input = sb.toString();
UAX29URLEmailTokenizer tokenizer = new UAX29URLEmailTokenizer(TEST_VERSION_CURRENT, new StringReader(input));
BaseTokenStreamTestCase.assertTokenStreamContents(tokenizer, new String[] { "testing", "1234" });
}
private Analyzer a = new Analyzer() {
@Override
protected TokenStreamComponents createComponents
(String fieldName, Reader reader) {
Tokenizer tokenizer = new UAX29URLEmailTokenizer(TEST_VERSION_CURRENT, reader);
return new TokenStreamComponents(tokenizer);
}
};
/** Passes through tokens with type "<URL>" and blocks all other types. */
private class URLFilter extends TokenFilter {
private final TypeAttribute typeAtt = addAttribute(TypeAttribute.class);
public URLFilter(TokenStream in) {
super(in);
}
@Override
public final boolean incrementToken() throws java.io.IOException {
boolean isTokenAvailable = false;
while (input.incrementToken()) {
if (typeAtt.type() == UAX29URLEmailTokenizer.TOKEN_TYPES[UAX29URLEmailTokenizer.URL]) {
isTokenAvailable = true;
break;
}
}
return isTokenAvailable;
}
}
/** Passes through tokens with type "<EMAIL>" and blocks all other types. */
private class EmailFilter extends TokenFilter {
private final TypeAttribute typeAtt = addAttribute(TypeAttribute.class);
public EmailFilter(TokenStream in) {
super(in);
}
@Override
public final boolean incrementToken() throws java.io.IOException {
boolean isTokenAvailable = false;
while (input.incrementToken()) {
if (typeAtt.type() == UAX29URLEmailTokenizer.TOKEN_TYPES[UAX29URLEmailTokenizer.EMAIL]) {
isTokenAvailable = true;
break;
}
}
return isTokenAvailable;
}
}
private Analyzer urlAnalyzer = new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
UAX29URLEmailTokenizer tokenizer = new UAX29URLEmailTokenizer(TEST_VERSION_CURRENT, reader);
tokenizer.setMaxTokenLength(Integer.MAX_VALUE); // Tokenize arbitrary length URLs
TokenFilter filter = new URLFilter(tokenizer);
return new TokenStreamComponents(tokenizer, filter);
}
};
private Analyzer emailAnalyzer = new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
UAX29URLEmailTokenizer tokenizer = new UAX29URLEmailTokenizer(TEST_VERSION_CURRENT, reader);
TokenFilter filter = new EmailFilter(tokenizer);
return new TokenStreamComponents(tokenizer, filter);
}
};
public void testArmenian() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Վիքիպեդիայի 13 միլիոն հոդվածները (4,600` հայերեն վիքիպեդիայում) գրվել են կամավորների կողմից ու համարյա բոլոր հոդվածները կարող է խմբագրել ցանկաց մարդ ով կարող է բացել Վիքիպեդիայի կայքը։",
new String[] { "Վիքիպեդիայի", "13", "միլիոն", "հոդվածները", "4,600", "հայերեն", "վիքիպեդիայում", "գրվել", "են", "կամավորների", "կողմից",
"ու", "համարյա", "բոլոր", "հոդվածները", "կարող", "է", "խմբագրել", "ցանկաց", "մարդ", "ով", "կարող", "է", "բացել", "Վիքիպեդիայի", "կայքը" } );
}
public void testAmharic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ዊኪፔድያ የባለ ብዙ ቋንቋ የተሟላ ትክክለኛና ነጻ መዝገበ ዕውቀት (ኢንሳይክሎፒዲያ) ነው። ማንኛውም",
new String[] { "ዊኪፔድያ", "የባለ", "ብዙ", "ቋንቋ", "የተሟላ", "ትክክለኛና", "ነጻ", "መዝገበ", "ዕውቀት", "ኢንሳይክሎፒዲያ", "ነው", "ማንኛውም" } );
}
public void testArabic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "الفيلم الوثائقي الأول عن ويكيبيديا يسمى \"الحقيقة بالأرقام: قصة ويكيبيديا\" (بالإنجليزية: Truth in Numbers: The Wikipedia Story)، سيتم إطلاقه في 2008.",
new String[] { "الفيلم", "الوثائقي", "الأول", "عن", "ويكيبيديا", "يسمى", "الحقيقة", "بالأرقام", "قصة", "ويكيبيديا",
"بالإنجليزية", "Truth", "in", "Numbers", "The", "Wikipedia", "Story", "سيتم", "إطلاقه", "في", "2008" } );
}
public void testAramaic() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ܘܝܩܝܦܕܝܐ (ܐܢܓܠܝܐ: Wikipedia) ܗܘ ܐܝܢܣܩܠܘܦܕܝܐ ܚܐܪܬܐ ܕܐܢܛܪܢܛ ܒܠܫܢ̈ܐ ܣܓܝܐ̈ܐ܂ ܫܡܗ ܐܬܐ ܡܢ ܡ̈ܠܬܐ ܕ\"ܘܝܩܝ\" ܘ\"ܐܝܢܣܩܠܘܦܕܝܐ\"܀",
new String[] { "ܘܝܩܝܦܕܝܐ", "ܐܢܓܠܝܐ", "Wikipedia", "ܗܘ", "ܐܝܢܣܩܠܘܦܕܝܐ", "ܚܐܪܬܐ", "ܕܐܢܛܪܢܛ", "ܒܠܫܢ̈ܐ", "ܣܓܝܐ̈ܐ", "ܫܡܗ",
"ܐܬܐ", "ܡܢ", "ܡ̈ܠܬܐ", "ܕ", "ܘܝܩܝ", "ܘ", "ܐܝܢܣܩܠܘܦܕܝܐ"});
}
public void testBengali() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "এই বিশ্বকোষ পরিচালনা করে উইকিমিডিয়া ফাউন্ডেশন (একটি অলাভজনক সংস্থা)। উইকিপিডিয়ার শুরু ১৫ জানুয়ারি, ২০০১ সালে। এখন পর্যন্ত ২০০টিরও বেশী ভাষায় উইকিপিডিয়া রয়েছে।",
new String[] { "এই", "বিশ্বকোষ", "পরিচালনা", "করে", "উইকিমিডিয়া", "ফাউন্ডেশন", "একটি", "অলাভজনক", "সংস্থা", "উইকিপিডিয়ার",
"শুরু", "১৫", "জানুয়ারি", "২০০১", "সালে", "এখন", "পর্যন্ত", "২০০টিরও", "বেশী", "ভাষায়", "উইকিপিডিয়া", "রয়েছে" });
}
public void testFarsi() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ویکی پدیای انگلیسی در تاریخ ۲۵ دی ۱۳۷۹ به صورت مکملی برای دانشنامهٔ تخصصی نوپدیا نوشته شد.",
new String[] { "ویکی", "پدیای", "انگلیسی", "در", "تاریخ", "۲۵", "دی", "۱۳۷۹", "به", "صورت", "مکملی",
"برای", "دانشنامهٔ", "تخصصی", "نوپدیا", "نوشته", "شد" });
}
public void testGreek() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Γράφεται σε συνεργασία από εθελοντές με το λογισμικό wiki, κάτι που σημαίνει ότι άρθρα μπορεί να προστεθούν ή να αλλάξουν από τον καθένα.",
new String[] { "Γράφεται", "σε", "συνεργασία", "από", "εθελοντές", "με", "το", "λογισμικό", "wiki", "κάτι", "που",
"σημαίνει", "ότι", "άρθρα", "μπορεί", "να", "προστεθούν", "ή", "να", "αλλάξουν", "από", "τον", "καθένα" });
}
public void testThai() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "การที่ได้ต้องแสดงว่างานดี. แล้วเธอจะไปไหน? ๑๒๓๔",
new String[] { "การที่ได้ต้องแสดงว่างานดี", "แล้วเธอจะไปไหน", "๑๒๓๔" });
}
public void testLao() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ສາທາລະນະລັດ ປະຊາທິປະໄຕ ປະຊາຊົນລາວ",
new String[] { "ສາທາລະນະລັດ", "ປະຊາທິປະໄຕ", "ປະຊາຊົນລາວ" });
}
public void testTibetan() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "སྣོན་མཛོད་དང་ལས་འདིས་བོད་ཡིག་མི་ཉམས་གོང་འཕེལ་དུ་གཏོང་བར་ཧ་ཅང་དགེ་མཚན་མཆིས་སོ། །",
new String[] { "སྣོན", "མཛོད", "དང", "ལས", "འདིས", "བོད", "ཡིག",
"མི", "ཉམས", "གོང", "འཕེལ", "དུ", "གཏོང", "བར",
"ཧ", "ཅང", "དགེ", "མཚན", "མཆིས", "སོ" });
}
/*
* For chinese, tokenize as char (these can later form bigrams or whatever)
*/
public void testChinese() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "我是中国人。 1234 Tests ",
new String[] { "我", "是", "中", "国", "人", "1234", "Tests"});
}
public void testEmpty() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "", new String[] {});
BaseTokenStreamTestCase.assertAnalyzesTo(a, ".", new String[] {});
BaseTokenStreamTestCase.assertAnalyzesTo(a, " ", new String[] {});
}
/* test various jira issues this analyzer is related to */
public void testLUCENE1545() throws Exception {
/*
* Standard analyzer does not correctly tokenize combining character U+0364 COMBINING LATIN SMALL LETTRE E.
* The word "moͤchte" is incorrectly tokenized into "mo" "chte", the combining character is lost.
* Expected result is only on token "moͤchte".
*/
BaseTokenStreamTestCase.assertAnalyzesTo(a, "moͤchte", new String[] { "moͤchte" });
}
/* Tests from StandardAnalyzer, just to show behavior is similar */
public void testAlphanumericSA() throws Exception {
// alphanumeric tokens
BaseTokenStreamTestCase.assertAnalyzesTo(a, "B2B", new String[]{"B2B"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "2B", new String[]{"2B"});
}
public void testDelimitersSA() throws Exception {
// other delimiters: "-", "/", ","
BaseTokenStreamTestCase.assertAnalyzesTo(a, "some-dashed-phrase", new String[]{"some", "dashed", "phrase"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "dogs,chase,cats", new String[]{"dogs", "chase", "cats"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "ac/dc", new String[]{"ac", "dc"});
}
public void testApostrophesSA() throws Exception {
// internal apostrophes: O'Reilly, you're, O'Reilly's
BaseTokenStreamTestCase.assertAnalyzesTo(a, "O'Reilly", new String[]{"O'Reilly"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "you're", new String[]{"you're"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "she's", new String[]{"she's"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "Jim's", new String[]{"Jim's"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "don't", new String[]{"don't"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "O'Reilly's", new String[]{"O'Reilly's"});
}
public void testNumericSA() throws Exception {
// floating point, serial, model numbers, ip addresses, etc.
BaseTokenStreamTestCase.assertAnalyzesTo(a, "21.35", new String[]{"21.35"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "R2D2 C3PO", new String[]{"R2D2", "C3PO"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "216.239.63.104", new String[]{"216.239.63.104"});
}
public void testTextWithNumbersSA() throws Exception {
// numbers
BaseTokenStreamTestCase.assertAnalyzesTo(a, "David has 5000 bones", new String[]{"David", "has", "5000", "bones"});
}
public void testVariousTextSA() throws Exception {
// various
BaseTokenStreamTestCase.assertAnalyzesTo(a, "C embedded developers wanted", new String[]{"C", "embedded", "developers", "wanted"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "foo bar FOO BAR", new String[]{"foo", "bar", "FOO", "BAR"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "foo bar . FOO <> BAR", new String[]{"foo", "bar", "FOO", "BAR"});
BaseTokenStreamTestCase.assertAnalyzesTo(a, "\"QUOTED\" word", new String[]{"QUOTED", "word"});
}
public void testKoreanSA() throws Exception {
// Korean words
BaseTokenStreamTestCase.assertAnalyzesTo(a, "안녕하세요 한글입니다", new String[]{"안녕하세요", "한글입니다"});
}
public void testOffsets() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "David has 5000 bones",
new String[] {"David", "has", "5000", "bones"},
new int[] {0, 6, 10, 15},
new int[] {5, 9, 14, 20});
}
public void testTypes() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "David has 5000 bones",
new String[] {"David", "has", "5000", "bones"},
new String[] { "<ALPHANUM>", "<ALPHANUM>", "<NUM>", "<ALPHANUM>" });
}
public void testWikiURLs() throws Exception {
Reader reader = null;
String luceneResourcesWikiPage;
try {
reader = new InputStreamReader(getClass().getResourceAsStream
("LuceneResourcesWikiPage.html"), "UTF-8");
StringBuilder builder = new StringBuilder();
char[] buffer = new char[1024];
int numCharsRead;
while (-1 != (numCharsRead = reader.read(buffer))) {
builder.append(buffer, 0, numCharsRead);
}
luceneResourcesWikiPage = builder.toString();
} finally {
if (null != reader) {
reader.close();
}
}
assertTrue(null != luceneResourcesWikiPage
&& luceneResourcesWikiPage.length() > 0);
BufferedReader bufferedReader = null;
String[] urls;
try {
List<String> urlList = new ArrayList<String>();
bufferedReader = new BufferedReader(new InputStreamReader
(getClass().getResourceAsStream("LuceneResourcesWikiPageURLs.txt"), "UTF-8"));
String line;
while (null != (line = bufferedReader.readLine())) {
line = line.trim();
if (line.length() > 0) {
urlList.add(line);
}
}
urls = urlList.toArray(new String[urlList.size()]);
} finally {
if (null != bufferedReader) {
bufferedReader.close();
}
}
assertTrue(null != urls && urls.length > 0);
BaseTokenStreamTestCase.assertAnalyzesTo
(urlAnalyzer, luceneResourcesWikiPage, urls);
}
public void testEmails() throws Exception {
Reader reader = null;
String randomTextWithEmails;
try {
reader = new InputStreamReader(getClass().getResourceAsStream
("random.text.with.email.addresses.txt"), "UTF-8");
StringBuilder builder = new StringBuilder();
char[] buffer = new char[1024];
int numCharsRead;
while (-1 != (numCharsRead = reader.read(buffer))) {
builder.append(buffer, 0, numCharsRead);
}
randomTextWithEmails = builder.toString();
} finally {
if (null != reader) {
reader.close();
}
}
assertTrue(null != randomTextWithEmails
&& randomTextWithEmails.length() > 0);
BufferedReader bufferedReader = null;
String[] emails;
try {
List<String> emailList = new ArrayList<String>();
bufferedReader = new BufferedReader(new InputStreamReader
(getClass().getResourceAsStream
("email.addresses.from.random.text.with.email.addresses.txt"), "UTF-8"));
String line;
while (null != (line = bufferedReader.readLine())) {
line = line.trim();
if (line.length() > 0) {
emailList.add(line);
}
}
emails = emailList.toArray(new String[emailList.size()]);
} finally {
if (null != bufferedReader) {
bufferedReader.close();
}
}
assertTrue(null != emails && emails.length > 0);
BaseTokenStreamTestCase.assertAnalyzesTo
(emailAnalyzer, randomTextWithEmails, emails);
}
public void testMailtoSchemeEmails () throws Exception {
// See LUCENE-3880
BaseTokenStreamTestCase.assertAnalyzesTo(a, "mailto:[email protected]",
new String[] {"mailto", "[email protected]"},
new String[] { "<ALPHANUM>", "<EMAIL>" });
// TODO: Support full mailto: scheme URIs. See RFC 6068: http://tools.ietf.org/html/rfc6068
BaseTokenStreamTestCase.assertAnalyzesTo
(a, "mailto:[email protected],[email protected][email protected]"
+ "&subject=Subjectivity&body=Corpusivity%20or%20something%20like%20that",
new String[] { "mailto",
"[email protected]",
// TODO: recognize ',' address delimiter. Also, see examples of ';' delimiter use at: http://www.mailto.co.uk/
",[email protected]",
"[email protected]", // TODO: split field keys/values
"subject", "Subjectivity",
"body", "Corpusivity", "20or", "20something","20like", "20that" }, // TODO: Hex decoding + re-tokenization
new String[] { "<ALPHANUM>",
"<EMAIL>",
"<EMAIL>",
"<EMAIL>",
"<ALPHANUM>", "<ALPHANUM>",
"<ALPHANUM>", "<ALPHANUM>", "<ALPHANUM>", "<ALPHANUM>", "<ALPHANUM>", "<ALPHANUM>" });
}
public void testURLs() throws Exception {
Reader reader = null;
String randomTextWithURLs;
try {
reader = new InputStreamReader(getClass().getResourceAsStream
("random.text.with.urls.txt"), "UTF-8");
StringBuilder builder = new StringBuilder();
char[] buffer = new char[1024];
int numCharsRead;
while (-1 != (numCharsRead = reader.read(buffer))) {
builder.append(buffer, 0, numCharsRead);
}
randomTextWithURLs = builder.toString();
} finally {
if (null != reader) {
reader.close();
}
}
assertTrue(null != randomTextWithURLs
&& randomTextWithURLs.length() > 0);
BufferedReader bufferedReader = null;
String[] urls;
try {
List<String> urlList = new ArrayList<String>();
bufferedReader = new BufferedReader(new InputStreamReader
(getClass().getResourceAsStream
("urls.from.random.text.with.urls.txt"), "UTF-8"));
String line;
while (null != (line = bufferedReader.readLine())) {
line = line.trim();
if (line.length() > 0) {
urlList.add(line);
}
}
urls = urlList.toArray(new String[urlList.size()]);
} finally {
if (null != bufferedReader) {
bufferedReader.close();
}
}
assertTrue(null != urls && urls.length > 0);
BaseTokenStreamTestCase.assertAnalyzesTo
(urlAnalyzer, randomTextWithURLs, urls);
}
public void testUnicodeWordBreaks() throws Exception {
WordBreakTestUnicode_6_3_0 wordBreakTest = new WordBreakTestUnicode_6_3_0();
wordBreakTest.test(a);
}
public void testSupplementary() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "𩬅艱鍟䇹愯瀛",
new String[] {"𩬅", "艱", "鍟", "䇹", "愯", "瀛"},
new String[] { "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>" });
}
public void testKorean() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "훈민정음",
new String[] { "훈민정음" },
new String[] { "<HANGUL>" });
}
public void testJapanese() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "仮名遣い カタカナ",
new String[] { "仮", "名", "遣", "い", "カタカナ" },
new String[] { "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<HIRAGANA>", "<KATAKANA>" });
}
public void testCombiningMarks() throws Exception {
checkOneTerm(a, "ざ", "ざ"); // hiragana
checkOneTerm(a, "ザ", "ザ"); // katakana
checkOneTerm(a, "壹゙", "壹゙"); // ideographic
checkOneTerm(a, "아゙", "아゙"); // hangul
}
/** @deprecated remove this and sophisticated backwards layer in 5.0 */
@Deprecated
public void testCombiningMarksBackwards() throws Exception {
Analyzer a = new Analyzer() {
@Override
protected TokenStreamComponents createComponents
(String fieldName, Reader reader) {
Tokenizer tokenizer = new UAX29URLEmailTokenizer(Version.LUCENE_31, reader);
return new TokenStreamComponents(tokenizer);
}
};
checkOneTerm(a, "ざ", "さ"); // hiragana Bug
checkOneTerm(a, "ザ", "ザ"); // katakana Works
checkOneTerm(a, "壹゙", "壹"); // ideographic Bug
checkOneTerm(a, "아゙", "아゙"); // hangul Works
}
// LUCENE-3880
/** @deprecated remove this and sophisticated backwards layer in 5.0 */
@Deprecated
public void testMailtoBackwards() throws Exception {
Analyzer a = new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
Tokenizer tokenizer = new UAX29URLEmailTokenizer(Version.LUCENE_34, reader);
return new TokenStreamComponents(tokenizer);
}
};
assertAnalyzesTo(a, "mailto:[email protected]",
new String[] { "mailto:test", "example.org" });
}
/** @deprecated uses older unicode (6.0). simple test to make sure its basically working */
@Deprecated
public void testVersion36() throws Exception {
Analyzer a = new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
Tokenizer tokenizer = new UAX29URLEmailTokenizer(Version.LUCENE_36, reader);
return new TokenStreamComponents(tokenizer);
}
};
assertAnalyzesTo(a, "this is just a t\u08E6st [email protected]", // new combining mark in 6.1
new String[] { "this", "is", "just", "a", "t", "st", "[email protected]" });
};
/** @deprecated uses older unicode (6.1). simple test to make sure its basically working */
@Deprecated
public void testVersion40() throws Exception {
Analyzer a = new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
Tokenizer tokenizer = new UAX29URLEmailTokenizer(Version.LUCENE_40, reader);
return new TokenStreamComponents(tokenizer);
}
};
// U+061C is a new combining mark in 6.3, found using "[[\p{WB:Format}\p{WB:Extend}]&[^\p{Age:6.2}]]"
// on the online UnicodeSet utility: <http://unicode.org/cldr/utility/list-unicodeset.jsp>
assertAnalyzesTo(a, "this is just a t\u061Cst [email protected]",
new String[] { "this", "is", "just", "a", "t", "st", "[email protected]" });
};
/** blast some random strings through the analyzer */
public void testRandomStrings() throws Exception {
checkRandomData(random(), a, 1000*RANDOM_MULTIPLIER);
}
/** blast some random large strings through the analyzer */
public void testRandomHugeStrings() throws Exception {
Random random = random();
checkRandomData(random, a, 100*RANDOM_MULTIPLIER, 8192);
}
}
| andyetitmoves/lucene-solr | lucene/analysis/common/src/test/org/apache/lucene/analysis/core/TestUAX29URLEmailTokenizer.java |
43,307 | package org.apache.lucene.analysis.icu.segmentation;
/*
* 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.
*/
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.BaseTokenStreamTestCase;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.icu.ICUNormalizer2Filter;
import org.apache.lucene.analysis.icu.tokenattributes.ScriptAttribute;
import com.ibm.icu.lang.UScript;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.Arrays;
import java.util.Random;
public class TestICUTokenizer extends BaseTokenStreamTestCase {
public void testHugeDoc() throws IOException {
StringBuilder sb = new StringBuilder();
char whitespace[] = new char[4094];
Arrays.fill(whitespace, ' ');
sb.append(whitespace);
sb.append("testing 1234");
String input = sb.toString();
ICUTokenizer tokenizer = new ICUTokenizer(new StringReader(input), new DefaultICUTokenizerConfig(false));
assertTokenStreamContents(tokenizer, new String[] { "testing", "1234" });
}
public void testHugeTerm2() throws IOException {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 40960; i++) {
sb.append('a');
}
String input = sb.toString();
ICUTokenizer tokenizer = new ICUTokenizer(new StringReader(input), new DefaultICUTokenizerConfig(false));
char token[] = new char[4096];
Arrays.fill(token, 'a');
String expectedToken = new String(token);
String expected[] = {
expectedToken, expectedToken, expectedToken,
expectedToken, expectedToken, expectedToken,
expectedToken, expectedToken, expectedToken,
expectedToken
};
assertTokenStreamContents(tokenizer, expected);
}
private Analyzer a = new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName,
Reader reader) {
Tokenizer tokenizer = new ICUTokenizer(reader, new DefaultICUTokenizerConfig(false));
TokenFilter filter = new ICUNormalizer2Filter(tokenizer);
return new TokenStreamComponents(tokenizer, filter);
}
};
public void testArmenian() throws Exception {
assertAnalyzesTo(a, "Վիքիպեդիայի 13 միլիոն հոդվածները (4,600` հայերեն վիքիպեդիայում) գրվել են կամավորների կողմից ու համարյա բոլոր հոդվածները կարող է խմբագրել ցանկաց մարդ ով կարող է բացել Վիքիպեդիայի կայքը։",
new String[] { "վիքիպեդիայի", "13", "միլիոն", "հոդվածները", "4,600", "հայերեն", "վիքիպեդիայում", "գրվել", "են", "կամավորների", "կողմից",
"ու", "համարյա", "բոլոր", "հոդվածները", "կարող", "է", "խմբագրել", "ցանկաց", "մարդ", "ով", "կարող", "է", "բացել", "վիքիպեդիայի", "կայքը" } );
}
public void testAmharic() throws Exception {
assertAnalyzesTo(a, "ዊኪፔድያ የባለ ብዙ ቋንቋ የተሟላ ትክክለኛና ነጻ መዝገበ ዕውቀት (ኢንሳይክሎፒዲያ) ነው። ማንኛውም",
new String[] { "ዊኪፔድያ", "የባለ", "ብዙ", "ቋንቋ", "የተሟላ", "ትክክለኛና", "ነጻ", "መዝገበ", "ዕውቀት", "ኢንሳይክሎፒዲያ", "ነው", "ማንኛውም" } );
}
public void testArabic() throws Exception {
assertAnalyzesTo(a, "الفيلم الوثائقي الأول عن ويكيبيديا يسمى \"الحقيقة بالأرقام: قصة ويكيبيديا\" (بالإنجليزية: Truth in Numbers: The Wikipedia Story)، سيتم إطلاقه في 2008.",
new String[] { "الفيلم", "الوثائقي", "الأول", "عن", "ويكيبيديا", "يسمى", "الحقيقة", "بالأرقام", "قصة", "ويكيبيديا",
"بالإنجليزية", "truth", "in", "numbers", "the", "wikipedia", "story", "سيتم", "إطلاقه", "في", "2008" } );
}
public void testAramaic() throws Exception {
assertAnalyzesTo(a, "ܘܝܩܝܦܕܝܐ (ܐܢܓܠܝܐ: Wikipedia) ܗܘ ܐܝܢܣܩܠܘܦܕܝܐ ܚܐܪܬܐ ܕܐܢܛܪܢܛ ܒܠܫܢ̈ܐ ܣܓܝܐ̈ܐ܂ ܫܡܗ ܐܬܐ ܡܢ ܡ̈ܠܬܐ ܕ\"ܘܝܩܝ\" ܘ\"ܐܝܢܣܩܠܘܦܕܝܐ\"܀",
new String[] { "ܘܝܩܝܦܕܝܐ", "ܐܢܓܠܝܐ", "wikipedia", "ܗܘ", "ܐܝܢܣܩܠܘܦܕܝܐ", "ܚܐܪܬܐ", "ܕܐܢܛܪܢܛ", "ܒܠܫܢ̈ܐ", "ܣܓܝܐ̈ܐ", "ܫܡܗ",
"ܐܬܐ", "ܡܢ", "ܡ̈ܠܬܐ", "ܕ", "ܘܝܩܝ", "ܘ", "ܐܝܢܣܩܠܘܦܕܝܐ"});
}
public void testBengali() throws Exception {
assertAnalyzesTo(a, "এই বিশ্বকোষ পরিচালনা করে উইকিমিডিয়া ফাউন্ডেশন (একটি অলাভজনক সংস্থা)। উইকিপিডিয়ার শুরু ১৫ জানুয়ারি, ২০০১ সালে। এখন পর্যন্ত ২০০টিরও বেশী ভাষায় উইকিপিডিয়া রয়েছে।",
new String[] { "এই", "বিশ্বকোষ", "পরিচালনা", "করে", "উইকিমিডিয়া", "ফাউন্ডেশন", "একটি", "অলাভজনক", "সংস্থা", "উইকিপিডিয়ার",
"শুরু", "১৫", "জানুয়ারি", "২০০১", "সালে", "এখন", "পর্যন্ত", "২০০টিরও", "বেশী", "ভাষায়", "উইকিপিডিয়া", "রয়েছে" });
}
public void testFarsi() throws Exception {
assertAnalyzesTo(a, "ویکی پدیای انگلیسی در تاریخ ۲۵ دی ۱۳۷۹ به صورت مکملی برای دانشنامهٔ تخصصی نوپدیا نوشته شد.",
new String[] { "ویکی", "پدیای", "انگلیسی", "در", "تاریخ", "۲۵", "دی", "۱۳۷۹", "به", "صورت", "مکملی",
"برای", "دانشنامهٔ", "تخصصی", "نوپدیا", "نوشته", "شد" });
}
public void testGreek() throws Exception {
assertAnalyzesTo(a, "Γράφεται σε συνεργασία από εθελοντές με το λογισμικό wiki, κάτι που σημαίνει ότι άρθρα μπορεί να προστεθούν ή να αλλάξουν από τον καθένα.",
new String[] { "γράφεται", "σε", "συνεργασία", "από", "εθελοντέσ", "με", "το", "λογισμικό", "wiki", "κάτι", "που",
"σημαίνει", "ότι", "άρθρα", "μπορεί", "να", "προστεθούν", "ή", "να", "αλλάξουν", "από", "τον", "καθένα" });
}
public void testLao() throws Exception {
assertAnalyzesTo(a, "ກວ່າດອກ", new String[] { "ກວ່າ", "ດອກ" });
assertAnalyzesTo(a, "ພາສາລາວ", new String[] { "ພາສາ", "ລາວ"}, new String[] { "<ALPHANUM>", "<ALPHANUM>" });
}
public void testThai() throws Exception {
assertAnalyzesTo(a, "การที่ได้ต้องแสดงว่างานดี. แล้วเธอจะไปไหน? ๑๒๓๔",
new String[] { "การ", "ที่", "ได้", "ต้อง", "แสดง", "ว่า", "งาน", "ดี", "แล้ว", "เธอ", "จะ", "ไป", "ไหน", "๑๒๓๔"});
}
public void testTibetan() throws Exception {
assertAnalyzesTo(a, "སྣོན་མཛོད་དང་ལས་འདིས་བོད་ཡིག་མི་ཉམས་གོང་འཕེལ་དུ་གཏོང་བར་ཧ་ཅང་དགེ་མཚན་མཆིས་སོ། །",
new String[] { "སྣོན", "མཛོད", "དང", "ལས", "འདིས", "བོད", "ཡིག", "མི", "ཉམས", "གོང", "འཕེལ", "དུ", "གཏོང", "བར", "ཧ", "ཅང", "དགེ", "མཚན", "མཆིས", "སོ" });
}
/*
* For chinese, tokenize as char (these can later form bigrams or whatever)
*/
public void testChinese() throws Exception {
assertAnalyzesTo(a, "我是中国人。 1234 Tests ",
new String[] { "我", "是", "中", "国", "人", "1234", "tests"});
}
public void testHebrew() throws Exception {
assertAnalyzesTo(a, "דנקנר תקף את הדו\"ח",
new String[] { "דנקנר", "תקף", "את", "הדו\"ח" });
assertAnalyzesTo(a, "חברת בת של מודי'ס",
new String[] { "חברת", "בת", "של", "מודי'ס" });
}
public void testEmpty() throws Exception {
assertAnalyzesTo(a, "", new String[] {});
assertAnalyzesTo(a, ".", new String[] {});
assertAnalyzesTo(a, " ", new String[] {});
}
/* test various jira issues this analyzer is related to */
public void testLUCENE1545() throws Exception {
/*
* Standard analyzer does not correctly tokenize combining character U+0364 COMBINING LATIN SMALL LETTRE E.
* The word "moͤchte" is incorrectly tokenized into "mo" "chte", the combining character is lost.
* Expected result is only on token "moͤchte".
*/
assertAnalyzesTo(a, "moͤchte", new String[] { "moͤchte" });
}
/* Tests from StandardAnalyzer, just to show behavior is similar */
public void testAlphanumericSA() throws Exception {
// alphanumeric tokens
assertAnalyzesTo(a, "B2B", new String[]{"b2b"});
assertAnalyzesTo(a, "2B", new String[]{"2b"});
}
public void testDelimitersSA() throws Exception {
// other delimiters: "-", "/", ","
assertAnalyzesTo(a, "some-dashed-phrase", new String[]{"some", "dashed", "phrase"});
assertAnalyzesTo(a, "dogs,chase,cats", new String[]{"dogs", "chase", "cats"});
assertAnalyzesTo(a, "ac/dc", new String[]{"ac", "dc"});
}
public void testApostrophesSA() throws Exception {
// internal apostrophes: O'Reilly, you're, O'Reilly's
assertAnalyzesTo(a, "O'Reilly", new String[]{"o'reilly"});
assertAnalyzesTo(a, "you're", new String[]{"you're"});
assertAnalyzesTo(a, "she's", new String[]{"she's"});
assertAnalyzesTo(a, "Jim's", new String[]{"jim's"});
assertAnalyzesTo(a, "don't", new String[]{"don't"});
assertAnalyzesTo(a, "O'Reilly's", new String[]{"o'reilly's"});
}
public void testNumericSA() throws Exception {
// floating point, serial, model numbers, ip addresses, etc.
// every other segment must have at least one digit
assertAnalyzesTo(a, "21.35", new String[]{"21.35"});
assertAnalyzesTo(a, "R2D2 C3PO", new String[]{"r2d2", "c3po"});
assertAnalyzesTo(a, "216.239.63.104", new String[]{"216.239.63.104"});
assertAnalyzesTo(a, "216.239.63.104", new String[]{"216.239.63.104"});
}
public void testTextWithNumbersSA() throws Exception {
// numbers
assertAnalyzesTo(a, "David has 5000 bones", new String[]{"david", "has", "5000", "bones"});
}
public void testVariousTextSA() throws Exception {
// various
assertAnalyzesTo(a, "C embedded developers wanted", new String[]{"c", "embedded", "developers", "wanted"});
assertAnalyzesTo(a, "foo bar FOO BAR", new String[]{"foo", "bar", "foo", "bar"});
assertAnalyzesTo(a, "foo bar . FOO <> BAR", new String[]{"foo", "bar", "foo", "bar"});
assertAnalyzesTo(a, "\"QUOTED\" word", new String[]{"quoted", "word"});
}
public void testKoreanSA() throws Exception {
// Korean words
assertAnalyzesTo(a, "안녕하세요 한글입니다", new String[]{"안녕하세요", "한글입니다"});
}
public void testReusableTokenStream() throws Exception {
assertAnalyzesTo(a, "སྣོན་མཛོད་དང་ལས་འདིས་བོད་ཡིག་མི་ཉམས་གོང་འཕེལ་དུ་གཏོང་བར་ཧ་ཅང་དགེ་མཚན་མཆིས་སོ། །",
new String[] { "སྣོན", "མཛོད", "དང", "ལས", "འདིས", "བོད", "ཡིག", "མི", "ཉམས", "གོང",
"འཕེལ", "དུ", "གཏོང", "བར", "ཧ", "ཅང", "དགེ", "མཚན", "མཆིས", "སོ" });
}
public void testOffsets() throws Exception {
assertAnalyzesTo(a, "David has 5000 bones",
new String[] {"david", "has", "5000", "bones"},
new int[] {0, 6, 10, 15},
new int[] {5, 9, 14, 20});
}
public void testTypes() throws Exception {
assertAnalyzesTo(a, "David has 5000 bones",
new String[] {"david", "has", "5000", "bones"},
new String[] { "<ALPHANUM>", "<ALPHANUM>", "<NUM>", "<ALPHANUM>" });
}
public void testKorean() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "훈민정음",
new String[] { "훈민정음" },
new String[] { "<HANGUL>" });
}
public void testJapanese() throws Exception {
BaseTokenStreamTestCase.assertAnalyzesTo(a, "仮名遣い カタカナ",
new String[] { "仮", "名", "遣", "い", "カタカナ" },
new String[] { "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<IDEOGRAPHIC>", "<HIRAGANA>", "<KATAKANA>" });
}
/** blast some random strings through the analyzer */
public void testRandomStrings() throws Exception {
checkRandomData(random(), a, 1000*RANDOM_MULTIPLIER);
}
/** blast some random large strings through the analyzer */
public void testRandomHugeStrings() throws Exception {
Random random = random();
checkRandomData(random, a, 100*RANDOM_MULTIPLIER, 8192);
}
public void testTokenAttributes() throws Exception {
try (TokenStream ts = a.tokenStream("dummy", "This is a test")) {
ScriptAttribute scriptAtt = ts.addAttribute(ScriptAttribute.class);
ts.reset();
while (ts.incrementToken()) {
assertEquals(UScript.LATIN, scriptAtt.getCode());
assertEquals(UScript.getName(UScript.LATIN), scriptAtt.getName());
assertEquals(UScript.getShortName(UScript.LATIN), scriptAtt.getShortName());
assertTrue(ts.reflectAsString(false).contains("script=Latin"));
}
ts.end();
}
}
}
| kpheliosearch/heliosearch | lucene/analysis/icu/src/test/org/apache/lucene/analysis/icu/segmentation/TestICUTokenizer.java |
43,308 | package org.apache.lucene.analysis.icu.segmentation;
/**
* 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.
*/
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.BaseTokenStreamTestCase;
import org.apache.lucene.analysis.ReusableAnalyzerBase;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.icu.ICUNormalizer2Filter;
import java.util.Arrays;
public class TestICUTokenizer extends BaseTokenStreamTestCase {
public void testHugeDoc() throws IOException {
StringBuilder sb = new StringBuilder();
char whitespace[] = new char[4094];
Arrays.fill(whitespace, ' ');
sb.append(whitespace);
sb.append("testing 1234");
String input = sb.toString();
ICUTokenizer tokenizer = new ICUTokenizer(new StringReader(input));
assertTokenStreamContents(tokenizer, new String[] { "testing", "1234" });
}
public void testHugeTerm2() throws IOException {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 40960; i++) {
sb.append('a');
}
String input = sb.toString();
ICUTokenizer tokenizer = new ICUTokenizer(new StringReader(input));
char token[] = new char[4096];
Arrays.fill(token, 'a');
String expectedToken = new String(token);
String expected[] = {
expectedToken, expectedToken, expectedToken,
expectedToken, expectedToken, expectedToken,
expectedToken, expectedToken, expectedToken,
expectedToken
};
assertTokenStreamContents(tokenizer, expected);
}
private Analyzer a = new ReusableAnalyzerBase() {
@Override
protected TokenStreamComponents createComponents(String fieldName,
Reader reader) {
Tokenizer tokenizer = new ICUTokenizer(reader);
TokenFilter filter = new ICUNormalizer2Filter(tokenizer);
return new TokenStreamComponents(tokenizer, filter);
}
};
public void testArmenian() throws Exception {
assertAnalyzesTo(a, "Վիքիպեդիայի 13 միլիոն հոդվածները (4,600` հայերեն վիքիպեդիայում) գրվել են կամավորների կողմից ու համարյա բոլոր հոդվածները կարող է խմբագրել ցանկաց մարդ ով կարող է բացել Վիքիպեդիայի կայքը։",
new String[] { "վիքիպեդիայի", "13", "միլիոն", "հոդվածները", "4,600", "հայերեն", "վիքիպեդիայում", "գրվել", "են", "կամավորների", "կողմից",
"ու", "համարյա", "բոլոր", "հոդվածները", "կարող", "է", "խմբագրել", "ցանկաց", "մարդ", "ով", "կարող", "է", "բացել", "վիքիպեդիայի", "կայքը" } );
}
public void testAmharic() throws Exception {
assertAnalyzesTo(a, "ዊኪፔድያ የባለ ብዙ ቋንቋ የተሟላ ትክክለኛና ነጻ መዝገበ ዕውቀት (ኢንሳይክሎፒዲያ) ነው። ማንኛውም",
new String[] { "ዊኪፔድያ", "የባለ", "ብዙ", "ቋንቋ", "የተሟላ", "ትክክለኛና", "ነጻ", "መዝገበ", "ዕውቀት", "ኢንሳይክሎፒዲያ", "ነው", "ማንኛውም" } );
}
public void testArabic() throws Exception {
assertAnalyzesTo(a, "الفيلم الوثائقي الأول عن ويكيبيديا يسمى \"الحقيقة بالأرقام: قصة ويكيبيديا\" (بالإنجليزية: Truth in Numbers: The Wikipedia Story)، سيتم إطلاقه في 2008.",
new String[] { "الفيلم", "الوثائقي", "الأول", "عن", "ويكيبيديا", "يسمى", "الحقيقة", "بالأرقام", "قصة", "ويكيبيديا",
"بالإنجليزية", "truth", "in", "numbers", "the", "wikipedia", "story", "سيتم", "إطلاقه", "في", "2008" } );
}
public void testAramaic() throws Exception {
assertAnalyzesTo(a, "ܘܝܩܝܦܕܝܐ (ܐܢܓܠܝܐ: Wikipedia) ܗܘ ܐܝܢܣܩܠܘܦܕܝܐ ܚܐܪܬܐ ܕܐܢܛܪܢܛ ܒܠܫܢ̈ܐ ܣܓܝܐ̈ܐ܂ ܫܡܗ ܐܬܐ ܡܢ ܡ̈ܠܬܐ ܕ\"ܘܝܩܝ\" ܘ\"ܐܝܢܣܩܠܘܦܕܝܐ\"܀",
new String[] { "ܘܝܩܝܦܕܝܐ", "ܐܢܓܠܝܐ", "wikipedia", "ܗܘ", "ܐܝܢܣܩܠܘܦܕܝܐ", "ܚܐܪܬܐ", "ܕܐܢܛܪܢܛ", "ܒܠܫܢ̈ܐ", "ܣܓܝܐ̈ܐ", "ܫܡܗ",
"ܐܬܐ", "ܡܢ", "ܡ̈ܠܬܐ", "ܕ", "ܘܝܩܝ", "ܘ", "ܐܝܢܣܩܠܘܦܕܝܐ"});
}
public void testBengali() throws Exception {
assertAnalyzesTo(a, "এই বিশ্বকোষ পরিচালনা করে উইকিমিডিয়া ফাউন্ডেশন (একটি অলাভজনক সংস্থা)। উইকিপিডিয়ার শুরু ১৫ জানুয়ারি, ২০০১ সালে। এখন পর্যন্ত ২০০টিরও বেশী ভাষায় উইকিপিডিয়া রয়েছে।",
new String[] { "এই", "বিশ্বকোষ", "পরিচালনা", "করে", "উইকিমিডিয়া", "ফাউন্ডেশন", "একটি", "অলাভজনক", "সংস্থা", "উইকিপিডিয়ার",
"শুরু", "১৫", "জানুয়ারি", "২০০১", "সালে", "এখন", "পর্যন্ত", "২০০টিরও", "বেশী", "ভাষায়", "উইকিপিডিয়া", "রয়েছে" });
}
public void testFarsi() throws Exception {
assertAnalyzesTo(a, "ویکی پدیای انگلیسی در تاریخ ۲۵ دی ۱۳۷۹ به صورت مکملی برای دانشنامهٔ تخصصی نوپدیا نوشته شد.",
new String[] { "ویکی", "پدیای", "انگلیسی", "در", "تاریخ", "۲۵", "دی", "۱۳۷۹", "به", "صورت", "مکملی",
"برای", "دانشنامهٔ", "تخصصی", "نوپدیا", "نوشته", "شد" });
}
public void testGreek() throws Exception {
assertAnalyzesTo(a, "Γράφεται σε συνεργασία από εθελοντές με το λογισμικό wiki, κάτι που σημαίνει ότι άρθρα μπορεί να προστεθούν ή να αλλάξουν από τον καθένα.",
new String[] { "γράφεται", "σε", "συνεργασία", "από", "εθελοντέσ", "με", "το", "λογισμικό", "wiki", "κάτι", "που",
"σημαίνει", "ότι", "άρθρα", "μπορεί", "να", "προστεθούν", "ή", "να", "αλλάξουν", "από", "τον", "καθένα" });
}
public void testLao() throws Exception {
assertAnalyzesTo(a, "ກວ່າດອກ", new String[] { "ກວ່າ", "ດອກ" });
}
public void testThai() throws Exception {
assertAnalyzesTo(a, "การที่ได้ต้องแสดงว่างานดี. แล้วเธอจะไปไหน? ๑๒๓๔",
new String[] { "การ", "ที่", "ได้", "ต้อง", "แสดง", "ว่า", "งาน", "ดี", "แล้ว", "เธอ", "จะ", "ไป", "ไหน", "๑๒๓๔"});
}
public void testTibetan() throws Exception {
assertAnalyzesTo(a, "སྣོན་མཛོད་དང་ལས་འདིས་བོད་ཡིག་མི་ཉམས་གོང་འཕེལ་དུ་གཏོང་བར་ཧ་ཅང་དགེ་མཚན་མཆིས་སོ། །",
new String[] { "སྣོན", "མཛོད", "དང", "ལས", "འདིས", "བོད", "ཡིག", "མི", "ཉམས", "གོང", "འཕེལ", "དུ", "གཏོང", "བར", "ཧ", "ཅང", "དགེ", "མཚན", "མཆིས", "སོ" });
}
/*
* For chinese, tokenize as char (these can later form bigrams or whatever)
* TODO: why do full-width numerics have no word-break prop?
*/
public void testChinese() throws Exception {
assertAnalyzesTo(a, "我是中国人。 1234 Tests ",
new String[] { "我", "是", "中", "国", "人", "tests"});
}
public void testEmpty() throws Exception {
assertAnalyzesTo(a, "", new String[] {});
assertAnalyzesTo(a, ".", new String[] {});
assertAnalyzesTo(a, " ", new String[] {});
}
/* test various jira issues this analyzer is related to */
public void testLUCENE1545() throws Exception {
/*
* Standard analyzer does not correctly tokenize combining character U+0364 COMBINING LATIN SMALL LETTRE E.
* The word "moͤchte" is incorrectly tokenized into "mo" "chte", the combining character is lost.
* Expected result is only on token "moͤchte".
*/
assertAnalyzesTo(a, "moͤchte", new String[] { "moͤchte" });
}
/* Tests from StandardAnalyzer, just to show behavior is similar */
public void testAlphanumericSA() throws Exception {
// alphanumeric tokens
assertAnalyzesTo(a, "B2B", new String[]{"b2b"});
assertAnalyzesTo(a, "2B", new String[]{"2b"});
}
public void testDelimitersSA() throws Exception {
// other delimiters: "-", "/", ","
assertAnalyzesTo(a, "some-dashed-phrase", new String[]{"some", "dashed", "phrase"});
assertAnalyzesTo(a, "dogs,chase,cats", new String[]{"dogs", "chase", "cats"});
assertAnalyzesTo(a, "ac/dc", new String[]{"ac", "dc"});
}
public void testApostrophesSA() throws Exception {
// internal apostrophes: O'Reilly, you're, O'Reilly's
assertAnalyzesTo(a, "O'Reilly", new String[]{"o'reilly"});
assertAnalyzesTo(a, "you're", new String[]{"you're"});
assertAnalyzesTo(a, "she's", new String[]{"she's"});
assertAnalyzesTo(a, "Jim's", new String[]{"jim's"});
assertAnalyzesTo(a, "don't", new String[]{"don't"});
assertAnalyzesTo(a, "O'Reilly's", new String[]{"o'reilly's"});
}
public void testNumericSA() throws Exception {
// floating point, serial, model numbers, ip addresses, etc.
// every other segment must have at least one digit
assertAnalyzesTo(a, "21.35", new String[]{"21.35"});
assertAnalyzesTo(a, "R2D2 C3PO", new String[]{"r2d2", "c3po"});
assertAnalyzesTo(a, "216.239.63.104", new String[]{"216.239.63.104"});
assertAnalyzesTo(a, "216.239.63.104", new String[]{"216.239.63.104"});
}
public void testTextWithNumbersSA() throws Exception {
// numbers
assertAnalyzesTo(a, "David has 5000 bones", new String[]{"david", "has", "5000", "bones"});
}
public void testVariousTextSA() throws Exception {
// various
assertAnalyzesTo(a, "C embedded developers wanted", new String[]{"c", "embedded", "developers", "wanted"});
assertAnalyzesTo(a, "foo bar FOO BAR", new String[]{"foo", "bar", "foo", "bar"});
assertAnalyzesTo(a, "foo bar . FOO <> BAR", new String[]{"foo", "bar", "foo", "bar"});
assertAnalyzesTo(a, "\"QUOTED\" word", new String[]{"quoted", "word"});
}
public void testKoreanSA() throws Exception {
// Korean words
assertAnalyzesTo(a, "안녕하세요 한글입니다", new String[]{"안녕하세요", "한글입니다"});
}
public void testReusableTokenStream() throws Exception {
assertAnalyzesToReuse(a, "སྣོན་མཛོད་དང་ལས་འདིས་བོད་ཡིག་མི་ཉམས་གོང་འཕེལ་དུ་གཏོང་བར་ཧ་ཅང་དགེ་མཚན་མཆིས་སོ། །",
new String[] { "སྣོན", "མཛོད", "དང", "ལས", "འདིས", "བོད", "ཡིག", "མི", "ཉམས", "གོང",
"འཕེལ", "དུ", "གཏོང", "བར", "ཧ", "ཅང", "དགེ", "མཚན", "མཆིས", "སོ" });
}
public void testOffsets() throws Exception {
assertAnalyzesTo(a, "David has 5000 bones",
new String[] {"david", "has", "5000", "bones"},
new int[] {0, 6, 10, 15},
new int[] {5, 9, 14, 20});
}
public void testTypes() throws Exception {
assertAnalyzesTo(a, "David has 5000 bones",
new String[] {"david", "has", "5000", "bones"},
new String[] { "<WORD>", "<WORD>", "<NUM>", "<WORD>" });
}
}
| rohankumardubey/lucene-solr-core | lucene/contrib/icu/src/test/org/apache/lucene/analysis/icu/segmentation/TestICUTokenizer.java |
43,340 | package org.threeabn.apps.mysdainterless.security;
import java.io.File;
/**
* Envisioned to handle the list != null && list.size() > 0 and decryption logic when the program/video files are stored on the dongo file sytstem
* Created by k-joseph on 12/10/2017.
*/
public class CryptoLauncher {
private static final String κλειδί = "[3ⱯBИNꓭAƐ]";
/**
* Encrypts and replaces file
*/
public static void encrypt(File file) {
try {
CryptoUtils.encrypt(κλειδί, file, file);
} catch (CryptoException e) {
e.printStackTrace();
//TODO handle this
}
}
/**
* Decrypts and replaces file
*/
public static void dencrypt(File file) {
try {
CryptoUtils.decrypt(κλειδί, file, file);
} catch (CryptoException e) {
e.printStackTrace();
//TODO handle this
}
}
}
| sherrif10/MySDAInterless | app/src/main/java/org/threeabn/apps/mysdainterless/security/CryptoLauncher.java |
43,347 | package gr.aueb.cf.ch4;
import java.util.Scanner;
/**
* Ο χρήστης έχει 10 ευκαιρίες για να βρει
* ένα μυστικό κλειδί (int). Αν το βρει
* νωρίτερα από τη 10η φορά, η for θα πρέπει
* να σταματήσει (break)
*/
public class FindTheSecretApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
final int SECRET_KEY = 12;
int num;
boolean found = false;
for (int i = 1; i <= 10; i++) {
System.out.println("Please make a guess");
num = in.nextInt();
if (num == SECRET_KEY) {
found = true;
break;
}
}
if (!found) {
System.out.println("No worries, play again");
System.exit(1);
}
System.out.println("Success! Play again!");
}
}
| a8anassis/codingfactory23a | src/gr/aueb/cf/ch4/FindTheSecretApp.java |
43,400 | package net.ages.alwb.utils.transformers.adapters;
import java.net.URL;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import org.joda.time.LocalDate;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.ocmc.ioc.liturgical.schemas.constants.BIBLIOGRAPHY_CITATION_OVERRIDE;
import org.ocmc.ioc.liturgical.schemas.constants.NOTE_TYPES;
import org.ocmc.ioc.liturgical.schemas.constants.SCHEMA_CLASSES;
import org.ocmc.ioc.liturgical.schemas.constants.nlp.DEPENDENCY_LABELS_PERSEUS;
import org.ocmc.ioc.liturgical.schemas.constants.nlp.GRAMMAR_ABBREVIATIONS;
import org.ocmc.ioc.liturgical.schemas.constants.nlp.UD_DEPENDENCY_LABELS;
import org.ocmc.ioc.liturgical.schemas.models.db.docs.nlp.TokenAnalysis;
import org.ocmc.ioc.liturgical.schemas.models.db.docs.notes.TextualNote;
import org.ocmc.ioc.liturgical.schemas.models.db.docs.notes.UserNote;
import org.ocmc.ioc.liturgical.schemas.models.db.docs.ontology.TextLiturgical;
import org.ocmc.ioc.liturgical.schemas.models.supers.BibliographyEntry;
import org.ocmc.ioc.liturgical.schemas.models.ws.response.ResultJsonObjectArray;
import org.ocmc.ioc.liturgical.utils.ErrorUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import ioc.liturgical.ws.managers.databases.external.neo4j.ExternalDbManager;
import net.ages.alwb.utils.core.id.managers.IdManager;
import net.ages.alwb.utils.oslw.OslwUtils;
/**
* This class creates a .tex file and a .bib file (if there are citations) to be
* written to disk and then processed by Xelatex. Since there could be
* a bibliography, it is necessary to run xelatex, then biber, then xelatex again.
* These are all combined in the script makepdf, which is placed in the data
* directory where the .tex and .bib files are written to.
*/
public class TextInformationToPdf {
private static final Logger logger = LoggerFactory.getLogger(TextInformationToPdf.class);
private String basePath = "";
private String pathToPdf = "";
private String textId = "";
private JsonObject jsonObject = null;
private StringBuffer texFileSb = new StringBuffer(); // latex tex file content
private StringBuffer bibtexFileSb = new StringBuffer(); // latex tex file content
private Gson gson = new Gson();
private Map<String,List<TokenAnalysis>> map = new TreeMap<String,List<TokenAnalysis>>();
private JsonArray nodes = null;
private JsonArray tokens = null;
private Map<String, Map<NOTE_TYPES, List<TextualNote>>> bigMap = new TreeMap<String,Map<NOTE_TYPES,List<TextualNote>>>();
private Map<String,String> abbr = new TreeMap<String,String>();
private Map<String,JsonObject> abbrJsonStrings = new TreeMap<String,JsonObject>();
private Map<String,JsonObject> biblioJsonStrings = new TreeMap<String,JsonObject>();
private Map<String,String> usedAbbreviations = new TreeMap<String,String>();
private String biblioLibraryTopic = "";
private List<TextualNote> notesList = new ArrayList<TextualNote>();
private List<TextualNote> checkBibleList = new ArrayList<TextualNote>();
private List<TextualNote> adviceList = new ArrayList<TextualNote>();
private List<TextualNote> summaryList = new ArrayList<TextualNote>();
private List<TextualNote> supplementalList = new ArrayList<TextualNote>();
private List<UserNote> userList = new ArrayList<UserNote>();
private List<String> noteIds = new ArrayList<String>();
private Map<String,String> domainMap = null;
private ExternalDbManager dbManager = null;
private String fileId = "";
private boolean hasBibliography = false;
private boolean hasBibliographyList = false;
private boolean hasBibliographyPrimary = false;
private boolean hasBibliographySecondary = false;
private boolean hasBibliographyTertiary = false;
private boolean includeAdviceNotes = false;
private boolean includeGrammar = false;
private boolean includePersonalNotes = false;
private boolean combineNotes = false;
private boolean createToc = false;
private String pdfTitle = "";
private String pdfSubTitle = "";
private String alignmentLibrary = "";
private String alignmentLibraryLatex = "";
private String alignmentText = "";
private String author = "";
private String authorTitle = "";
private String authorAffiliation = "";
private String citestyle = "authoryear";
private StringBuffer textFile = new StringBuffer();
private String NETS = "Quotations marked NETS are taken from A New English Translation of the Septuagint, ©2007 by the International Organization for Septuagint and Cognate Studies, Inc. Used by permission of Oxford University Press. All rights reserved.";
public TextInformationToPdf (
JsonObject jsonObject
, String textId
, Map<String,String> domainMap
, ExternalDbManager dbManager
, String fileId
, boolean includePersonalNotes
, boolean includeAdviceNotes
, boolean includeGrammar
, boolean combineNotes
, boolean createToc
, String alignmentLibrary
, String pdfTitle
, String pdfSubTitle
, String author
, String authorTitle
, String authorAffiliation
, String citestyle
) throws JsonParseException {
this.jsonObject = jsonObject;
this.textId = textId;
this.domainMap = domainMap;
this.dbManager = dbManager;
this.fileId = fileId;
this.includeAdviceNotes = includeAdviceNotes;
this.includePersonalNotes = includePersonalNotes;
this.includeGrammar = includeGrammar;
this.combineNotes = combineNotes;
this.createToc = createToc;
this.alignmentLibrary = alignmentLibrary;
this.pdfTitle = pdfTitle.trim();
this.pdfSubTitle = pdfSubTitle.trim();
if (pdfTitle.equals("undefined")) {
this.pdfTitle = "";
}
if (pdfSubTitle.equals("undefined")) {
this.pdfSubTitle = "";
}
this.author = author.trim();
if (author.equals("undefined")) {
this.author = "";
}
this.authorTitle = authorTitle.trim();
if (authorTitle.equals("undefined")) {
this.authorTitle = "";
}
this.authorAffiliation = authorAffiliation.trim();
if (authorAffiliation.equals("undefined")) {
this.authorAffiliation = "";
}
this.citestyle = citestyle;
if (citestyle.equals("undefined")) {
this.citestyle = "authoryear";
}
this.process();
}
public List<TextualNote> sortNotes(List<TextualNote> list) {
List<TextualNote> result = new ArrayList<TextualNote>();
Map<String, List<String>> noteFollowers = new TreeMap<String,List<String>>();
Map<String, TextualNote> noteMap = new TreeMap<String,TextualNote>();
// create the maps
for (TextualNote note : list) {
noteMap.put(note.id, note);
String follows = "Root";
if (note.followsNoteId.length() > 0 && this.noteIds.contains(note.followsNoteId)) {
follows = note.followsNoteId;
}
List<String> followers = new ArrayList<String>();
if (noteFollowers.containsKey(follows)) {
followers = noteFollowers.get(follows);
}
followers.add(note.getId());
noteFollowers.put(follows, followers);
}
// create the sorted result
List<String> followers = this.getFollowers("Root", noteFollowers);
int counter = 1;
for (String id : followers) {
TextualNote note = noteMap.get(id);
note.adhocSortKey = String.format("%03d", counter);
result.add(note);
counter++;
}
return result;
}
// makes a recursive call
public List<String> getFollowers(String forId, Map<String,List<String>> map) {
List<String> result = new ArrayList<String>();
if (map.containsKey(forId)) {
List<String> followers = map.get(forId);
if (followers != null) {
for (String follower : followers) {
if (! result.contains(follower)) { // just in case this is cyclical instead of a linked list
result.add(follower);
List<String> moreFollowers = this.getFollowers(follower, map);
for (String id : moreFollowers) {
result.add(id);
}
}
}
}
}
return result;
}
private String createBibFileContent() {
StringBuffer sb = new StringBuffer();
for (JsonObject json: this.biblioJsonStrings.values()) {
try {
BibliographyEntry record =
(BibliographyEntry) gson.fromJson(
json.toString()
, SCHEMA_CLASSES
.classForSchemaName(
json.get("_valueSchemaId").getAsString())
.ltkDb.getClass()
);
// we use hasBibliographyList later to determine whether to print an abbreviation based bibliography
if (this.hasBibliographyList) {
// ignore
} else {
if (record.citeoverride != BIBLIOGRAPHY_CITATION_OVERRIDE.NONE) {
this.hasBibliographyList = true;
}
}
switch (record.getSourceType()) {
case PRIMARY:
this.hasBibliographyPrimary = true;
break;
case SECONDARY:
this.hasBibliographySecondary = true;
break;
case TERTIARY:
this.hasBibliographyTertiary = true;
break;
}
String bibTex = record.toBibtex();
sb.append(bibTex);
sb.append("\n");
} catch (Exception e) {
ErrorUtils.report(logger, e);
}
}
return sb.toString();
}
private void appendText(String text) {
this.textFile.append(text);
this.textFile.append("\n");
}
private String getTitle() {
StringBuffer sb = new StringBuffer();
sb.append("\\Large ");
sb.append("\\begin{center}\n\\textbf{");
sb.append(this.pdfTitle);
this.appendText(this.pdfTitle);
sb.append("}\n\\end{center}");
if (this.pdfSubTitle.length() > 0) {
sb.append("{\\scshape\\large ");
sb.append("\\begin{center}");
sb.append(this.pdfSubTitle);
this.appendText(this.pdfSubTitle);
sb.append("\\end{center}");
sb.append("}%\n");
}
sb.append("{\\scshape\\small\n");
sb.append("\\begin{center}\n\\textit{");
if (this.author.length() > 0) {
sb.append(this.author);
this.appendText(this.author);
sb.append("\\\\");
}
if (this.authorTitle.length() > 0) {
sb.append(this.authorTitle);
this.appendText(this.authorTitle);
sb.append("\\\\");
}
if (this.authorAffiliation.length() > 0) {
sb.append(this.authorAffiliation);
this.appendText(this.authorAffiliation);
sb.append("\\\\");
}
sb.append(LocalDate.now().toString());
sb.append("}\n\\end{center}");
sb.append("}%\n");
if (this.includeAdviceNotes && this.author.contains("Colburn")) {
sb.append("\\includegraphics[width=.5\\textwidth]{system/images/nicodemos.jpg}");
sb.append("{\\scshape\\footnotesize\n");
sb.append("\\begin{center}\n");
sb.append("O Lord, through the prayers of our Holy Fathers Kosmos the Poet, John of Damascus, and Nikodemos of the Holy Mountain, give us understanding and grace to create translations that are pleasing to You!");
sb.append("\n\\end{center}");
sb.append("}%\n");
}
sb.append("\\vfill%\n");
return sb.toString();
}
private String getTableOfContents() {
StringBuffer sb = new StringBuffer();
sb.append("\\tableofcontents*\n");
sb.append("\\vfill\n");
return sb.toString();
}
private String getPreface() {
StringBuffer sb = new StringBuffer();
sb.append("\\pagebreak\\n\\renewcommand*{\\pagenumbering}[1]{}\\n\\section{Purpose}\n");
sb.append("This handbook is for people who speak English as a foreign language and are translating the liturgical texts into a non-Indoeuropean language. It answers the following questions: What does the Greek text say? What does it mean? What problems might I have translating it and how might I solve those problems? It answers these questions by providing the Greek text, example English translations, notes about each Greek word or phrase, and a detailed grammatical analysis\\footnote{Comments, corrections, and suggestions for improvement should be sent to Michael Colburn at [email protected].}.");
sb.append("\n\\section{Types of Translations}\n");
sb.append("The type of translation a person creates depends on what the priority is. If the priority is to preserve the order of the Greek words and phrases and to use words that give the literal meaning of the Greek, I call this a \\textit{Structure-Oriented Translation}. I created the GE-SOT as an example. If the priority is to convey the meaning of the Greek text, I call this a \\textit{Meaning-Oriented Translation}. I created the GE-MOT as an example. Some translations balance these two priorities, for example, the translation in \\textit{The Festal Menaion} by His Eminence Kallistos Ware and Mother Mary (TFM). I created the GEV as another example. Whether or not a translation is structure-oriented, or meaning-oriented, or falls in between, when you translate a hymn, it is important to create a translation that can be sung based on a melody. So, the translation sometimes has to be adjusted by using different words or a different word order. Fr. Seraphim Dedes' translation is an example.");
sb.append("\n\\section{About the Global English Translations}\n");
sb.append("");
sb.append("\nThe GEV, GE-SOT and GE-MOT use the Oxford 3000\\footnote{\\url{https://www.oxfordlearnersdictionaries.com/us/about/oxford3000}.} list of the most important English words. People who speak English as a second language should know these words. By trying to use only these 3000 words, the Global English translations have to adjust the translation in ways similar to what happens when people translate the Greek into non-Indoeuropean languages. These translations demonstrate three types of translation. The GE-SOT is the closest to the Greek word order and the literal meaning. It is used for the word by word discussion of the meaning and for the interlinear grammar and dependency diagram. The GE-MOT will help you understand the meaning. It does this by adding information that is implied by the Greek text. If you must translate from English, ask your Bishop which translation He prefers. If He is not available to ask, then use the GEV.\n");
sb.append("\n\\section{How to Use this Handbook}\n");
sb.append("If you can, first read the Greek text. Then study the translations. Note what is similar and different. Make a first draft translation from the Greek or the GEV. Write down questions you have. Look for answers in the notes and grammar sections. Make changes to your translation based on what you read. Let other people read your translation. Ask questions to learn how they understand it. Make changes as needed. Adjust the translation to fit the melody it will be sung to.");
return sb.toString();
}
private String getTitlePage() {
StringBuffer sb = new StringBuffer();
sb.append("\\begin{titlingpage}%\n");
sb.append("\\openup .5em%\n");
sb.append("\\begin{center}%\n");
sb.append("\\begin{minipage}{25em}%\n");
sb.append("\\begin{center}%\n");
sb.append("\\linespread{2}%\n");
sb.append(this.getTitle());
sb.append("\\end{center}%\n");
sb.append("\\end{minipage}%\n");
sb.append("\\end{center}%\n");
sb.append("\\end{titlingpage}%\n");
return sb.toString();
}
public void process() {
IdManager idManager = new IdManager(this.textId);
this.texFileSb.append("\\documentclass[extrafontsizes,openany,12pt]{memoir}\n");
this.texFileSb.append("\\usepackage{multicol}%\n");
this.texFileSb.append("\\usepackage{system/ocmc-grammar}%\n");
this.texFileSb.append("\\usepackage[hyphenate]{system/ocmc-liturgical-text}%\n");
this.texFileSb.append("\\input{system/control} %\n");
this.texFileSb.append("\\usepackage[defaultlines=4,all]{nowidow}%\n");
boolean sbl = false; // note working yet
if (sbl) {
this.texFileSb.append(this.getBiblatexSblPackage());
} else {
this.texFileSb.append(this.getBiblatexPackage(
this.citestyle // bibstyle
, this.citestyle // citestyle
, "nyt" // sorting
, "true" // sortcites
, "true" // autopunct
, "hyphen" // babel
, "true" // hyperref
, "false" // abbreviate
));
}
this.loadAbbreviations();
if (this.includeGrammar) {
this.loadGrammar();
// add the values for the titles
if (this.pdfTitle.length() == 0) {
this.pdfTitle = this.tokens.get(0).getAsString() + " " + this.tokens.get(1).getAsString();
}
}
try {
String firstChar = this.pdfTitle.substring(0, 1).toLowerCase();
if (firstChar.matches("[α-ω]")) {
TextLiturgical dummy = new TextLiturgical("en_us_system", "a", "b");
dummy.setValue(this.pdfTitle);
this.pdfTitle = dummy.getNnp().toUpperCase();
}
} catch (Exception e) {
ErrorUtils.report(logger, e, this.pdfTitle);
}
String title = this.pdfTitle.replaceAll("\\\\", " ");
this.texFileSb.append(OslwUtils.getOslwTitleResources(
idManager.getLibrary()
, this.pdfTitle
, title
, title
, ""
)
);
this.loadNotes();
this.hasBibliography = this.biblioJsonStrings.size() > 0;
if (this.hasBibliography) {
this.hasBibliography = true;
this.texFileSb.append("\\addbibresource{");
this.texFileSb.append(this.fileId);
this.texFileSb.append(".bib}%\n\n");
this.bibtexFileSb.append(this.createBibFileContent());
this.texFileSb.append("\n\\DeclareFieldFormat*{citetitle}{\\textnormal{\\textit{#1}}}\n");
this.texFileSb.append("\\newcommand{\\ltCitePrimary}[1]{\n");
this.texFileSb.append("\\citeauthor*{#1}. \\citetitle*{#1}.%\n");
this.texFileSb.append("}\n");
}
// this.texFileSb.append("\\OnehalfSpacing");
this.texFileSb.append("\\linespread{1.0}%\n");
this.texFileSb.append("\\setaftersecskip{0}");
this.texFileSb.append("\\begin{document}%\n");
this.texFileSb.append("\\parskip=6pt");
this.texFileSb.append(this.getTitlePage());
if (this.createToc) {
this.texFileSb.append(this.getTableOfContents());
}
this.texFileSb.append("\n");
if (this.includeAdviceNotes && this.author.contains("Colburn")) {
this.texFileSb.append(this.getPreface());
}
this.texFileSb.append("\n");
this.texFileSb.append("\\mainmatter%\n");
this.texFileSb.append("\\nopartblankpage");
this.texFileSb.append("\\selectlanguage{english}\n");
// set the title for the pdf
this.texFileSb.append("\\ltChapter{pdf}{title}\n");
// provide the topic and key we are using
StringBuffer ages = new StringBuffer();
ages.append("\\begin{center}\n");
ages.append("\\tiny{");
ages.append("\nAGES Topic\\textasciitilde Key: ");
ages.append(idManager.getTopic());
ages.append("\\textasciitilde ");
ages.append(idManager.getKey());
ages.append("}\n");
String description = idManager.getTopicDescription();
if (description.length() > 0) {
ages.append("\n\n\\color{red}");
ages.append(description);
ages.append("\\color{black}\n");
}
ages.append("\\end{center}\n");
// process the content
this.texFileSb.append(this.getVersionsAsLatex(ages.toString()));
this.texFileSb.append("\\vfill");
this.texFileSb.append(this.getNotesAsLatex());
this.texFileSb.append("\\vfill");
if (this.includeGrammar) {
this.texFileSb.append("\n\\section{Grammar}");
this.texFileSb.append(this.getInterlinearAsLatex());
this.texFileSb.append("\\vfill");
this.texFileSb.append(this.getDependencyDiagramAsLatex());
this.texFileSb.append("\\vfill");
}
this.texFileSb.append(this.getAbbreviationsAsLatex());
if (this.hasBibliography) {
this.texFileSb.append("\n\\section{Bibliography}\n\n");
this.texFileSb.append("\\selectlanguage{english}\n");
if (this.hasBibliographyList) {
this.texFileSb.append("\\small{\\textbf{By Abbreviation}}\n\n");
this.texFileSb.append("\\printbiblist[heading=bibempty]{shorttitle}\n\n");
}
if (this.hasBibliographyPrimary || this.hasBibliographySecondary || this.hasBibliographyTertiary) {
if (this.hasBibliographyPrimary) {
this.texFileSb.append("\\small{\\textbf{By Author (Primary Sources)}}\n\n");
this.texFileSb.append("\\printbibliography[heading=bibempty,keyword=primary]\n");
}
if (this.hasBibliographySecondary) {
this.texFileSb.append("\\small{\\textbf{By Author (Secondary Sources)}}\n\n");
this.texFileSb.append("\\printbibliography[heading=bibempty,keyword=secondary]\n");
}
if (this.hasBibliographyTertiary) {
this.texFileSb.append("\\small{\\textbf{By Author (Tertiary Sources)}}\n\n");
this.texFileSb.append("\\printbibliography[heading=bibempty,keyword=tertiary]\n");
}
} else {
this.texFileSb.append("\\small{\\textbf{By Author}}\n\n");
this.texFileSb.append("\\printbibliography[heading=bibempty]\n");
}
}
if (this.includePersonalNotes) {
this.texFileSb.append(this.getUserNotesAsLatex());
}
// close out the generation
this.texFileSb.append(
"\n\n\\tiny\\textit{Generated ");
this.texFileSb.append(ZonedDateTime.now(ZoneOffset.UTC));
this.texFileSb.append(" (Universal Time) using the OCMC Online Liturgical Workstation at ");
this.texFileSb.append("\\url{https://olw.ocmc.org}");
this.texFileSb.append(". Glory to God! Δόξα σοι, ὁ Θεὸς ἡμῶν· δόξα σοι! }%\n");
// this.texFileSb.append(" (Universal Time) using liturgical software from the Orthodox Christian Mission Center (OCMC), St. Augustine, FL, USA. Glory to God! Δόξα σοι, ὁ Θεὸς ἡμῶν· δόξα σοι! }%\n");
this.texFileSb.append("\\vfill");
this.texFileSb.append("\\end{document}%\n");
}
public String getUserNotesAsLatex() {
StringBuffer sb = new StringBuffer();
// sb.append("\n\\vfill%\n");
// sb.append("\\pagebreak%\n");
this.texFileSb.append("\n\\section{Your Personal Notes}\n\n");
if (this.userList.size() > 0) {
for (UserNote note : this.userList) {
if (note.getValue() != null) {
sb.append("\n");
sb.append(note.getValue());
if (note.getTags().size() > 0) {
sb.append(" Tags: ");
sb.append(note.getTags().toString());
}
sb.append("\n\n");
}
}
} else {
sb.append("No personal notes found for this text.");
}
return sb.toString();
}
public String getInterlinearAsLatex() {
StringBuffer sb = new StringBuffer();
sb.append("\n\\subsection{Interlinear Text}\n");
sb.append("This section provides information about the grammar of words (that is, the morphology) \\footnote{You can read about Greek grammar at \\url{https://ancientgreek.pressbooks.com}.}. The Greek words appear in the same order as they do in the source text.\n");
sb.append(this.nodesToInterlinear());
sb.append("\n\\sectionline\n");
return sb.toString();
}
public String getDependencyDiagramAsLatex() {
StringBuffer sb = new StringBuffer();
sb.append("\n\\subsection{Dependency Diagram}\n");
sb.append("A dependency diagram shows the syntax of the text. \\textit{Syntax} means \\textit{the grammatical relationship between words}. It shows the relationships based on dependency grammar\\footnote{See \\url{http://universaldependencies.org}}. The order of each Greek word in the diagram is based on the word it depends on\\footnote{\\textit{depends on} means \\textit{is governed by or subordinate to}.}. It appears indented and after the word it depends on. The first word in the diagram is the root, that is, the starting point of the dependencies.");
sb.append("\\newline");
sb.append("{\\footnotesize ");
sb.append(this.processNode(null, new StringBuffer(),0));
sb.append("}\n\\sectionline\n");
return sb.toString();
}
private void loadGrammar() {
JsonArray array = this.jsonObject.get("grammar").getAsJsonArray();
this.tokens = array.get(1).getAsJsonObject().get("tokens").getAsJsonArray();
this.nodes = array.get(3).getAsJsonObject().get("nodes").getAsJsonArray();
for (JsonElement e : this.nodes) {
TokenAnalysis node = this.gson.fromJson(e, TokenAnalysis.class);
String dependsOn = node.getDependsOn();
List<TokenAnalysis> children = null;
if (this.map.containsKey(dependsOn)) {
children = this.map.get(dependsOn);
} else {
children = new ArrayList<TokenAnalysis>();
}
children.add(node);
this.map.put(dependsOn, children);
}
}
private String nodesToInterlinear() {
StringBuffer sb = new StringBuffer();
int j = this.nodes.size();
sb.append("\n\\begingl[glstyle=nlevel]\n");
for (int i=0; i < j; i++) {
TokenAnalysis node = this.gson.fromJson(this.nodes.get(i), TokenAnalysis.class);
String gloss = node.getGloss();
gloss = gloss.replaceAll("\\[", "{[}");
gloss = gloss.replaceAll("\\]", "{]}");
sb.append("\\color{burgundy}");
sb.append(i+1);
sb.append("[\\color{blue}\\textbf{");
sb.append(node.getToken());
sb.append("}/\\color{burgundy}");
sb.append(gloss);
sb.append("/");
sb.append(node.getGrammar());
sb.append("/\\color{blue}");
sb.append(node.getLemma());
sb.append("\\color{black}]\n");
this.addGrammarAbbreviations(node.getGrammar());
}
sb.append("\\endgl\n\\vfill\n");
return sb.toString();
}
private void addGrammarAbbreviations(String grammar) {
try {
String [] keys = grammar.split("\\.");
for (String key : keys) {
if (! this.usedAbbreviations.containsKey(key)) {
String value = "";
if (this.abbr.containsKey(key)) {
value = this.abbr.get(key);
}
this.usedAbbreviations.put(key, value);
}
}
} catch (Exception e) {
// ignore
}
}
private String getBiblatexPackage(
String bibstyle
, String citestyle
, String sorting
, String sortcites
, String autopunct
, String babel
, String hyperref
, String abbreviate
) {
StringBuffer sb = new StringBuffer();
sb.append("\\usepackage[bibstyle=");
sb.append(bibstyle);
sb.append(",citestyle=");
sb.append(citestyle);
sb.append(",sorting=");
sb.append(sorting);
sb.append(",sortcites=");
sb.append(sortcites);
sb.append(",autopunct=");
sb.append(autopunct);
sb.append(",babel=");
sb.append(babel);
sb.append(",hyperref=");
sb.append(hyperref);
sb.append(",abbreviate=");
sb.append(abbreviate);
sb.append(",backref=true,bibencoding=utf8, backend=biber]{biblatex}%\n");
sb.append("\\defbibheading{bibempty}{}%\n");
return sb.toString();
}
private String getBiblatexSblPackage(
) {
StringBuffer sb = new StringBuffer();
sb.append("\\usepackage{biblatex-sbl}%\n");
sb.append("\\usepackage[style=sbl]{biblatex}%\n");
return sb.toString();
}
private void addSyntacticLabel(String key) {
try {
if (! this.usedAbbreviations.containsKey(key)) {
String value = "";
if (this.abbr.containsKey(key)) {
value = this.abbr.get(key);
}
this.usedAbbreviations.put(key, value);
}
} catch (Exception e) {
// ignore
}
}
private StringBuffer processNode(
TokenAnalysis node
, StringBuffer sb
, int spaces
) {
String key = "";
if (node == null) {
key = "Root";
} else {
sb.append("\\newline");
sb.append("\\color{white}");
sb.append("$\\vert$");
for (int i=0; i < spaces; i++) {
if (i == spaces - 2) {
sb.append("\\color{black}$\\vert$");
} else {
sb.append("--");
}
}
key = node.getKey();
int intKey = Integer.parseInt(key);
intKey++;
String label = node.getLabel();
this.addSyntacticLabel(label);
if (label.endsWith("_CO")) {
label = label.replace("_", "\\textunderscore ");
}
String gloss = node.getGloss();
gloss = gloss.replaceAll("\\[", "{[}");
gloss = gloss.replaceAll("\\]", "{]}");
sb.append("\\grNode");
sb.append("{");
sb.append(intKey);
sb.append("}");
sb.append("{");
sb.append(label);
sb.append( "}");
sb.append("{");
sb.append(node.getToken());
sb.append("}");
sb.append("{");
sb.append(gloss);
sb.append("}");
sb.append("{");
sb.append(node.getGrammar());
sb.append("}");
sb.append("{");
sb.append(node.getLemma());
sb.append("}\n");
}
if (this.map.containsKey(key)) {
List<TokenAnalysis> children = this.map.get(key);
for (TokenAnalysis child : children) {
this.processNode(child, sb, spaces+2);
}
}
if (node != null) {
// sb.append("\\end{minipage}\n\n");
// sb.append("\\prevdepth\n\n");
// sb.append("\\end{mdframed}\n");
}
return sb;
}
public void loadAbbreviations() {
for (DEPENDENCY_LABELS_PERSEUS v : DEPENDENCY_LABELS_PERSEUS.values()) {
abbr.put(v.keyname, v.description);
}
for (UD_DEPENDENCY_LABELS v : UD_DEPENDENCY_LABELS.values()) {
abbr.put(v.keyname, v.fullname);
}
for (GRAMMAR_ABBREVIATIONS v : GRAMMAR_ABBREVIATIONS.values()) {
abbr.put(v.keyname, v.description);
}
}
public String getAbbreviationsAsLatex() {
StringBuffer sb = new StringBuffer();
if (this.usedAbbreviations.size() > 0) {
sb.append("\\section{Abbreviations}\n");
sb.append("\\begin{tabular}{ r | l }\n");
int i = 0;
for (Entry<String,String> entry : this.usedAbbreviations.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (! value.startsWith("empty")) {
if (key.endsWith("_CO")) {
key = key.replace("_", "\\textunderscore ");
}
sb.append(key);
sb.append(" & ");
sb.append(entry.getValue());
sb.append("\\\\");
sb.append("\n");
i++;
if (i == 25) {
sb.append("\\end{tabular}\n");
sb.append("\\vfill\\newpage\n");
sb.append("\\begin{tabular}{ r | l }\n");
i = 0;
}
}
}
sb.append("\\end{tabular}\n");
}
sb.append("\n\\sectionline\n");
return sb.toString();
}
public String getNotesAsLatex() {
StringBuffer sb = new StringBuffer();
sb.append("\\section{Notes About the Text}");
sb.append("\\subsection{Summary}\n");
for (TextualNote note : this.summaryList) {
sb.append(note.getValue());
sb.append("\n");
}
if (! this.checkBibleList.isEmpty()) {
// sb.append("\\vfill%\n");
sb.append("\n\\subsection{References to the Bible}\n\n");
sb.append("This liturgical text makes the following references to the Bible:\n");
sb.append(this.processCheckBibleNotes());
}
sb.append("\n\n\\subsection{Discussion}\n");
if (this.combineNotes) {
sb.append("The notes are sorted based the order of words in the ");
sb.append(this.alignmentLibraryLatex);
sb.append(" version of the text. English quotations from the Bible are from the World English Bible British Edition (WEBBE) unless otherwise stated.\n");
// sb.append("\\vfill%\n");
sb.append(this.combineNotes());
} else {
sb.append(this.processNotesByType());
if (this.includeAdviceNotes) {
sb.append("\\subsection{Advice for Translators and Translation Checkers}\n");
sb.append(this.processAdviceNotes());
}
}
if (this.supplementalList.size() > 0) {
sb.append("\n\\subsection{Supplemental Notes}\n");
for (TextualNote note : this.supplementalList) {
sb.append(
this.getNoteAsLatexForNonRef(
note
, true
)
);
// sb.append(note.getValue());
sb.append("\n");
}
}
sb.append("\n\\sectionline\n");
sb.append("\\vfill%\n");
return sb.toString();
}
private void addListToBigMap(List<TextualNote> listToAdd) {
for (TextualNote note : listToAdd) {
String scope = note.getLiturgicalScope().trim();
Map<NOTE_TYPES, List<TextualNote>> multi = new TreeMap<NOTE_TYPES,List<TextualNote>>();
if (this.bigMap.containsKey(scope)) {
multi = this.bigMap.get(scope);
}
List<TextualNote> list = new ArrayList<TextualNote>();
if (multi.containsKey(note.getNoteType())) {
list = multi.get(note.getNoteType());
}
list.add(note);
multi.put(note.getNoteType(), list);
this.bigMap.put(scope, multi);
}
}
private String getNoteAsGenericLatex(TextualNote note) {
StringBuffer sb = new StringBuffer();
sb.append("\\noteGeneric{");
sb.append(note.getNoteType().notename);
sb.append("}{");
if (note.getNoteTitle().trim().length() > 0) {
sb.append(note.getNoteTitle());
sb.append("}{");
}
sb.append(note.getValue());
sb.append("}");
return sb.toString();
}
private String getNotesAsGenericLatex(List<TextualNote> list) {
StringBuffer sb = new StringBuffer();
for (TextualNote note : list) {
sb.append(this.getNoteAsGenericLatex(note));
}
return sb.toString();
}
private String getNoteAsReferenceLatex(TextualNote note) {
StringBuffer sb = new StringBuffer();
sb.append("\\noteRefersTo{");
sb.append(note.getNoteType().notename);
sb.append("}{");
if (note.getNoteTitle().trim().length() > 0) {
sb.append(note.getNoteTitle());
sb.append("}{");
}
sb.append(note.getValue());
sb.append("}");
return sb.toString();
}
private String getNotesAsReferencesLatex(List<TextualNote> list) {
StringBuffer sb = new StringBuffer();
for (TextualNote note : list) {
sb.append(this.getNoteAsReferenceLatex(note));
}
return sb.toString();
}
private Map<Integer, String> getAlignmentList() {
Map<String, List<String>> indexMap = new TreeMap<String, List<String>>();
TextLiturgical dummy = new TextLiturgical("en_us_system", "a", "b");
dummy.setValue(this.alignmentText);
String nnp = ' ' + dummy.getNnp() + ' ';
List<String> notFound = new ArrayList<String>();
for (String scope : this.bigMap.keySet()) {
scope = scope.trim();
dummy.setValue(scope);
String scopeNnp = ' ' + dummy.getNnp() + ' ';
int i = 0;
if (nnp.contains(scopeNnp)) {
while (i > -1) {
i = nnp.indexOf(scopeNnp, i);
if (i > -1) {
List<String> list = new ArrayList<String>();
if (indexMap.containsKey(scope)) {
list = indexMap.get(scope);
}
if (! list.contains(i)) {
list.add(Integer.toString(i));
}
indexMap.put(scope, list);
i++;
}
}
} else {
notFound.add(scope);
}
}
Map<Integer, String> sortedScopes = new TreeMap<Integer,String>();
Integer index = 0;
for (Entry<String,List<String>> entry : indexMap.entrySet()) {
List<String> list = entry.getValue();
for (String s : list) {
index = Integer.parseInt(s);
if (sortedScopes.containsKey(index)) {
index++;
}
sortedScopes.put(index, entry.getKey());
}
}
// add any that we could not align
Collections.sort(notFound);
for (String scope : notFound) {
index++;
sortedScopes.put(index, scope);
}
return sortedScopes;
}
private String combineNotes() {
StringBuffer sb = new StringBuffer();
// load the big Map
this.addListToBigMap(this.notesList);
if (this.includeAdviceNotes) {
this.addListToBigMap(this.adviceList);
}
// create the alignment index
Collection<String> scopeCollection = null;
if (this.alignmentText.length() > 0) {
scopeCollection = this.getAlignmentList().values();
}
if (scopeCollection == null || scopeCollection.size() == 0) {
scopeCollection = this.bigMap.keySet();
}
// process the notes grouped by scope
for (String bigMapKey : scopeCollection) {
StringBuffer combo = new StringBuffer();
Map<NOTE_TYPES, List<TextualNote>> scopeMap = this.bigMap.get(bigMapKey);
NOTE_TYPES sampleKey = null;
for (NOTE_TYPES t : scopeMap.keySet()) {
sampleKey = t;
break;
}
TextualNote sample = scopeMap.get(sampleKey).get(0);
String scope = sample.getLiturgicalScope().trim();
String lemma = sample.getLiturgicalLemma();
combo.append("\n\\noteLexical{");
combo.append(scope);
combo.append("}{");
combo.append(lemma);
combo.append("} ");
// we need to strictly control the order for some types of notes
if (scopeMap.containsKey(NOTE_TYPES.MEANING)) {
combo.append(this.getNotesAsGenericLatex(scopeMap.get(NOTE_TYPES.MEANING)));
}
if (scopeMap.containsKey(NOTE_TYPES.GRAMMAR)) {
combo.append(this.getNotesAsGenericLatex(scopeMap.get(NOTE_TYPES.GRAMMAR)));
}
for (Entry<NOTE_TYPES, List<TextualNote>> entry : scopeMap.entrySet()) {
NOTE_TYPES key = entry.getKey();
if (key == NOTE_TYPES.REF_TO_BIBLE) {
for (TextualNote note : scopeMap.get(key)) {
combo.append("\\noteRefToBible{");
combo.append(note.biblicalScope);
combo.append("}{");
combo.append(note.biblicalLemma);
if (note.noteTitle.trim().length() > 0) {
combo.append("}{");
combo.append(note.noteTitle);
}
if (note.getValue().trim().length() > 0) {
combo.append("}{");
combo.append(note.getValue());
} else {
combo.append(".");
}
combo.append("}");
}
} else if (key.name().startsWith("REF_TO")) {
combo.append(this.getNotesAsReferencesLatex(scopeMap.get(key)));
} else {
if (key == NOTE_TYPES.MEANING
|| key == NOTE_TYPES.GRAMMAR
|| key == NOTE_TYPES.ADVICE_FOR_TRANSLATION_CHECKERS
|| key == NOTE_TYPES.ADVICE_FOR_TRANSLATORS
|| key == NOTE_TYPES.CHECK_YOUR_BIBLE
) {
// ignore
} else {
combo.append(this.getNotesAsGenericLatex(scopeMap.get(key)));
}
}
}
if (this.includeAdviceNotes) {
if (scopeMap.containsKey(NOTE_TYPES.ADVICE_FOR_TRANSLATORS)) {
combo.append(this.getNotesAsGenericLatex(scopeMap.get(NOTE_TYPES.ADVICE_FOR_TRANSLATORS)));
}
if (scopeMap.containsKey(NOTE_TYPES.ADVICE_FOR_TRANSLATION_CHECKERS)) {
combo.append(this.getNotesAsGenericLatex(scopeMap.get(NOTE_TYPES.ADVICE_FOR_TRANSLATION_CHECKERS)));
}
if (scopeMap.containsKey(NOTE_TYPES.CHECK_YOUR_BIBLE)) {
for (TextualNote note : scopeMap.get(NOTE_TYPES.CHECK_YOUR_BIBLE)) {
combo.append("\\noteCheckYourBible{");
combo.append(note.biblicalScope);
combo.append("}{");
combo.append(note.biblicalLemma);
if (note.noteTitle.trim().length() > 0) {
combo.append("}{");
combo.append(note.noteTitle);
}
if (note.getValue().trim().length() > 0) {
combo.append("}{");
combo.append(note.getValue());
} else {
combo.append(".");
}
combo.append("}");
}
}
}
sb.append("\n");
sb.append(combo.toString());
}
sb.append("\n\\vfill%");
return sb.toString();
}
private void loadNotes() {
List<TextualNote> tempAdviceList = new ArrayList<TextualNote>();
List<TextualNote> tempTopicsList = new ArrayList<TextualNote>();
for (JsonElement e : this.jsonObject.get("textNotes").getAsJsonArray()) {
TextualNote note = this.gson.fromJson(
e.getAsJsonObject().get("properties(to)").getAsJsonObject()
, TextualNote.class
);
this.noteIds.add(note.getId());
note.setValueFormatted(this.htmlToLatex(note.getValueFormatted()));
if (note.getNoteType() == NOTE_TYPES.UNIT) {
this.summaryList.add(note);
} else if (note.getNoteType() == NOTE_TYPES.REF_TO_BIBLE) {
this.checkBibleList.add(note);
} else if (note.getNoteType() == NOTE_TYPES.ADVICE_FOR_TRANSLATION_CHECKERS
|| note.getNoteType() == NOTE_TYPES.ADVICE_FOR_TRANSLATORS
) {
tempAdviceList.add(note);
} else if (note.getNoteType() == NOTE_TYPES.SUPPLEMENTAL_NOTE) {
this.supplementalList.add(note);
} else {
tempTopicsList.add(note);
}
}
if (this.includeAdviceNotes) {
this.adviceList = this.sortNotes(tempAdviceList); // sorts using the followsNoteId property
}
Collections.sort(tempTopicsList);
this.notesList = tempTopicsList;
if (this.includePersonalNotes) {
if (this.jsonObject.has("userNotes")) {
for (JsonElement e : this.jsonObject.get("userNotes").getAsJsonArray()) {
UserNote note = this.gson.fromJson(
e.getAsJsonObject().get("properties(to)").getAsJsonObject()
, UserNote.class
);
this.userList.add(note);
}
}
}
}
private String processNotesByType() {
StringBuffer sb = new StringBuffer();
NOTE_TYPES currentType = null;
Collections.sort(
this.notesList
, TextualNote.noteTypeLiturgicalScopeComparator);
for (TextualNote note : this.notesList) {
NOTE_TYPES type = note.getNoteType();
if (currentType != type) {
sb.append("\n\\subsubsection{");
sb.append(type.fullname);
sb.append("}\n");
currentType = type;
}
if (type == NOTE_TYPES.REF_TO_BIBLE) {
// sb.append(this.getNoteAsLatexForBibleRef(note));
} else if (type.name().startsWith("REF_TO")){
sb.append(
this.getNoteAsLatexRefersTo(
note
)
);
} else {
sb.append(
this.getNoteAsLatexForNonRef(
note
, true
)
);
}
}
return sb.toString();
}
private String processCheckBibleNotes() {
StringBuffer sb = new StringBuffer();
Collections.sort(
this.checkBibleList
, TextualNote.noteTypeLiturgicalScopeComparator);
for (TextualNote note : this.checkBibleList) {
sb.append(this.getNoteAsLatexForBibleRef(note));
}
return sb.toString();
}
private String processAdviceNotes() {
StringBuffer sb = new StringBuffer();
Collections.sort(
this.adviceList
, TextualNote.noteLiturgicalScopeComparator);
// the noteTypeAdHocComparator is used if we use the dependency sort
// Collections.sort(
// this.adviceList
// , TextualNote.noteTypeAdHocComparator);
for (TextualNote note : this.adviceList) {
sb.append(
this.getNoteAsLatexForNonRef(
note
, true
)
);
}
return sb.toString();
}
private String getNoteAsLatexForBibleRef(
TextualNote note
) {
StringBuffer sb = new StringBuffer();
if (note.value.trim().length() > 0) {
sb.append("\n\\noteLexicalRefToBibleTitle{");
} else {
sb.append("\n\\noteLexicalRefToBible{");
}
sb.append(note.liturgicalScope.trim());
sb.append("}{");
sb.append(note.liturgicalLemma);
sb.append("}{");
sb.append(note.biblicalScope);
sb.append("}{");
sb.append(note.biblicalLemma);
if (note.noteTitle.trim().length() > 0) {
sb.append("}{");
sb.append(note.noteTitle);
}
if (note.value.trim().length() > 0) {
sb.append("}{");
sb.append(note.value);
}
sb.append("}\n");
return sb.toString();
}
private String getNoteAsLatexRefersTo(
TextualNote note
) {
StringBuffer sb = new StringBuffer();
sb.append("\n\\noteRefersTo{");
sb.append(note.liturgicalScope.trim());
sb.append("}{");
sb.append(note.liturgicalLemma);
sb.append("}{");
sb.append(note.noteTitle);
if (note.value.trim().length() > 0) {
sb.append("}{");
sb.append(note.value);
}
sb.append("}\n");
return sb.toString();
}
private String htmlToLatex(String html) {
try {
// process the anchors, which represent an abbreviation or a citation
// e.g. @
Document doc = Jsoup.parse(html);
Elements anchors = doc.select("a");
for (Element anchor : anchors) {
String id = anchor.attr("href");
if (id.startsWith("http")) {
URL url = new URL(id);
id = url.getPath().substring(1);
}
if (id.contains("~")) {
String dataValue = anchor.attr("data-value");
if (dataValue == null || dataValue.length() == 0) {
try {
dataValue = anchor.attr("href").split("~")[2];
} catch (Exception e) {
// ignore
}
}
IdManager idManager = new IdManager(id);
switch (idManager.getTopic()) {
case ("abbreviation"): {
if (! this.abbrJsonStrings.containsKey(id)) {
try {
ResultJsonObjectArray queryResult = this.dbManager.getForId(id);
if (queryResult.valueCount > 0) {
this.abbrJsonStrings.put(id, queryResult.getFirstObjectValueAsObject());
}
} catch (Exception e) {
ErrorUtils.report(logger, e, id + " not found");
}
}
break;
}
case ("biblioentry"): {
if (! this.biblioJsonStrings.containsKey(id)) {
try {
if (this.biblioLibraryTopic.length() < 1) {
this.biblioLibraryTopic = idManager.getLibrary() + "~" + idManager.getTopic();
}
ResultJsonObjectArray queryResult = this.dbManager.getForId(id);
if (queryResult.valueCount > 0) {
this.biblioJsonStrings.put(id, queryResult.getFirstObjectValueAsObject());
}
} catch (Exception e) {
ErrorUtils.report(logger, e, id + " not found");
}
}
break;
}
default: {
}
}
// convert to latex citation
anchor.tagName("span");
// TODO: language selection should be automatic in Babel but not working.
// it is printing και for and, as in Louw και Nida. So, for now, force it to be English
try {
JsonObject o = this.biblioJsonStrings.get(this.biblioLibraryTopic + "~" + dataValue);
String shortTitle = "";
try {
shortTitle = o.get("shorttitle").getAsString();
} catch (Exception e) {
ErrorUtils.report(logger, e);
}
String citeOverride = o.get("citeoverride").getAsString();
if (shortTitle.trim().length() > 0) {
switch (citeOverride) {
case ("NONE"): {
anchor.text("\\selectlanguage{english}\\cite{" + dataValue + "}");
break;
}
case ("AUTHOR_TITLE"): {
anchor.text("\\selectlanguage{english}\\ltCitePrimary{" + dataValue + "}");
break;
}
case ("SHORT_TITLE"): {
anchor.text("\\selectlanguage{english}\\citetitle{" + dataValue + "}");
break;
}
}
} else {
anchor.text("\\selectlanguage{english}\\cite{" + dataValue + "}");
}
} catch (Exception e) {
ErrorUtils.report(logger, e);
anchor.text("\\selectlanguage{english}\\cite{" + dataValue + "}");
}
} else {
// this is a real macoy anchor and href
anchor.tagName("span");
String href = anchor.attr("href");
String innerText = anchor.text();
anchor.text(innerText + "\\footnote{\\url{" + href + "}})");
}
}
html = doc.html();
html = html.replaceAll("<p>", "");
html = html.replaceAll("</p>", "\n");
html = html.replaceAll("<em>", "\\\\textit{");
html = html.replaceAll("</em>", "}");
html = html.replaceAll("<strong>", "\\\\textbf{");
html = html.replaceAll("</strong>", "}");
html = html.replaceAll("<ins>", "\\\\underline{");
html = html.replaceAll("</ins>", "}");
html = html.replaceAll(" ", " ");
} catch (Exception e) {
ErrorUtils.report(logger, e);
}
return html;
}
private String getNoteAsLatexForNonRef(
TextualNote note
, boolean lexical
) {
StringBuffer sb = new StringBuffer();
sb.append("\\noteLexicalTitleText{");
sb.append(note.liturgicalScope.trim());
sb.append("}{");
sb.append(note.liturgicalLemma);
if (note.getNoteTitle().trim().length() > 0) {
sb.append("}{");
sb.append(note.noteTitle);
}
if (note.value.trim().length() > 0) {
sb.append("}{");
sb.append(note.value);
}
sb.append("}\n\n");
return sb.toString();
}
public String getVersionsAsLatex(
String ages
) {
StringBuffer transSb = new StringBuffer();
StringBuffer result = new StringBuffer();
boolean hasScansion = false;
String greekLibrary = "gr_gr_cog";
String greekLatex = "";
String greekValue = "";
String gevLibrary = "en_uk_gev";
String gevLatex = "";
String gevValue = "";
String gevMotLibrary = "en_uk_gemot";
String gevMotLatex = "";
String gevMotValue = "";
String gevSotLibrary = "en_uk_gesot";
String gevSotLatex = "";
String gevSotValue = "";
String libraryLatex = "";
String tfmLibrary = "en_uk_tfm";
String dedesLibrary = "en_us_dedes";
StringBuffer lf = new StringBuffer();
greekLatex = lf.toString();
transSb.append("\\setlength{\\arrayrulewidth}{0.4pt}");
transSb.append("\\setlength{\\tabcolsep}{18pt}");
transSb.append("\\renewcommand{\\arraystretch}{1.5}");
transSb.append("\\begin{tabular}{ |p{3cm}|p{10cm}| }\n\\hline\n");
for (JsonElement e : this.jsonObject.get("versions").getAsJsonArray()) {
JsonObject o = e.getAsJsonObject();
String library = o.get("library").getAsString();
IdManager idManager = new IdManager(o.get("id").getAsString());
lf = new StringBuffer();
lf.append(idManager.getLibraryLanguage());
lf.append("\\textunderscore ");
lf.append(idManager.getLibraryCountry());
lf.append("\\textunderscore ");
lf.append(idManager.getLibraryRealm());
libraryLatex = lf.toString();
String value = o.get("value").getAsString();
if (value != null && value.trim().length() > 0) {
if (idManager.getLibrary().equals(this.alignmentLibrary)) {
this.alignmentText = value; // we will use this later if we are aligning notes
this.alignmentLibraryLatex = lf.toString();
}
// check for scansion but don't bother if we already found a text with it...
if (!hasScansion) {
if (value.contains("*") || value.contains("/")) {
if (! hasScansion) {
hasScansion = true;
}
}
}
if (library.equals(greekLibrary)) {
greekValue = value;
greekLatex = lf.toString();
} else if (library.equals(gevLibrary)) {
gevValue = value;
gevLatex = lf.toString();
} else if (library.equals(gevMotLibrary)) {
gevMotValue = value;
gevMotLatex = lf.toString();
} else if (library.equals(gevSotLibrary)) {
gevSotValue = value;
gevSotLatex = lf.toString();
} else if (library.equals(tfmLibrary) || library.equals(dedesLibrary)){
transSb.append(libraryLatex);
transSb.append(" & ");
transSb.append(value);
transSb.append(" \\\\ ");
transSb.append("\n\\hline\n");
} else if (! this.author.contains("Colburn")) {
transSb.append(libraryLatex);
transSb.append(" & ");
transSb.append(value);
transSb.append(" \\\\ ");
transSb.append("\n\\hline\n");
}
// add the version (library) to the list of those used
if (library.equals(greekLibrary) || library.equals(gevSotLibrary) || library.equals(gevMotLibrary) || library.equals(gevLibrary) || library.equals(tfmLibrary) || library.equals(dedesLibrary)) {
if (! this.usedAbbreviations.containsKey(libraryLatex)) {
String description = "";
if (this.domainMap.containsKey(idManager.getLibrary())) {
description = this.domainMap.get(idManager.getLibrary());
if (idManager.getId().equals(description)) { // this means the description is missing
description = "";
}
} else {
description = "";
}
if (description.contains("_")) {
description = "(description unavailable)";
}
this.usedAbbreviations.put(libraryLatex, description);
}
}
}
}
transSb.append("\n\\hline\n\\end{tabular}\n\n\n");
if (hasScansion) {
transSb.append("Note: some liturgical hymns originally used punctuation marks to indicate the boundary of metric feet. They do not have a grammatical role. They are called \\textit{scansion} symbols. In the modern version of source text or translations you might see asterisks (*) or forward slashes (/) used as scansion symbols.\n");
}
if (this.includeAdviceNotes && this.author.contains("Colburn")) {
transSb.append("\n\\begin{center}\\n\\includegraphics[width=1.0\\textwidth]{system/images/translationContinuumWhite.jpg}\\n\\end{center}\\n");
}
result.append("\\section{The Text and Translations}");
this.appendText("The Text and Translations");
result.append(ages);
if (greekValue.length() > 0) {
result.append("\\subsection{Source Text}\n");
result.append("If you know Greek, use this as your source text:\n\n");
this.appendText("Source Text");
result.append("\\setlength{\\arrayrulewidth}{0.4pt}");
result.append("\\setlength{\\tabcolsep}{18pt}");
result.append("\\renewcommand{\\arraystretch}{1.5}");
result.append("\\begin{tabular}{ |m{3cm}|p{10cm}| }\n\\hline\n");
result.append(greekLatex);
result.append(" & ");
result.append(greekValue);
this.appendText(greekValue);
result.append(" \\\\ ");
result.append("\n");
result.append("\n\\hline\n\\end{tabular}\n");
result.append("\\vfill\n");
}
if (this.includeAdviceNotes && (gevValue.length() > 0 || gevSotValue.length() > 0 || gevMotValue.length() > 0) ) {
result.append("\\subsection{Global English Translations}\n");
result.append("If you do not know Greek, you can use the en\\textunderscore uk\\textunderscore gev as your source text (model):\n");
result.append("\\setlength{\\arrayrulewidth}{0.4pt}");
result.append("\\setlength{\\tabcolsep}{18pt}");
result.append("\\renewcommand{\\arraystretch}{1.5}");
result.append("\\begin{tabular}{ |p{3cm}|p{10cm}| }\n\\hline\n");
if (gevSotValue.length() > 0) {
result.append("Structure Oriented (");
result.append(gevSotLatex);
result.append(")");
result.append(" & ");
result.append(gevSotValue);
result.append(" \\\\ ");
result.append("\n\\hline\n");
}
if (gevValue.length() > 0) {
result.append("Model (");
result.append(gevLatex);
result.append(")");
result.append(" & ");
result.append(gevValue);
result.append(" \\\\ ");
result.append("\n\\hline\n");
}
if (gevMotValue.length() > 0) {
result.append("Meaning Oriented (");
result.append(gevMotLatex);
result.append(")");
result.append(" & ");
result.append(gevMotValue);
result.append(" \\\\ ");
result.append("\n\\hline\n");
}
result.append("\n\\hline\n\\end{tabular}\n\n");
result.append("\\vfill\n");
result.append("\\subsection{Other Translations}\n");
} else {
result.append("\\subsection{Translations}\n");
}
result.append(transSb.toString());
result.append("\\vfill");
return result.toString();
}
public String getBasePath() {
return basePath;
}
public void setBasePath(String basePath) {
this.basePath = basePath;
}
public String getPathToPdf() {
return pathToPdf;
}
public void setPathToPdf(String pathToPdf) {
this.pathToPdf = pathToPdf;
}
/**
* Get the the Xeatex tex file content that Xelatex can use
* to create the PDF.
* @return
*/
public StringBuffer getTexFileContent() {
return texFileSb;
}
public void setTexFileContent(StringBuffer resFileSb) {
this.texFileSb = resFileSb;
}
public boolean hasBibliography() {
return hasBibliography;
}
public void setHasBibliography(boolean hasBibliography) {
this.hasBibliography = hasBibliography;
}
public StringBuffer getBibtexFileSb() {
return bibtexFileSb;
}
public void setBibtexFileSb(StringBuffer bibtexFileSb) {
this.bibtexFileSb = bibtexFileSb;
}
public StringBuffer getTextFile() {
return textFile;
}
public void setTextFile(StringBuffer textFile) {
this.textFile = textFile;
}
}
| ocmc-olw/ioc-liturgical-ws | src/main/java/net/ages/alwb/utils/transformers/adapters/TextInformationToPdf.java |
43,435 | package gr.aueb.cf.ch4;
import java.io.IOException;
public class IOApp {
public static void main(String[] args) throws IOException {
char ch = ' ';
System.out.println("Please insert a char");
ch = (char) System.in.read(); // Διαβάζει byte επιστρεφει int. Διαβαζει μονο ASCII
System.out.println(ch);
}
}
| MytilinisV/codingfactorytestbed | ch4/IOApp.java |
43,459 | /*
* copyright 2021
* taxofficer.eu
* ProtoERP - Open source invocing program
* [email protected]
*/
package eu.taxofficer.protoerp.company.enums;
import gr.codebb.lib.crud.intf.Displayable;
public enum CompanyMorfi implements Displayable {
PLACEHOLDER_NO_USE(0, "NOUSE"),
AE(1, "A.E."),
MIKE(2, "Μονοπρ. Ι.Κ.Ε");
private int id;
private String name;
private CompanyMorfi(int id, String name) {
this.id = id;
this.name = name;
}
public static CompanyMorfi[] getNames() {
/*
return all the itemstype except for the placeholder one (used for combobox fill)
*/
CompanyMorfi[] names = new CompanyMorfi[CompanyMorfi.values().length - 1];
for (int i = 0; i < names.length; i++) {
names[i] = CompanyMorfi.values()[i + 1];
}
return names;
}
@Override
public String getComboDisplayValue() {
return name;
}
public static CompanyMorfi fromInteger(int x) {
switch (x) {
case 1:
return AE;
case 2:
return MIKE;
}
return null;
}
}
| georgemoralis/protoERP | src/main/java/eu/taxofficer/protoerp/company/enums/CompanyMorfi.java |
43,516 | import Items.EncDecSoftware;
import Items.Handler;
import Items.TrustedAuthority;
import Items.User;
import fame.*;
import javax.swing.JFileChooser;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
FAME cpabe=new FAME();
User us=new User();
Map<String,String> user1=us.attrs;
TrustedAuthority TA=new TrustedAuthority(cpabe);
EncDecSoftware EDS=new EncDecSoftware(cpabe);
Handler hnd=new Handler(cpabe,EDS,TA,us);
System.out.println("~~~~WELCOME TO THE ED SOFTWARE~~~~");
System.out.println("Your Attributes are: ");
user1.put("id","12345");
user1.put("username","John Davies");
user1.put("email","[email protected]");
user1.put("sector","Πνευμονολογικό");
user1.put("hospital","ΓΝ Λαμίας");
for (Map.Entry<String, String> me : user1.entrySet()) {
System.out.print(me.getKey() + ":");
System.out.println(me.getValue());
}
hnd.menu();
}
} | krotskas/Converter-XACML-to-ABE | src/Main.java |
43,544 | package io.zerows.extension.runtime.skeleton.eon;
import io.vertx.core.json.JsonArray;
/**
* Standard Ipc for Zero extension module
* It's for communication
*/
public interface KeIpc {
interface Workflow {
/*
* Event Addr Prefix for workflow
* This value will be shared between zero-ambient / zero-wf
* */
String EVENT = "Ἀτλαντὶς νῆσος://Ροή εργασίας/";
}
/* Module Crud */
interface Module {
// zero-is
String IS = "is";
// zero-battery
String BATTERY = "battery";
// zero-ambient
String AMBIENT = "ambient";
// zero-rbac
String RBAC = "rbac";
// zero-erp
String ERP = "erp";
// zero-psi
String PSI = "psi";
// zero-fm
String FM = "fm";
// zero-ui
String UI = "ui";
// zero-jet
String JET = "jet";
// zero-graphic
String G = "graphic";
// zero-argument
String ATOM = "atom";
// zero-lbs
String LBS = "lbs";
// zero-wf
String WF = "wf";
// zero-tpl
String TPL = "tpl";
// zero-crud
String CRUD = "crud";
// zero-doc
String DOC = "doc";
}
/*
* Rbac Ipc
*/
interface Sc {
/* Ipc for verify token */
String IPC_TOKEN_VERIFY = "IPC://TOKEN/VERIFY";
/* Ipc for access token */
String IPC_TOKEN_ACCESS = "IPC://TOKEN/ACCESS";
}
interface Audit {
JsonArray INCLUDE = new JsonArray()
.add("/api/user") // zero-rbac 用户创建
.add("/api/permission") // zero-rbac 权限创建
.add("/api/authority/region/:path") // zero-rbac 权限管理专用
.add("/api/employee") // zero-erp 员工创建
.add("/api/wh") // zero-psi 仓库创建
.add("/api/i-directory") // zero-is 目录创建
.add("/api/file/upload") // zero-ambient 文件上传
.add("/api/my/menu/save") // zero-ambient 个人菜单保存
.add("/api/up/flow") // zero-wf 流程处理专用
.add("/api/linkage/sync") // zero-wf, zero-ambient 关联创建
.add("/api/bill/") // zero-fm 账单通用接口
.add("/api/bill-item/") // zero-fm 账单项通用接口
.add("/api/trans/") // zero-fm 交易创建通用接口
.add("/api/trans-proc/") // zero-fm 交易处理通用接口
.add("/api/settle/") // zero-fm 结算通用接口
;
JsonArray EXCLUDE = new JsonArray()
.add("/api/:actor/search") // zero-crud 默认统一搜索接口
.add("/api/:actor/missing") // zero-crud 默认统一缺失检查接口
.add("/api/:actor/existing") // zero-crud 默认统一存在检查接口
.add("/api/:actor/export") // zero-crud 默认统一导出接口
.add("/api/:actor/import") // zero-crud 默认统一导入接口
.add("/api/up/flow-queue") // zero-wf 流程处理队列
.add("/api/up/flow-history") // zero-wf 流程历史队列
.add("/api/user/search/:identifier") // zero-rbac 按统一标识符查询用户信息(某一类用户查询)
;
}
}
| zero-ws/zero-extension | Zero.Extension.Runtime.Skeleton/src/main/java/io/zerows/extension/runtime/skeleton/eon/KeIpc.java |
43,550 | package io.vertx.tp.workflow.init;
import cn.vertxup.workflow.domain.tables.pojos.WFlow;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.tp.ke.refine.Ke;
import io.vertx.tp.workflow.refine.Wf;
import io.vertx.tp.workflow.uca.deployment.DeployOn;
import io.vertx.up.fn.Fn;
import org.camunda.bpm.engine.*;
import org.camunda.bpm.engine.impl.history.handler.HistoryEventHandler;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* @author <a href="http://www.origin-x.cn">Lang</a>
*/
public class WfPin {
public static Future<Boolean> init(final Vertx vertx) {
Ke.banner("「Ροή εργασίας」- ( Workflow )");
Wf.Log.infoInit(WfPin.class, "WfConfiguration...");
WfConfiguration.init();
Wf.Log.infoInit(WfPin.class, "WfTodo...");
WfTodo.init();
Wf.Log.infoInit(WfPin.class, "Workflow Engine Start...");
final List<String> resources = WfConfiguration.camundaResources();
Wf.Log.infoInit(WfPin.class, "Here are {0} folder that will be waited for deployment...",
String.valueOf(resources.size()));
final List<Future<Boolean>> futures = new ArrayList<>();
// Deployment for .bpmn files
resources.forEach(resource -> DeployOn.get(resource).initialize());
return Fn.combineT(futures)
// Flow initialized
.compose(nil -> WfConfiguration.init(vertx));
}
public static RepositoryService camundaRepository() {
return WfConfiguration.camunda().getRepositoryService();
}
public static FormService camundaForm() {
return WfConfiguration.camunda().getFormService();
}
public static RuntimeService camundaRuntime() {
return WfConfiguration.camunda().getRuntimeService();
}
public static TaskService camundaTask() {
return WfConfiguration.camunda().getTaskService();
}
public static HistoryService camundaHistory() {
return WfConfiguration.camunda().getHistoryService();
}
public static HistoryEventHandler camundaLogger() {
return WfConfiguration.camundaLogger();
}
/**
* Return to configuration data that convert to {@link io.vertx.core.json.JsonObject} here by type.
*
* @param type {@link java.lang.String} The type value passed.
*
* @return {@link io.vertx.core.json.JsonObject}
*/
public static JsonObject getTodo(final String type) {
return WfTodo.getTodo(type);
}
public static WFlow getFlow(final String code) {
return WfConfiguration.workflow(code);
}
public static Set<String> getBuiltIn() {
return WfConfiguration.camundaBuiltIn();
}
}
| himozhang/vertx-zero | vertx-pin/zero-wf/src/main/java/io/vertx/tp/workflow/init/WfPin.java |
43,554 | package io.zerows.extension.runtime.workflow.bootstrap;
import io.horizon.uca.boot.KPivot;
import io.macrocosm.specification.app.HAmbient;
import io.macrocosm.specification.app.HRegistry;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.up.eon.configure.YmlCore;
import io.vertx.up.fn.Fn;
import io.zerows.core.metadata.store.OZeroStore;
import io.zerows.extension.runtime.skeleton.refine.Ke;
import io.zerows.extension.runtime.workflow.domain.tables.pojos.WFlow;
import io.zerows.extension.runtime.workflow.uca.deployment.DeployOn;
import org.camunda.bpm.engine.*;
import org.camunda.bpm.engine.impl.history.handler.HistoryEventHandler;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import static io.zerows.extension.runtime.workflow.util.Wf.LOG;
/**
* @author <a href="http://www.origin-x.cn">Lang</a>
*/
public class WfPin implements HRegistry.Mod<Vertx> {
public static RepositoryService camundaRepository() {
return WfConfiguration.camunda().getRepositoryService();
}
public static FormService camundaForm() {
return WfConfiguration.camunda().getFormService();
}
public static RuntimeService camundaRuntime() {
return WfConfiguration.camunda().getRuntimeService();
}
public static TaskService camundaTask() {
return WfConfiguration.camunda().getTaskService();
}
public static HistoryService camundaHistory() {
return WfConfiguration.camunda().getHistoryService();
}
public static HistoryEventHandler camundaLogger() {
return WfConfiguration.camundaLogger();
}
public static JsonObject getTodo(final String type) {
return WfTodo.getTodo(type);
}
public static WFlow getFlow(final String code) {
return WfConfiguration.workflow(code);
}
public static Set<String> getBuiltIn() {
return WfConfiguration.camundaBuiltIn();
}
/**
* 新版模块注册器,工作流模块的注册机制和其他模块不同,由于此处存在大量的新库访问以及 Camunda 流程引擎
* 的调用,因此此处的注册器需要异步执行,而且需要等待 Camunda 引擎初始化完成之后才能执行。
*/
@Override
public Future<Boolean> configureAsync(final Vertx container, final HAmbient ambient) {
// 1. 检查是否启用
if (!OZeroStore.is(YmlCore.workflow.__KEY)) {
return Future.succeededFuture(Boolean.TRUE);
}
// 2. 遗留系统待办模块初始化
{
LOG.Init.info(WfPin.class, "WfTodo...");
WfTodo.initLegacy();
}
// 3. 正式初始化工作流
Ke.banner("「Ροή εργασίας」- ( Workflow )");
LOG.Init.info(WfPin.class, "WfConfiguration...");
return WfConfiguration.registry(KPivot.running(), container).compose(configured -> {
LOG.Init.info(WfPin.class, "Workflow Engine Start...");
final List<String> resources = WfConfiguration.camundaResources();
LOG.Init.info(WfPin.class, "Here are {0} folder that will be waited for deployment...",
String.valueOf(resources.size()));
final List<Future<Boolean>> futures = new ArrayList<>();
// Deployment for .bpmn files
resources.forEach(resource -> DeployOn.get(resource).initialize());
return Fn.combineT(futures).compose(nil -> Future.succeededFuture(Boolean.TRUE));
});
}
}
| zero-ws/zero-extension | Zero.Extension.Runtime.Workflow.DB/src/main/java/io/zerows/extension/runtime/workflow/bootstrap/WfPin.java |
43,565 | package io.vertx.tp.ke.cv;
import io.vertx.core.json.JsonArray;
/**
* Standard Ipc for Zero extension module
* It's for communication
*/
public interface KeIpc {
interface Workflow {
/*
* Event Addr Prefix for workflow
* This value will be shared between zero-ambient / zero-wf
* */
String EVENT = "Ἀτλαντὶς νῆσος://Ροή εργασίας/";
}
/* Module Crud */
interface Module {
// zero-is
String IS = "is";
// zero-battery
String BATTERY = "battery";
// zero-ambient
String AMBIENT = "ambient";
// zero-rbac
String RBAC = "rbac";
// zero-erp
String ERP = "erp";
// zero-psi
String PSI = "psi";
// zero-fm
String FM = "fm";
// zero-ui
String UI = "ui";
// zero-jet
String JET = "jet";
// zero-graphic
String G = "graphic";
// zero-atom
String ATOM = "atom";
// zero-lbs
String LBS = "lbs";
// zero-wf
String WF = "wf";
// zero-tpl
String TPL = "tpl";
}
/*
* Rbac Ipc
*/
interface Sc {
/* Ipc for verify token */
String IPC_TOKEN_VERIFY = "IPC://TOKEN/VERIFY";
/* Ipc for access token */
String IPC_TOKEN_ACCESS = "IPC://TOKEN/ACCESS";
}
interface Audit {
JsonArray INCLUDE = new JsonArray()
.add("/api/user") // zero-rbac
.add("/api/permission") // zero-rbac
.add("/api/authority/region/:path") // zero-rbac
.add("/api/employee") // zero-erp
.add("/api/wh") // zero-psi
.add("/api/i-directory") // zero-is
.add("/api/file/upload") // zero-ambient
.add("/api/my/menu/save") // zero-ambient
.add("/api/up/flow") // zero-wf
.add("/api/linkage/sync") // zero-wf, zero-ambient
.add("/api/bill/") // zero-fm
.add("/api/bill-item/") // zero-fm
.add("/api/settle/") // zero-fm
.add("/api/payment"); // zero-fm
JsonArray EXCLUDE = new JsonArray()
.add("/api/:actor/search") // zero-crud
.add("/api/:actor/missing") // zero-crud
.add("/api/:actor/existing") // zero-crud
.add("/api/:actor/export") // zero-crud
.add("/api/:actor/import") // zero-crud
.add("/api/up/flow-queue") // zero-wf
.add("/api/up/flow-history") // zero-wf
.add("/api/user/search/:identifier") // zero-rbac
;
}
}
| himozhang/vertx-zero | vertx-pin/zero-ke/src/main/java/io/vertx/tp/ke/cv/KeIpc.java |
43,566 | package io.zerows.extension.runtime.workflow.util;
import io.zerows.extension.runtime.workflow.eon.em.PassWay;
import io.horizon.uca.log.Log;
import io.horizon.uca.log.LogModule;
import io.vertx.core.json.JsonObject;
import org.camunda.bpm.engine.repository.ProcessDefinition;
import org.camunda.bpm.engine.task.Task;
import java.util.List;
/**
* @author <a href="http://www.origin-x.cn">Lang</a>
*/
public class Wf {
/*
* Workflow Output
* {
* "definitionId": "Process Definition Id",
* "definitionKey": "Process Definition Key",
* "bpmn": "Xml format of BPMN 2.0 diagram",
* "name": "Process Definition Name"
* }
*/
public static JsonObject outBpmn(final ProcessDefinition definition) {
return WfFlow.outBpmn(definition);
}
public static JsonObject outLinkage(final JsonObject linkageJ) {
return WfFlow.outLinkage(linkageJ);
}
public static PassWay inGateway(final JsonObject requestJ) {
return WfFlow.inGateway(requestJ);
}
public static String nameEvent(final Task task) {
return WfFlow.nameEvent(task);
}
public static List<Task> taskNext(final Task task, final List<Task> source) {
return WfFlow.taskNext(task, source);
}
public interface LOG {
String MODULE = "Ροή εργασίας";
LogModule Init = Log.modulat(MODULE).extension("Init");
LogModule Queue = Log.modulat(MODULE).extension("Queue");
LogModule Deploy = Log.modulat(MODULE).extension("Deploy");
LogModule Move = Log.modulat(MODULE).extension("Move");
LogModule Plugin = Log.modulat(MODULE).extension("Infusion");
LogModule Web = Log.modulat(MODULE).extension("Web");
}
}
| zero-ws/zero-extension | Zero.Extension.Runtime.Workflow.DB/src/main/java/io/zerows/extension/runtime/workflow/util/Wf.java |
43,568 | package io.vertx.mod.workflow.init;
import cn.vertxup.workflow.domain.tables.pojos.WFlow;
import io.horizon.uca.boot.KPivot;
import io.macrocosm.specification.app.HRegistry;
import io.macrocosm.specification.program.HArk;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.mod.ke.refine.Ke;
import io.vertx.mod.workflow.uca.deployment.DeployOn;
import io.vertx.up.eon.configure.YmlCore;
import io.vertx.up.fn.Fn;
import io.vertx.up.runtime.ZeroStore;
import org.camunda.bpm.engine.*;
import org.camunda.bpm.engine.impl.history.handler.HistoryEventHandler;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import static io.vertx.mod.workflow.refine.Wf.LOG;
/**
* @author <a href="http://www.origin-x.cn">Lang</a>
*/
public class WfPin implements HRegistry.Mod<Vertx> {
public static RepositoryService camundaRepository() {
return WfConfiguration.camunda().getRepositoryService();
}
public static FormService camundaForm() {
return WfConfiguration.camunda().getFormService();
}
public static RuntimeService camundaRuntime() {
return WfConfiguration.camunda().getRuntimeService();
}
public static TaskService camundaTask() {
return WfConfiguration.camunda().getTaskService();
}
public static HistoryService camundaHistory() {
return WfConfiguration.camunda().getHistoryService();
}
public static HistoryEventHandler camundaLogger() {
return WfConfiguration.camundaLogger();
}
public static JsonObject getTodo(final String type) {
return WfTodo.getTodo(type);
}
public static WFlow getFlow(final String code) {
return WfConfiguration.workflow(code);
}
public static Set<String> getBuiltIn() {
return WfConfiguration.camundaBuiltIn();
}
/**
* 新版模块注册器,工作流模块的注册机制和其他模块不同,由于此处存在大量的新库访问以及 Camunda 流程引擎
* 的调用,因此此处的注册器需要异步执行,而且需要等待 Camunda 引擎初始化完成之后才能执行。
*/
@Override
public Future<Boolean> registryAsync(final Vertx container, final HArk ark) {
// 1. 检查是否启用
if (!ZeroStore.is(YmlCore.workflow.__KEY)) {
return Future.succeededFuture(Boolean.TRUE);
}
// 2. 遗留系统待办模块初始化
{
LOG.Init.info(WfPin.class, "WfTodo...");
WfTodo.initLegacy();
}
// 3. 正式初始化工作流
Ke.banner("「Ροή εργασίας」- ( Workflow )");
LOG.Init.info(WfPin.class, "WfConfiguration...");
return WfConfiguration.registry(KPivot.running(), container).compose(configured -> {
LOG.Init.info(WfPin.class, "Workflow Engine Start...");
final List<String> resources = WfConfiguration.camundaResources();
LOG.Init.info(WfPin.class, "Here are {0} folder that will be waited for deployment...",
String.valueOf(resources.size()));
final List<Future<Boolean>> futures = new ArrayList<>();
// Deployment for .bpmn files
resources.forEach(resource -> DeployOn.get(resource).initialize());
return Fn.combineT(futures).compose(nil -> Future.succeededFuture(Boolean.TRUE));
});
}
}
| silentbalanceyh/vertx-zero | vertx-pin/zero-wf/src/main/modulat/io/vertx/mod/workflow/init/WfPin.java |
43,601 | package com.example.touristguide;
import android.os.Bundle;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import androidx.appcompat.app.AppCompatActivity;
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.mapView);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// ορισμός τοποθεσίας και λοιπές ρυθμίσεις χάρτη
}
} | texnologia-logismikou2023/TouristGuide | TouristGuide/app/src/main/java/com/example/touristguide/MapActivity.java |
43,648 | package com.ots.trainingapi.trn.services.impl;
import com.ots.trainingapi.global.utils.MessageSourceProvider;
import com.ots.trainingapi.trn.core.domain.QCampaignType;
import com.ots.trainingapi.trn.dto.mini.CampaignTypeMiniDto;
import com.ots.trainingapi.trn.repositories.CampaignTypeRepository;
import com.ots.trainingapi.trn.services.CampaignTypeService;
import com.querydsl.core.types.FactoryExpression;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class CampaignTypeServiceImpl implements CampaignTypeService {
private static final Logger logger = LogManager.getLogger(CampaignTypeServiceImpl.class);
@Autowired
private JPAQueryFactory queryFactory;
@Autowired
private MessageSourceProvider messageSourceProvider;
@Autowired
private CampaignTypeRepository campaignTypeRepository;
/**
* Ορισμός των πεδίων που έρχονται στο mini dto
*/
private FactoryExpression<CampaignTypeMiniDto> campaignTypeMiniDtoExpression(QCampaignType qCampaignType) {
return Projections.bean(CampaignTypeMiniDto.class,
qCampaignType.id,
qCampaignType.description
);
}
@Override
public List<CampaignTypeMiniDto> getAllCampaignTypes() {
QCampaignType qCampaignType = QCampaignType.campaignType;
FactoryExpression<CampaignTypeMiniDto> factoryExpression = campaignTypeMiniDtoExpression(qCampaignType);
return queryFactory
.select(factoryExpression)
.from(qCampaignType)
.fetch();
}
}
| gkalathas/Angular-Spring-boot | trainingapi/src/main/java/com/ots/trainingapi/trn/services/impl/CampaignTypeServiceImpl.java |
43,666 | package com.emmanouilpapadimitrou.healthapp.Fragments;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.emmanouilpapadimitrou.healthapp.Activities.PatientsActivity;
import com.emmanouilpapadimitrou.healthapp.POJOs.Message;
import com.emmanouilpapadimitrou.healthapp.POJOs.Patient;
import com.emmanouilpapadimitrou.healthapp.POJOs.Users;
import com.emmanouilpapadimitrou.healthapp.R;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class ChatFragment extends Fragment implements View.OnClickListener {
private FirebaseUser fUser;
private FirebaseAuth firebaseAuth;
private FirebaseDatabase database;
private DatabaseReference referenceDB;
private DatabaseReference usersDB;
private Patient patient;
private EditText editMessage;
private FloatingActionButton sendMessageBtn;
private RecyclerView messageList;
private Timer timer;
private String nameToWrite;
private String getType;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_chat, container, false);
//Μεταβλητή που μας δίνει τα στοιχεία του συνδεδεμένου χρήστη
firebaseAuth = FirebaseAuth.getInstance();
//Παίρνουμε τον επιλεγμένο χρήστη με όλα του τα στοιχεία
patient = ((PatientsActivity)getActivity()).getCurrentPatient();
//Ορισμός της βάσης στην μεταβλητή για οποιαδήποτε μελλοντική χρήστη
database = FirebaseDatabase.getInstance();
referenceDB = FirebaseDatabase.getInstance().getReference().child("messages").child(patient.getId());
editMessage = (EditText) view.findViewById(R.id.editMessage);
sendMessageBtn = (FloatingActionButton) view.findViewById(R.id.sendMessageBtn);
sendMessageBtn.setOnClickListener(this);
final FirebaseRecyclerAdapter <Message,MessageViewHolder> FBRA = new FirebaseRecyclerAdapter<Message, MessageViewHolder>(
Message.class,
R.layout.single_message,
MessageViewHolder.class,
referenceDB
) {
@Override
protected void populateViewHolder(MessageViewHolder viewHolder, Message model, int position) {
viewHolder.setContent(model.getContent());
viewHolder.setName(model.getName());
viewHolder.setTime(model.getTime());
}
};
messageList = (RecyclerView) view.findViewById(R.id.messageRec);
messageList.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setStackFromEnd(true);
messageList.setLayoutManager(linearLayoutManager);
messageList.setAdapter(FBRA);
messageList.scrollToPosition(messageList.getAdapter().getItemCount() - 1);
return view;
}
@Override
public void onClick(View v) {
if(v == sendMessageBtn){
fUser = firebaseAuth.getCurrentUser();
usersDB = FirebaseDatabase.getInstance().getReference().child("users").child(fUser.getUid());
final String messageValue = editMessage.getText().toString().trim();
if(!TextUtils.isEmpty(messageValue)){
final DatabaseReference newPost = referenceDB.push();
usersDB.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
newPost.child("content").setValue(messageValue);
getType = dataSnapshot.child("type").getValue().toString();
if(getType.equals("doctor")){
nameToWrite = "Δρ. " + dataSnapshot.child("name").getValue() + " " + dataSnapshot.child("surname").getValue();
}
else{
nameToWrite = dataSnapshot.child("name").getValue() + " " + dataSnapshot.child("surname").getValue();
}
newPost.child("name").setValue(nameToWrite).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
}
});
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
String time = simpleDateFormat.format(calendar.getTime());
newPost.child("time").setValue(time).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
}
});
editMessage.setText("");
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
}
public static class MessageViewHolder extends RecyclerView.ViewHolder{
View mView;
public MessageViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setContent(String content){
TextView messageText = (TextView) mView.findViewById(R.id.messageText);
messageText.setText(content);
}
public void setName(String name){
TextView usernameText = (TextView) mView.findViewById(R.id.usernameText);
usernameText.setText(name);
}
public void setTime(String time){
TextView messageTime = (TextView) mView.findViewById(R.id.messageTime);
messageTime.setText(time);
}
}
}
| ManolisPapd/HealthApp | Android/HealthApp/app/src/main/java/com/emmanouilpapadimitrou/healthapp/Fragments/ChatFragment.java |
43,677 | // License: GPL. For details, see LICENSE file.
package org.openstreetmap.josm.data.validation.tests;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.openstreetmap.josm.TestUtils;
import org.openstreetmap.josm.data.osm.OsmPrimitive;
import org.openstreetmap.josm.data.osm.OsmUtils;
import org.openstreetmap.josm.data.osm.Tag;
import org.openstreetmap.josm.data.validation.Severity;
import org.openstreetmap.josm.data.validation.TestError;
import org.openstreetmap.josm.testutils.annotations.I18n;
import org.openstreetmap.josm.testutils.annotations.TaggingPresets;
/**
* JUnit Test of {@link TagChecker}.
*/
@I18n
@TaggingPresets
class TagCheckerTest {
List<TestError> test(OsmPrimitive primitive) throws IOException {
final TagChecker checker = new TagChecker() {
@Override
protected boolean includeOtherSeverityChecks() {
return true;
}
};
checker.initialize();
checker.startTest(null);
checker.check(TestUtils.addFakeDataSet(primitive));
return checker.getErrors();
}
/**
* Check for misspelled key.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledKey1() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node Name=Main"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'Name' looks like 'name'.", errors.get(0).getDescription());
assertTrue(errors.get(0).isFixable());
}
/**
* Check for misspelled key.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledKey2() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node landuse;=forest"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'landuse;' looks like 'landuse'.", errors.get(0).getDescription());
assertTrue(errors.get(0).isFixable());
}
/**
* Check for misspelled key where the suggested alternative is in use. The error should not be fixable.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledKeyButAlternativeInUse() throws IOException {
// ticket 12329
final List<TestError> errors = test(OsmUtils.createPrimitive("node amenity=fuel brand=bah Brand=foo"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'Brand' looks like 'brand'.", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled key where the suggested alternative is given with prefix E: in ignoreTags.cfg.
* The error should be fixable.
* @throws IOException if any I/O error occurs
*/
@Test
void testUpperCaseIgnoredKey() throws IOException {
// ticket 17468
final List<TestError> errors = test(OsmUtils.createPrimitive("node wheelchair:Description=bla"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'wheelchair:Description' looks like 'wheelchair:description'.", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertTrue(errors.get(0).isFixable());
}
/**
* Check for misspelled key where the suggested alternative is given with prefix K: in ignoreTags.cfg.
* The error should be fixable.
* @throws IOException if any I/O error occurs
*/
@Test
void testUpperCaseInKeyIgnoredTag() throws IOException {
// ticket 17468
final List<TestError> errors = test(OsmUtils.createPrimitive("node land_Area=administrative"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'land_Area' looks like 'land_area'.", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertTrue(errors.get(0).isFixable());
}
/**
* Check for unknown key.
* @throws IOException if any I/O error occurs
*/
@Test
void testTranslatedNameKey() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node namez=Baz"));
assertEquals(1, errors.size());
assertEquals("Presets do not contain property key", errors.get(0).getMessage());
assertEquals("Key 'namez' not in presets.", errors.get(0).getDescription());
assertEquals(Severity.OTHER, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled value.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledTag() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node landuse=forrest"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals("Value 'forrest' for key 'landuse' is unknown, maybe 'forest' is meant?", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled value with multiple alternatives in presets.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledTag2() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node highway=servics"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals(
"Value 'servics' for key 'highway' is unknown, maybe one of [service, services] is meant?",
errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled value.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledTag3() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node highway=residentail"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals("Value 'residentail' for key 'highway' is unknown, maybe 'residential' is meant?",
errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled value.
* @throws IOException if any I/O error occurs
*/
@Test
void testShortValNotInPreset2() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node shop=abs"));
assertEquals(1, errors.size());
assertEquals("Presets do not contain property value", errors.get(0).getMessage());
assertEquals("Value 'abs' for key 'shop' not in presets.", errors.get(0).getDescription());
assertEquals(Severity.OTHER, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Checks that tags specifically ignored are effectively not in internal presets.
* @throws IOException if any I/O error occurs
*/
@Test
void testIgnoredTagsNotInPresets() throws IOException {
new TagChecker().initialize();
List<String> errors = TagChecker.getIgnoredTags().stream()
.filter(tag -> TagChecker.isTagInPresets(tag.getKey(), tag.getValue()))
.map(Tag::toString)
.collect(Collectors.toList());
assertTrue(errors.isEmpty(), errors::toString);
}
/**
* Check regression: Don't fix surface=u -> surface=mud.
* @throws IOException if any I/O error occurs
*/
@Test
void testTooShortToFix() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node surface=u"));
assertEquals(1, errors.size());
assertEquals("Presets do not contain property value", errors.get(0).getMessage());
assertEquals("Value 'u' for key 'surface' not in presets.", errors.get(0).getDescription());
assertEquals(Severity.OTHER, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check value with upper case
* @throws IOException if any I/O error occurs
*/
@Test
void testValueDifferentCase() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node highway=Residential"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals("Value 'Residential' for key 'highway' is unknown, maybe 'residential' is meant?",
errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
@Test
void testRegionKey() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node highway=crossing crossing_ref=zebra"));
assertEquals(1, errors.size());
assertEquals("Key from a preset is invalid in this region", errors.get(0).getMessage());
assertEquals("Preset Pedestrian Crossing should not have the key crossing_ref", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
@Test
void testRegionTag() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("relation type=waterway gnis:feature_id=123456"));
assertEquals(1, errors.size());
assertEquals("Key from a preset is invalid in this region", errors.get(0).getMessage());
assertEquals("Preset Waterway should not have the key gnis:feature_id", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Key in presets but not in ignored.cfg. Caused a NPE with r14727.
* @throws IOException if any I/O error occurs
*/
@Test
void testRegression17246() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node access=privat"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals("Value 'privat' for key 'access' is unknown, maybe 'private' is meant?",
errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Checks for unwanted non printing control characters
* @param s String to test
* @param assertionC assertion on the result (true/false)
* @param expected expected fixed value
*/
private static void doTestUnwantedNonprintingControlCharacters(String s, Consumer<Boolean> assertionC, String expected) {
assertionC.accept(TagChecker.containsUnwantedNonPrintingControlCharacter(s));
assertEquals(expected, TagChecker.removeUnwantedNonPrintingControlCharacters(s));
}
private static void doTestUnwantedNonprintingControlCharacters(String s) {
doTestUnwantedNonprintingControlCharacters(s, Assertions::assertTrue, "");
}
/**
* Unit test of {@link TagChecker#containsUnwantedNonPrintingControlCharacter}
* / {@link TagChecker#removeUnwantedNonPrintingControlCharacters}
*/
@Test
void testContainsRemoveUnwantedNonprintingControlCharacters() {
// Check empty string is handled
doTestUnwantedNonprintingControlCharacters("", Assertions::assertFalse, "");
// Check 65 ASCII control characters are removed, except new lines
for (char c = 0x0; c < 0x20; c++) {
if (c != '\r' && c != '\n') {
doTestUnwantedNonprintingControlCharacters(Character.toString(c));
} else {
doTestUnwantedNonprintingControlCharacters(Character.toString(c), Assertions::assertFalse, Character.toString(c));
}
}
doTestUnwantedNonprintingControlCharacters(Character.toString((char) 0x7F));
// Check 7 Unicode bidi control characters are removed
for (char c = 0x200e; c <= 0x200f; c++) {
doTestUnwantedNonprintingControlCharacters(Character.toString(c));
}
for (char c = 0x202a; c <= 0x202e; c++) {
doTestUnwantedNonprintingControlCharacters(Character.toString(c));
}
// Check joining characters are removed if located at the beginning or end of the string
for (char c = 0x200c; c <= 0x200d; c++) {
final String s = Character.toString(c);
doTestUnwantedNonprintingControlCharacters(s);
doTestUnwantedNonprintingControlCharacters(s + s);
doTestUnwantedNonprintingControlCharacters(s + 'a' + s, Assertions::assertTrue, "a");
final String ok = 'a' + s + 'b';
doTestUnwantedNonprintingControlCharacters(ok, Assertions::assertFalse, ok);
doTestUnwantedNonprintingControlCharacters(s + ok, Assertions::assertTrue, ok);
doTestUnwantedNonprintingControlCharacters(ok + s, Assertions::assertTrue, ok);
doTestUnwantedNonprintingControlCharacters(s + ok + s, Assertions::assertTrue, ok);
}
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/17667">Bug #17667</a>.
*/
@Test
void testTicket17667() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Bus 118: Berlin, Rathaus Zehlendorf => Potsdam, Drewitz Stern-Center"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Καρδίτσα → Λάρισα"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("traffic_sign", "FI:871[← Lippuautomaatti]"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("traffic_sign", "FI:871[↑ Nostopaikka ↑]"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Cinderella II - Strandvägen ↔ Hagede"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Tallinn — Narva"));
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/18322">Bug #18322</a>.
*/
@Test
void testTicket18322() {
assertTrue(TagChecker.containsUnusualUnicodeCharacter("name", "D36ᴬ"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("ref", "D36ᴬ"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("old_ref", "D36ᴬ"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("old_ref", "D36ᵂ"));
assertTrue(TagChecker.containsUnusualUnicodeCharacter("old_ref", "D36ᴫ"));
assertTrue(TagChecker.containsUnusualUnicodeCharacter("old_ref", "D36ᵃ"));
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/18449">Bug #18449</a>.
*/
@Test
void testTicket18449() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Hökumət Evi"));
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/18740">Bug #18740</a>.
*/
@Test
void testTicket18740() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:ak", "Frɛnkyeman"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:bm", "Esipaɲi"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:oym", "Wɨlapaleya Ɨtu"));
}
/**
* Detects objects with types not supported by their presets.
* @throws IOException in case of I/O error
*/
@Test
void testObjectTypeNotSupportedByPreset() throws IOException {
List<TestError> errors = test(OsmUtils.createPrimitive("relation waterway=river"));
assertEquals(1, errors.size());
assertEquals(TagChecker.INVALID_PRESETS_TYPE, errors.get(0).getCode());
errors = test(OsmUtils.createPrimitive("relation type=waterway waterway=river"));
assertTrue(errors.isEmpty(), errors::toString);
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/19519">Bug #19519</a>.
* @throws IOException ignored
*/
@Test
@Disabled("broken, see #19519")
void testTicket19519() throws IOException {
List<TestError> errors = test(OsmUtils.createPrimitive("node amenity=restaurant cuisine=bavarian;beef_bowl"));
assertEquals(0, errors.size());
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/20437">Bug #20437</a>.
*/
@Test
void testTicket20437() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:kbp", "Wasɩŋtɔŋ"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:kbp", "Kalɩfɔrnii"));
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/20754">Bug #20754</a>.
*/
@Test
void testTicket20754() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Yuułuʔiłʔatḥ Lands"));
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/21348">Bug #21348</a>.
* Key ref is in presets but without any value.
* @throws IOException if any I/O error occurs
*/
@Test
void testTicket21348() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node power=tower ref=12"));
assertEquals(0, errors.size());
}
}
| JOSM/josm | test/unit/org/openstreetmap/josm/data/validation/tests/TagCheckerTest.java |
43,678 | // License: GPL. For details, see LICENSE file.
package org.openstreetmap.josm.data.validation.tests;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.junit.Assert;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.openstreetmap.josm.TestUtils;
import org.openstreetmap.josm.data.osm.OsmPrimitive;
import org.openstreetmap.josm.data.osm.OsmUtils;
import org.openstreetmap.josm.data.osm.Tag;
import org.openstreetmap.josm.data.validation.Severity;
import org.openstreetmap.josm.data.validation.TestError;
import org.openstreetmap.josm.testutils.JOSMTestRules;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
/**
* JUnit Test of {@link TagChecker}.
*/
class TagCheckerTest {
/**
* Setup test.
*/
@RegisterExtension
@SuppressFBWarnings(value = "URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD")
public JOSMTestRules rule = new JOSMTestRules().presets();
List<TestError> test(OsmPrimitive primitive) throws IOException {
final TagChecker checker = new TagChecker() {
@Override
protected boolean includeOtherSeverityChecks() {
return true;
}
};
checker.initialize();
checker.startTest(null);
checker.check(TestUtils.addFakeDataSet(primitive));
return checker.getErrors();
}
/**
* Check for misspelled key.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledKey1() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node Name=Main"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'Name' looks like 'name'.", errors.get(0).getDescription());
assertTrue(errors.get(0).isFixable());
}
/**
* Check for misspelled key.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledKey2() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node landuse;=forest"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'landuse;' looks like 'landuse'.", errors.get(0).getDescription());
assertTrue(errors.get(0).isFixable());
}
/**
* Check for misspelled key where the suggested alternative is in use. The error should not be fixable.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledKeyButAlternativeInUse() throws IOException {
// ticket 12329
final List<TestError> errors = test(OsmUtils.createPrimitive("node amenity=fuel brand=bah Brand=foo"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'Brand' looks like 'brand'.", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled key where the suggested alternative is given with prefix E: in ignoreTags.cfg.
* The error should be fixable.
* @throws IOException if any I/O error occurs
*/
@Test
void testUpperCaseIgnoredKey() throws IOException {
// ticket 17468
final List<TestError> errors = test(OsmUtils.createPrimitive("node wheelchair:Description=bla"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'wheelchair:Description' looks like 'wheelchair:description'.", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertTrue(errors.get(0).isFixable());
}
/**
* Check for misspelled key where the suggested alternative is given with prefix K: in ignoreTags.cfg.
* The error should be fixable.
* @throws IOException if any I/O error occurs
*/
@Test
void testUpperCaseInKeyIgnoredTag() throws IOException {
// ticket 17468
final List<TestError> errors = test(OsmUtils.createPrimitive("node land_Area=administrative"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'land_Area' looks like 'land_area'.", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertTrue(errors.get(0).isFixable());
}
/**
* Check for unknown key.
* @throws IOException if any I/O error occurs
*/
@Test
void testTranslatedNameKey() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node namez=Baz"));
assertEquals(1, errors.size());
assertEquals("Presets do not contain property key", errors.get(0).getMessage());
assertEquals("Key 'namez' not in presets.", errors.get(0).getDescription());
assertEquals(Severity.OTHER, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled value.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledTag() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node landuse=forrest"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals("Value 'forrest' for key 'landuse' is unknown, maybe 'forest' is meant?", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled value with multiple alternatives in presets.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledTag2() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node highway=servics"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals(
"Value 'servics' for key 'highway' is unknown, maybe one of [service, services] is meant?",
errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled value.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledTag3() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node highway=residentail"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals("Value 'residentail' for key 'highway' is unknown, maybe 'residential' is meant?",
errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled value.
* @throws IOException if any I/O error occurs
*/
@Test
void testShortValNotInPreset2() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node shop=abs"));
assertEquals(1, errors.size());
assertEquals("Presets do not contain property value", errors.get(0).getMessage());
assertEquals("Value 'abs' for key 'shop' not in presets.", errors.get(0).getDescription());
assertEquals(Severity.OTHER, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Checks that tags specifically ignored are effectively not in internal presets.
* @throws IOException if any I/O error occurs
*/
@Test
void testIgnoredTagsNotInPresets() throws IOException {
new TagChecker().initialize();
List<String> errors = TagChecker.getIgnoredTags().stream()
.filter(tag -> TagChecker.isTagInPresets(tag.getKey(), tag.getValue()))
.map(Tag::toString)
.collect(Collectors.toList());
assertTrue(errors.isEmpty(), errors::toString);
}
/**
* Check regression: Don't fix surface=u -> surface=mud.
* @throws IOException if any I/O error occurs
*/
@Test
void testTooShortToFix() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node surface=u"));
assertEquals(1, errors.size());
assertEquals("Presets do not contain property value", errors.get(0).getMessage());
assertEquals("Value 'u' for key 'surface' not in presets.", errors.get(0).getDescription());
assertEquals(Severity.OTHER, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check value with upper case
* @throws IOException if any I/O error occurs
*/
@Test
void testValueDifferentCase() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node highway=Residential"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals("Value 'Residential' for key 'highway' is unknown, maybe 'residential' is meant?",
errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Key in presets but not in ignored.cfg. Caused a NPE with r14727.
* @throws IOException if any I/O error occurs
*/
@Test
void testRegression17246() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node access=privat"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals("Value 'privat' for key 'access' is unknown, maybe 'private' is meant?",
errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Checks for unwanted non printing control characters
* @param s String to test
* @param assertionC assertion on the result (true/false)
* @param expected expected fixed value
*/
private static void doTestUnwantedNonprintingControlCharacters(String s, Consumer<Boolean> assertionC, String expected) {
assertionC.accept(TagChecker.containsUnwantedNonPrintingControlCharacter(s));
assertEquals(expected, TagChecker.removeUnwantedNonPrintingControlCharacters(s));
}
private static void doTestUnwantedNonprintingControlCharacters(String s) {
doTestUnwantedNonprintingControlCharacters(s, Assert::assertTrue, "");
}
/**
* Unit test of {@link TagChecker#containsUnwantedNonPrintingControlCharacter}
* / {@link TagChecker#removeUnwantedNonPrintingControlCharacters}
*/
@Test
void testContainsRemoveUnwantedNonprintingControlCharacters() {
// Check empty string is handled
doTestUnwantedNonprintingControlCharacters("", Assert::assertFalse, "");
// Check 65 ASCII control characters are removed, except new lines
for (char c = 0x0; c < 0x20; c++) {
if (c != '\r' && c != '\n') {
doTestUnwantedNonprintingControlCharacters(Character.toString(c));
} else {
doTestUnwantedNonprintingControlCharacters(Character.toString(c), Assert::assertFalse, Character.toString(c));
}
}
doTestUnwantedNonprintingControlCharacters(Character.toString((char) 0x7F));
// Check 7 Unicode bidi control characters are removed
for (char c = 0x200e; c <= 0x200f; c++) {
doTestUnwantedNonprintingControlCharacters(Character.toString(c));
}
for (char c = 0x202a; c <= 0x202e; c++) {
doTestUnwantedNonprintingControlCharacters(Character.toString(c));
}
// Check joining characters are removed if located at the beginning or end of the string
for (char c = 0x200c; c <= 0x200d; c++) {
final String s = Character.toString(c);
doTestUnwantedNonprintingControlCharacters(s);
doTestUnwantedNonprintingControlCharacters(s + s);
doTestUnwantedNonprintingControlCharacters(s + 'a' + s, Assert::assertTrue, "a");
final String ok = 'a' + s + 'b';
doTestUnwantedNonprintingControlCharacters(ok, Assert::assertFalse, ok);
doTestUnwantedNonprintingControlCharacters(s + ok, Assert::assertTrue, ok);
doTestUnwantedNonprintingControlCharacters(ok + s, Assert::assertTrue, ok);
doTestUnwantedNonprintingControlCharacters(s + ok + s, Assert::assertTrue, ok);
}
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/17667">Bug #17667</a>.
*/
@Test
void testTicket17667() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Bus 118: Berlin, Rathaus Zehlendorf => Potsdam, Drewitz Stern-Center"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Καρδίτσα → Λάρισα"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("traffic_sign", "FI:871[← Lippuautomaatti]"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("traffic_sign", "FI:871[↑ Nostopaikka ↑]"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Cinderella II - Strandvägen ↔ Hagede"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Tallinn — Narva"));
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/18322">Bug #18322</a>.
*/
@Test
void testTicket18322() {
assertTrue(TagChecker.containsUnusualUnicodeCharacter("name", "D36ᴬ"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("ref", "D36ᴬ"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("old_ref", "D36ᴬ"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("old_ref", "D36ᵂ"));
assertTrue(TagChecker.containsUnusualUnicodeCharacter("old_ref", "D36ᴫ"));
assertTrue(TagChecker.containsUnusualUnicodeCharacter("old_ref", "D36ᵃ"));
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/18449">Bug #18449</a>.
*/
@Test
void testTicket18449() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Hökumət Evi"));
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/18740">Bug #18740</a>.
*/
@Test
void testTicket18740() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:ak", "Frɛnkyeman"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:bm", "Esipaɲi"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:oym", "Wɨlapaleya Ɨtu"));
}
/**
* Detects objects with types not supported by their presets.
* @throws IOException in case of I/O error
*/
@Test
void testObjectTypeNotSupportedByPreset() throws IOException {
List<TestError> errors = test(OsmUtils.createPrimitive("relation waterway=river"));
assertEquals(1, errors.size());
assertEquals(TagChecker.INVALID_PRESETS_TYPE, errors.get(0).getCode());
errors = test(OsmUtils.createPrimitive("relation type=waterway waterway=river"));
assertTrue(errors.isEmpty(), errors::toString);
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/19519">Bug #19519</a>.
* @throws IOException ignored
*/
@Test
@Disabled("broken, see #19519")
void testTicket19519() throws IOException {
List<TestError> errors = test(OsmUtils.createPrimitive("node amenity=restaurant cuisine=bavarian;beef_bowl"));
assertEquals(0, errors.size());
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/20437">Bug #20437</a>.
*/
@Test
void testTicket20437() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:kbp", "Wasɩŋtɔŋ"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:kbp", "Kalɩfɔrnii"));
}
}
| simon04/josm | test/unit/org/openstreetmap/josm/data/validation/tests/TagCheckerTest.java |
43,679 | // License: GPL. For details, see LICENSE file.
package org.openstreetmap.josm.data.validation.tests;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.junit.Assert;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.openstreetmap.josm.TestUtils;
import org.openstreetmap.josm.data.osm.OsmPrimitive;
import org.openstreetmap.josm.data.osm.OsmUtils;
import org.openstreetmap.josm.data.osm.Tag;
import org.openstreetmap.josm.data.validation.Severity;
import org.openstreetmap.josm.data.validation.TestError;
import org.openstreetmap.josm.testutils.JOSMTestRules;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
/**
* JUnit Test of {@link TagChecker}.
*/
class TagCheckerTest {
/**
* Setup test.
*/
@RegisterExtension
@SuppressFBWarnings(value = "URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD")
public JOSMTestRules rule = new JOSMTestRules().presets();
List<TestError> test(OsmPrimitive primitive) throws IOException {
final TagChecker checker = new TagChecker() {
@Override
protected boolean includeOtherSeverityChecks() {
return true;
}
};
checker.initialize();
checker.startTest(null);
checker.check(TestUtils.addFakeDataSet(primitive));
return checker.getErrors();
}
/**
* Check for misspelled key.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledKey1() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node Name=Main"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'Name' looks like 'name'.", errors.get(0).getDescription());
assertTrue(errors.get(0).isFixable());
}
/**
* Check for misspelled key.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledKey2() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node landuse;=forest"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'landuse;' looks like 'landuse'.", errors.get(0).getDescription());
assertTrue(errors.get(0).isFixable());
}
/**
* Check for misspelled key where the suggested alternative is in use. The error should not be fixable.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledKeyButAlternativeInUse() throws IOException {
// ticket 12329
final List<TestError> errors = test(OsmUtils.createPrimitive("node amenity=fuel brand=bah Brand=foo"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'Brand' looks like 'brand'.", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled key where the suggested alternative is given with prefix E: in ignoreTags.cfg.
* The error should be fixable.
* @throws IOException if any I/O error occurs
*/
@Test
void testUpperCaseIgnoredKey() throws IOException {
// ticket 17468
final List<TestError> errors = test(OsmUtils.createPrimitive("node wheelchair:Description=bla"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'wheelchair:Description' looks like 'wheelchair:description'.", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertTrue(errors.get(0).isFixable());
}
/**
* Check for misspelled key where the suggested alternative is given with prefix K: in ignoreTags.cfg.
* The error should be fixable.
* @throws IOException if any I/O error occurs
*/
@Test
void testUpperCaseInKeyIgnoredTag() throws IOException {
// ticket 17468
final List<TestError> errors = test(OsmUtils.createPrimitive("node land_Area=administrative"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'land_Area' looks like 'land_area'.", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertTrue(errors.get(0).isFixable());
}
/**
* Check for unknown key.
* @throws IOException if any I/O error occurs
*/
@Test
void testTranslatedNameKey() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node namez=Baz"));
assertEquals(1, errors.size());
assertEquals("Presets do not contain property key", errors.get(0).getMessage());
assertEquals("Key 'namez' not in presets.", errors.get(0).getDescription());
assertEquals(Severity.OTHER, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled value.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledTag() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node landuse=forrest"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals("Value 'forrest' for key 'landuse' is unknown, maybe 'forest' is meant?", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled value with multiple alternatives in presets.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledTag2() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node highway=servics"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals(
"Value 'servics' for key 'highway' is unknown, maybe one of [service, services] is meant?",
errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled value.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledTag3() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node highway=residentail"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals("Value 'residentail' for key 'highway' is unknown, maybe 'residential' is meant?",
errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled value.
* @throws IOException if any I/O error occurs
*/
@Test
void testShortValNotInPreset2() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node shop=abs"));
assertEquals(1, errors.size());
assertEquals("Presets do not contain property value", errors.get(0).getMessage());
assertEquals("Value 'abs' for key 'shop' not in presets.", errors.get(0).getDescription());
assertEquals(Severity.OTHER, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Checks that tags specifically ignored are effectively not in internal presets.
* @throws IOException if any I/O error occurs
*/
@Test
void testIgnoredTagsNotInPresets() throws IOException {
new TagChecker().initialize();
List<String> errors = TagChecker.getIgnoredTags().stream()
.filter(tag -> TagChecker.isTagInPresets(tag.getKey(), tag.getValue()))
.map(Tag::toString)
.collect(Collectors.toList());
assertTrue(errors.isEmpty(), errors::toString);
}
/**
* Check regression: Don't fix surface=u -> surface=mud.
* @throws IOException if any I/O error occurs
*/
@Test
void testTooShortToFix() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node surface=u"));
assertEquals(1, errors.size());
assertEquals("Presets do not contain property value", errors.get(0).getMessage());
assertEquals("Value 'u' for key 'surface' not in presets.", errors.get(0).getDescription());
assertEquals(Severity.OTHER, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check value with upper case
* @throws IOException if any I/O error occurs
*/
@Test
void testValueDifferentCase() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node highway=Residential"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals("Value 'Residential' for key 'highway' is unknown, maybe 'residential' is meant?",
errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Key in presets but not in ignored.cfg. Caused a NPE with r14727.
* @throws IOException if any I/O error occurs
*/
@Test
void testRegression17246() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node access=privat"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals("Value 'privat' for key 'access' is unknown, maybe 'private' is meant?",
errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Checks for unwanted non printing control characters
* @param s String to test
* @param assertionC assertion on the result (true/false)
* @param expected expected fixed value
*/
private static void doTestUnwantedNonprintingControlCharacters(String s, Consumer<Boolean> assertionC, String expected) {
assertionC.accept(TagChecker.containsUnwantedNonPrintingControlCharacter(s));
assertEquals(expected, TagChecker.removeUnwantedNonPrintingControlCharacters(s));
}
private static void doTestUnwantedNonprintingControlCharacters(String s) {
doTestUnwantedNonprintingControlCharacters(s, Assert::assertTrue, "");
}
/**
* Unit test of {@link TagChecker#containsUnwantedNonPrintingControlCharacter}
* / {@link TagChecker#removeUnwantedNonPrintingControlCharacters}
*/
@Test
void testContainsRemoveUnwantedNonprintingControlCharacters() {
// Check empty string is handled
doTestUnwantedNonprintingControlCharacters("", Assert::assertFalse, "");
// Check 65 ASCII control characters are removed, except new lines
for (char c = 0x0; c < 0x20; c++) {
if (c != '\r' && c != '\n') {
doTestUnwantedNonprintingControlCharacters(Character.toString(c));
} else {
doTestUnwantedNonprintingControlCharacters(Character.toString(c), Assert::assertFalse, Character.toString(c));
}
}
doTestUnwantedNonprintingControlCharacters(Character.toString((char) 0x7F));
// Check 7 Unicode bidi control characters are removed
for (char c = 0x200e; c <= 0x200f; c++) {
doTestUnwantedNonprintingControlCharacters(Character.toString(c));
}
for (char c = 0x202a; c <= 0x202e; c++) {
doTestUnwantedNonprintingControlCharacters(Character.toString(c));
}
// Check joining characters are removed if located at the beginning or end of the string
for (char c = 0x200c; c <= 0x200d; c++) {
final String s = Character.toString(c);
doTestUnwantedNonprintingControlCharacters(s);
doTestUnwantedNonprintingControlCharacters(s + s);
doTestUnwantedNonprintingControlCharacters(s + 'a' + s, Assert::assertTrue, "a");
final String ok = 'a' + s + 'b';
doTestUnwantedNonprintingControlCharacters(ok, Assert::assertFalse, ok);
doTestUnwantedNonprintingControlCharacters(s + ok, Assert::assertTrue, ok);
doTestUnwantedNonprintingControlCharacters(ok + s, Assert::assertTrue, ok);
doTestUnwantedNonprintingControlCharacters(s + ok + s, Assert::assertTrue, ok);
}
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/17667">Bug #17667</a>.
*/
@Test
void testTicket17667() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Bus 118: Berlin, Rathaus Zehlendorf => Potsdam, Drewitz Stern-Center"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Καρδίτσα → Λάρισα"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("traffic_sign", "FI:871[← Lippuautomaatti]"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("traffic_sign", "FI:871[↑ Nostopaikka ↑]"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Cinderella II - Strandvägen ↔ Hagede"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Tallinn — Narva"));
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/18322">Bug #18322</a>.
*/
@Test
void testTicket18322() {
assertTrue(TagChecker.containsUnusualUnicodeCharacter("name", "D36ᴬ"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("ref", "D36ᴬ"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("old_ref", "D36ᴬ"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("old_ref", "D36ᵂ"));
assertTrue(TagChecker.containsUnusualUnicodeCharacter("old_ref", "D36ᴫ"));
assertTrue(TagChecker.containsUnusualUnicodeCharacter("old_ref", "D36ᵃ"));
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/18449">Bug #18449</a>.
*/
@Test
void testTicket18449() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Hökumət Evi"));
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/18740">Bug #18740</a>.
*/
@Test
void testTicket18740() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:ak", "Frɛnkyeman"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:bm", "Esipaɲi"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:oym", "Wɨlapaleya Ɨtu"));
}
/**
* Detects objects with types not supported by their presets.
* @throws IOException in case of I/O error
*/
@Test
void testObjectTypeNotSupportedByPreset() throws IOException {
List<TestError> errors = test(OsmUtils.createPrimitive("relation waterway=river"));
assertEquals(1, errors.size());
assertEquals(TagChecker.INVALID_PRESETS_TYPE, errors.get(0).getCode());
errors = test(OsmUtils.createPrimitive("relation type=waterway waterway=river"));
assertTrue(errors.isEmpty(), errors::toString);
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/19519">Bug #19519</a>.
* @throws IOException ignored
*/
@Test
@Disabled("broken, see #19519")
void testTicket19519() throws IOException {
List<TestError> errors = test(OsmUtils.createPrimitive("node amenity=restaurant cuisine=bavarian;beef_bowl"));
assertEquals(0, errors.size());
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/20437">Bug #20437</a>.
*/
@Test
void testTicket20437() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:kbp", "Wasɩŋtɔŋ"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:kbp", "Kalɩfɔrnii"));
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/20754">Bug #20754</a>.
*/
@Test
void testTicket20754() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Yuułuʔiłʔatḥ Lands"));
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/21348">Bug #21348</a>.
* Key ref is in presets but without any value.
* @throws IOException if any I/O error occurs
*/
@Test
void testTicket21348() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node power=tower ref=12"));
assertEquals(0, errors.size());
}
}
| developmentseed/josm | test/unit/org/openstreetmap/josm/data/validation/tests/TagCheckerTest.java |
43,680 | // License: GPL. For details, see LICENSE file.
package org.openstreetmap.josm.data.validation.tests;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.openstreetmap.josm.TestUtils;
import org.openstreetmap.josm.data.osm.OsmPrimitive;
import org.openstreetmap.josm.data.osm.OsmUtils;
import org.openstreetmap.josm.data.osm.Tag;
import org.openstreetmap.josm.data.validation.Severity;
import org.openstreetmap.josm.data.validation.TestError;
import org.openstreetmap.josm.testutils.JOSMTestRules;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
/**
* JUnit Test of {@link TagChecker}.
*/
public class TagCheckerTest {
/**
* Setup test.
*/
@Rule
@SuppressFBWarnings(value = "URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD")
public JOSMTestRules rule = new JOSMTestRules().presets();
List<TestError> test(OsmPrimitive primitive) throws IOException {
final TagChecker checker = new TagChecker();
checker.initialize();
checker.startTest(null);
checker.check(TestUtils.addFakeDataSet(primitive));
return checker.getErrors();
}
/**
* Check for misspelled key.
* @throws IOException if any I/O error occurs
*/
@Test
public void testMisspelledKey1() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node Name=Main"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'Name' looks like 'name'.", errors.get(0).getDescription());
assertTrue(errors.get(0).isFixable());
}
/**
* Check for misspelled key.
* @throws IOException if any I/O error occurs
*/
@Test
public void testMisspelledKey2() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node landuse;=forest"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'landuse;' looks like 'landuse'.", errors.get(0).getDescription());
assertTrue(errors.get(0).isFixable());
}
/**
* Check for misspelled key where the suggested alternative is in use. The error should not be fixable.
* @throws IOException if any I/O error occurs
*/
@Test
public void testMisspelledKeyButAlternativeInUse() throws IOException {
// ticket 12329
final List<TestError> errors = test(OsmUtils.createPrimitive("node amenity=fuel brand=bah Brand=foo"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'Brand' looks like 'brand'.", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled key where the suggested alternative is given with prefix E: in ignoreTags.cfg.
* The error should be fixable.
* @throws IOException if any I/O error occurs
*/
@Test
public void testUpperCaseIgnoredKey() throws IOException {
// ticket 17468
final List<TestError> errors = test(OsmUtils.createPrimitive("node wheelchair:Description=bla"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'wheelchair:Description' looks like 'wheelchair:description'.", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertTrue(errors.get(0).isFixable());
}
/**
* Check for misspelled key where the suggested alternative is given with prefix K: in ignoreTags.cfg.
* The error should be fixable.
* @throws IOException if any I/O error occurs
*/
@Test
public void testUpperCaseInKeyIgnoredTag() throws IOException {
// ticket 17468
final List<TestError> errors = test(OsmUtils.createPrimitive("node land_Area=administrative"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'land_Area' looks like 'land_area'.", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertTrue(errors.get(0).isFixable());
}
/**
* Check for unknown key.
* @throws IOException if any I/O error occurs
*/
@Test
public void testTranslatedNameKey() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node namez=Baz"));
assertEquals(1, errors.size());
assertEquals("Presets do not contain property key", errors.get(0).getMessage());
assertEquals("Key 'namez' not in presets.", errors.get(0).getDescription());
assertEquals(Severity.OTHER, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled value.
* @throws IOException if any I/O error occurs
*/
@Test
public void testMisspelledTag() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node landuse=forrest"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals("Value 'forrest' for key 'landuse' is unknown, maybe 'forest' is meant?", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled value with multiple alternatives in presets.
* @throws IOException if any I/O error occurs
*/
@Test
public void testMisspelledTag2() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node highway=servics"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals(
"Value 'servics' for key 'highway' is unknown, maybe one of [service, services] is meant?",
errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled value.
* @throws IOException if any I/O error occurs
*/
@Test
public void testMisspelledTag3() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node highway=residentail"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals("Value 'residentail' for key 'highway' is unknown, maybe 'residential' is meant?",
errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled value.
* @throws IOException if any I/O error occurs
*/
@Test
public void testShortValNotInPreset2() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node shop=abs"));
assertEquals(1, errors.size());
assertEquals("Presets do not contain property value", errors.get(0).getMessage());
assertEquals("Value 'abs' for key 'shop' not in presets.", errors.get(0).getDescription());
assertEquals(Severity.OTHER, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Checks that tags specifically ignored are effectively not in internal presets.
* @throws IOException if any I/O error occurs
*/
@Test
public void testIgnoredTagsNotInPresets() throws IOException {
List<String> errors = new ArrayList<>();
new TagChecker().initialize();
for (Tag tag : TagChecker.getIgnoredTags()) {
if (TagChecker.isTagInPresets(tag.getKey(), tag.getValue())) {
errors.add(tag.toString());
}
}
assertTrue(errors.toString(), errors.isEmpty());
}
/**
* Check regression: Don't fix surface=u -> surface=mud.
* @throws IOException if any I/O error occurs
*/
@Test
public void testTooShortToFix() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node surface=u"));
assertEquals(1, errors.size());
assertEquals("Presets do not contain property value", errors.get(0).getMessage());
assertEquals("Value 'u' for key 'surface' not in presets.", errors.get(0).getDescription());
assertEquals(Severity.OTHER, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check value with upper case
* @throws IOException if any I/O error occurs
*/
@Test
public void testValueDifferentCase() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node highway=Residential"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals("Value 'Residential' for key 'highway' is unknown, maybe 'residential' is meant?",
errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Key in presets but not in ignored.cfg. Caused a NPE with r14727.
* @throws IOException if any I/O error occurs
*/
@Test
public void testRegression17246() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node access=privat"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals("Value 'privat' for key 'access' is unknown, maybe 'private' is meant?",
errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Checks for unwanted non printing control characters
* @param s String to test
* @param assertionC assertion on the result (true/false)
* @param expected expected fixed value
*/
private static void doTestUnwantedNonprintingControlCharacters(String s, Consumer<Boolean> assertionC, String expected) {
assertionC.accept(TagChecker.containsUnwantedNonPrintingControlCharacter(s));
assertEquals(expected, TagChecker.removeUnwantedNonPrintingControlCharacters(s));
}
private static void doTestUnwantedNonprintingControlCharacters(String s) {
doTestUnwantedNonprintingControlCharacters(s, Assert::assertTrue, "");
}
/**
* Unit test of {@link TagChecker#containsUnwantedNonPrintingControlCharacter}
* / {@link TagChecker#removeUnwantedNonPrintingControlCharacters}
*/
@Test
public void testContainsRemoveUnwantedNonprintingControlCharacters() {
// Check empty string is handled
doTestUnwantedNonprintingControlCharacters("", Assert::assertFalse, "");
// Check 65 ASCII control characters are removed, except new lines
for (char c = 0x0; c < 0x20; c++) {
if (c != '\r' && c != '\n') {
doTestUnwantedNonprintingControlCharacters(Character.toString(c));
} else {
doTestUnwantedNonprintingControlCharacters(Character.toString(c), Assert::assertFalse, Character.toString(c));
}
}
doTestUnwantedNonprintingControlCharacters(Character.toString((char) 0x7F));
// Check 7 Unicode bidi control characters are removed
for (char c = 0x200e; c <= 0x200f; c++) {
doTestUnwantedNonprintingControlCharacters(Character.toString(c));
}
for (char c = 0x202a; c <= 0x202e; c++) {
doTestUnwantedNonprintingControlCharacters(Character.toString(c));
}
// Check joining characters are removed if located at the beginning or end of the string
for (char c = 0x200c; c <= 0x200d; c++) {
final String s = Character.toString(c);
doTestUnwantedNonprintingControlCharacters(s);
doTestUnwantedNonprintingControlCharacters(s + s);
doTestUnwantedNonprintingControlCharacters(s + 'a' + s, Assert::assertTrue, "a");
final String ok = 'a' + s + 'b';
doTestUnwantedNonprintingControlCharacters(ok, Assert::assertFalse, ok);
doTestUnwantedNonprintingControlCharacters(s + ok, Assert::assertTrue, ok);
doTestUnwantedNonprintingControlCharacters(ok + s, Assert::assertTrue, ok);
doTestUnwantedNonprintingControlCharacters(s + ok + s, Assert::assertTrue, ok);
}
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/17667">Bug #17667</a>.
*/
@Test
public void testTicket17667() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Bus 118: Berlin, Rathaus Zehlendorf => Potsdam, Drewitz Stern-Center"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Καρδίτσα → Λάρισα"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("traffic_sign", "FI:871[← Lippuautomaatti]"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("traffic_sign", "FI:871[↑ Nostopaikka ↑]"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Cinderella II - Strandvägen ↔ Hagede"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Tallinn — Narva"));
}
}
| geeksperiments/josm | test/unit/org/openstreetmap/josm/data/validation/tests/TagCheckerTest.java |
43,681 | // License: GPL. For details, see LICENSE file.
package org.openstreetmap.josm.data.validation.tests;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.openstreetmap.josm.TestUtils;
import org.openstreetmap.josm.data.osm.OsmPrimitive;
import org.openstreetmap.josm.data.osm.OsmUtils;
import org.openstreetmap.josm.data.osm.Tag;
import org.openstreetmap.josm.data.validation.Severity;
import org.openstreetmap.josm.data.validation.TestError;
import org.openstreetmap.josm.testutils.JOSMTestRules;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
/**
* JUnit Test of {@link TagChecker}.
*/
public class TagCheckerTest {
/**
* Setup test.
*/
@Rule
@SuppressFBWarnings(value = "URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD")
public JOSMTestRules rule = new JOSMTestRules().presets();
List<TestError> test(OsmPrimitive primitive) throws IOException {
final TagChecker checker = new TagChecker() {
@Override
protected boolean includeOtherSeverityChecks() {
return true;
}
};
checker.initialize();
checker.startTest(null);
checker.check(TestUtils.addFakeDataSet(primitive));
return checker.getErrors();
}
/**
* Check for misspelled key.
* @throws IOException if any I/O error occurs
*/
@Test
public void testMisspelledKey1() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node Name=Main"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'Name' looks like 'name'.", errors.get(0).getDescription());
assertTrue(errors.get(0).isFixable());
}
/**
* Check for misspelled key.
* @throws IOException if any I/O error occurs
*/
@Test
public void testMisspelledKey2() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node landuse;=forest"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'landuse;' looks like 'landuse'.", errors.get(0).getDescription());
assertTrue(errors.get(0).isFixable());
}
/**
* Check for misspelled key where the suggested alternative is in use. The error should not be fixable.
* @throws IOException if any I/O error occurs
*/
@Test
public void testMisspelledKeyButAlternativeInUse() throws IOException {
// ticket 12329
final List<TestError> errors = test(OsmUtils.createPrimitive("node amenity=fuel brand=bah Brand=foo"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'Brand' looks like 'brand'.", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled key where the suggested alternative is given with prefix E: in ignoreTags.cfg.
* The error should be fixable.
* @throws IOException if any I/O error occurs
*/
@Test
public void testUpperCaseIgnoredKey() throws IOException {
// ticket 17468
final List<TestError> errors = test(OsmUtils.createPrimitive("node wheelchair:Description=bla"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'wheelchair:Description' looks like 'wheelchair:description'.", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertTrue(errors.get(0).isFixable());
}
/**
* Check for misspelled key where the suggested alternative is given with prefix K: in ignoreTags.cfg.
* The error should be fixable.
* @throws IOException if any I/O error occurs
*/
@Test
public void testUpperCaseInKeyIgnoredTag() throws IOException {
// ticket 17468
final List<TestError> errors = test(OsmUtils.createPrimitive("node land_Area=administrative"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'land_Area' looks like 'land_area'.", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertTrue(errors.get(0).isFixable());
}
/**
* Check for unknown key.
* @throws IOException if any I/O error occurs
*/
@Test
public void testTranslatedNameKey() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node namez=Baz"));
assertEquals(1, errors.size());
assertEquals("Presets do not contain property key", errors.get(0).getMessage());
assertEquals("Key 'namez' not in presets.", errors.get(0).getDescription());
assertEquals(Severity.OTHER, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled value.
* @throws IOException if any I/O error occurs
*/
@Test
public void testMisspelledTag() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node landuse=forrest"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals("Value 'forrest' for key 'landuse' is unknown, maybe 'forest' is meant?", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled value with multiple alternatives in presets.
* @throws IOException if any I/O error occurs
*/
@Test
public void testMisspelledTag2() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node highway=servics"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals(
"Value 'servics' for key 'highway' is unknown, maybe one of [service, services] is meant?",
errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled value.
* @throws IOException if any I/O error occurs
*/
@Test
public void testMisspelledTag3() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node highway=residentail"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals("Value 'residentail' for key 'highway' is unknown, maybe 'residential' is meant?",
errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled value.
* @throws IOException if any I/O error occurs
*/
@Test
public void testShortValNotInPreset2() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node shop=abs"));
assertEquals(1, errors.size());
assertEquals("Presets do not contain property value", errors.get(0).getMessage());
assertEquals("Value 'abs' for key 'shop' not in presets.", errors.get(0).getDescription());
assertEquals(Severity.OTHER, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Checks that tags specifically ignored are effectively not in internal presets.
* @throws IOException if any I/O error occurs
*/
@Test
public void testIgnoredTagsNotInPresets() throws IOException {
new TagChecker().initialize();
List<String> errors = TagChecker.getIgnoredTags().stream()
.filter(tag -> TagChecker.isTagInPresets(tag.getKey(), tag.getValue()))
.map(Tag::toString)
.collect(Collectors.toList());
assertTrue(errors.toString(), errors.isEmpty());
}
/**
* Check regression: Don't fix surface=u -> surface=mud.
* @throws IOException if any I/O error occurs
*/
@Test
public void testTooShortToFix() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node surface=u"));
assertEquals(1, errors.size());
assertEquals("Presets do not contain property value", errors.get(0).getMessage());
assertEquals("Value 'u' for key 'surface' not in presets.", errors.get(0).getDescription());
assertEquals(Severity.OTHER, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check value with upper case
* @throws IOException if any I/O error occurs
*/
@Test
public void testValueDifferentCase() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node highway=Residential"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals("Value 'Residential' for key 'highway' is unknown, maybe 'residential' is meant?",
errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Key in presets but not in ignored.cfg. Caused a NPE with r14727.
* @throws IOException if any I/O error occurs
*/
@Test
public void testRegression17246() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node access=privat"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals("Value 'privat' for key 'access' is unknown, maybe 'private' is meant?",
errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Checks for unwanted non printing control characters
* @param s String to test
* @param assertionC assertion on the result (true/false)
* @param expected expected fixed value
*/
private static void doTestUnwantedNonprintingControlCharacters(String s, Consumer<Boolean> assertionC, String expected) {
assertionC.accept(TagChecker.containsUnwantedNonPrintingControlCharacter(s));
assertEquals(expected, TagChecker.removeUnwantedNonPrintingControlCharacters(s));
}
private static void doTestUnwantedNonprintingControlCharacters(String s) {
doTestUnwantedNonprintingControlCharacters(s, Assert::assertTrue, "");
}
/**
* Unit test of {@link TagChecker#containsUnwantedNonPrintingControlCharacter}
* / {@link TagChecker#removeUnwantedNonPrintingControlCharacters}
*/
@Test
public void testContainsRemoveUnwantedNonprintingControlCharacters() {
// Check empty string is handled
doTestUnwantedNonprintingControlCharacters("", Assert::assertFalse, "");
// Check 65 ASCII control characters are removed, except new lines
for (char c = 0x0; c < 0x20; c++) {
if (c != '\r' && c != '\n') {
doTestUnwantedNonprintingControlCharacters(Character.toString(c));
} else {
doTestUnwantedNonprintingControlCharacters(Character.toString(c), Assert::assertFalse, Character.toString(c));
}
}
doTestUnwantedNonprintingControlCharacters(Character.toString((char) 0x7F));
// Check 7 Unicode bidi control characters are removed
for (char c = 0x200e; c <= 0x200f; c++) {
doTestUnwantedNonprintingControlCharacters(Character.toString(c));
}
for (char c = 0x202a; c <= 0x202e; c++) {
doTestUnwantedNonprintingControlCharacters(Character.toString(c));
}
// Check joining characters are removed if located at the beginning or end of the string
for (char c = 0x200c; c <= 0x200d; c++) {
final String s = Character.toString(c);
doTestUnwantedNonprintingControlCharacters(s);
doTestUnwantedNonprintingControlCharacters(s + s);
doTestUnwantedNonprintingControlCharacters(s + 'a' + s, Assert::assertTrue, "a");
final String ok = 'a' + s + 'b';
doTestUnwantedNonprintingControlCharacters(ok, Assert::assertFalse, ok);
doTestUnwantedNonprintingControlCharacters(s + ok, Assert::assertTrue, ok);
doTestUnwantedNonprintingControlCharacters(ok + s, Assert::assertTrue, ok);
doTestUnwantedNonprintingControlCharacters(s + ok + s, Assert::assertTrue, ok);
}
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/17667">Bug #17667</a>.
*/
@Test
public void testTicket17667() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Bus 118: Berlin, Rathaus Zehlendorf => Potsdam, Drewitz Stern-Center"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Καρδίτσα → Λάρισα"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("traffic_sign", "FI:871[← Lippuautomaatti]"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("traffic_sign", "FI:871[↑ Nostopaikka ↑]"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Cinderella II - Strandvägen ↔ Hagede"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Tallinn — Narva"));
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/18322">Bug #18322</a>.
*/
@Test
public void testTicket18322() {
assertTrue(TagChecker.containsUnusualUnicodeCharacter("name", "D36ᴬ"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("ref", "D36ᴬ"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("old_ref", "D36ᴬ"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("old_ref", "D36ᵂ"));
assertTrue(TagChecker.containsUnusualUnicodeCharacter("old_ref", "D36ᴫ"));
assertTrue(TagChecker.containsUnusualUnicodeCharacter("old_ref", "D36ᵃ"));
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/18449">Bug #18449</a>.
*/
@Test
public void testTicket18449() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Hökumət Evi"));
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/18740">Bug #18740</a>.
*/
@Test
public void testTicket18740() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:ak", "Frɛnkyeman"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:bm", "Esipaɲi"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:oym", "Wɨlapaleya Ɨtu"));
}
/**
* Detects objects with types not supported by their presets.
* @throws IOException in case of I/O error
*/
@Test
public void testObjectTypeNotSupportedByPreset() throws IOException {
List<TestError> errors = test(OsmUtils.createPrimitive("relation waterway=river"));
assertEquals(1, errors.size());
assertEquals(TagChecker.INVALID_PRESETS_TYPE, errors.get(0).getCode());
errors = test(OsmUtils.createPrimitive("relation type=waterway waterway=river"));
assertTrue(errors.toString(), errors.isEmpty());
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/19519">Bug #19519</a>.
*/
@Test
@Ignore("broken, see #19519")
public void testTicket19519() throws IOException {
List<TestError> errors = test(OsmUtils.createPrimitive("node amenity=restaurant cuisine=bavarian;beef_bowl"));
assertEquals(0, errors.size());
}
}
| korzhyk/josm | test/unit/org/openstreetmap/josm/data/validation/tests/TagCheckerTest.java |
43,682 | // License: GPL. For details, see LICENSE file.
package org.openstreetmap.josm.data.validation.tests;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.openstreetmap.josm.TestUtils;
import org.openstreetmap.josm.data.osm.OsmPrimitive;
import org.openstreetmap.josm.data.osm.OsmUtils;
import org.openstreetmap.josm.data.osm.Tag;
import org.openstreetmap.josm.data.validation.Severity;
import org.openstreetmap.josm.data.validation.TestError;
import org.openstreetmap.josm.testutils.annotations.I18n;
import org.openstreetmap.josm.testutils.annotations.TaggingPresets;
/**
* JUnit Test of {@link TagChecker}.
*/
@I18n
@TaggingPresets
class TagCheckerTest {
List<TestError> test(OsmPrimitive primitive) throws IOException {
final TagChecker checker = new TagChecker() {
@Override
protected boolean includeOtherSeverityChecks() {
return true;
}
};
checker.initialize();
checker.startTest(null);
checker.check(TestUtils.addFakeDataSet(primitive));
return checker.getErrors();
}
/**
* Check for misspelled key.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledKey1() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node Name=Main"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'Name' looks like 'name'.", errors.get(0).getDescription());
assertTrue(errors.get(0).isFixable());
}
/**
* Check for misspelled key.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledKey2() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node landuse;=forest"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'landuse;' looks like 'landuse'.", errors.get(0).getDescription());
assertTrue(errors.get(0).isFixable());
}
/**
* Check for misspelled key where the suggested alternative is in use. The error should not be fixable.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledKeyButAlternativeInUse() throws IOException {
// ticket 12329
final List<TestError> errors = test(OsmUtils.createPrimitive("node amenity=fuel brand=bah Brand=foo"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'Brand' looks like 'brand'.", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled key where the suggested alternative is given with prefix E: in ignoreTags.cfg.
* The error should be fixable.
* @throws IOException if any I/O error occurs
*/
@Test
void testUpperCaseIgnoredKey() throws IOException {
// ticket 17468
final List<TestError> errors = test(OsmUtils.createPrimitive("node wheelchair:Description=bla"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'wheelchair:Description' looks like 'wheelchair:description'.", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertTrue(errors.get(0).isFixable());
}
/**
* Check for misspelled key where the suggested alternative is given with prefix K: in ignoreTags.cfg.
* The error should be fixable.
* @throws IOException if any I/O error occurs
*/
@Test
void testUpperCaseInKeyIgnoredTag() throws IOException {
// ticket 17468
final List<TestError> errors = test(OsmUtils.createPrimitive("node land_Area=administrative"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'land_Area' looks like 'land_area'.", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertTrue(errors.get(0).isFixable());
}
/**
* Check for unknown key.
* @throws IOException if any I/O error occurs
*/
@Test
void testTranslatedNameKey() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node namez=Baz"));
assertEquals(1, errors.size());
assertEquals("Presets do not contain property key", errors.get(0).getMessage());
assertEquals("Key 'namez' not in presets.", errors.get(0).getDescription());
assertEquals(Severity.OTHER, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled value.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledTag() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node landuse=forrest"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals("Value 'forrest' for key 'landuse' is unknown, maybe 'forest' is meant?", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled value with multiple alternatives in presets.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledTag2() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node highway=servics"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals(
"Value 'servics' for key 'highway' is unknown, maybe one of [service, services] is meant?",
errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled value.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledTag3() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node highway=residentail"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals("Value 'residentail' for key 'highway' is unknown, maybe 'residential' is meant?",
errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled value.
* @throws IOException if any I/O error occurs
*/
@Test
void testShortValNotInPreset2() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node shop=abs"));
assertEquals(1, errors.size());
assertEquals("Presets do not contain property value", errors.get(0).getMessage());
assertEquals("Value 'abs' for key 'shop' not in presets.", errors.get(0).getDescription());
assertEquals(Severity.OTHER, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Checks that tags specifically ignored are effectively not in internal presets.
* @throws IOException if any I/O error occurs
*/
@Test
void testIgnoredTagsNotInPresets() throws IOException {
new TagChecker().initialize();
List<String> errors = TagChecker.getIgnoredTags().stream()
.filter(tag -> TagChecker.isTagInPresets(tag.getKey(), tag.getValue()))
.map(Tag::toString)
.collect(Collectors.toList());
assertTrue(errors.isEmpty(), errors::toString);
}
/**
* Check regression: Don't fix surface=u -> surface=mud.
* @throws IOException if any I/O error occurs
*/
@Test
void testTooShortToFix() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node surface=u"));
assertEquals(1, errors.size());
assertEquals("Presets do not contain property value", errors.get(0).getMessage());
assertEquals("Value 'u' for key 'surface' not in presets.", errors.get(0).getDescription());
assertEquals(Severity.OTHER, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check value with upper case
* @throws IOException if any I/O error occurs
*/
@Test
void testValueDifferentCase() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node highway=Residential"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals("Value 'Residential' for key 'highway' is unknown, maybe 'residential' is meant?",
errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
@Test
void testRegionKey() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node highway=crossing crossing_ref=zebra"));
assertEquals(1, errors.size());
assertEquals("Key from a preset is invalid in this region", errors.get(0).getMessage());
assertEquals("Preset Pedestrian Crossing should not have the key crossing_ref", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
@Test
void testRegionTag() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("relation type=waterway gnis:feature_id=123456"));
assertEquals(1, errors.size());
assertEquals("Key from a preset is invalid in this region", errors.get(0).getMessage());
assertEquals("Preset Waterway should not have the key gnis:feature_id", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Key in presets but not in ignored.cfg. Caused a NPE with r14727.
* @throws IOException if any I/O error occurs
*/
@Test
void testRegression17246() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node access=privat"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals("Value 'privat' for key 'access' is unknown, maybe 'private' is meant?",
errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Checks for unwanted non printing control characters
* @param s String to test
* @param assertionC assertion on the result (true/false)
* @param expected expected fixed value
*/
private static void doTestUnwantedNonprintingControlCharacters(String s, Consumer<Boolean> assertionC, String expected) {
assertionC.accept(TagChecker.containsUnwantedNonPrintingControlCharacter(s));
assertEquals(expected, TagChecker.removeUnwantedNonPrintingControlCharacters(s));
}
private static void doTestUnwantedNonprintingControlCharacters(String s) {
doTestUnwantedNonprintingControlCharacters(s, Assertions::assertTrue, "");
}
/**
* Unit test of {@link TagChecker#containsUnwantedNonPrintingControlCharacter}
* / {@link TagChecker#removeUnwantedNonPrintingControlCharacters}
*/
@Test
void testContainsRemoveUnwantedNonprintingControlCharacters() {
// Check empty string is handled
doTestUnwantedNonprintingControlCharacters("", Assertions::assertFalse, "");
// Check 65 ASCII control characters are removed, except new lines
for (char c = 0x0; c < 0x20; c++) {
if (c != '\r' && c != '\n') {
doTestUnwantedNonprintingControlCharacters(Character.toString(c));
} else {
doTestUnwantedNonprintingControlCharacters(Character.toString(c), Assertions::assertFalse, Character.toString(c));
}
}
doTestUnwantedNonprintingControlCharacters(Character.toString((char) 0x7F));
// Check 7 Unicode bidi control characters are removed
for (char c = 0x200e; c <= 0x200f; c++) {
doTestUnwantedNonprintingControlCharacters(Character.toString(c));
}
for (char c = 0x202a; c <= 0x202e; c++) {
doTestUnwantedNonprintingControlCharacters(Character.toString(c));
}
// Check joining characters are removed if located at the beginning or end of the string
for (char c = 0x200c; c <= 0x200d; c++) {
final String s = Character.toString(c);
doTestUnwantedNonprintingControlCharacters(s);
doTestUnwantedNonprintingControlCharacters(s + s);
doTestUnwantedNonprintingControlCharacters(s + 'a' + s, Assertions::assertTrue, "a");
final String ok = 'a' + s + 'b';
doTestUnwantedNonprintingControlCharacters(ok, Assertions::assertFalse, ok);
doTestUnwantedNonprintingControlCharacters(s + ok, Assertions::assertTrue, ok);
doTestUnwantedNonprintingControlCharacters(ok + s, Assertions::assertTrue, ok);
doTestUnwantedNonprintingControlCharacters(s + ok + s, Assertions::assertTrue, ok);
}
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/17667">Bug #17667</a>.
*/
@Test
void testTicket17667() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Bus 118: Berlin, Rathaus Zehlendorf => Potsdam, Drewitz Stern-Center"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Καρδίτσα → Λάρισα"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("traffic_sign", "FI:871[← Lippuautomaatti]"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("traffic_sign", "FI:871[↑ Nostopaikka ↑]"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Cinderella II - Strandvägen ↔ Hagede"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Tallinn — Narva"));
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/18322">Bug #18322</a>.
*/
@Test
void testTicket18322() {
assertTrue(TagChecker.containsUnusualUnicodeCharacter("name", "D36ᴬ"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("ref", "D36ᴬ"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("old_ref", "D36ᴬ"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("old_ref", "D36ᵂ"));
assertTrue(TagChecker.containsUnusualUnicodeCharacter("old_ref", "D36ᴫ"));
assertTrue(TagChecker.containsUnusualUnicodeCharacter("old_ref", "D36ᵃ"));
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/18449">Bug #18449</a>.
*/
@Test
void testTicket18449() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Hökumət Evi"));
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/18740">Bug #18740</a>.
*/
@Test
void testTicket18740() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:ak", "Frɛnkyeman"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:bm", "Esipaɲi"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:oym", "Wɨlapaleya Ɨtu"));
}
/**
* Detects objects with types not supported by their presets.
* @throws IOException in case of I/O error
*/
@Test
void testObjectTypeNotSupportedByPreset() throws IOException {
List<TestError> errors = test(OsmUtils.createPrimitive("relation waterway=river"));
assertEquals(1, errors.size());
assertEquals(TagChecker.INVALID_PRESETS_TYPE, errors.get(0).getCode());
errors = test(OsmUtils.createPrimitive("relation type=waterway waterway=river"));
assertTrue(errors.isEmpty(), errors::toString);
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/19519">Bug #19519</a>.
* @throws IOException ignored
*/
@Test
@Disabled("broken, see #19519")
void testTicket19519() throws IOException {
List<TestError> errors = test(OsmUtils.createPrimitive("node amenity=restaurant cuisine=bavarian;beef_bowl"));
assertEquals(0, errors.size());
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/20437">Bug #20437</a>.
*/
@Test
void testTicket20437() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:kbp", "Wasɩŋtɔŋ"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:kbp", "Kalɩfɔrnii"));
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/20754">Bug #20754</a>.
*/
@Test
void testTicket20754() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Yuułuʔiłʔatḥ Lands"));
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/21348">Bug #21348</a>.
* Key ref is in presets but without any value.
* @throws IOException if any I/O error occurs
*/
@Test
void testTicket21348() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node power=tower ref=12"));
assertEquals(0, errors.size());
}
}
| tsmock/josm | test/unit/org/openstreetmap/josm/data/validation/tests/TagCheckerTest.java |
43,683 | // License: GPL. For details, see LICENSE file.
package org.openstreetmap.josm.data.validation.tests;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.junit.Assert;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.openstreetmap.josm.TestUtils;
import org.openstreetmap.josm.data.osm.OsmPrimitive;
import org.openstreetmap.josm.data.osm.OsmUtils;
import org.openstreetmap.josm.data.osm.Tag;
import org.openstreetmap.josm.data.validation.Severity;
import org.openstreetmap.josm.data.validation.TestError;
import org.openstreetmap.josm.testutils.JOSMTestRules;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
/**
* JUnit Test of {@link TagChecker}.
*/
class TagCheckerTest {
/**
* Setup test.
*/
@RegisterExtension
@SuppressFBWarnings(value = "URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD")
public JOSMTestRules rule = new JOSMTestRules().presets();
List<TestError> test(OsmPrimitive primitive) throws IOException {
final TagChecker checker = new TagChecker() {
@Override
protected boolean includeOtherSeverityChecks() {
return true;
}
};
checker.initialize();
checker.startTest(null);
checker.check(TestUtils.addFakeDataSet(primitive));
return checker.getErrors();
}
/**
* Check for misspelled key.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledKey1() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node Name=Main"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'Name' looks like 'name'.", errors.get(0).getDescription());
assertTrue(errors.get(0).isFixable());
}
/**
* Check for misspelled key.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledKey2() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node landuse;=forest"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'landuse;' looks like 'landuse'.", errors.get(0).getDescription());
assertTrue(errors.get(0).isFixable());
}
/**
* Check for misspelled key where the suggested alternative is in use. The error should not be fixable.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledKeyButAlternativeInUse() throws IOException {
// ticket 12329
final List<TestError> errors = test(OsmUtils.createPrimitive("node amenity=fuel brand=bah Brand=foo"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'Brand' looks like 'brand'.", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled key where the suggested alternative is given with prefix E: in ignoreTags.cfg.
* The error should be fixable.
* @throws IOException if any I/O error occurs
*/
@Test
void testUpperCaseIgnoredKey() throws IOException {
// ticket 17468
final List<TestError> errors = test(OsmUtils.createPrimitive("node wheelchair:Description=bla"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'wheelchair:Description' looks like 'wheelchair:description'.", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertTrue(errors.get(0).isFixable());
}
/**
* Check for misspelled key where the suggested alternative is given with prefix K: in ignoreTags.cfg.
* The error should be fixable.
* @throws IOException if any I/O error occurs
*/
@Test
void testUpperCaseInKeyIgnoredTag() throws IOException {
// ticket 17468
final List<TestError> errors = test(OsmUtils.createPrimitive("node land_Area=administrative"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'land_Area' looks like 'land_area'.", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertTrue(errors.get(0).isFixable());
}
/**
* Check for unknown key.
* @throws IOException if any I/O error occurs
*/
@Test
void testTranslatedNameKey() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node namez=Baz"));
assertEquals(1, errors.size());
assertEquals("Presets do not contain property key", errors.get(0).getMessage());
assertEquals("Key 'namez' not in presets.", errors.get(0).getDescription());
assertEquals(Severity.OTHER, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled value.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledTag() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node landuse=forrest"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals("Value 'forrest' for key 'landuse' is unknown, maybe 'forest' is meant?", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled value with multiple alternatives in presets.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledTag2() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node highway=servics"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals(
"Value 'servics' for key 'highway' is unknown, maybe one of [service, services] is meant?",
errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled value.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledTag3() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node highway=residentail"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals("Value 'residentail' for key 'highway' is unknown, maybe 'residential' is meant?",
errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled value.
* @throws IOException if any I/O error occurs
*/
@Test
void testShortValNotInPreset2() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node shop=abs"));
assertEquals(1, errors.size());
assertEquals("Presets do not contain property value", errors.get(0).getMessage());
assertEquals("Value 'abs' for key 'shop' not in presets.", errors.get(0).getDescription());
assertEquals(Severity.OTHER, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Checks that tags specifically ignored are effectively not in internal presets.
* @throws IOException if any I/O error occurs
*/
@Test
void testIgnoredTagsNotInPresets() throws IOException {
new TagChecker().initialize();
List<String> errors = TagChecker.getIgnoredTags().stream()
.filter(tag -> TagChecker.isTagInPresets(tag.getKey(), tag.getValue()))
.map(Tag::toString)
.collect(Collectors.toList());
assertTrue(errors.isEmpty(), errors::toString);
}
/**
* Check regression: Don't fix surface=u -> surface=mud.
* @throws IOException if any I/O error occurs
*/
@Test
void testTooShortToFix() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node surface=u"));
assertEquals(1, errors.size());
assertEquals("Presets do not contain property value", errors.get(0).getMessage());
assertEquals("Value 'u' for key 'surface' not in presets.", errors.get(0).getDescription());
assertEquals(Severity.OTHER, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check value with upper case
* @throws IOException if any I/O error occurs
*/
@Test
void testValueDifferentCase() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node highway=Residential"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals("Value 'Residential' for key 'highway' is unknown, maybe 'residential' is meant?",
errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Key in presets but not in ignored.cfg. Caused a NPE with r14727.
* @throws IOException if any I/O error occurs
*/
@Test
void testRegression17246() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node access=privat"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals("Value 'privat' for key 'access' is unknown, maybe 'private' is meant?",
errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Checks for unwanted non printing control characters
* @param s String to test
* @param assertionC assertion on the result (true/false)
* @param expected expected fixed value
*/
private static void doTestUnwantedNonprintingControlCharacters(String s, Consumer<Boolean> assertionC, String expected) {
assertionC.accept(TagChecker.containsUnwantedNonPrintingControlCharacter(s));
assertEquals(expected, TagChecker.removeUnwantedNonPrintingControlCharacters(s));
}
private static void doTestUnwantedNonprintingControlCharacters(String s) {
doTestUnwantedNonprintingControlCharacters(s, Assert::assertTrue, "");
}
/**
* Unit test of {@link TagChecker#containsUnwantedNonPrintingControlCharacter}
* / {@link TagChecker#removeUnwantedNonPrintingControlCharacters}
*/
@Test
void testContainsRemoveUnwantedNonprintingControlCharacters() {
// Check empty string is handled
doTestUnwantedNonprintingControlCharacters("", Assert::assertFalse, "");
// Check 65 ASCII control characters are removed, except new lines
for (char c = 0x0; c < 0x20; c++) {
if (c != '\r' && c != '\n') {
doTestUnwantedNonprintingControlCharacters(Character.toString(c));
} else {
doTestUnwantedNonprintingControlCharacters(Character.toString(c), Assert::assertFalse, Character.toString(c));
}
}
doTestUnwantedNonprintingControlCharacters(Character.toString((char) 0x7F));
// Check 7 Unicode bidi control characters are removed
for (char c = 0x200e; c <= 0x200f; c++) {
doTestUnwantedNonprintingControlCharacters(Character.toString(c));
}
for (char c = 0x202a; c <= 0x202e; c++) {
doTestUnwantedNonprintingControlCharacters(Character.toString(c));
}
// Check joining characters are removed if located at the beginning or end of the string
for (char c = 0x200c; c <= 0x200d; c++) {
final String s = Character.toString(c);
doTestUnwantedNonprintingControlCharacters(s);
doTestUnwantedNonprintingControlCharacters(s + s);
doTestUnwantedNonprintingControlCharacters(s + 'a' + s, Assert::assertTrue, "a");
final String ok = 'a' + s + 'b';
doTestUnwantedNonprintingControlCharacters(ok, Assert::assertFalse, ok);
doTestUnwantedNonprintingControlCharacters(s + ok, Assert::assertTrue, ok);
doTestUnwantedNonprintingControlCharacters(ok + s, Assert::assertTrue, ok);
doTestUnwantedNonprintingControlCharacters(s + ok + s, Assert::assertTrue, ok);
}
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/17667">Bug #17667</a>.
*/
@Test
void testTicket17667() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Bus 118: Berlin, Rathaus Zehlendorf => Potsdam, Drewitz Stern-Center"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Καρδίτσα → Λάρισα"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("traffic_sign", "FI:871[← Lippuautomaatti]"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("traffic_sign", "FI:871[↑ Nostopaikka ↑]"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Cinderella II - Strandvägen ↔ Hagede"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Tallinn — Narva"));
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/18322">Bug #18322</a>.
*/
@Test
void testTicket18322() {
assertTrue(TagChecker.containsUnusualUnicodeCharacter("name", "D36ᴬ"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("ref", "D36ᴬ"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("old_ref", "D36ᴬ"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("old_ref", "D36ᵂ"));
assertTrue(TagChecker.containsUnusualUnicodeCharacter("old_ref", "D36ᴫ"));
assertTrue(TagChecker.containsUnusualUnicodeCharacter("old_ref", "D36ᵃ"));
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/18449">Bug #18449</a>.
*/
@Test
void testTicket18449() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Hökumət Evi"));
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/18740">Bug #18740</a>.
*/
@Test
void testTicket18740() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:ak", "Frɛnkyeman"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:bm", "Esipaɲi"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:oym", "Wɨlapaleya Ɨtu"));
}
/**
* Detects objects with types not supported by their presets.
* @throws IOException in case of I/O error
*/
@Test
void testObjectTypeNotSupportedByPreset() throws IOException {
List<TestError> errors = test(OsmUtils.createPrimitive("relation waterway=river"));
assertEquals(1, errors.size());
assertEquals(TagChecker.INVALID_PRESETS_TYPE, errors.get(0).getCode());
errors = test(OsmUtils.createPrimitive("relation type=waterway waterway=river"));
assertTrue(errors.isEmpty(), errors::toString);
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/19519">Bug #19519</a>.
* @throws IOException ignored
*/
@Test
@Disabled("broken, see #19519")
void testTicket19519() throws IOException {
List<TestError> errors = test(OsmUtils.createPrimitive("node amenity=restaurant cuisine=bavarian;beef_bowl"));
assertEquals(0, errors.size());
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/20437">Bug #20437</a>.
*/
@Test
void testTicket20437() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:kbp", "Wasɩŋtɔŋ"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:kbp", "Kalɩfɔrnii"));
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/20754">Bug #20754</a>.
*/
@Test
void testTicket20754() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Yuułuʔiłʔatḥ Lands"));
}
}
| isabella232/josm | test/unit/org/openstreetmap/josm/data/validation/tests/TagCheckerTest.java |
43,684 | // License: GPL. For details, see LICENSE file.
package org.openstreetmap.josm.data.validation.tests;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.openstreetmap.josm.TestUtils;
import org.openstreetmap.josm.data.osm.OsmPrimitive;
import org.openstreetmap.josm.data.osm.OsmUtils;
import org.openstreetmap.josm.data.osm.Tag;
import org.openstreetmap.josm.data.validation.Severity;
import org.openstreetmap.josm.data.validation.TestError;
import org.openstreetmap.josm.testutils.JOSMTestRules;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
/**
* JUnit Test of {@link TagChecker}.
*/
class TagCheckerTest {
/**
* Setup test.
*/
@RegisterExtension
@SuppressFBWarnings(value = "URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD")
public JOSMTestRules rule = new JOSMTestRules().presets();
List<TestError> test(OsmPrimitive primitive) throws IOException {
final TagChecker checker = new TagChecker() {
@Override
protected boolean includeOtherSeverityChecks() {
return true;
}
};
checker.initialize();
checker.startTest(null);
checker.check(TestUtils.addFakeDataSet(primitive));
return checker.getErrors();
}
/**
* Check for misspelled key.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledKey1() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node Name=Main"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'Name' looks like 'name'.", errors.get(0).getDescription());
assertTrue(errors.get(0).isFixable());
}
/**
* Check for misspelled key.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledKey2() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node landuse;=forest"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'landuse;' looks like 'landuse'.", errors.get(0).getDescription());
assertTrue(errors.get(0).isFixable());
}
/**
* Check for misspelled key where the suggested alternative is in use. The error should not be fixable.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledKeyButAlternativeInUse() throws IOException {
// ticket 12329
final List<TestError> errors = test(OsmUtils.createPrimitive("node amenity=fuel brand=bah Brand=foo"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'Brand' looks like 'brand'.", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled key where the suggested alternative is given with prefix E: in ignoreTags.cfg.
* The error should be fixable.
* @throws IOException if any I/O error occurs
*/
@Test
void testUpperCaseIgnoredKey() throws IOException {
// ticket 17468
final List<TestError> errors = test(OsmUtils.createPrimitive("node wheelchair:Description=bla"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'wheelchair:Description' looks like 'wheelchair:description'.", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertTrue(errors.get(0).isFixable());
}
/**
* Check for misspelled key where the suggested alternative is given with prefix K: in ignoreTags.cfg.
* The error should be fixable.
* @throws IOException if any I/O error occurs
*/
@Test
void testUpperCaseInKeyIgnoredTag() throws IOException {
// ticket 17468
final List<TestError> errors = test(OsmUtils.createPrimitive("node land_Area=administrative"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'land_Area' looks like 'land_area'.", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertTrue(errors.get(0).isFixable());
}
/**
* Check for unknown key.
* @throws IOException if any I/O error occurs
*/
@Test
void testTranslatedNameKey() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node namez=Baz"));
assertEquals(1, errors.size());
assertEquals("Presets do not contain property key", errors.get(0).getMessage());
assertEquals("Key 'namez' not in presets.", errors.get(0).getDescription());
assertEquals(Severity.OTHER, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled value.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledTag() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node landuse=forrest"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals("Value 'forrest' for key 'landuse' is unknown, maybe 'forest' is meant?", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled value with multiple alternatives in presets.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledTag2() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node highway=servics"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals(
"Value 'servics' for key 'highway' is unknown, maybe one of [service, services] is meant?",
errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled value.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledTag3() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node highway=residentail"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals("Value 'residentail' for key 'highway' is unknown, maybe 'residential' is meant?",
errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled value.
* @throws IOException if any I/O error occurs
*/
@Test
void testShortValNotInPreset2() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node shop=abs"));
assertEquals(1, errors.size());
assertEquals("Presets do not contain property value", errors.get(0).getMessage());
assertEquals("Value 'abs' for key 'shop' not in presets.", errors.get(0).getDescription());
assertEquals(Severity.OTHER, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Checks that tags specifically ignored are effectively not in internal presets.
* @throws IOException if any I/O error occurs
*/
@Test
void testIgnoredTagsNotInPresets() throws IOException {
new TagChecker().initialize();
List<String> errors = TagChecker.getIgnoredTags().stream()
.filter(tag -> TagChecker.isTagInPresets(tag.getKey(), tag.getValue()))
.map(Tag::toString)
.collect(Collectors.toList());
assertTrue(errors.isEmpty(), errors::toString);
}
/**
* Check regression: Don't fix surface=u -> surface=mud.
* @throws IOException if any I/O error occurs
*/
@Test
void testTooShortToFix() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node surface=u"));
assertEquals(1, errors.size());
assertEquals("Presets do not contain property value", errors.get(0).getMessage());
assertEquals("Value 'u' for key 'surface' not in presets.", errors.get(0).getDescription());
assertEquals(Severity.OTHER, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check value with upper case
* @throws IOException if any I/O error occurs
*/
@Test
void testValueDifferentCase() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node highway=Residential"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals("Value 'Residential' for key 'highway' is unknown, maybe 'residential' is meant?",
errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Key in presets but not in ignored.cfg. Caused a NPE with r14727.
* @throws IOException if any I/O error occurs
*/
@Test
void testRegression17246() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node access=privat"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals("Value 'privat' for key 'access' is unknown, maybe 'private' is meant?",
errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Checks for unwanted non printing control characters
* @param s String to test
* @param assertionC assertion on the result (true/false)
* @param expected expected fixed value
*/
private static void doTestUnwantedNonprintingControlCharacters(String s, Consumer<Boolean> assertionC, String expected) {
assertionC.accept(TagChecker.containsUnwantedNonPrintingControlCharacter(s));
assertEquals(expected, TagChecker.removeUnwantedNonPrintingControlCharacters(s));
}
private static void doTestUnwantedNonprintingControlCharacters(String s) {
doTestUnwantedNonprintingControlCharacters(s, Assertions::assertTrue, "");
}
/**
* Unit test of {@link TagChecker#containsUnwantedNonPrintingControlCharacter}
* / {@link TagChecker#removeUnwantedNonPrintingControlCharacters}
*/
@Test
void testContainsRemoveUnwantedNonprintingControlCharacters() {
// Check empty string is handled
doTestUnwantedNonprintingControlCharacters("", Assertions::assertFalse, "");
// Check 65 ASCII control characters are removed, except new lines
for (char c = 0x0; c < 0x20; c++) {
if (c != '\r' && c != '\n') {
doTestUnwantedNonprintingControlCharacters(Character.toString(c));
} else {
doTestUnwantedNonprintingControlCharacters(Character.toString(c), Assertions::assertFalse, Character.toString(c));
}
}
doTestUnwantedNonprintingControlCharacters(Character.toString((char) 0x7F));
// Check 7 Unicode bidi control characters are removed
for (char c = 0x200e; c <= 0x200f; c++) {
doTestUnwantedNonprintingControlCharacters(Character.toString(c));
}
for (char c = 0x202a; c <= 0x202e; c++) {
doTestUnwantedNonprintingControlCharacters(Character.toString(c));
}
// Check joining characters are removed if located at the beginning or end of the string
for (char c = 0x200c; c <= 0x200d; c++) {
final String s = Character.toString(c);
doTestUnwantedNonprintingControlCharacters(s);
doTestUnwantedNonprintingControlCharacters(s + s);
doTestUnwantedNonprintingControlCharacters(s + 'a' + s, Assertions::assertTrue, "a");
final String ok = 'a' + s + 'b';
doTestUnwantedNonprintingControlCharacters(ok, Assertions::assertFalse, ok);
doTestUnwantedNonprintingControlCharacters(s + ok, Assertions::assertTrue, ok);
doTestUnwantedNonprintingControlCharacters(ok + s, Assertions::assertTrue, ok);
doTestUnwantedNonprintingControlCharacters(s + ok + s, Assertions::assertTrue, ok);
}
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/17667">Bug #17667</a>.
*/
@Test
void testTicket17667() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Bus 118: Berlin, Rathaus Zehlendorf => Potsdam, Drewitz Stern-Center"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Καρδίτσα → Λάρισα"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("traffic_sign", "FI:871[← Lippuautomaatti]"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("traffic_sign", "FI:871[↑ Nostopaikka ↑]"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Cinderella II - Strandvägen ↔ Hagede"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Tallinn — Narva"));
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/18322">Bug #18322</a>.
*/
@Test
void testTicket18322() {
assertTrue(TagChecker.containsUnusualUnicodeCharacter("name", "D36ᴬ"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("ref", "D36ᴬ"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("old_ref", "D36ᴬ"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("old_ref", "D36ᵂ"));
assertTrue(TagChecker.containsUnusualUnicodeCharacter("old_ref", "D36ᴫ"));
assertTrue(TagChecker.containsUnusualUnicodeCharacter("old_ref", "D36ᵃ"));
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/18449">Bug #18449</a>.
*/
@Test
void testTicket18449() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Hökumət Evi"));
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/18740">Bug #18740</a>.
*/
@Test
void testTicket18740() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:ak", "Frɛnkyeman"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:bm", "Esipaɲi"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:oym", "Wɨlapaleya Ɨtu"));
}
/**
* Detects objects with types not supported by their presets.
* @throws IOException in case of I/O error
*/
@Test
void testObjectTypeNotSupportedByPreset() throws IOException {
List<TestError> errors = test(OsmUtils.createPrimitive("relation waterway=river"));
assertEquals(1, errors.size());
assertEquals(TagChecker.INVALID_PRESETS_TYPE, errors.get(0).getCode());
errors = test(OsmUtils.createPrimitive("relation type=waterway waterway=river"));
assertTrue(errors.isEmpty(), errors::toString);
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/19519">Bug #19519</a>.
* @throws IOException ignored
*/
@Test
@Disabled("broken, see #19519")
void testTicket19519() throws IOException {
List<TestError> errors = test(OsmUtils.createPrimitive("node amenity=restaurant cuisine=bavarian;beef_bowl"));
assertEquals(0, errors.size());
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/20437">Bug #20437</a>.
*/
@Test
void testTicket20437() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:kbp", "Wasɩŋtɔŋ"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:kbp", "Kalɩfɔrnii"));
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/20754">Bug #20754</a>.
*/
@Test
void testTicket20754() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Yuułuʔiłʔatḥ Lands"));
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/21348">Bug #21348</a>.
* Key ref is in presets but without any value.
* @throws IOException if any I/O error occurs
*/
@Test
void testTicket21348() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node power=tower ref=12"));
assertEquals(0, errors.size());
}
}
| joker234/josm | test/unit/org/openstreetmap/josm/data/validation/tests/TagCheckerTest.java |
43,685 | // License: GPL. For details, see LICENSE file.
package org.openstreetmap.josm.data.validation.tests;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.openstreetmap.josm.TestUtils;
import org.openstreetmap.josm.data.osm.OsmPrimitive;
import org.openstreetmap.josm.data.osm.OsmUtils;
import org.openstreetmap.josm.data.osm.Tag;
import org.openstreetmap.josm.data.validation.Severity;
import org.openstreetmap.josm.data.validation.TestError;
import org.openstreetmap.josm.testutils.annotations.I18n;
import org.openstreetmap.josm.testutils.annotations.TaggingPresets;
/**
* JUnit Test of {@link TagChecker}.
*/
@I18n
@TaggingPresets
class TagCheckerTest {
List<TestError> test(OsmPrimitive primitive) throws IOException {
final TagChecker checker = new TagChecker() {
@Override
protected boolean includeOtherSeverityChecks() {
return true;
}
};
checker.initialize();
checker.startTest(null);
checker.check(TestUtils.addFakeDataSet(primitive));
return checker.getErrors();
}
/**
* Check for misspelled key.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledKey1() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node Name=Main"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'Name' looks like 'name'.", errors.get(0).getDescription());
assertTrue(errors.get(0).isFixable());
}
/**
* Check for misspelled key.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledKey2() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node landuse;=forest"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'landuse;' looks like 'landuse'.", errors.get(0).getDescription());
assertTrue(errors.get(0).isFixable());
}
/**
* Check for misspelled key where the suggested alternative is in use. The error should not be fixable.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledKeyButAlternativeInUse() throws IOException {
// ticket 12329
final List<TestError> errors = test(OsmUtils.createPrimitive("node amenity=fuel brand=bah Brand=foo"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'Brand' looks like 'brand'.", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled key where the suggested alternative is given with prefix E: in ignoreTags.cfg.
* The error should be fixable.
* @throws IOException if any I/O error occurs
*/
@Test
void testUpperCaseIgnoredKey() throws IOException {
// ticket 17468
final List<TestError> errors = test(OsmUtils.createPrimitive("node wheelchair:Description=bla"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'wheelchair:Description' looks like 'wheelchair:description'.", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertTrue(errors.get(0).isFixable());
}
/**
* Check for misspelled key where the suggested alternative is given with prefix K: in ignoreTags.cfg.
* The error should be fixable.
* @throws IOException if any I/O error occurs
*/
@Test
void testUpperCaseInKeyIgnoredTag() throws IOException {
// ticket 17468
final List<TestError> errors = test(OsmUtils.createPrimitive("node land_Area=administrative"));
assertEquals(1, errors.size());
assertEquals("Misspelled property key", errors.get(0).getMessage());
assertEquals("Key 'land_Area' looks like 'land_area'.", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertTrue(errors.get(0).isFixable());
}
/**
* Check for unknown key.
* @throws IOException if any I/O error occurs
*/
@Test
void testTranslatedNameKey() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node namez=Baz"));
assertEquals(1, errors.size());
assertEquals("Presets do not contain property key", errors.get(0).getMessage());
assertEquals("Key 'namez' not in presets.", errors.get(0).getDescription());
assertEquals(Severity.OTHER, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled value.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledTag() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node landuse=forrest"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals("Value 'forrest' for key 'landuse' is unknown, maybe 'forest' is meant?", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled value with multiple alternatives in presets.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledTag2() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node highway=servics"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals(
"Value 'servics' for key 'highway' is unknown, maybe one of [service, services] is meant?",
errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled value.
* @throws IOException if any I/O error occurs
*/
@Test
void testMisspelledTag3() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node highway=residentail"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals("Value 'residentail' for key 'highway' is unknown, maybe 'residential' is meant?",
errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check for misspelled value.
* @throws IOException if any I/O error occurs
*/
@Test
void testShortValNotInPreset2() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node shop=abs"));
assertEquals(1, errors.size());
assertEquals("Presets do not contain property value", errors.get(0).getMessage());
assertEquals("Value 'abs' for key 'shop' not in presets.", errors.get(0).getDescription());
assertEquals(Severity.OTHER, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Checks that tags specifically ignored are effectively not in internal presets.
* @throws IOException if any I/O error occurs
*/
@Test
void testIgnoredTagsNotInPresets() throws IOException {
new TagChecker().initialize();
List<String> errors = TagChecker.getIgnoredTags().stream()
.filter(tag -> TagChecker.isTagInPresets(tag.getKey(), tag.getValue()))
.map(Tag::toString)
.collect(Collectors.toList());
assertTrue(errors.isEmpty(), errors::toString);
}
/**
* Check regression: Don't fix surface=u -> surface=mud.
* @throws IOException if any I/O error occurs
*/
@Test
void testTooShortToFix() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node surface=u"));
assertEquals(1, errors.size());
assertEquals("Presets do not contain property value", errors.get(0).getMessage());
assertEquals("Value 'u' for key 'surface' not in presets.", errors.get(0).getDescription());
assertEquals(Severity.OTHER, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Check value with upper case
* @throws IOException if any I/O error occurs
*/
@Test
void testValueDifferentCase() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node highway=Residential"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals("Value 'Residential' for key 'highway' is unknown, maybe 'residential' is meant?",
errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
@Test
void testRegionKey() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node highway=crossing crossing_ref=zebra"));
assertEquals(1, errors.size());
assertEquals("Key from a preset is invalid in this region", errors.get(0).getMessage());
assertEquals("Preset Pedestrian Crossing should not have the key crossing_ref", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
@Test
void testRegionTag() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("relation type=waterway gnis:feature_id=123456"));
assertEquals(1, errors.size());
assertEquals("Key from a preset is invalid in this region", errors.get(0).getMessage());
assertEquals("Preset Waterway should not have the key gnis:feature_id", errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Key in presets but not in ignored.cfg. Caused a NPE with r14727.
* @throws IOException if any I/O error occurs
*/
@Test
void testRegression17246() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node access=privat"));
assertEquals(1, errors.size());
assertEquals("Unknown property value", errors.get(0).getMessage());
assertEquals("Value 'privat' for key 'access' is unknown, maybe 'private' is meant?",
errors.get(0).getDescription());
assertEquals(Severity.WARNING, errors.get(0).getSeverity());
assertFalse(errors.get(0).isFixable());
}
/**
* Checks for unwanted non printing control characters
* @param s String to test
* @param assertionC assertion on the result (true/false)
* @param expected expected fixed value
*/
private static void doTestUnwantedNonprintingControlCharacters(String s, Consumer<Boolean> assertionC, String expected) {
assertionC.accept(TagChecker.containsUnwantedNonPrintingControlCharacter(s));
assertEquals(expected, TagChecker.removeUnwantedNonPrintingControlCharacters(s));
}
private static void doTestUnwantedNonprintingControlCharacters(String s) {
doTestUnwantedNonprintingControlCharacters(s, Assertions::assertTrue, "");
}
/**
* Unit test of {@link TagChecker#containsUnwantedNonPrintingControlCharacter}
* / {@link TagChecker#removeUnwantedNonPrintingControlCharacters}
*/
@Test
void testContainsRemoveUnwantedNonprintingControlCharacters() {
// Check empty string is handled
doTestUnwantedNonprintingControlCharacters("", Assertions::assertFalse, "");
// Check 65 ASCII control characters are removed, except new lines
for (char c = 0x0; c < 0x20; c++) {
if (c != '\r' && c != '\n') {
doTestUnwantedNonprintingControlCharacters(Character.toString(c));
} else {
doTestUnwantedNonprintingControlCharacters(Character.toString(c), Assertions::assertFalse, Character.toString(c));
}
}
doTestUnwantedNonprintingControlCharacters(Character.toString((char) 0x7F));
// Check 7 Unicode bidi control characters are removed
for (char c = 0x200e; c <= 0x200f; c++) {
doTestUnwantedNonprintingControlCharacters(Character.toString(c));
}
for (char c = 0x202a; c <= 0x202e; c++) {
doTestUnwantedNonprintingControlCharacters(Character.toString(c));
}
// Check joining characters are removed if located at the beginning or end of the string
for (char c = 0x200c; c <= 0x200d; c++) {
final String s = Character.toString(c);
doTestUnwantedNonprintingControlCharacters(s);
doTestUnwantedNonprintingControlCharacters(s + s);
doTestUnwantedNonprintingControlCharacters(s + 'a' + s, Assertions::assertTrue, "a");
final String ok = 'a' + s + 'b';
doTestUnwantedNonprintingControlCharacters(ok, Assertions::assertFalse, ok);
doTestUnwantedNonprintingControlCharacters(s + ok, Assertions::assertTrue, ok);
doTestUnwantedNonprintingControlCharacters(ok + s, Assertions::assertTrue, ok);
doTestUnwantedNonprintingControlCharacters(s + ok + s, Assertions::assertTrue, ok);
}
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/17667">Bug #17667</a>.
*/
@Test
void testTicket17667() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Bus 118: Berlin, Rathaus Zehlendorf => Potsdam, Drewitz Stern-Center"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Καρδίτσα → Λάρισα"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("traffic_sign", "FI:871[← Lippuautomaatti]"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("traffic_sign", "FI:871[↑ Nostopaikka ↑]"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Cinderella II - Strandvägen ↔ Hagede"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Tallinn — Narva"));
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/18322">Bug #18322</a>.
*/
@Test
void testTicket18322() {
assertTrue(TagChecker.containsUnusualUnicodeCharacter("name", "D36ᴬ"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("ref", "D36ᴬ"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("old_ref", "D36ᴬ"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("old_ref", "D36ᵂ"));
assertTrue(TagChecker.containsUnusualUnicodeCharacter("old_ref", "D36ᴫ"));
assertTrue(TagChecker.containsUnusualUnicodeCharacter("old_ref", "D36ᵃ"));
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/18449">Bug #18449</a>.
*/
@Test
void testTicket18449() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Hökumət Evi"));
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/18740">Bug #18740</a>.
*/
@Test
void testTicket18740() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:ak", "Frɛnkyeman"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:bm", "Esipaɲi"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:oym", "Wɨlapaleya Ɨtu"));
}
/**
* Detects objects with types not supported by their presets.
* @throws IOException in case of I/O error
*/
@Test
void testObjectTypeNotSupportedByPreset() throws IOException {
List<TestError> errors = test(OsmUtils.createPrimitive("relation waterway=river"));
assertEquals(1, errors.size());
assertEquals(TagChecker.INVALID_PRESETS_TYPE, errors.get(0).getCode());
errors = test(OsmUtils.createPrimitive("relation type=waterway waterway=river"));
assertTrue(errors.isEmpty(), errors::toString);
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/19519">Bug #19519</a>.
* @throws IOException ignored
*/
@Test
@Disabled("broken, see #19519")
void testTicket19519() throws IOException {
List<TestError> errors = test(OsmUtils.createPrimitive("node amenity=restaurant cuisine=bavarian;beef_bowl"));
assertEquals(0, errors.size());
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/20437">Bug #20437</a>.
*/
@Test
void testTicket20437() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:kbp", "Wasɩŋtɔŋ"));
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name:kbp", "Kalɩfɔrnii"));
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/20754">Bug #20754</a>.
*/
@Test
void testTicket20754() {
assertFalse(TagChecker.containsUnusualUnicodeCharacter("name", "Yuułuʔiłʔatḥ Lands"));
}
/**
* Non-regression test for <a href="https://josm.openstreetmap.de/ticket/21348">Bug #21348</a>.
* Key ref is in presets but without any value.
* @throws IOException if any I/O error occurs
*/
@Test
void testTicket21348() throws IOException {
final List<TestError> errors = test(OsmUtils.createPrimitive("node power=tower ref=12"));
assertEquals(0, errors.size());
}
}
| gabortim/josm | test/unit/org/openstreetmap/josm/data/validation/tests/TagCheckerTest.java |
43,743 | /*
* 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 gr.uoa.di.rdf.Geographica2.graphdbsut;
import gr.uoa.di.rdf.Geographica2.systemsundertest.SystemUnderTest;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.apache.log4j.Logger;
import org.eclipse.rdf4j.model.Resource;
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
import org.eclipse.rdf4j.model.impl.TreeModel;
import org.eclipse.rdf4j.model.util.Models;
import org.eclipse.rdf4j.model.vocabulary.RDF;
import org.eclipse.rdf4j.query.BindingSet;
import org.eclipse.rdf4j.query.QueryLanguage;
import org.eclipse.rdf4j.query.TupleQuery;
import org.eclipse.rdf4j.query.TupleQueryResult;
import org.eclipse.rdf4j.repository.Repository;
import org.eclipse.rdf4j.repository.RepositoryConnection;
import org.eclipse.rdf4j.query.MalformedQueryException;
import org.eclipse.rdf4j.query.QueryEvaluationException;
import org.eclipse.rdf4j.query.TupleQueryResultHandlerException;
import org.eclipse.rdf4j.query.Update;
import org.eclipse.rdf4j.query.UpdateExecutionException;
import org.eclipse.rdf4j.repository.RepositoryException;
import org.eclipse.rdf4j.repository.config.RepositoryConfig;
import org.eclipse.rdf4j.repository.config.RepositoryConfigException;
import org.eclipse.rdf4j.repository.config.RepositoryConfigSchema;
import org.eclipse.rdf4j.repository.manager.LocalRepositoryManager;
import org.eclipse.rdf4j.rio.*;
import org.eclipse.rdf4j.rio.RDFParser;
import org.eclipse.rdf4j.rio.Rio;
import org.eclipse.rdf4j.rio.helpers.StatementCollector;
/**
*
* @author tioannid
*/
public class GraphDBSUT implements SystemUnderTest {
// --------------------- Class Members ---------------------------------
static Logger logger = Logger.getLogger(GraphDBSUT.class.getSimpleName());
/* The following commands run on UBUNTU 16.04LTS
** and demand that the <sudo xxx> commands are added to
** /etc/sudoers for the system user that will be running the test
*/
static final String SYSCMD_SYNC = "sync";
static final String SYSCMD_CLEARCACHE = "sudo /sbin/sysctl vm.drop_caches=3";
/* Utility static nested class GraphDBSUT.GraphDB
** Similar to Strabon, encapsulates key objects of GraphDB
*/
public static class GraphDB {
// ---------------- Static Mmebers & Methods ---------------------------
private static String[] GeoSPARQLPluginDDLQueries = new String[]{
// Q1: Configure GeoSPARQL plugin
"PREFIX : <http://www.ontotext.com/plugins/geosparql#>"
+ "\n INSERT DATA { _:s :ignoreErrors \"true\" . };"
+ "\n INSERT DATA { _:s :enabled \"true\" . };"
+ "\n INSERT DATA { _:s :prefixTree \"<<algorithm>>\"; :precision \"@@precision@@\" . };"
+ "\n INSERT DATA { _:s :maxBufferedDocs \"5000\" . };"
+ "\n INSERT DATA { _:s :ramBufferSizeMB \"512.0\" . };",
// Q2: Enable plugin
"PREFIX : <http://www.ontotext.com/plugins/geosparql#>"
+ "\n INSERT DATA { _:s :enabled \"true\" . }",
// Q3: Disable plugin
"PREFIX : <http://www.ontotext.com/plugins/geosparql#>"
+ "\n INSERT DATA { _:s :enabled \"false\" . }",
// Q4: Force reindex geometry data
// usually used after a configuration change or when index files
// are either corrupted or have been mistakenly deleted
"PREFIX : <http://www.ontotext.com/plugins/geosparql#>"
+ "\n INSERT DATA {_:s :forceReindex . }"
};
static final String EMPTY_TEMPLATE_TTL
= "/home/tioannid/NetBeansProjects/PhD/Geographica/GraphDBSUT/graphdb-free_template.ttl";
// --------------------- Data Members ----------------------------------
private final String baseDir; // base directory for repository manager
private final LocalRepositoryManager repositoryManager; // repository manager
private final String repositoryId; // repository Id
private Repository repository; // repository
private RepositoryConnection connection; // repository connection
// --------------------- Constructors ----------------------------------
// Constructor 1: Opens an existing repository <repositoryId> in <baseDir>
public GraphDB(String baseDir, String repositoryId) {
this(baseDir, repositoryId, false);
}
// Constructor 2: Creates a new EMPTY repository <repositoryId> in <baseDir>
public GraphDB(String baseDir, String repositoryId, boolean createRepository) {
this(baseDir, repositoryId, createRepository, EMPTY_TEMPLATE_TTL);
}
/* Constructor 3: Creates/Opens a repository <repositoryId> in <baseDir>
** following the template <templateTTL>
*/
public GraphDB(String baseDir, String repositoryId, boolean createRepository, String templateTTL) {
// check if baseDir exists, otherwise throw exception
File dir = new File(baseDir);
if (!dir.exists()) {
throw new RuntimeException("Directory " + baseDir + " does not exist.");
} else {
this.baseDir = baseDir;
}
// create a new embedded instance of GraphDB in baseDir
repositoryManager = new LocalRepositoryManager(dir);
repositoryManager.initialize();
// if repository does not exist check what the user requested
if (!repositoryManager.hasRepositoryConfig(repositoryId)) {
if (!createRepository) { // do not create new repository
throw new RuntimeException("Repository " + repositoryId + " does not exist. Cannot proceed unless a new repository is created!");
} else { // create a new repository
if (!createNewRepository(repositoryId, templateTTL)) {
throw new RuntimeException("Failed creating repository " + repositoryId);
}
}
}
// repository exists
this.repositoryId = repositoryId;
// open the repository configuration to check if it OK
try {
RepositoryConfig repconfig = repositoryManager.getRepositoryConfig(repositoryId);
} catch (RepositoryConfigException e) {
logger.error("GraphDB repository configuration exception " + e.toString());
throw new RuntimeException("Error retrieving repository " + repositoryId + " configuration");
} catch (RepositoryException e) {
logger.error("GraphDB repository exception " + e.toString());
throw new RuntimeException("Generic error with repository " + repositoryId + " configuration");
}
// retrieve the repository
try {
repository = repositoryManager.getRepository(repositoryId);
} catch (RepositoryConfigException e) {
logger.error("GraphDB repository configuration exception " + e.toString());
throw new RuntimeException("Error retrieving repository " + repositoryId);
} catch (RepositoryException e) {
logger.error("GraphDB repository exception " + e.toString());
throw new RuntimeException("Generic error with repository " + repositoryId);
}
// create a repository connection, otherwise throw exception
connection = repository.getConnection();
if (connection == null) {
throw new RuntimeException("Could not establish connection to repository " + repositoryId);
}
}
// --------------------- Data Accessors --------------------------------
public String getBaseDir() {
return baseDir;
}
public LocalRepositoryManager getRepositoryManager() {
return repositoryManager;
}
public String getRepositoryId() {
return repositoryId;
}
public Repository getRepository() {
return repository;
}
public RepositoryConnection getConnection() {
return connection;
}
// --------------------- Methods --------------------------------
/*
** Preconditions: baseDir and repositoryManager must be initialized
*/
public boolean createNewRepository(String repositoryId, String templateTTL) {
boolean result = false;
InputStream config = null;
try {
TreeModel graph = new TreeModel();
config = new BufferedInputStream(new FileInputStream(templateTTL));
RDFParser rdfParser = Rio.createParser(RDFFormat.TURTLE);
rdfParser.setRDFHandler(new StatementCollector(graph));
rdfParser.parse(config, RepositoryConfigSchema.NAMESPACE);
config.close();
Resource repositoryNode = Models.subject(graph.filter(null, RDF.TYPE, RepositoryConfigSchema.REPOSITORY)).orElse(null);
graph.add(repositoryNode, RepositoryConfigSchema.REPOSITORYID,
SimpleValueFactory.getInstance().createLiteral(repositoryId));
RepositoryConfig repositoryConfig = RepositoryConfig.create(graph, repositoryNode);
repositoryManager.addRepositoryConfig(repositoryConfig);
} catch (FileNotFoundException ex) {
logger.error("Template " + templateTTL + " was not found!");
} catch (IOException ex) {
logger.error("Error while parsing the repository configuration!");
} finally {
try {
config.close();
result = true;
} catch (IOException ex) {
logger.error("Error while parsing the repository configuration!");
}
}
return result;
}
public void close() {
logger.info("[GraphDB.close] Closing connection...");
try {
connection.commit();
} catch (RepositoryException e) {
logger.error("[GraphDB.close]", e);
} finally {
try {
connection.close();
repository.shutDown();
} catch (RepositoryException e) {
logger.error("[GraphDB.close]", e);
}
logger.info("[GraphDB.close] Connection closed.");
}
}
// Execute GeoSPARQL Update the current configuration
public static long execGeoSPARQL_UpdateConfiguration(String indexingAlgorith, int indexingPrecision, String baseDirString, String repositoryId) {
String queryString = GeoSPARQLPluginDDLQueries[0];
// we need to dynamically replace the indexing algorithm and precision
queryString = queryString.replace("<<algorithm>>", indexingAlgorith);
queryString = queryString.replace("@@precision@@", String.valueOf(indexingPrecision));
return execQuery(baseDirString, repositoryId, queryString);
}
// Execute GeoSPARQL Enable plugin
public static long execGeoSPARQL_EnablePlugin(String baseDirString, String repositoryId) {
String queryString = GeoSPARQLPluginDDLQueries[1];
return execQuery(baseDirString, repositoryId, queryString);
}
// Execute GeoSPARQL Enable plugin
public static long execGeoSPARQL_DisablePlugin(String baseDirString, String repositoryId) {
String queryString = GeoSPARQLPluginDDLQueries[2];
return execQuery(baseDirString, repositoryId, queryString);
}
// Execute GeoSPARQL Enable plugin
public static long execGeoSPARQL_ForceReindex(String baseDirString, String repositoryId) {
String queryString = GeoSPARQLPluginDDLQueries[3];
return execQuery(baseDirString, repositoryId, queryString);
}
// Execute GeoSPARQL DDL Query in <repoDir>
public static long execQuery(String baseDirString, String repositoryId, String query) {
long start = System.currentTimeMillis();
// create a new LocalRepositoryManager in <baseDirString>
File baseDir = new File(baseDirString);
LocalRepositoryManager manager = new LocalRepositoryManager(baseDir);
manager.init();
// request the repository <repoId> back from the LocalRepositoryManager
Repository repository = null;
try {
repository = manager.getRepository(repositoryId);
repository.init();
} catch (RepositoryException | RepositoryConfigException e) {
logger.error(e.getMessage());
}
// Open a connection to the database
// RepositoryNotificationsListener listener = null;
// NotifyingOwlimConnection nConn = null;
RepositoryConnection conn = null;
try {
conn = repository.getConnection();
// listener = new RepositoryNotificationsListener() {
//
// @Override
// public void transactionStarted(long tid) {
// System.out.println("Started transaction " + tid);
// }
//
// @Override
// public void transactionComplete(long tid) {
// System.out.println("Finished transaction " + tid);
// }
//
// @Override
// public void addStatement(Resource rsrc, IRI iri, Value value, Resource rsrc1, boolean bln, long l) {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
// }
//
// @Override
// public void removeStatement(Resource rsrc, IRI iri, Value value, Resource rsrc1, boolean bln, long l) {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
// }
// };
//
// nConn = new NotifyingOwlimConnection(conn);
// IRI _s = SimpleValueFactory.getInstance().createIRI("_:s");
// IRI _enabled = SimpleValueFactory.getInstance().createIRI(":enabled");
// Literal _true = SimpleValueFactory.getInstance().createLiteral("\"true\"");
// // subscribe for statements
// nConn.subscribe(listener, null, null, _true);
conn.begin();
Update updateQuery = conn.prepareUpdate(QueryLanguage.SPARQL, query);
logger.info("Executing query : " + query + "\n");
updateQuery.execute();
conn.commit();
} catch (UpdateExecutionException e) {
logger.error(e.getMessage());
conn.rollback();
} catch (MalformedQueryException | RepositoryException e) {
logger.error(e.getMessage());
conn.rollback();
} finally {
// before our program exits, make sure the database is properly shut down.
try {
repository.shutDown();
} catch (RepositoryException e) {
logger.error(e.getMessage());
}
}
return (System.currentTimeMillis() - start);
}
}
/* Utility class GraphDBSUT.Executor
** Executes queries on GraphDB
*/
static class Executor implements Runnable {
// --------------------- Data Members ----------------------------------
private final String query;
private final GraphDB graphDB;
private BindingSet firstBindingSet;
private int dispres;
/*
private long evaluationTime,
fullResultScanTime,
noOfResults;
*/
private long[] returnValue;
// --------------------- Constructors ----------------------------------
public Executor(String query, GraphDB graphDB, int timeoutSecs, int dispres) {
this.query = query;
this.graphDB = graphDB;
this.dispres = dispres;
/*
this.evaluationTime = timeoutSecs + 1;
this.fullResultScanTime = timeoutSecs + 1;
this.noOfResults = -1;
*/
this.returnValue = new long[]{timeoutSecs + 1, timeoutSecs + 1, timeoutSecs + 1, -1};
}
// --------------------- Data Accessors --------------------------------
/*
public long[] getExecutorResults() {
return new long[]{evaluationTime, fullResultScanTime, evaluationTime + fullResultScanTime, noOfResults};
}
*/
public long[] getRetValue() {
return returnValue;
}
public BindingSet getFirstBindingSet() {
return firstBindingSet;
}
// --------------------- Methods --------------------------------
@Override
public void run() {
try {
//runQuery();
runQueryPrintLimitedRows(this.dispres);
} catch (MalformedQueryException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (QueryEvaluationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TupleQueryResultHandlerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// private void runQuery() throws MalformedQueryException, QueryEvaluationException, TupleQueryResultHandlerException, IOException {
//
// logger.info("Evaluating query...");
// TupleQuery tupleQuery = graphDB.getConnection().prepareTupleQuery(QueryLanguage.SPARQL, query);
//
// // Evaluate and time the evaluation of the prepared query
// // noOfResults = 0;
// long results = 0;
//
// long t1 = System.nanoTime();
// TupleQueryResult tupleQueryResult = tupleQuery.evaluate();
// long t2 = System.nanoTime();
//
// if (tupleQueryResult.hasNext()) {
// firstBindingSet = tupleQueryResult.next();
// //noOfResults++;
// results++;
// }
//
// while (tupleQueryResult.hasNext()) {
// //noOfResults++;
// results++;
// tupleQueryResult.next();
// }
// long t3 = System.nanoTime();
//
// logger.info("Query evaluated");
//
// // Calculate durations: Evaluation, Full ResultSet Scan
// /*
// fullResultScanTime = System.nanoTime() - t2;
// evaluationTime = t2 - t1;
// */
// this.returnValue = new long[]{t2 - t1, t3 - t2, t3 - t1, results};
// }
// private void runQueryPrintLimit(int rowsToDisplay) throws MalformedQueryException, QueryEvaluationException, TupleQueryResultHandlerException, IOException {
// long t1 = 0, t2 = 0, t3 = 0;
// long results = 0, noOfScanErrors = 0;
// int printedrow = 0;
// String bindingLine = "", labelsTitle = "\t";
// List<String> bindings = null;
// boolean displayRowsFlag = (rowsToDisplay != 0);
//
// logger.info("Evaluating query...");
// TupleQuery tupleQuery = graphDB.getConnection().prepareTupleQuery(QueryLanguage.SPARQL, query);
//
// // Evaluate and time the evaluation of the prepared query
// TupleQueryResult tupleQueryResult = null;
// t1 = System.nanoTime();
// // if there is an exception during evaluation throw it and return
// try {
// tupleQueryResult = tupleQuery.evaluate();
// } catch (QueryEvaluationException ex) {
// logger.error("[Query evaluation phase]", ex);
// throw new QueryEvaluationException("[Query evaluation phase]", ex);
// }
// t2 = System.nanoTime();
//
// // if there is a valid request for rows to display, first display headers
// if (displayRowsFlag) {
// // process results
// bindings = tupleQueryResult.getBindingNames();
// for (String label : bindings) {
// labelsTitle += (label + "\t\t");
// }
// logger.info("\n" + labelsTitle + "\n------------------------------------>");
// }
//
// while (tupleQueryResult.hasNext()) {
// try {
// firstBindingSet = tupleQueryResult.next();
// if (displayRowsFlag) {
// if (printedrow < rowsToDisplay) {
// bindingLine = "";
// for (String label : bindings) {
// bindingLine += (firstBindingSet.getValue(label) + "\t");
// }
// logger.info(bindingLine);
// printedrow++;
// }
// }
// results++;
// } catch (Exception ex) {
// noOfScanErrors++;
// logger.error("[Query full scan phase]");
// }
// }
// t3 = System.nanoTime();
// logger.info("\t<-----------\n\n");
// logger.info("Query evaluated with " + results + " results and " + noOfScanErrors + " scan errors!");
// this.returnValue = new long[]{t2 - t1, t3 - t2, t3 - t1, results};
// }
// }
private void runQueryPrintLimitedRows(int rowsToDisplay) throws MalformedQueryException, QueryEvaluationException, TupleQueryResultHandlerException, IOException {
long t1 = 0, t2 = 0, t3 = 0;
long results = 0, noOfScanErrors = 0;
int printedrow = 0;
String bindingLine = "", labelsTitle = "\t";
List<String> bindings = null;
boolean displayRowsFlag = (rowsToDisplay != 0);
logger.info("Evaluating query...");
TupleQuery tupleQuery = graphDB.getConnection().prepareTupleQuery(QueryLanguage.SPARQL, query);
// Evaluate and time the evaluation of the prepared query
TupleQueryResult tupleQueryResult = null;
t1 = System.nanoTime();
// if there is an exception during evaluation throw it and return
try {
tupleQueryResult = tupleQuery.evaluate();
} catch (QueryEvaluationException ex) {
logger.error("[Query evaluation phase]", ex);
throw new QueryEvaluationException("[Query evaluation phase]", ex);
}
t2 = System.nanoTime();
// if there is a valid request for rows to display, first display headers
if (displayRowsFlag) {
// process results
bindings = tupleQueryResult.getBindingNames();
for (String label : bindings) {
labelsTitle += (label + "\t\t");
}
logger.info(labelsTitle);
logger.info("------------------------------------>");
while (tupleQueryResult.hasNext()) {
try {
firstBindingSet = tupleQueryResult.next();
if (printedrow < rowsToDisplay) {
bindingLine = "";
for (String label : bindings) {
bindingLine += (firstBindingSet.getValue(label) + "\t");
}
logger.info(bindingLine);
printedrow++;
}
results++;
} catch (Exception ex) {
noOfScanErrors++;
logger.error("[Query full scan phase]");
}
}
} else {
while (tupleQueryResult.hasNext()) {
try {
firstBindingSet = tupleQueryResult.next();
results++;
} catch (Exception ex) {
noOfScanErrors++;
logger.error("[Query full scan phase]");
}
}
}
t3 = System.nanoTime();
if (displayRowsFlag) {
logger.info("<------------------------------------\n");
}
logger.info("Query evaluated with " + results + " results and " + noOfScanErrors + " scan errors!");
this.returnValue = new long[]{t2 - t1, t3 - t2, t3 - t1, results};
}
}
// --------------------- Data Members ----------------------------------
private String baseDir; // base directory for repository manager
private String repositoryId; // repository Id
private boolean createRepository;
private GraphDB graphDB;
private int displres;
private BindingSet firstBindingSet;
// --------------------- Constructors ----------------------------------
public GraphDBSUT(String baseDir, String repositoryId, boolean createRepository, int displres) {
this.baseDir = baseDir;
this.repositoryId = repositoryId;
this.createRepository = createRepository;
this.displres = displres;
}
// --------------------- Data Accessors --------------------------------
@Override
public BindingSet getFirstBindingSet() {
return firstBindingSet;
}
// --------------------- Methods --------------------------------
@Override
public Object getSystem() {
return graphDB;
}
@Override
public void initialize() {
try {
graphDB = new GraphDB(baseDir, repositoryId, createRepository);
} catch (RuntimeException e) {
logger.fatal("Cannot initialize GraphDB(\"" + baseDir + "\", \"" + repositoryId + "\"");
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
logger.fatal(sw.toString());
}
}
@Override
public long[] runQueryWithTimeout(String query, int timeoutSecs) throws Exception {
//maintains a thread for executing the doWork method
final ExecutorService pool = Executors.newFixedThreadPool(1);
//set the pool thread working
Executor runnable = new Executor(query, graphDB, timeoutSecs, this.displres);
final Future<?> future = pool.submit(runnable);
boolean isTimedout = false;
//check the outcome of the pool thread and limit the time allowed for it to complete
long tt1 = System.nanoTime();
try {
logger.debug("Future started");
/* Wait if necessary for at most <timeoutsSecs> for the computation
** to complete, and then retrieves its result, if available */
future.get(timeoutSecs, TimeUnit.SECONDS);
logger.debug("Future end");
} catch (InterruptedException e) { // current thread was interrupted while waiting
logger.debug(e.toString());
} catch (ExecutionException e) { // the computation threw an exception
logger.debug(e.toString());
} catch (TimeoutException e) { // the wait timed out
isTimedout = true;
logger.info("timed out!");
logger.info("Restarting GraphDB...");
this.restart();
logger.info("Closing GraphDB...");
this.close();
} finally {
logger.debug("Future canceling...");
future.cancel(true);
logger.debug("Executor shutting down...");
pool.shutdown();
try {
logger.debug("Executor waiting for termination...");
pool.awaitTermination(timeoutSecs, TimeUnit.SECONDS);
} catch (InterruptedException e) {
logger.debug(e.toString());
}
System.gc();
}
// logger.debug("RetValue: " + runnable.getExecutorResults());
logger.debug("RetValue: " + runnable.getRetValue());
if (isTimedout) {
long tt2 = System.nanoTime();
return new long[]{tt2 - tt1, tt2 - tt1, tt2 - tt1, -1};
} else {
this.firstBindingSet = runnable.getFirstBindingSet();
//return runnable.getExecutorResults();
return runnable.getRetValue();
}
}
@Override
public long[] runUpdate(String query) throws MalformedQueryException, QueryEvaluationException, TupleQueryResultHandlerException, IOException {
logger.info("Executing update...");
long t1 = System.nanoTime();
Update preparedUpdate = null;
try {
preparedUpdate = this.graphDB.getConnection().prepareUpdate(QueryLanguage.SPARQL, query);
} catch (RepositoryException e) {
logger.error("[Strabon.update]", e);
}
logger.info("[Strabon.update] executing update query: " + query);
try {
preparedUpdate.execute();
} catch (UpdateExecutionException e) {
logger.error("[Strabon.update]", e);
}
long t2 = System.nanoTime();
logger.info("Update executed");
long[] ret = {-1, -1, t2 - t1, -1};
return ret;
}
@Override
public void close() {
logger.info("Closing..");
try {
graphDB.close();
graphDB = null;
firstBindingSet = null;
} catch (Exception e) {
}
// TODO - Να ελέγξω ποιός και τί ήθελε να κάνει!
// Runtime run = Runtime.getRuntime();
// Process pr = run.exec(restart_script);
// pr.waitFor();
//
System.gc();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
logger.fatal("Cannot clear caches");
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String stacktrace = sw.toString();
logger.fatal(stacktrace);
}
logger.info("Closed (caches not cleared)");
}
@Override
public void clearCaches() {
String[] sys_sync = {"/bin/sh", "-c", SYSCMD_SYNC};
String[] clear_caches = {"/bin/sh", "-c", SYSCMD_CLEARCACHE};
Process pr;
try {
logger.info("Clearing caches...");
pr = Runtime.getRuntime().exec(sys_sync);
pr.waitFor();
if (pr.exitValue() != 0) {
logger.error("Something went wrong while system sync");
}
pr = Runtime.getRuntime().exec(clear_caches);
pr.waitFor();
if (pr.exitValue() != 0) {
logger.error("Something went wrong while clearing caches");
}
Thread.sleep(5000);
logger.info("Caches cleared");
} catch (Exception e) {
logger.fatal("Cannot clear caches");
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String stacktrace = sw.toString();
logger.fatal(stacktrace);
}
}
@Override
public void restart() {
Process pr;
try {
logger.info("Restarting GraphDB ...");
if (graphDB != null) {
try {
graphDB.close();
} catch (Exception e) {
logger.error("Exception occured while restarting GraphDB. ");
logger.debug(e.toString());
} finally {
graphDB = null;
}
}
firstBindingSet = null;
graphDB = new GraphDB(baseDir, repositoryId, createRepository);
logger.info("GraphDB restarted");
} catch (RuntimeException e) {
logger.fatal("Cannot restart GraphDB");
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String stacktrace = sw.toString();
logger.fatal(stacktrace);
}
}
@Override
public String translateQuery(String query, String label) {
String translatedQuery = null;
translatedQuery = query;
if (label.matches("Q14_Within_GeoNames_Point_Buffer")) {
translatedQuery = translatedQuery.replaceAll("3000, <http://www.opengis.net/def/uom/OGC/1.0/metre>", "0.03");
} else if (label.matches("Q4_Buffer_GeoNames")
|| label.matches("Q5_Buffer_LGD")) {
translatedQuery = translatedQuery.replaceAll("4, <http://www.opengis.net/def/uom/OGC/1.0/metre>", "0.04");
} else if (label.matches("Q6_Area_CLC")) {
translatedQuery = translatedQuery.replaceAll("strdf:area", "ext:area");
} else if (label.indexOf("Synthetic_Selection_Distance") != -1) { // Synthetic_POIs experiment
// convert this: FILTER ( bif:st_within(?geo1, bif:st_point(45, 45), 5000.000000))
// .....to this: FILTER ( geof:sfWithin(?geo1, geof:buffer("POINT(23.71622 37.97945)"^^<http://www.opengis.net/ont/geosparql#wktLiteral>, 5000, <http://www.opengis.net/def/uom/OGC/1.0/metre>)))
// 1. locate the last part of the query which starts with FILTER
String cGeom = "";
long cRadious = 0;
String oldFilter = translatedQuery.substring(translatedQuery.indexOf("FILTER"));
// 2. split to 4 parts using the comma as delimiter
String[] oldfilterPart = oldFilter.split(",");
// 3. split part-0 using the ( as delimiter
// ?geo1 is portion-2 of part-0
cGeom = oldfilterPart[0].split("\\(")[2];
// 4. split part-3 using the ) as delimiter
// RADIOUS is portion-0 of part-3 converted to long
cRadious = (long) Float.parseFloat(oldfilterPart[3].split("\\)")[0]);
// In the SyntheticOnly experiment the radius is in meters therefore
// we have to divide by 100000 to convert it to degrees, because this
// the analogy of Km/degree around the average latitude 45 and GraphDB
// uses geof:buffer(geom, TOL) where TOL is expressed in the same units
// as geom, which for the Synthetic_POIs dataset is in EPSG 4326, that
// is degrees!! The SyntheticGenerator especially for POIs returns
// radious in Km, that is the cRadius is already divide by 1000
cRadious = cRadious / 100;
// 5. create the new filter using the desired format
String newFilter = String.format("FILTER(geof:sfWithin(%s, geof:buffer(\"POINT(45 45)\"^^<http://www.opengis.net/ont/geosparql#wktLiteral>, %d))).\n}\n", cGeom, cRadious);
// 6. replace old with new filter
translatedQuery = translatedQuery.substring(0, translatedQuery.indexOf("FILTER")) + newFilter;
}
return translatedQuery;
}
}
| tioannid/geordfbench | GraphDBSUT/src/main/java/gr/uoa/di/rdf/Geographica2/graphdbsut/GraphDBSUT.java |
43,744 | package gr.uoa.di.rdf.Geographica3.runtime.sut.impl;
import gr.uoa.di.rdf.Geographica3.runtime.sys.executor.RDF4JbasedExecutor;
import gr.uoa.di.rdf.Geographica3.runtime.sys.interfaces.impl.RDF4JBasedGeographicaSystem;
import gr.uoa.di.rdf.Geographica3.runtime.resultscollector.impl.ResultException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.apache.log4j.Logger;
import org.eclipse.rdf4j.query.QueryLanguage;
import org.eclipse.rdf4j.query.Update;
import org.eclipse.rdf4j.query.UpdateExecutionException;
import org.eclipse.rdf4j.repository.RepositoryException;
import gr.uoa.di.rdf.Geographica3.runtime.executionspecs.IExecutionSpec;
import gr.uoa.di.rdf.Geographica3.runtime.hosts.IHost;
import gr.uoa.di.rdf.Geographica3.runtime.reportspecs.IReportSpec;
import gr.uoa.di.rdf.Geographica3.runtime.resultscollector.impl.QueryEvaluationFlag;
import gr.uoa.di.rdf.Geographica3.runtime.resultscollector.impl.QueryRepResults.QueryRepResult;
import gr.uoa.di.rdf.Geographica3.runtime.sut.ISUT;
import gr.uoa.di.rdf.Geographica3.runtime.sys.interfaces.IGeographicaSystem;
import java.util.concurrent.Callable;
import java.util.logging.Level;
import org.eclipse.rdf4j.query.QueryEvaluationException;
/**
*
* @author GeoRDFBench Creator <GeoRDFBench@Creator>
* @since 09/12/2019
*/
public abstract class RDF4JBasedSUT implements ISUT<RDF4JBasedGeographicaSystem> {
// --- Static members -----------------------------
protected static Logger logger = Logger.getLogger(RDF4JBasedSUT.class.getSimpleName());
// --- Data members ------------------------------
protected IHost host;
protected Map<String, String> sysProperties;
protected RDF4JBasedGeographicaSystem _sys;
protected IReportSpec reportSpec;
protected IExecutionSpec execSpec;
protected Map<String, String> firstBindingSetValueMap;
protected int noRecsToPause = -1; // number of scanned records after which executor thread pauses to receive main thread's interrupts
protected int noMsecsToPause = 100; // number of msecs to pause the worker thread
// --- Constructors ------------------------------
public RDF4JBasedSUT(IHost host, Map<String, String> sysProperties,
IReportSpec reportSpec, IExecutionSpec execSpec) {
this.host = host;
if (sysProperties == null) {
System.out.println("ALERT! sysProperties is NULL!");
}
this.sysProperties = sysProperties;
this.reportSpec = reportSpec;
this.execSpec = execSpec;
this.firstBindingSetValueMap = new HashMap<>();
}
// --- Data Accessors -----------------------------------
@Override
public IHost getHost() {
return host;
}
@Override
public IReportSpec getReportSpec() {
return reportSpec;
}
@Override
public IExecutionSpec getExecSpec() {
return execSpec;
}
@Override
public int getNoRecsToPause() {
return noRecsToPause;
}
@Override
public void setNoRecsToPause(int noRecsToPause) {
this.noRecsToPause = noRecsToPause;
}
@Override
public int getNoMsecsToPause() {
return noMsecsToPause;
}
@Override
public void setNoMsecsToPause(int noMsecsToPause) {
this.noMsecsToPause = noMsecsToPause;
}
// --- Methods -----------------------------------
/**
* Return the value of the binding with {@link bindingName} from the first
* BindingSet.
*
* @return a String representing the value for the binding
*/
@Override
public Map<String, String> getFirstBindingSetValueMap() {
return firstBindingSetValueMap;
}
@Override
public RDF4JBasedGeographicaSystem getSystem() {
return _sys;
}
@Override
public void initialize() {
try {
logger.info("Initializing..");
// create an RDF4JBasedGeographicaSystem instance with default constructor
this._sys = new RDF4JBasedGeographicaSystem(this.sysProperties);
} catch (RuntimeException e) {
logger.fatal("Cannot initialize " + this.getClass().getSimpleName());
logger.fatal(e.toString());
} catch (Exception ex) {
java.util.logging.Logger.getLogger(RDF4JBasedSUT.class.getName()).log(Level.SEVERE, null, ex);
}
}
// @Override
// Using Callable interface and Futures for thread management
public QueryRepResult runTimedQueryByExecutor_ORIGINAL(String query, long timeoutSecs) throws Exception {
QueryRepResult qryRepResult = new QueryRepResult(QueryRepResult.DEFAULT);
boolean isFutureDone = false;
//maintains a thread for executing the doWork method
final ExecutorService execService = Executors.newFixedThreadPool(1);
//set the execService thread working
RDF4JbasedExecutor executor = new RDF4JbasedExecutor(query, _sys,
this.reportSpec, qryRepResult);
final Future<QueryRepResult> future = execService.submit((Callable<QueryRepResult>) executor);
//check the outcome of the execService thread and limit the time allowed for it to complete
long tt1 = System.nanoTime();
long tt2 = 0;
try {
//logger.info("Future started");
/* Wait if necessary for at most <timeoutsSecs> for the computation
** to complete, and then retrieves its result, if available */
qryRepResult = future.get(timeoutSecs, TimeUnit.SECONDS);
isFutureDone = true;
} catch (InterruptedException e) { // current thread was interrupted while waiting
future.cancel(true);
logger.error(e.toString());
} catch (ExecutionException e) { // the computation threw an exception
executor.setIsOpNotsupported(true);
qryRepResult = executor.getQryRepResult();
future.cancel(true);
tt2 = System.nanoTime();
logger.error(e.toString());
} catch (TimeoutException e) { // the wait timed out
executor.setIsTimedout(true);
qryRepResult = executor.getQryRepResult();
future.cancel(true);
tt2 = System.nanoTime();
logger.info("Time out occurred!");
this.restart();
// this.close();
} catch (QueryEvaluationException e) {
logger.error(e.toString());
} finally {
//logger.info("Executor shutting down the execService...");
execService.shutdown(); // Disable new tasks from being submitted
try {
//logger.info("Executor waiting for termination...");
execService.awaitTermination(timeoutSecs, TimeUnit.SECONDS);
} catch (InterruptedException e) {
logger.error(e.toString());
}
System.gc();
}
if (isFutureDone) {
this.firstBindingSetValueMap = executor.getFirstBindingSetValueMap();
return qryRepResult;
} else {
// logger.info("Future did not terminate properly ("
// + String.valueOf((executor.isIsTimedout()) ? "timed out" : (executor.isIsOpNotsupported()) ? "unsupported operation" : "unknown") + ")"
// + "\nExecutor returned (at interrupt time) query repetition result: " + qryRepResult.toString()
// + "\nExecutor returned (NOW) query repetition result: " + executor.getQryRepResult().toString());
if (executor.isIsOpNotsupported()) {
//logger.error("Future not done AND OperationNotSupported!");
qryRepResult.setNoResults(ResultException.UNSUPPORTED_OPERATOR.getResultException());
qryRepResult.setEvalFlag(QueryEvaluationFlag.EVALUATION_ERROR);
} else if (executor.isIsTimedout()) {
//logger.error("Future not done AND Timed out!");
qryRepResult.setNoResults(ResultException.TIMEDOUT.getResultException());
qryRepResult.setEvalFlag(QueryEvaluationFlag.EVALUATED);
}
// logger.info("Modified query repetition result is: " + qryRepResult.toString());
return qryRepResult;
}
}
@Override
// Using Runnable interface and explicit Thread management
public QueryRepResult runTimedQueryByExecutor(String query, long timeoutSecs) throws Exception {
QueryRepResult qryRepResult = new QueryRepResult(QueryRepResult.DEFAULT);
//maintains a thread for executing the doWork method
logger.info("Starting QueryExecutor thread");
long patience = timeoutSecs * (long) Math.pow(10, 9);
// int noRecsToPause = -1; // number of scanned records after which executor thread pauses to receive main thread's interrupts
// int noMsecsToPause = 100; // number of msecs to pause the worker thread
// logger.info("noRecsToPause = " + noRecsToPause + ", noMsecsToPause = " + noMsecsToPause);
RDF4JbasedExecutor executor = new RDF4JbasedExecutor(query, _sys,
this.reportSpec, qryRepResult, noRecsToPause, noMsecsToPause);
executor.setMaxQueryExecTime((int) timeoutSecs); // explicit conversion is ok!
Thread qet = new Thread(executor);
long startTime = System.nanoTime();
if (this._sys == null) {
logger.error("The _sys object is null. Cannot start executor!");
throw new Exception("[The _sys object is null. Cannot start executor!");
}
qet.start();
logger.info("Waiting for QueryExecutor thread to finish");
// boolean isFutureDone = true;
long timeoutProgressDuration; // nsecs
long timeoutProgressStep = timeoutSecs * 1000 / 4; // msecs
logger.info("Timeout progress step is " + timeoutProgressStep + " msecs");
float timeoutProgressPercentage;
while (qet.isAlive()) {
// Wait maximum of 1 second
// for MessageLoop thread
// to finish.
qet.join(timeoutProgressStep);
timeoutProgressDuration = System.nanoTime() - startTime;
timeoutProgressPercentage = timeoutProgressDuration * 100 / patience;
if ((timeoutProgressDuration > patience)) {
if (qet.isAlive()) {
qet.interrupt();
logger.info("Timeout expired! Sent interrupt to worker thread and waiting for it to join.");
// Shouldn't be long now
// -- wait indefinitely
qet.join();
}
} else {
logger.info("Percentage of expired timeout is " + timeoutProgressPercentage + " %");
}
}
this.firstBindingSetValueMap = executor.getFirstBindingSetValueMap();
System.gc();
// if (isFutureDone) {
// this.firstBindingSetValueMap = executor.getFirstBindingSetValueMap();
//// logger.info("Future did not terminate properly ("
//// + String.valueOf((executor.isIsTimedout()) ? "timed out" : (executor.isIsOpNotsupported()) ? "unsupported operation" : "unknown") + ")"
//// + "\nExecutor returned (at interrupt time) query repetition result: " + qryRepResult.toString()
//// + "\nExecutor returned (NOW) query repetition result: " + executor.getQryRepResult().toString());
// if (executor.isIsOpNotsupported()) {
// //logger.error("Future not done AND OperationNotSupported!");
// qryRepResult.setNoResults(ResultException.UNSUPPORTED_OPERATOR.getResultException());
// qryRepResult.setEvalFlag(QueryEvaluationFlag.EVALUATION_ERROR);
// } else if (executor.isIsTimedout()) {
// //logger.error("Future not done AND Timed out!");
// qryRepResult.setNoResults(ResultException.TIMEDOUT.getResultException());
// qryRepResult.setEvalFlag(QueryEvaluationFlag.EVALUATED);
// }
//// logger.info("Modified query repetition result is: " + qryRepResult.toString());
// }
return qryRepResult;
}
@Override
public long[] runUpdate(String query
) {
logger.info("Executing update...");
long t1 = System.nanoTime();
Update preparedUpdate = null;
try {
preparedUpdate = this._sys.getConnection().prepareUpdate(QueryLanguage.SPARQL, query);
} catch (RepositoryException e) {
logger.error("[RDF4J.update]", e);
}
logger.info("[RDF4J.update] executing update query: " + query);
try {
preparedUpdate.execute();
} catch (UpdateExecutionException e) {
logger.error("[RDF4J.update]", e);
}
long t2 = System.nanoTime();
logger.info("Update executed");
long[] ret = {-1, -1, t2 - t1, -1};
return ret;
}
@Override
public void close() {
logger.info("Closing..");
try {
if (_sys != null) {
_sys.close();
_sys = null;
} else {
logger.info("There is no instance of " + this.getClass().getSimpleName());
}
this.firstBindingSetValueMap = null;
} catch (Exception e) {
logger.error("TODO - Handle this Exception!");
e.printStackTrace();
}
// TODO - Να ελέγξω ποιός και τί ήθελε να κάνει!
// Runtime run = Runtime.getRuntime();
// Process pr = run.exec(restart_script);
// pr.waitFor();
//
System.gc();
try {
Thread.sleep(this.execSpec.getClearCacheDelaymSecs()); // TODO use different parameter for Java GC
} catch (InterruptedException e) {
logger.fatal("Cannot clear caches");
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String stacktrace = sw.toString();
logger.fatal(stacktrace);
}
logger.info("Closed (caches not cleared)");
}
/**
* Plain RDF4JBasedSUTs have only operating system (JVM) caches to clear
*/
@Override
public void clearCaches() {
host.getOs().clearCaches(this.execSpec.getClearCacheDelaymSecs());
}
@Override
public void restart() {
Process pr;
try {
logger.info("Restarting..");
// close _sys
if (_sys != null) {
try {
_sys.close();
} catch (Exception e) {
logger.error("Exception occured while restarting RDF4J. ");
logger.debug(e.toString());
} finally {
_sys = null;
}
}
// reset important properties
this.firstBindingSetValueMap = null;
// this._sys.setInitialized(false);
this.initialize();
logger.info("RDF4J restarted");
} catch (RuntimeException e) {
logger.fatal("Cannot restart RDF4J");
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String stacktrace = sw.toString();
logger.fatal(stacktrace);
}
}
// Bypass translation for RDF4J
@Override
public String translateQuery(String query, String label
) {
return query;
}
@Override
public IGeographicaSystem getGeographicaSystem() {
return this._sys;
}
/**
* By default RDF4J based SUT do not use a server component, therefore the
* default functionality is left empty.
*/
@Override
public void startServer() {
}
/**
* By default RDF4J based SUT do not use a server component, therefore the
* default functionality is left empty.
*/
@Override
public void stopServer() {
}
}
| tioannid/geordfbench | runtime/src/main/java/gr/uoa/di/rdf/Geographica3/runtime/sut/impl/RDF4JBasedSUT.java |
43,829 | package gr.aueb.cf.schoolapp;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.border.LineBorder;
import java.awt.Toolkit;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TeachersSearchForm extends JFrame {
private static final long serialVersionUID = 123456;
private JPanel contentPane;
private JTextField lastnameTxt;
private String lastname = "";
public TeachersSearchForm() {
addWindowListener(new WindowAdapter() {
@Override
public void windowActivated(WindowEvent e) {
lastnameTxt.setText("");
}
});
setTitle("Εισαγωγή / Αναζήτηση Εκπαιδευτή");
setIconImage(Toolkit.getDefaultToolkit().getImage(TeachersSearchForm.class.getResource("/resources/eduv2.png")));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 530, 451);
setLocationRelativeTo(null);
contentPane = new JPanel();
contentPane.setBackground(new Color(245, 255, 250));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
lastnameTxt = new JTextField();
lastnameTxt.setBounds(142, 89, 201, 37);
contentPane.add(lastnameTxt);
lastnameTxt.setColumns(10);
JLabel lblLastname = new JLabel("Επώνυμο");
lblLastname.setBounds(202, 58, 73, 20);
lblLastname.setFont(new Font("Tahoma", Font.BOLD, 16));
lblLastname.setForeground(new Color(160, 82, 45));
contentPane.add(lblLastname);
JButton SearchBtn = new JButton("Αναζήτηση");
SearchBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
lastname = lastnameTxt.getText();
Main.getTeachersUpdateDeleteForm().setVisible(true);
Main.getTeachersSearchForm().setEnabled(false);
}
});
SearchBtn.setFont(new Font("Tahoma", Font.PLAIN, 16));
SearchBtn.setForeground(new Color(0, 0, 255));
SearchBtn.setBounds(186, 137, 113, 37);
contentPane.add(SearchBtn);
JPanel panel = new JPanel();
panel.setBorder(new LineBorder(new Color(0, 0, 0)));
panel.setBounds(102, 40, 289, 161);
contentPane.add(panel);
JButton insertBtn = new JButton("Εισαγωγή");
insertBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Main.getTeachersInsertForm().setVisible(true);
Main.getTeachersSearchForm().setEnabled(false);
}
});
insertBtn.setFont(new Font("Tahoma", Font.PLAIN, 16));
insertBtn.setForeground(new Color(0, 0, 255));
insertBtn.setBounds(186, 238, 113, 37);
contentPane.add(insertBtn);
JPanel panel_1 = new JPanel();
panel_1.setBounds(102, 212, 289, 99);
contentPane.add(panel_1);
JButton closeBtn = new JButton("Close");
closeBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Main.getMenu().setEnabled(true);
Main.getTeachersSearchForm().setVisible(false);
}
});
closeBtn.setFont(new Font("Tahoma", Font.PLAIN, 16));
closeBtn.setForeground(new Color(0, 0, 255));
closeBtn.setBounds(302, 345, 89, 37);
contentPane.add(closeBtn);
}
public String getLastname() {
return lastname;
}
}
| LiontosDionisis/school-app | src/gr/aueb/cf/schoolapp/TeachersSearchForm.java |
43,937 | package gr.aueb.cf.ch11;
import java.util.Scanner;
/**
* Student JavaBean
* Data Class + default constructor + setter / getters
*/
public class Student {
private static int instancesCount ;
private int id;
private String firstname;
private String lastname;
private static Scanner in;
static {
in = new Scanner(System.in);
int num = in.nextInt();
instancesCount = (num == 1) ? 1 : 0;
}
public Student() {
instancesCount++;
}
// default constructor
// public Student() {
// id =0; // default constructor // αν δηλώσουμε τον Overloaded και θελουμε και τον default τοτε πρεπει να τον δηλωσουμε και τν default
// firstname = null;
// lastname = null;
// }
// Overloaded constructor
public Student(int id, String firstname, String lastname) {
this.id = id;
this.firstname = firstname;
this.lastname = lastname;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getFirstname() {
return firstname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getLastname() {
return lastname;
}
public static int getInstancesCount() {
return instancesCount;
}
}
| dimisysk/java-coding-factory | src/gr/aueb/cf/ch11/Student.java |
43,980 | package gr.aueb.cf.ch5;
/**
* δηλωση και αρχικοποίηση float & double
*/
public class DeclarationsApp {
public static void main(String[] args) {
float f = 30.5F;
float age = 25F;
double d = 19.35;
double price = 182D;
}
}
| KruglovaOlga/CodingFactoryJava | src/gr/aueb/cf/ch5/DeclarationsApp.java |
44,022 | package com.example.e_med_help.controllers;
import com.example.e_med_help.dtos.LoginUserDto;
import com.example.e_med_help.dtos.NewUserDto;
import com.example.e_med_help.models.Role;
import com.example.e_med_help.models.User;
import com.example.e_med_help.services.RolesServiceInterface;
import com.example.e_med_help.services.UsersServiceInterface;
import com.example.e_med_help.validators.LoginUserValidator;
import com.example.e_med_help.validators.NewUserDtoValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
@RequestMapping("/")
@Controller
public class MainController {
@Autowired
RolesServiceInterface rolesServiceInterface;
@Autowired
UsersServiceInterface usersServiceInterface;
@Autowired
PasswordEncoder passwordEncoder;
@Autowired
NewUserDtoValidator newUserDtoValidator;
@Autowired
LoginUserValidator loginUserValidator;
@GetMapping
public String welcomePage() {
return "index";
}
@InitBinder("LoginUserDto")// Εδω θα βαλεις το object που θες να κανεις validate
public void setupBinder1(WebDataBinder binder) {
binder.addValidators(loginUserValidator);
}
@GetMapping(value = "/registerForm")
public String registerForm(ModelMap mm) {
NewUserDto newUser = new NewUserDto();
mm.addAttribute("roles", rolesServiceInterface.getAllRoles());
mm.addAttribute("newUser", newUser);
return "addUser";
}
@GetMapping(value = "/shoppingbasket")
public String shoppingBasket() {
return "shoppingbasket";
}
@GetMapping(value = "/payment")
public String payment() {
return "payment";
}
@GetMapping(value = "/contact")
public String contact() {
return "contact";
}
@PostMapping(value = "/addUser")
public String addUser(@Valid @ModelAttribute(name = "newUser") NewUserDto newUser,
BindingResult br,
ModelMap mm) {
if (br.hasErrors()) {
mm.addAttribute("roles", rolesServiceInterface.getAllRoles());
return "addUser";
}
User temp = new User();
Role role = rolesServiceInterface.getById(newUser.getRole());
if (role != null) {
temp.setURoleId(role);
} else {
return "error";
}
temp.setUName(newUser.getName());
temp.setUSurname(newUser.getSurname());
temp.setULoginname(newUser.getUsername());
temp.setUPassword(passwordEncoder.encode(newUser.getPassword1()));
usersServiceInterface.insertUser(temp);
return "index";
}
@GetMapping(value = "/loginForm")
public String loginForm(ModelMap mm) {
mm.addAttribute("LoginUserDto", new LoginUserDto());
return "login";
}
@PostMapping(value = "/login")
public String login(@Valid @ModelAttribute(name = "LoginUserDto") LoginUserDto user,
BindingResult br,
HttpSession session,
ModelMap mm) {
if (br.hasErrors()) {
return "login";
}
User current = usersServiceInterface.getUserByUsername(user.getLousername());
System.out.println(current);
session.setAttribute("user", current);
if (current.getURoleId().getRoleId() == 2) {
return "redirect:physician/home";
}
if (current.getURoleId().getRoleId() == 3) {
return "redirect:pharmacist/home";
}
if (current.getURoleId().getRoleId() == 1) {
return "redirect:/patient/home";
} else return "login";
}
@ResponseBody
@PostMapping(value = "/checkUsername/{username}")
public boolean checkUsername(@PathVariable(name = "username") String username) {
User user = usersServiceInterface.getUserByUsername(username);
return (user != null);
}
}
| e-Med-Tech/e-med-help | src/main/java/com/example/e_med_help/controllers/MainController.java |
44,048 | package gr.aueb.softeng.project1801.dao;
import java.util.HashSet;
import java.util.Set;
import gr.aueb.softeng.project1801.DomainModel.Bus;
import gr.aueb.softeng.project1801.DomainModel.Card;
import gr.aueb.softeng.project1801.DomainModel.Driver;
import gr.aueb.softeng.project1801.DomainModel.Passenger;
import gr.aueb.softeng.project1801.DomainModel.Route;
import gr.aueb.softeng.project1801.DomainModel.Schedule;
import gr.aueb.softeng.project1801.DomainModel.ScheduleEntry;
import gr.aueb.softeng.project1801.SysUtils.SystemCalendar;
/**
* This class undertakes to initialize the data in the database.
* Provides data for the examples and control tests.
*/
public abstract class Initializer {
/**
* This method deletes all the saved data.
*/
protected abstract void eraseData();
/**
* This method inserts the training data.
*/
public void prepareData(){
//erase the data first
eraseData();
PassengerDAO passengerDAO = getPassengerData();
passengerDAO.save(new Passenger("Sot","Kot","SK123"));
CardDAO cardDAO = getCardData();
SystemCalendar calendar = new SystemCalendar(2020,4,14);
cardDAO.save(new Card("Sot Kot","1213343553",calendar,540));
passengerDAO.find("SK123").addCard(cardDAO.find("Sot Kot"));
BusDAO busDAO = getBusData();
busDAO.save(new Bus("Type1", "Mercedes", "AR1314",30));
busDAO.save(new Bus("Type2","Scania","SC1496",30));
busDAO.save(new Bus("Type1","Honda","H1269",30));
busDAO.save(new Bus("Type3","Scania","SC1269",30));
busDAO.save(new Bus("Type2","Ford","F1269",30));
busDAO.save(new Bus("Type4","Mercedes","M269",30));
busDAO.save(new Bus("Type3","Mercedes","M270",30));
busDAO.save(new Bus("Type1","Toyota","T260",30));
busDAO.save(new Bus("Type2","Scania","S220",30));
busDAO.save(new Bus("Type3","Ford","F265",30));
DriverDAO driverData = getDriverData();
driverData.save(new Driver("Anastasios Lepipas", "AL1997"));
driverData.save(new Driver("George Chatzo","GC1997"));
driverData.save(new Driver("Sotiris Kotitsas","SK1997"));
driverData.save(new Driver("Giannis Bouzios","GB1997"));
driverData.save(new Driver("Sotiris Vasileiou","SV1997"));
driverData.save(new Driver("Petros Dimitrakopoulos","PD1997"));
driverData.save(new Driver("Sot Kot","SP1997"));
driverData.save(new Driver("Rafaella Kot","RK1997"));
RouteDAO routeDAO = getRouteData();
SystemCalendar calendar1 = new SystemCalendar(2018,4,23);
SystemCalendar calendar2 = new SystemCalendar(2018,4,12);
SystemCalendar calendar3 = new SystemCalendar(2018,4,30);
SystemCalendar calendar4 = new SystemCalendar(2018,5,1);
SystemCalendar calendar5 = new SystemCalendar(2018,5,3);
SystemCalendar calendar6 = new SystemCalendar(2018,5,1);
routeDAO.save(new Route("Αθηνα","9:00AM","Ναυπλιο", calendar1,
"11:00PM", busDAO.find("AR1314"),driverData.find("AL1997")));
routeDAO.save(new Route("Πατρα","9:00AM","Αθηνα",calendar2,
"11:30PM", busDAO.find("SC1496"),driverData.find("GC1997")));
routeDAO.save(new Route("Θεσσαλονικη","2:15PM","Αθηνα",calendar3,
"8:15PM", busDAO.find("H1269"), driverData.find("SK1997")));
routeDAO.save(new Route("Χαλκιδα","10:30AM","Αθηνα",calendar4,
"11:30AM", busDAO.find("SC1269"),driverData.find("GB1997")));
routeDAO.save(new Route("Βολος","12:30AM","Αργος",calendar5,
"5:00PM", busDAO.find("F1269"),driverData.find("SV1997")));
routeDAO.save(new Route("Λαρισα","11:30AM","Θεσσαλονικη",calendar6,
"2:00PM", busDAO.find("M269"),driverData.find("PD1997")));
ScheduleDAO scheduleDAO = getScheduleData();
Set<String> Destinations = new HashSet<>();
Set<String> DeparturePoints = new HashSet<>();
Set<String> DepartureTimes = new HashSet<>();
Set<SystemCalendar> DepartureDates = new HashSet<>();
Destinations.add("Αθηνα");
Destinations.add("Πατρα");
Destinations.add("Θεσσαλονικη");
Destinations.add("Χαλκιδα");
Destinations.add("Βολος");
Destinations.add("Λαρισα");
Destinations.add("Ασπροπυργος");
Destinations.add("Ελευσινα");
Destinations.add("Ισθμος");
Destinations.add("Μεγαρα");
Destinations.add("Αδαμι");
Destinations.add("Αγιοι Αποστολοι");
Destinations.add("Αγναντα");
Destinations.add("Αρχαια Επιδαυρος");
Destinations.add("Αρχαια Τιρινθα");
Destinations.add("Αργος");
Destinations.add("Δαλαμαναρα");
Destinations.add("Δριοπι");
Destinations.add("Φουρνη");
Destinations.add("Γαλατας");
Destinations.add("Καλλονη");
Destinations.add("Κρανιδι");
Destinations.add("Λιγουριο");
Destinations.add("Πορτοχελι");
Destinations.add("Τριζινα");
Destinations.add("Κουτσοποδι");
DeparturePoints.add("Αθηνα");
DeparturePoints.add("Θεσσαλονικη");
DeparturePoints.add("Ναυπλιο");
DeparturePoints.add("Αργος");
DeparturePoints.add("Γαλατας");
DeparturePoints.add("Ισθμος");
DeparturePoints.add("Κρανιδι");
DeparturePoints.add("Μεθανα");
DeparturePoints.add("Τριπολη");
DeparturePoints.add("Βιτινα");
DeparturePoints.add("Χαλεπα");
DeparturePoints.add("Κιβερι");
DeparturePoints.add("Νεα Κιος");
DeparturePoints.add("Πατρα");
DeparturePoints.add("Λιγουριο");
DeparturePoints.add("Καργια");
DeparturePoints.add("Χουνη");
DeparturePoints.add("Δρεπανο");
DeparturePoints.add("Τολο");
DeparturePoints.add("Καλαματα");
DeparturePoints.add("Κουτσοποδι");
DepartureTimes.add("7:00PM");
DepartureTimes.add("8:00PM");
DepartureTimes.add("9:00PM");
DepartureTimes.add("10:00PM");
DepartureTimes.add("11:00PM");
DepartureTimes.add("12:00PM");
DepartureTimes.add("1:00AM");
DepartureTimes.add("2:00AM");
DepartureTimes.add("3:00AM");
DepartureTimes.add("4:00AM");
DepartureTimes.add("5:00AM");
DepartureTimes.add("6:00AM");
DepartureTimes.add("7:00AM");
DepartureTimes.add("8:00AM");
DepartureTimes.add("9:00AM");
DepartureTimes.add("10:00AM");
DepartureTimes.add("11:00AM");
DepartureTimes.add("12:00AM");
Schedule schedule = new Schedule();
schedule.setDestinations(Destinations);
schedule.setDeparturePoints(DeparturePoints);
schedule.setDepartureTimes(DepartureTimes);
schedule.setDepartureDates(DepartureDates);
schedule.addNewRoute(routeDAO.find("Αθηνα","9:00AM","Ναυπλιο", calendar1));
schedule.addNewRoute(routeDAO.find("Πατρα","9:00AM","Αθηνα",calendar2));
schedule.addNewRoute(routeDAO.find("Θεσσαλονικη","2:15PM","Αθηνα",calendar3));
schedule.addNewRoute(routeDAO.find("Χαλκιδα","10:30AM","Αθηνα",calendar4));
schedule.addNewRoute(routeDAO.find("Βολος","12:30AM","Αργος",calendar5));
schedule.addNewRoute(routeDAO.find("Λαρισα","11:30AM","Θεσσαλονικη",calendar6));
for(Route route: schedule.getRoutes()){
ScheduleEntry entry = new ScheduleEntry(route.getDepartureTime(),route.getDepartureDate());
schedule.addScheduleEntry(entry);
}
scheduleDAO.save(schedule);
}
/**
* This method returns the bus data.
* @return the bus data
*/
public abstract BusDAO getBusData();
/**
* This method returns the card data.
* @return the card data
*/
public abstract CardDAO getCardData();
/**
* This method returns the passenger data.
* @return the passenger data
*/
public abstract PassengerDAO getPassengerData();
/**
* This method returns the driver data.
* @return the driver data
*/
public abstract DriverDAO getDriverData();
/**
* This method returns the route data.
* @return the route data
*/
public abstract RouteDAO getRouteData();
/**
* This method returns the schedule data.
* @return the schedule data
*/
public abstract ScheduleDAO getScheduleData();
}
| SotirisKot/BusTicketReservation | app/src/main/java/gr/aueb/softeng/project1801/dao/Initializer.java |
44,062 | package gr.cti.eslate.scripting.logo;
import java.util.*;
/**
* Greek language localized strings for the bar chart component primitive group.
*
* @version 1.0.6, 21-Jan-2008
* @author Augustine Gryllakis
* @author Kriton Kyrimis
*/
public class BarChartPrimitivesBundle_el extends ListResourceBundle {
public Object[][] getContents() {
return contents;
}
static final Object[][] contents = {
{ "BARCHART.ZOOM", "ΡΑΒΔΟΓΡΑΜΜΑ.ΕΜΒΑΘΥΝΣΗ" },
{ "BARCHART.SETXAXISFIELD", "ΡΑΒΔΟΓΡΑΜΜΑ.ΘΕΣΕΠΕΔΙΟΑΞΟΝΑΧ" },
{ "BARCHART.SETYAXISFIELD", "ΡΑΒΔΟΓΡΑΜΜΑ.ΘΕΣΕΠΕΔΙΟΑΞΟΝΑΨ" },
{ "BARCHART.XAXISFIELD", "ΡΑΒΔΟΓΡΑΜΜΑ.ΠΕΔΙΟΑΞΟΝΑΧ" },
{ "BARCHART.YAXISFIELD", "ΡΑΒΔΟΓΡΑΜΜΑ.ΠΕΔΙΟΑΞΟΝΑΨ" },
{ "BARCHART.YAXISMIN", "ΡΑΒΔΟΓΡΑΜΜΑ.ΕΛΑΧΙΣΤΟΑΞΟΝΑΨ" },
{ "BARCHART.YAXISMAX", "ΡΑΒΔΟΓΡΑΜΜΑ.ΜΕΓΙΣΤΟΑΞΟΝΑΨ" },
{ "BARCHART.YAXISORIGIN", "ΡΑΒΔΟΓΡΑΜΜΑ.ΑΡΧΗΑΞΟΝΑΨ" },
{ "BARCHART.ADDNUMBERDATASET", "ΡΑΒΔΟΓΡΑΜΜΑ.ΠΡΟΣΘΕΣΕΣΥΝΟΛΟΑΡΙΘΜΩΝ" },
{ "BARCHART.ADDNAMEDATASET", "ΡΑΒΔΟΓΡΑΜΜΑ.ΠΡΟΣΘΕΣΕΣΥΝΟΛΟΟΝΟΜΑΤΩΝ" },
{ "BARCHART.SETDATASET", "ΡΑΒΔΟΓΡΑΜΜΑ.ΘΕΣΕΣΥΝΟΛΟΔΕΔΟΜΕΝΩΝ" },
{ "BARCHART.REMOVEDATASET", "ΡΑΒΔΟΓΡΑΜΜΑ.ΑΦΑΙΡΕΣΕΣΥΝΟΛΟΔΕΔΟΜΕΝΩΝ" },
{ "BARCHART.SETELEMENT", "ΡΑΒΔΟΓΡΑΜΜΑ.ΘΕΣΕΣΤΟΙΧΕΙΟ" },
{ "BARCHART.ADDELEMENT", "ΡΑΒΔΟΓΡΑΜΜΑ.ΠΡΟΣΘΕΣΕΣΤΟΙΧΕΙΟ" },
{ "BARCHART.REMOVEELEMENT", "ΡΑΒΔΟΓΡΑΜΜΑ.ΑΦΑΙΡΕΣΕΣΤΟΙΧΕΙΟ" },
{ "BARCHART.ELEMENT", "ΡΑΒΔΟΓΡΑΜΜΑ.ΣΤΟΙΧΕΙΟ" },
{ "BARCHART.DATASET", "ΡΑΒΔΟΓΡΑΜΜΑ.ΣΥΝΟΛΟΔΕΔΟΜΕΝΩΝ" },
{ "BARCHART.TITLES", "ΡΑΒΔΟΓΡΑΜΜΑ.ΤΙΤΛΟΙ" },
{ "BARCHART.SETTITLE", "ΡΑΒΔΟΓΡΑΜΜΑ.ΘΕΣΕΤΙΤΛΟ" },
{ "CantUseX", "Δεν μπορείτε να χρησιμοποιήσετε το πεδίο {0} στον άξονα των Χ" },
{ "CantUseY", "Δεν μπορείτε να χρησιμοποιήσετε το πεδίο {0} στον άξονα των Ψ" },
};
}
| vpapakir/myeslate | widgetESlate/src/gr/cti/eslate/scripting/logo/BarChartPrimitivesBundle_el.java |
44,068 | package gr.cti.eslate.scripting.logo;
import java.util.ListResourceBundle;
/**
* User: yiorgos
* Date: 17 Δεκ 2007
* Time: 12:17:59 μμ
*/
public class ContainerPrimitivesBundle_el_GR extends ListResourceBundle {
public Object [][] getContents() {
return contents;
}
static final Object[][] contents={
{"CLEARMICROWORLD", "ΑΒ.ΚΑΘΑΡΙΣΜΟΣΜΙΚΡΟΚΟΣΜΟΥ"},
{"PACKMICROWORLD", "ΑΒ.ΠΑΚΕΤΑΡΙΣΜΑ"},
{"SAVEMICROWORLD", "ΑΒ.ΑΠΟΘΗΚΕΥΣΗ"},
{"SAVEMICROWORLDAS", "ΑΒ.ΑΠΟΘΗΚΕΥΣΗΩΣ"},
{"LOADMICROWORLD", "ΑΒ.ΑΝΟΙΓΜΑΜΙΚΡΟΚΟΣΜΟΥ"},
{"CLOSEMICROWORLD", "ΑΒ.ΚΛΕΙΣΙΜΟΜΙΚΡΟΚΟΣΜΟΥ"},
{"PRINTMICROWORLD", "ΑΒ.ΕΚΤΥΠΩΣΗΜΙΚΡΟΚΟΣΜΟΥ"},
{"SETMICROWORLDBACKGROUND", "ΑΒ.ΥΠΟΒΑΘΡΟ"},
{"CREATECOMPONENT", "ΑΒ.ΝΕΑΨΗΦΙΔΑ"},
{"SHOWPLUGVIEW", "ΑΒ.ΕΜΦΑΝΙΣΗΔΙΑΧΕΙΡΙΣΤΗΣΥΝΔΕΣΜΩΝ"},
{"CLOSEPLUGVIEW", "ΑΒ.ΚΛΕΙΣΙΜΟΔΙΑΧΕΙΡΙΣΤΗΣΥΝΔΕΣΜΩΝ"},
{"PLUGVIEWVISIBLE", "ΑΒ.ΔΙΧΕΙΡΙΣΤΗΣΣΥΝΔΕΣΜΩΝΟΡΑΤΟΣ"},
{"SETMICROWORLDNAME", "ΑΒ.ΘΕΣΕΟΝΟΜΑΜΙΚΡΟΚΟΣΜΟΥ"},
{"MICROWORLDNAME", "ΑΒ.ΟΝΟΜΑΜΙΚΡΟΚΟΣΜΟΥ"},
{"MICROWORLDFOLDER", "ΑΒ.ΘΕΣΗΑΡΧΕΙΟΥΜΙΚΡΟΚΟΣΜΟΥ"},
{"ESLATEFOLDER", "ΑΒ.ΘΕΣΗΑΒΑΚΙΟΥ"},
{"COMPONENTCOUNT", "ΑΒ.ΑΡΙΘΜΟΣΨΗΦΙΔΩΝ"},
{"BACK", "ΑΒ.ΠΡΟΗΓΟΥΜΕΝΟΣΜΙΚΡΟΚΟΣΜΟΣ"},
{"FORWARD", "ΑΒ.ΕΠΟΜΕΝΟΣΜΙΚΡΟΚΟΣΜΟΣ"},
{"SETSCRIPT", "ΑΒ.ΘΕΣΕΠΡΟΓΡΑΜΜΑ"},
{"SHOWVIEW", "ΑΒ.ΠΡΟΒΟΛΗΟΨΗΣ"},
{"VIEWNAMES", "ΑΒ.ΟΝΟΜΑΤΑΟΨΕΩΝ"},
{"NEXTVIEW", "ΑΒ.ΕΠΟΜΕΝΗΟΨΗ"},
{"PREVIOUSVIEW", "ΑΒ.ΠΡΟΗΓΟΥΜΕΝΗΟΨΗ"},
};
}
| vpapakir/myeslate | widgetESlate/src/gr/cti/eslate/scripting/logo/ContainerPrimitivesBundle_el_GR.java |
44,073 | package gr.cti.eslate.scripting.logo;
import java.util.ListResourceBundle;
/**
* User: yiorgos
* Date: 17 Δεκ 2007
* Time: 11:55:56 πμ
*/
public class ContainerComponentPrimitivesBundle_el_GR extends ListResourceBundle {
public Object [][] getContents() {
return contents;
}
static final Object[][] contents={
{"MOVE", "ΑΒ.ΜΕΤΑΚΙΝΗΣΗ"},
{"LOCATION", "ΑΒ.ΘΕΣΗ"},
{"MAXIMIZE", "ΑΒ.ΜΕΓΙΣΤΟΠΟΙΗΣΗ"},
{"HIDE", "ΑΒ.ΑΠΟΚΡΥΨΗ"},
{"RESTORE", "ΑΒ.ΑΠΟΚΑΤΑΣΤΑΣΗ"},
{"SETRESIZABLE", "ΑΒ.ΘΕΣΕΜΕΓΕΘΟΣΜΕΤΑΒΑΛΛΟΜΕΝΟ"},
{"SETUNRESIZABLE", "ΑΒ.ΘΕΣΕΜΕΓΕΘΟΣΣΤΑΘΕΡΟ"},
{"RESIZABLE", "ΑΒ.ΜΕΤΑΒΑΛΛΟΜΕΝΟΜΕΓΕΘΟΣ"},
{"SETTITLEON", "ΑΒ.ΕΜΦΑΝΙΣΗΤΙΤΛΟΥ"},
{"SETTITLEOFF", "ΑΒ.ΑΠΟΚΡΥΨΗΤΙΤΛΟΥ"},
{"CLOSECOMPONENT", "ΑΒ.ΚΛΕΙΣΙΜΟ"},
{"ACTIVATECOMPONENT", "ΑΒ.ΕΝΕΡΓΟΠΟΙΗΣΗ"},
{"DEACTIVATECOMPONENT", "ΑΒ.ΑΠΕΝΕΡΓΟΠΟΙΗΣΗ"},
{"SETCOMPONENTSIZE", "ΑΒ.ΘΕΣΕΜΕΓΕΘΟΣ"},
{"COMPONENTSIZE", "ΑΒ.ΜΕΓΕΘΟΣ"},
{"SETCOMPONENTBOUNDS", "ΑΒ.ΘΕΣΕΔΙΑΣΤΑΣΕΙΣ"},
{"COMPONENTBOUNDS", "ΑΒ.ΔΙΑΣΤΑΣΕΙΣ"},
{"PRINTCOMPONENT", "ΑΒ.ΕΚΤΥΠΩΣΗ"},
};
}
| vpapakir/myeslate | widgetESlate/src/gr/cti/eslate/scripting/logo/ContainerComponentPrimitivesBundle_el_GR.java |
44,122 |
package com.example.theophilos.citizenprotectionproject.activities;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.theophilos.citizenprotectionproject.JsonApi;
import com.example.theophilos.citizenprotectionproject.R;
import com.example.theophilos.citizenprotectionproject.objects.SessionInfo;
import com.example.theophilos.citizenprotectionproject.objects.UserInfo;
import com.example.theophilos.citizenprotectionproject.objects.HealthCheck;
import com.example.theophilos.citizenprotectionproject.utilities.KeyboardUtils;
import java.security.cert.CertificateException;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class LoginActivity extends AppCompatActivity {
private TextView textViewResult;
private boolean ISOPEN = false;
private boolean FLAG = false;
public Retrofit retrofit = new Retrofit.Builder()
// .baseUrl("https://10.0.2.2:9000")
.baseUrl("https://83.212.76.248:9000")
.addConverterFactory(GsonConverterFactory.create())
.client( getUnsafeOkHttpClient().build())
.build();
private AsyncTask<Void,Void,Void> loginTask;
private final SessionInfo sInfo = null;
private class loginTask extends AsyncTask<Void,Void,Void> {
@Override
protected void onCancelled() {
Toast.makeText(getApplicationContext(),"OPA",Toast.LENGTH_SHORT).show();
}
@Override
protected Void doInBackground(Void... voids) {
if (!isCancelled()) {
EditText userText = (EditText) findViewById(R.id.userNameTextField);
EditText passText = (EditText) findViewById(R.id.passwordTextField);
UserInfo userInfo = new UserInfo(userText.getText().toString(), passText.getText().toString());
JsonApi jsonApi = retrofit.create(JsonApi.class);
Call<SessionInfo> call = jsonApi.login(userInfo);
call.enqueue(new Callback<SessionInfo>() {
@Override
public void onResponse(Call<SessionInfo> call, Response<SessionInfo> response) {
if (!response.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Αποτυχία Σύνδεσης", Toast.LENGTH_LONG).show();
return;
}
//Save token here
SessionInfo sInfo = response.body();
if ( sInfo.getUserType() != 2 ){
Toast.makeText(getApplicationContext(), "Αποτυχία Σύνδεσης", Toast.LENGTH_LONG).show();
return;
}
SharedPreferences preferences = LoginActivity.this.getSharedPreferences("MY_APP", Context.MODE_PRIVATE);
preferences.edit().putString("TOKEN", sInfo.getToken()).apply();
preferences.edit().putString("ID", sInfo.get_id()).apply();
preferences.edit().putString("USRNAME", sInfo.getUsername()).apply();
preferences.edit().putString("LAT", sInfo.getDetails().getLat()).apply();
preferences.edit().putString("LON", sInfo.getDetails().getLon()).apply();
preferences.edit().putString("FNAME", sInfo.getName().getFirstname()).apply();
preferences.edit().putString("LNAME", sInfo.getName().getLastname()).apply();
preferences.edit().putString("DEPID", sInfo.getDetails().getDepartmentId()).apply();
final Intent intent = new Intent(getApplicationContext(), AcceptedIncidentsActivity.class);
intent.putExtra("exitFlag","true");
if (sInfo != null && sInfo.getUserType() == 2 && !isCancelled()) {
startActivity(intent);
}
else if(!isCancelled()){
Toast.makeText(getApplicationContext(), "Αποτυχία Σύνδεσης", Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<SessionInfo> call, Throwable t) {
Toast.makeText(getApplicationContext(), "Αποτυχία Σύνδεσης", Toast.LENGTH_LONG).show();
}
});
}
return null;
}
}
public void login( View view ){
if( loginTask != null ) {
loginTask.cancel(true);
}
loginTask = new loginTask();
loginTask.execute();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
JsonApi jsonApi = retrofit.create(JsonApi.class);
Call<HealthCheck> call = jsonApi.getHealthCheck();
final LinearLayout linearLayout = findViewById(R.id.linearLayout);
KeyboardUtils.addKeyboardToggleListener( this , new KeyboardUtils.SoftKeyboardToggleListener()
{
@Override
public void onToggleSoftKeyboard(boolean isVisible)
{
if ( ISOPEN ){
setMargins( linearLayout , 18 , 350 , 0 , 0 );
ISOPEN = false;
}
else{
if ( FLAG ){
setMargins( linearLayout , 18 , 100 , 0 , 0 );
ISOPEN = true;
}
else{
FLAG = true;
}
}
}
});
call.enqueue(new Callback<HealthCheck>() {
@Override
public void onResponse(Call<HealthCheck> call, Response<HealthCheck> response) {
if(!response.isSuccessful()) {
textViewResult.setText("Code: "+ response.code());
return;
}
HealthCheck check = response.body();
}
@Override
public void onFailure(Call<HealthCheck> call, Throwable t) {
}
});
}
private void setMargins (View view, int left, int top, int right, int bottom) {
if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
p.setMargins(left, top, right, bottom);
view.requestLayout();
}
}
public static OkHttpClient.Builder getUnsafeOkHttpClient() {
try {
// Create a trust manager that does not validate certificate chains
final TrustManager[] trustAllCerts;
trustAllCerts = new TrustManager[]{
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
}
};
// Install the all-trusting trust manager
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
// Create an ssl socket factory with our all-trusting manager
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
builder.hostnameVerifier(new HostnameVerifier() {
private String hostname;
private SSLSession session;
@Override
public boolean verify(String hostname, SSLSession session) {
this.hostname = hostname;
this.session = session;
return true;
}
});
return builder;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void onBackPressed(){
return;
}
}
| pelekoudasq/CitizenProtectionProject | mobile-app/app/src/main/java/com/example/theophilos/citizenprotectionproject/activities/LoginActivity.java |
44,146 | //DIONYSIOS THEODOSIS AM:321/2015066 2H OMADIKH KATANEMHMENA
package clientgui;
import shared.FlightService;
import java.rmi.RemoteException;
import shared.FlightBooking;
import javax.swing.JOptionPane;
import static mytools.StringDate.*;
//KLASH GIA TO PANEL THN MONHS PTHSHS
public class OneWayPanel extends javax.swing.JPanel {
//PARAMETROI KLASHS
private final FlightBooking flight; //PARAMETROS GIA TIS KRATHSEIS
private final FlightService flightService; //PARAMETROS GIA THN METAVLITI SYNDESHS-INTERFACE
//CONSTRUCTOR KLASHS POU DEXETAI TIS KRATHSEIS KAI THN PARAMETRO TOU INTERFACE SUNDESHS
public OneWayPanel(FlightBooking flight,FlightService flightService) {
this.flight=flight;
this.flightService=flightService;
initComponents(); //KALEI THN METHODO THS ARXEIKOPOIHSHS TOU PANEL
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
MainPanel = new javax.swing.JPanel();
departureRoutePanel = new javax.swing.JPanel();
departureTitle = new javax.swing.JLabel();
flightRouteLabel = new javax.swing.JLabel();
flightCredPanel = new javax.swing.JPanel();
departurePanel = new javax.swing.JPanel();
departureTimeLabel = new javax.swing.JLabel();
departureAirCLabel = new javax.swing.JLabel();
arrivalPanel = new javax.swing.JPanel();
arrivalTimeLabel = new javax.swing.JLabel();
arrivalAirCLabel = new javax.swing.JLabel();
departureDateLabel = new javax.swing.JLabel();
availableSeatsPanel = new javax.swing.JPanel();
availableSeatsTLabel = new javax.swing.JLabel();
availableSeatsNLabel = new javax.swing.JLabel();
priceTitleLabel = new javax.swing.JLabel();
priceNLabel = new javax.swing.JLabel();
bookingButton = new javax.swing.JButton();
MainPanel.setBackground(java.awt.Color.lightGray);
departureRoutePanel.setBackground(java.awt.Color.lightGray);
departureTitle.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
departureTitle.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
departureTitle.setText("Αναχώρηση:");
flightRouteLabel.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
flightRouteLabel.setText(flight.getOutboundFlight().getOrigin()+"-"+flight.getOutboundFlight().getDestination());
javax.swing.GroupLayout departureRoutePanelLayout = new javax.swing.GroupLayout(departureRoutePanel);
departureRoutePanel.setLayout(departureRoutePanelLayout);
departureRoutePanelLayout.setHorizontalGroup(
departureRoutePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(departureRoutePanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(departureTitle, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(flightRouteLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 259, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(213, Short.MAX_VALUE))
);
departureRoutePanelLayout.setVerticalGroup(
departureRoutePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(departureRoutePanelLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(departureRoutePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(departureTitle, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(flightRouteLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)))
);
flightCredPanel.setBackground(new java.awt.Color(255, 255, 255));
departurePanel.setOpaque(false);
departureTimeLabel.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
departureTimeLabel.setText(flight.getOutboundFlight().getOriginAirportId());
departureAirCLabel.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
departureAirCLabel.setText(flight.getOutboundFlight().getDepartureDate().getHour()+":"+flight.getOutboundFlight().getDepartureDate().getMinute());
javax.swing.GroupLayout departurePanelLayout = new javax.swing.GroupLayout(departurePanel);
departurePanel.setLayout(departurePanelLayout);
departurePanelLayout.setHorizontalGroup(
departurePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(departurePanelLayout.createSequentialGroup()
.addContainerGap(36, Short.MAX_VALUE)
.addComponent(departureAirCLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(departureTimeLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
departurePanelLayout.setVerticalGroup(
departurePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(departurePanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(departurePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(departureAirCLabel)
.addComponent(departureTimeLabel))
.addContainerGap())
);
arrivalPanel.setOpaque(false);
arrivalTimeLabel.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
arrivalTimeLabel.setText(flight.getOutboundFlight().getDestinationAirportId());
arrivalAirCLabel.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
arrivalAirCLabel.setText(flight.getOutboundFlight().getArrivalDate().toLocalTime().getHour()+":"+flight.getOutboundFlight().getArrivalDate().toLocalTime().getMinute());
javax.swing.GroupLayout arrivalPanelLayout = new javax.swing.GroupLayout(arrivalPanel);
arrivalPanel.setLayout(arrivalPanelLayout);
arrivalPanelLayout.setHorizontalGroup(
arrivalPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(arrivalPanelLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(arrivalAirCLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(arrivalTimeLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
arrivalPanelLayout.setVerticalGroup(
arrivalPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(arrivalPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(arrivalPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(arrivalAirCLabel)
.addComponent(arrivalTimeLabel))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
departureDateLabel.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
departureDateLabel.setText(formatDate(flight.getOutboundFlight().getDepartureDate().toLocalDate()));
availableSeatsPanel.setOpaque(false);
availableSeatsTLabel.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
availableSeatsTLabel.setText("Θέσεις:");
availableSeatsNLabel.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
availableSeatsNLabel.setText(String.valueOf(flight.getOutboundFlight().getAvailableSeats()));
javax.swing.GroupLayout availableSeatsPanelLayout = new javax.swing.GroupLayout(availableSeatsPanel);
availableSeatsPanel.setLayout(availableSeatsPanelLayout);
availableSeatsPanelLayout.setHorizontalGroup(
availableSeatsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(availableSeatsPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(availableSeatsTLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(availableSeatsNLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
availableSeatsPanelLayout.setVerticalGroup(
availableSeatsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(availableSeatsPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(availableSeatsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(availableSeatsTLabel)
.addComponent(availableSeatsNLabel)))
);
javax.swing.GroupLayout flightCredPanelLayout = new javax.swing.GroupLayout(flightCredPanel);
flightCredPanel.setLayout(flightCredPanelLayout);
flightCredPanelLayout.setHorizontalGroup(
flightCredPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(flightCredPanelLayout.createSequentialGroup()
.addGroup(flightCredPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(flightCredPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(departurePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(60, 60, 60)
.addComponent(arrivalPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(availableSeatsPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(flightCredPanelLayout.createSequentialGroup()
.addGap(199, 199, 199)
.addComponent(departureDateLabel)))
.addGap(0, 0, Short.MAX_VALUE))
);
flightCredPanelLayout.setVerticalGroup(
flightCredPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, flightCredPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(departureDateLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(flightCredPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(arrivalPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(departurePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(flightCredPanelLayout.createSequentialGroup()
.addComponent(availableSeatsPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
priceTitleLabel.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
priceTitleLabel.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
priceTitleLabel.setText("Τιμή:");
priceNLabel.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
priceNLabel.setText(Double.toString(flight.getPrice())+"€");
priceNLabel.setToolTipText("");
bookingButton.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
bookingButton.setText("Κάνε Κράτηση");
bookingButton.setFocusable(false);
bookingButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bookingButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout MainPanelLayout = new javax.swing.GroupLayout(MainPanel);
MainPanel.setLayout(MainPanelLayout);
MainPanelLayout.setHorizontalGroup(
MainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(MainPanelLayout.createSequentialGroup()
.addGroup(MainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(departureRoutePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(MainPanelLayout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(flightCredPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(MainPanelLayout.createSequentialGroup()
.addGap(200, 200, 200)
.addComponent(bookingButton, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, MainPanelLayout.createSequentialGroup()
.addGap(12, 12, 12)
.addComponent(priceTitleLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 279, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(priceNLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 278, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(29, 29, 29))
);
MainPanelLayout.setVerticalGroup(
MainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(MainPanelLayout.createSequentialGroup()
.addComponent(departureRoutePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(flightCredPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(MainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(priceTitleLabel)
.addComponent(priceNLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(6, 6, 6)
.addComponent(bookingButton)
.addContainerGap(17, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(MainPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(MainPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(36, 36, 36))
);
}// </editor-fold>//GEN-END:initComponents
//METHODOS GIA TO OTAN PATITHEI TO KOUMPI THS KRATHSHS
private void bookingButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bookingButtonActionPerformed
try {
String answer = flightService.bookFlight(flight); //KANEI KLHSH STON SERVER1 GIA DWSEI THN KRATHSH KAI NA PAREI WS APANTHSH AN EGINE H OXI
if(answer.contains("Cannot invoke \"java.io.ObjectOutputStream.close()\" because \"this.output\" is null")){
JOptionPane.showMessageDialog(null, "Η σύνδεση με τον server βάσης χάθηκε\nΑποτυχία κράτησης",null,JOptionPane.ERROR_MESSAGE);
}
else{
JOptionPane.showMessageDialog(bookingButton.getRootPane(), answer, "Ενημέρωση Κράτησης", JOptionPane.INFORMATION_MESSAGE);
}
} catch (RemoteException ex) { //AN YPARXH KAPOIO EXCEPTION POU SXETIZETAI ME THN SYNDESH H ME TO AN DEN VRETHIKAN
//GIA THN PERIPTWSH POU EGINE KAPOIO PROVLHMA STHN SYNDESH
if (ex.getMessage() != null && (ex.getMessage().contains("Connection refused") || ex.getMessage().contains("No route to host"))) {
JOptionPane.showMessageDialog(null, "Η σύνδεση με τον server χάθηκε το πρόγραμμα θα τερματιστεί",null,JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
else{//GIA TO AN DEN EGINE H KRATHSH LOGO OTI DEN UPHRXAN THESEIS
JOptionPane.showMessageDialog(bookingButton.getRootPane(), "Αποτυχία κράτησης\nΔεν υπάρχουν διαθέσιμες θέσεις", "Ενημέρωση Κράτησης", JOptionPane.ERROR_MESSAGE);
}
}
//KAI TA PARAKATW GIA NA DIAGRAPSOUN TO PANEL THS KRATHSHS
this.removeAll();
this.revalidate();
this.repaint();
}//GEN-LAST:event_bookingButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel MainPanel;
private javax.swing.JLabel arrivalAirCLabel;
private javax.swing.JPanel arrivalPanel;
private javax.swing.JLabel arrivalTimeLabel;
private javax.swing.JLabel availableSeatsNLabel;
private javax.swing.JPanel availableSeatsPanel;
private javax.swing.JLabel availableSeatsTLabel;
private javax.swing.JButton bookingButton;
private javax.swing.JLabel departureAirCLabel;
private javax.swing.JLabel departureDateLabel;
private javax.swing.JPanel departurePanel;
private javax.swing.JPanel departureRoutePanel;
private javax.swing.JLabel departureTimeLabel;
private javax.swing.JLabel departureTitle;
private javax.swing.JPanel flightCredPanel;
private javax.swing.JLabel flightRouteLabel;
private javax.swing.JLabel priceNLabel;
private javax.swing.JLabel priceTitleLabel;
// End of variables declaration//GEN-END:variables
}
| DionysisTheodosis/Java-Exercises | Κατανεμημένα/DSPROGECT02icsd15066/ClientGui/src/clientgui/OneWayPanel.java |
44,160 | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JDialog.java to edit this template
*/
package wifipasswords;
import java.awt.CardLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.Timer;
/**
*
* @author dionysis
*/
public class DisplayMessageNotConnect extends javax.swing.JDialog {
private boolean connected;
/**
* Creates new form DisplayMessage
*/
public DisplayMessageNotConnect(JFrame parent, boolean modal) {
this.connected=connected;
initComponents();
setupTimer();
}
/**
* 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() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jPanel3 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jPanel1.setBackground(new java.awt.Color(51, 51, 51));
jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder(java.awt.Color.green, java.awt.Color.gray));
jLabel1.setBackground(new java.awt.Color(180, 184, 187));
jLabel1.setFont(new java.awt.Font("Segoe UI", 1, 24)); // NOI18N
jLabel1.setForeground(new java.awt.Color(51, 255, 0));
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("Συνδεθήκατε στο Wi-Fi");
jLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 306, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(34, 34, 34)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(34, 34, 34))
);
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setAlwaysOnTop(true);
setLocationByPlatform(true);
setModal(true);
setUndecorated(true);
setResizable(false);
jPanel3.setBackground(new java.awt.Color(51, 51, 51));
jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder(java.awt.Color.red, java.awt.Color.gray));
jLabel2.setBackground(new java.awt.Color(180, 184, 187));
jLabel2.setFont(new java.awt.Font("Segoe UI", 1, 24)); // NOI18N
jLabel2.setForeground(new java.awt.Color(255, 0, 0));
jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel2.setText("Αποτυχία Σύνδεσης");
jLabel2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 306, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(34, 34, 34)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(34, 34, 34))
);
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(0, 0, Short.MAX_VALUE)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
jPanel3.setVisible(true);
pack();
}// </editor-fold>//GEN-END:initComponents
// private void setupTimer() {
// int delay = 2000; // 2 seconds
// Timer timer = new Timer(delay, e -> {
// if (connected) {
// cardLayout.show(jPanel2, "connected");
// } else {
// cardLayout.show(jPanel2, "disconnected");
// }
// });
// timer.setRepeats(false); // Only run once
// timer.start();
// }
private void setupTimer() {
int delay = 2000; // 2 seconds
Timer timer = new Timer(delay, e -> {
dispose();
});
timer.setRepeats(false); // Only run once
timer.start();
jPanel1.setVisible(true);
}
//cardLayout = (CardLayout) frame.getContentPane().getLayout(); //DEXETE TO LAYOUT APO TO FRAME WS TYPO CARDLAYOUT
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel3;
// End of variables declaration//GEN-END:variables
}
| DionysisTheodosis/JavaAps | WifiPasswords1.3/src/wifipasswords/DisplayMessageNotConnect.java |
44,161 | //DIONYSIOS THEODOSIS AM:321/2015066 2H OMADIKH KATANEMHMENA
//PROGRAMMA GIA TON CLIENT
package clientgui;
import shared.FlightService;
import java.rmi.*;
import java.net.MalformedURLException;
import javax.swing.JOptionPane;
public class ClientGui{
private static FlightService flightService;
public static void main(String[] args) {
try{
String name = "//localhost/FlightServiceImpl";//TO URL POU VRISKETAI H KLASH POU YLOPOIEI TO SHARED INTERFACE
flightService = (FlightService) Naming.lookup(name);//SYNDESH ME TON RMI SERVER
MainJFrame mainFrame = new MainJFrame(flightService);//DHMIOURGIA TOU FRAME KAI PERASMA SSAN ANAFORA TO ANTIKEIMENO GIA THN SYNDESH
mainFrame.setLocationRelativeTo(null); //THETEI POU THA EMFANIZETAI TO FRAME
mainFrame.setVisible(true);//KANEI TO FRAME NA FAINETAI
}
catch(MalformedURLException |NotBoundException ex){//GIA NA PIASEI ERROR SXETIKA ME THN MH SWSTH SYNTAXH TOU URL,KAI GIA TO AN XRHSIMOPOIEI OBJECTS POU DEN YPARXOUN
JOptionPane.showMessageDialog(null, ex,null,JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
catch(RemoteException | NullPointerException e){//GIA NA PIASEI AN KAPOIOS SERVER DEN EINAI SYNDEDEMENOS
if(e instanceof RemoteException){
JOptionPane.showMessageDialog(null, "Αποτυχία σύνδεσης με τον σέρβερ",null,JOptionPane.ERROR_MESSAGE);
}
else if(e instanceof NullPointerException){
JOptionPane.showMessageDialog(null, "Αποτυχία σύνδεσης με τον σέρβερ της βάσης",null,JOptionPane.ERROR_MESSAGE);
}
}
}
}
| DionysisTheodosis/Java-Exercises | Κατανεμημένα/DSPROGECT02icsd15066/ClientGui/src/clientgui/ClientGui.java |
44,384 | /*
* Copyright (C) 2016 The Guava Authors
*
* 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.google.common.graph;
import com.google.common.annotations.Beta;
import java.util.Optional;
import java.util.Set;
import javax.annotation.CheckForNull;
/**
* An interface for <a
* href="https://en.wikipedia.org/wiki/Graph_(discrete_mathematics)">graph</a>-structured data,
* whose edges have associated non-unique values.
*
* <p>A graph is composed of a set of nodes and a set of edges connecting pairs of nodes.
*
* <p>There are three primary interfaces provided to represent graphs. In order of increasing
* complexity they are: {@link Graph}, {@link ValueGraph}, and {@link Network}. You should generally
* prefer the simplest interface that satisfies your use case. See the <a
* href="https://github.com/google/guava/wiki/GraphsExplained#choosing-the-right-graph-type">
* "Choosing the right graph type"</a> section of the Guava User Guide for more details.
*
* <h3>Capabilities</h3>
*
* <p>{@code ValueGraph} supports the following use cases (<a
* href="https://github.com/google/guava/wiki/GraphsExplained#definitions">definitions of
* terms</a>):
*
* <ul>
* <li>directed graphs
* <li>undirected graphs
* <li>graphs that do/don't allow self-loops
* <li>graphs whose nodes/edges are insertion-ordered, sorted, or unordered
* <li>graphs whose edges have associated values
* </ul>
*
* <p>{@code ValueGraph}, as a subtype of {@code Graph}, explicitly does not support parallel edges,
* and forbids implementations or extensions with parallel edges. If you need parallel edges, use
* {@link Network}. (You can use a positive {@code Integer} edge value as a loose representation of
* edge multiplicity, but the {@code *degree()} and mutation methods will not reflect your
* interpretation of the edge value as its multiplicity.)
*
* <h3>Building a {@code ValueGraph}</h3>
*
* <p>The implementation classes that {@code common.graph} provides are not public, by design. To
* create an instance of one of the built-in implementations of {@code ValueGraph}, use the {@link
* ValueGraphBuilder} class:
*
* <pre>{@code
* MutableValueGraph<Integer, Double> graph = ValueGraphBuilder.directed().build();
* }</pre>
*
* <p>{@link ValueGraphBuilder#build()} returns an instance of {@link MutableValueGraph}, which is a
* subtype of {@code ValueGraph} that provides methods for adding and removing nodes and edges. If
* you do not need to mutate a graph (e.g. if you write a method than runs a read-only algorithm on
* the graph), you should use the non-mutating {@link ValueGraph} interface, or an {@link
* ImmutableValueGraph}.
*
* <p>You can create an immutable copy of an existing {@code ValueGraph} using {@link
* ImmutableValueGraph#copyOf(ValueGraph)}:
*
* <pre>{@code
* ImmutableValueGraph<Integer, Double> immutableGraph = ImmutableValueGraph.copyOf(graph);
* }</pre>
*
* <p>Instances of {@link ImmutableValueGraph} do not implement {@link MutableValueGraph}
* (obviously!) and are contractually guaranteed to be unmodifiable and thread-safe.
*
* <p>The Guava User Guide has <a
* href="https://github.com/google/guava/wiki/GraphsExplained#building-graph-instances">more
* information on (and examples of) building graphs</a>.
*
* <h3>Additional documentation</h3>
*
* <p>See the Guava User Guide for the {@code common.graph} package (<a
* href="https://github.com/google/guava/wiki/GraphsExplained">"Graphs Explained"</a>) for
* additional documentation, including:
*
* <ul>
* <li><a
* href="https://github.com/google/guava/wiki/GraphsExplained#equals-hashcode-and-graph-equivalence">
* {@code equals()}, {@code hashCode()}, and graph equivalence</a>
* <li><a href="https://github.com/google/guava/wiki/GraphsExplained#synchronization">
* Synchronization policy</a>
* <li><a href="https://github.com/google/guava/wiki/GraphsExplained#notes-for-implementors">Notes
* for implementors</a>
* </ul>
*
* @author James Sexton
* @author Joshua O'Madadhain
* @param <N> Node parameter type
* @param <V> Value parameter type
* @since 20.0
*/
@Beta
@ElementTypesAreNonnullByDefault
public interface ValueGraph<N, V> extends BaseGraph<N> {
//
// ValueGraph-level accessors
//
/** Returns all nodes in this graph, in the order specified by {@link #nodeOrder()}. */
@Override
Set<N> nodes();
/** Returns all edges in this graph. */
@Override
Set<EndpointPair<N>> edges();
/**
* Returns a live view of this graph as a {@link Graph}. The resulting {@link Graph} will have an
* edge connecting node A to node B if this {@link ValueGraph} has an edge connecting A to B.
*/
Graph<N> asGraph();
//
// ValueGraph properties
//
/**
* Returns true if the edges in this graph are directed. Directed edges connect a {@link
* EndpointPair#source() source node} to a {@link EndpointPair#target() target node}, while
* undirected edges connect a pair of nodes to each other.
*/
@Override
boolean isDirected();
/**
* Returns true if this graph allows self-loops (edges that connect a node to itself). Attempting
* to add a self-loop to a graph that does not allow them will throw an {@link
* IllegalArgumentException}.
*/
@Override
boolean allowsSelfLoops();
/** Returns the order of iteration for the elements of {@link #nodes()}. */
@Override
ElementOrder<N> nodeOrder();
/**
* Returns an {@link ElementOrder} that specifies the order of iteration for the elements of
* {@link #edges()}, {@link #adjacentNodes(Object)}, {@link #predecessors(Object)}, {@link
* #successors(Object)} and {@link #incidentEdges(Object)}.
*
* @since 29.0
*/
@Override
ElementOrder<N> incidentEdgeOrder();
//
// Element-level accessors
//
/**
* Returns a live view of the nodes which have an incident edge in common with {@code node} in
* this graph.
*
* <p>This is equal to the union of {@link #predecessors(Object)} and {@link #successors(Object)}.
*
* <p>If {@code node} is removed from the graph after this method is called, the {@code Set}
* {@code view} returned by this method will be invalidated, and will throw {@code
* IllegalStateException} if it is accessed in any way, with the following exceptions:
*
* <ul>
* <li>{@code view.equals(view)} evaluates to {@code true} (but any other `equals()` expression
* involving {@code view} will throw)
* <li>{@code hashCode()} does not throw
* <li>if {@code node} is re-added to the graph after having been removed, {@code view}'s
* behavior is undefined
* </ul>
*
* @throws IllegalArgumentException if {@code node} is not an element of this graph
*/
@Override
Set<N> adjacentNodes(N node);
/**
* Returns a live view of all nodes in this graph adjacent to {@code node} which can be reached by
* traversing {@code node}'s incoming edges <i>against</i> the direction (if any) of the edge.
*
* <p>In an undirected graph, this is equivalent to {@link #adjacentNodes(Object)}.
*
* <p>If {@code node} is removed from the graph after this method is called, the `Set` returned by
* this method will be invalidated, and will throw `IllegalStateException` if it is accessed in
* any way.
*
* @throws IllegalArgumentException if {@code node} is not an element of this graph
*/
@Override
Set<N> predecessors(N node);
/**
* Returns a live view of all nodes in this graph adjacent to {@code node} which can be reached by
* traversing {@code node}'s outgoing edges in the direction (if any) of the edge.
*
* <p>In an undirected graph, this is equivalent to {@link #adjacentNodes(Object)}.
*
* <p>This is <i>not</i> the same as "all nodes reachable from {@code node} by following outgoing
* edges". For that functionality, see {@link Graphs#reachableNodes(Graph, Object)}.
*
* <p>If {@code node} is removed from the graph after this method is called, the {@code Set}
* {@code view} returned by this method will be invalidated, and will throw {@code
* IllegalStateException} if it is accessed in any way, with the following exceptions:
*
* <ul>
* <li>{@code view.equals(view)} evaluates to {@code true} (but any other `equals()` expression
* involving {@code view} will throw)
* <li>{@code hashCode()} does not throw
* <li>if {@code node} is re-added to the graph after having been removed, {@code view}'s
* behavior is undefined
* </ul>
*
* @throws IllegalArgumentException if {@code node} is not an element of this graph
*/
@Override
Set<N> successors(N node);
/**
* Returns a live view of the edges in this graph whose endpoints include {@code node}.
*
* <p>This is equal to the union of incoming and outgoing edges.
*
* <p>If {@code node} is removed from the graph after this method is called, the {@code Set}
* {@code view} returned by this method will be invalidated, and will throw {@code
* IllegalStateException} if it is accessed in any way, with the following exceptions:
*
* <ul>
* <li>{@code view.equals(view)} evaluates to {@code true} (but any other `equals()` expression
* involving {@code view} will throw)
* <li>{@code hashCode()} does not throw
* <li>if {@code node} is re-added to the graph after having been removed, {@code view}'s
* behavior is undefined
* </ul>
*
* @throws IllegalArgumentException if {@code node} is not an element of this graph
* @since 24.0
*/
@Override
Set<EndpointPair<N>> incidentEdges(N node);
/**
* Returns the count of {@code node}'s incident edges, counting self-loops twice (equivalently,
* the number of times an edge touches {@code node}).
*
* <p>For directed graphs, this is equal to {@code inDegree(node) + outDegree(node)}.
*
* <p>For undirected graphs, this is equal to {@code incidentEdges(node).size()} + (number of
* self-loops incident to {@code node}).
*
* <p>If the count is greater than {@code Integer.MAX_VALUE}, returns {@code Integer.MAX_VALUE}.
*
* @throws IllegalArgumentException if {@code node} is not an element of this graph
*/
@Override
int degree(N node);
/**
* Returns the count of {@code node}'s incoming edges (equal to {@code predecessors(node).size()})
* in a directed graph. In an undirected graph, returns the {@link #degree(Object)}.
*
* <p>If the count is greater than {@code Integer.MAX_VALUE}, returns {@code Integer.MAX_VALUE}.
*
* @throws IllegalArgumentException if {@code node} is not an element of this graph
*/
@Override
int inDegree(N node);
/**
* Returns the count of {@code node}'s outgoing edges (equal to {@code successors(node).size()})
* in a directed graph. In an undirected graph, returns the {@link #degree(Object)}.
*
* <p>If the count is greater than {@code Integer.MAX_VALUE}, returns {@code Integer.MAX_VALUE}.
*
* @throws IllegalArgumentException if {@code node} is not an element of this graph
*/
@Override
int outDegree(N node);
/**
* Returns true if there is an edge that directly connects {@code nodeU} to {@code nodeV}. This is
* equivalent to {@code nodes().contains(nodeU) && successors(nodeU).contains(nodeV)}.
*
* <p>In an undirected graph, this is equal to {@code hasEdgeConnecting(nodeV, nodeU)}.
*
* @since 23.0
*/
@Override
boolean hasEdgeConnecting(N nodeU, N nodeV);
/**
* Returns true if there is an edge that directly connects {@code endpoints} (in the order, if
* any, specified by {@code endpoints}). This is equivalent to {@code
* edges().contains(endpoints)}.
*
* <p>Unlike the other {@code EndpointPair}-accepting methods, this method does not throw if the
* endpoints are unordered and the graph is directed; it simply returns {@code false}. This is for
* consistency with the behavior of {@link Collection#contains(Object)} (which does not generally
* throw if the object cannot be present in the collection), and the desire to have this method's
* behavior be compatible with {@code edges().contains(endpoints)}.
*
* @since 27.1
*/
@Override
boolean hasEdgeConnecting(EndpointPair<N> endpoints);
/**
* Returns the value of the edge that connects {@code nodeU} to {@code nodeV} (in the order, if
* any, specified by {@code endpoints}), if one is present; otherwise, returns {@code
* Optional.empty()}.
*
* @throws IllegalArgumentException if {@code nodeU} or {@code nodeV} is not an element of this
* graph
* @since 23.0 (since 20.0 with return type {@code V})
*/
Optional<V> edgeValue(N nodeU, N nodeV);
/**
* Returns the value of the edge that connects {@code endpoints} (in the order, if any, specified
* by {@code endpoints}), if one is present; otherwise, returns {@code Optional.empty()}.
*
* <p>If this graph is directed, the endpoints must be ordered.
*
* @throws IllegalArgumentException if either endpoint is not an element of this graph
* @throws IllegalArgumentException if the endpoints are unordered and the graph is directed
* @since 27.1
*/
Optional<V> edgeValue(EndpointPair<N> endpoints);
/**
* Returns the value of the edge that connects {@code nodeU} to {@code nodeV}, if one is present;
* otherwise, returns {@code defaultValue}.
*
* <p>In an undirected graph, this is equal to {@code edgeValueOrDefault(nodeV, nodeU,
* defaultValue)}.
*
* @throws IllegalArgumentException if {@code nodeU} or {@code nodeV} is not an element of this
* graph
*/
@CheckForNull
V edgeValueOrDefault(N nodeU, N nodeV, @CheckForNull V defaultValue);
/**
* Returns the value of the edge that connects {@code endpoints} (in the order, if any, specified
* by {@code endpoints}), if one is present; otherwise, returns {@code defaultValue}.
*
* <p>If this graph is directed, the endpoints must be ordered.
*
* @throws IllegalArgumentException if either endpoint is not an element of this graph
* @throws IllegalArgumentException if the endpoints are unordered and the graph is directed
* @since 27.1
*/
@CheckForNull
V edgeValueOrDefault(EndpointPair<N> endpoints, @CheckForNull V defaultValue);
//
// ValueGraph identity
//
/**
* Returns {@code true} iff {@code object} is a {@link ValueGraph} that has the same elements and
* the same structural relationships as those in this graph.
*
* <p>Thus, two value graphs A and B are equal if <b>all</b> of the following are true:
*
* <ul>
* <li>A and B have equal {@link #isDirected() directedness}.
* <li>A and B have equal {@link #nodes() node sets}.
* <li>A and B have equal {@link #edges() edge sets}.
* <li>The {@link #edgeValue(N, N) value} of a given edge is the same in both A and B.
* </ul>
*
* <p>Graph properties besides {@link #isDirected() directedness} do <b>not</b> affect equality.
* For example, two graphs may be considered equal even if one allows self-loops and the other
* doesn't. Additionally, the order in which nodes or edges are added to the graph, and the order
* in which they are iterated over, are irrelevant.
*
* <p>A reference implementation of this is provided by {@link AbstractValueGraph#equals(Object)}.
*/
@Override
boolean equals(@CheckForNull Object object);
/**
* Returns the hash code for this graph. The hash code of a graph is defined as the hash code of a
* map from each of its {@link #edges() edges} to the associated {@link #edgeValue(N, N) edge
* value}.
*
* <p>A reference implementation of this is provided by {@link AbstractValueGraph#hashCode()}.
*/
@Override
int hashCode();
}
| google/guava | guava/src/com/google/common/graph/ValueGraph.java |
44,387 | /*
* Copyright (C) 2014 The Guava Authors
*
* 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.google.common.graph;
import com.google.common.annotations.Beta;
import com.google.errorprone.annotations.DoNotMock;
import java.util.Optional;
import java.util.Set;
import javax.annotation.CheckForNull;
/**
* An interface for <a
* href="https://en.wikipedia.org/wiki/Graph_(discrete_mathematics)">graph</a>-structured data,
* whose edges are unique objects.
*
* <p>A graph is composed of a set of nodes and a set of edges connecting pairs of nodes.
*
* <p>There are three primary interfaces provided to represent graphs. In order of increasing
* complexity they are: {@link Graph}, {@link ValueGraph}, and {@link Network}. You should generally
* prefer the simplest interface that satisfies your use case. See the <a
* href="https://github.com/google/guava/wiki/GraphsExplained#choosing-the-right-graph-type">
* "Choosing the right graph type"</a> section of the Guava User Guide for more details.
*
* <h3>Capabilities</h3>
*
* <p>{@code Network} supports the following use cases (<a
* href="https://github.com/google/guava/wiki/GraphsExplained#definitions">definitions of
* terms</a>):
*
* <ul>
* <li>directed graphs
* <li>undirected graphs
* <li>graphs that do/don't allow parallel edges
* <li>graphs that do/don't allow self-loops
* <li>graphs whose nodes/edges are insertion-ordered, sorted, or unordered
* <li>graphs whose edges are unique objects
* </ul>
*
* <h3>Building a {@code Network}</h3>
*
* <p>The implementation classes that {@code common.graph} provides are not public, by design. To
* create an instance of one of the built-in implementations of {@code Network}, use the {@link
* NetworkBuilder} class:
*
* <pre>{@code
* MutableNetwork<Integer, MyEdge> network = NetworkBuilder.directed().build();
* }</pre>
*
* <p>{@link NetworkBuilder#build()} returns an instance of {@link MutableNetwork}, which is a
* subtype of {@code Network} that provides methods for adding and removing nodes and edges. If you
* do not need to mutate a network (e.g. if you write a method than runs a read-only algorithm on
* the network), you should use the non-mutating {@link Network} interface, or an {@link
* ImmutableNetwork}.
*
* <p>You can create an immutable copy of an existing {@code Network} using {@link
* ImmutableNetwork#copyOf(Network)}:
*
* <pre>{@code
* ImmutableNetwork<Integer, MyEdge> immutableGraph = ImmutableNetwork.copyOf(network);
* }</pre>
*
* <p>Instances of {@link ImmutableNetwork} do not implement {@link MutableNetwork} (obviously!) and
* are contractually guaranteed to be unmodifiable and thread-safe.
*
* <p>The Guava User Guide has <a
* href="https://github.com/google/guava/wiki/GraphsExplained#building-graph-instances">more
* information on (and examples of) building graphs</a>.
*
* <h3>Additional documentation</h3>
*
* <p>See the Guava User Guide for the {@code common.graph} package (<a
* href="https://github.com/google/guava/wiki/GraphsExplained">"Graphs Explained"</a>) for
* additional documentation, including:
*
* <ul>
* <li><a
* href="https://github.com/google/guava/wiki/GraphsExplained#equals-hashcode-and-graph-equivalence">
* {@code equals()}, {@code hashCode()}, and graph equivalence</a>
* <li><a href="https://github.com/google/guava/wiki/GraphsExplained#synchronization">
* Synchronization policy</a>
* <li><a href="https://github.com/google/guava/wiki/GraphsExplained#notes-for-implementors">Notes
* for implementors</a>
* </ul>
*
* @author James Sexton
* @author Joshua O'Madadhain
* @param <N> Node parameter type
* @param <E> Edge parameter type
* @since 20.0
*/
@Beta
@DoNotMock("Use NetworkBuilder to create a real instance")
@ElementTypesAreNonnullByDefault
public interface Network<N, E> extends SuccessorsFunction<N>, PredecessorsFunction<N> {
//
// Network-level accessors
//
/** Returns all nodes in this network, in the order specified by {@link #nodeOrder()}. */
Set<N> nodes();
/** Returns all edges in this network, in the order specified by {@link #edgeOrder()}. */
Set<E> edges();
/**
* Returns a live view of this network as a {@link Graph}. The resulting {@link Graph} will have
* an edge connecting node A to node B if this {@link Network} has an edge connecting A to B.
*
* <p>If this network {@link #allowsParallelEdges() allows parallel edges}, parallel edges will be
* treated as if collapsed into a single edge. For example, the {@link #degree(Object)} of a node
* in the {@link Graph} view may be less than the degree of the same node in this {@link Network}.
*/
Graph<N> asGraph();
//
// Network properties
//
/**
* Returns true if the edges in this network are directed. Directed edges connect a {@link
* EndpointPair#source() source node} to a {@link EndpointPair#target() target node}, while
* undirected edges connect a pair of nodes to each other.
*/
boolean isDirected();
/**
* Returns true if this network allows parallel edges. Attempting to add a parallel edge to a
* network that does not allow them will throw an {@link IllegalArgumentException}.
*/
boolean allowsParallelEdges();
/**
* Returns true if this network allows self-loops (edges that connect a node to itself).
* Attempting to add a self-loop to a network that does not allow them will throw an {@link
* IllegalArgumentException}.
*/
boolean allowsSelfLoops();
/** Returns the order of iteration for the elements of {@link #nodes()}. */
ElementOrder<N> nodeOrder();
/** Returns the order of iteration for the elements of {@link #edges()}. */
ElementOrder<E> edgeOrder();
//
// Element-level accessors
//
/**
* Returns a live view of the nodes which have an incident edge in common with {@code node} in
* this graph.
*
* <p>This is equal to the union of {@link #predecessors(Object)} and {@link #successors(Object)}.
*
* <p>If {@code node} is removed from the network after this method is called, the {@code Set}
* {@code view} returned by this method will be invalidated, and will throw {@code
* IllegalStateException} if it is accessed in any way, with the following exceptions:
*
* <ul>
* <li>{@code view.equals(view)} evaluates to {@code true} (but any other `equals()` expression
* involving {@code view} will throw)
* <li>{@code hashCode()} does not throw
* <li>if {@code node} is re-added to the network after having been removed, {@code view}'s
* behavior is undefined
* </ul>
*
* @throws IllegalArgumentException if {@code node} is not an element of this network
*/
Set<N> adjacentNodes(N node);
/**
* Returns a live view of all nodes in this network adjacent to {@code node} which can be reached
* by traversing {@code node}'s incoming edges <i>against</i> the direction (if any) of the edge.
*
* <p>In an undirected network, this is equivalent to {@link #adjacentNodes(Object)}.
*
* <p>If {@code node} is removed from the network after this method is called, the `Set` returned
* by this method will be invalidated, and will throw `IllegalStateException` if it is accessed in
* any way.
*
* @throws IllegalArgumentException if {@code node} is not an element of this network
*/
@Override
Set<N> predecessors(N node);
/**
* Returns a live view of all nodes in this network adjacent to {@code node} which can be reached
* by traversing {@code node}'s outgoing edges in the direction (if any) of the edge.
*
* <p>In an undirected network, this is equivalent to {@link #adjacentNodes(Object)}.
*
* <p>This is <i>not</i> the same as "all nodes reachable from {@code node} by following outgoing
* edges". For that functionality, see {@link Graphs#reachableNodes(Graph, Object)}.
*
* <p>If {@code node} is removed from the network after this method is called, the {@code Set}
* {@code view} returned by this method will be invalidated, and will throw {@code
* IllegalStateException} if it is accessed in any way, with the following exceptions:
*
* <ul>
* <li>{@code view.equals(view)} evaluates to {@code true} (but any other `equals()` expression
* involving {@code view} will throw)
* <li>{@code hashCode()} does not throw
* <li>if {@code node} is re-added to the network after having been removed, {@code view}'s
* behavior is undefined
* </ul>
*
* @throws IllegalArgumentException if {@code node} is not an element of this network
*/
@Override
Set<N> successors(N node);
/**
* Returns a live view of the edges whose {@link #incidentNodes(Object) incident nodes} in this
* network include {@code node}.
*
* <p>This is equal to the union of {@link #inEdges(Object)} and {@link #outEdges(Object)}.
*
* <p>If {@code node} is removed from the network after this method is called, the {@code Set}
* {@code view} returned by this method will be invalidated, and will throw {@code
* IllegalStateException} if it is accessed in any way, with the following exceptions:
*
* <ul>
* <li>{@code view.equals(view)} evaluates to {@code true} (but any other `equals()` expression
* involving {@code view} will throw)
* <li>{@code hashCode()} does not throw
* <li>if {@code node} is re-added to the network after having been removed, {@code view}'s
* behavior is undefined
* </ul>
*
* @throws IllegalArgumentException if {@code node} is not an element of this network
* @since 24.0
*/
Set<E> incidentEdges(N node);
/**
* Returns a live view of all edges in this network which can be traversed in the direction (if
* any) of the edge to end at {@code node}.
*
* <p>In a directed network, an incoming edge's {@link EndpointPair#target()} equals {@code node}.
*
* <p>In an undirected network, this is equivalent to {@link #incidentEdges(Object)}.
*
* <p>If {@code node} is removed from the network after this method is called, the {@code Set}
* {@code view} returned by this method will be invalidated, and will throw {@code
* IllegalStateException} if it is accessed in any way, with the following exceptions:
*
* <ul>
* <li>{@code view.equals(view)} evaluates to {@code true} (but any other `equals()` expression
* involving {@code view} will throw)
* <li>{@code hashCode()} does not throw
* <li>if {@code node} is re-added to the network after having been removed, {@code view}'s
* behavior is undefined
* </ul>
*
* @throws IllegalArgumentException if {@code node} is not an element of this network
*/
Set<E> inEdges(N node);
/**
* Returns a live view of all edges in this network which can be traversed in the direction (if
* any) of the edge starting from {@code node}.
*
* <p>In a directed network, an outgoing edge's {@link EndpointPair#source()} equals {@code node}.
*
* <p>In an undirected network, this is equivalent to {@link #incidentEdges(Object)}.
*
* <p>If {@code node} is removed from the network after this method is called, the {@code Set}
* {@code view} returned by this method will be invalidated, and will throw {@code
* IllegalStateException} if it is accessed in any way, with the following exceptions:
*
* <ul>
* <li>{@code view.equals(view)} evaluates to {@code true} (but any other `equals()` expression
* involving {@code view} will throw)
* <li>{@code hashCode()} does not throw
* <li>if {@code node} is re-added to the network after having been removed, {@code view}'s
* behavior is undefined
* </ul>
*
* @throws IllegalArgumentException if {@code node} is not an element of this network
*/
Set<E> outEdges(N node);
/**
* Returns the count of {@code node}'s {@link #incidentEdges(Object) incident edges}, counting
* self-loops twice (equivalently, the number of times an edge touches {@code node}).
*
* <p>For directed networks, this is equal to {@code inDegree(node) + outDegree(node)}.
*
* <p>For undirected networks, this is equal to {@code incidentEdges(node).size()} + (number of
* self-loops incident to {@code node}).
*
* <p>If the count is greater than {@code Integer.MAX_VALUE}, returns {@code Integer.MAX_VALUE}.
*
* @throws IllegalArgumentException if {@code node} is not an element of this network
*/
int degree(N node);
/**
* Returns the count of {@code node}'s {@link #inEdges(Object) incoming edges} in a directed
* network. In an undirected network, returns the {@link #degree(Object)}.
*
* <p>If the count is greater than {@code Integer.MAX_VALUE}, returns {@code Integer.MAX_VALUE}.
*
* @throws IllegalArgumentException if {@code node} is not an element of this network
*/
int inDegree(N node);
/**
* Returns the count of {@code node}'s {@link #outEdges(Object) outgoing edges} in a directed
* network. In an undirected network, returns the {@link #degree(Object)}.
*
* <p>If the count is greater than {@code Integer.MAX_VALUE}, returns {@code Integer.MAX_VALUE}.
*
* @throws IllegalArgumentException if {@code node} is not an element of this network
*/
int outDegree(N node);
/**
* Returns the nodes which are the endpoints of {@code edge} in this network.
*
* @throws IllegalArgumentException if {@code edge} is not an element of this network
*/
EndpointPair<N> incidentNodes(E edge);
/**
* Returns a live view of the edges which have an {@link #incidentNodes(Object) incident node} in
* common with {@code edge}. An edge is not considered adjacent to itself.
*
* <p>If {@code edge} is removed from the network after this method is called, the {@code Set}
* {@code view} returned by this method will be invalidated, and will throw {@code
* IllegalStateException} if it is accessed in any way, with the following exceptions:
*
* <ul>
* <li>{@code view.equals(view)} evaluates to {@code true} (but any other `equals()` expression
* involving {@code view} will throw)
* <li>{@code hashCode()} does not throw
* <li>if {@code edge} is re-added to the network after having been removed, {@code view}'s
* behavior is undefined
* </ul>
*
* @throws IllegalArgumentException if {@code edge} is not an element of this network
*/
Set<E> adjacentEdges(E edge);
/**
* Returns a live view of the set of edges that each directly connect {@code nodeU} to {@code
* nodeV}.
*
* <p>In an undirected network, this is equal to {@code edgesConnecting(nodeV, nodeU)}.
*
* <p>The resulting set of edges will be parallel (i.e. have equal {@link
* #incidentNodes(Object)}). If this network does not {@link #allowsParallelEdges() allow parallel
* edges}, the resulting set will contain at most one edge (equivalent to {@code
* edgeConnecting(nodeU, nodeV).asSet()}).
*
* <p>If either {@code nodeU} or {@code nodeV} are removed from the network after this method is
* called, the {@code Set} {@code view} returned by this method will be invalidated, and will
* throw {@code IllegalStateException} if it is accessed in any way, with the following
* exceptions:
*
* <ul>
* <li>{@code view.equals(view)} evaluates to {@code true} (but any other `equals()` expression
* involving {@code view} will throw)
* <li>{@code hashCode()} does not throw
* <li>if {@code nodeU} or {@code nodeV} are re-added to the network after having been removed,
* {@code view}'s behavior is undefined
* </ul>
*
* @throws IllegalArgumentException if {@code nodeU} or {@code nodeV} is not an element of this
* network
*/
Set<E> edgesConnecting(N nodeU, N nodeV);
/**
* Returns a live view of the set of edges that each directly connect {@code endpoints} (in the
* order, if any, specified by {@code endpoints}).
*
* <p>The resulting set of edges will be parallel (i.e. have equal {@link
* #incidentNodes(Object)}). If this network does not {@link #allowsParallelEdges() allow parallel
* edges}, the resulting set will contain at most one edge (equivalent to {@code
* edgeConnecting(endpoints).asSet()}).
*
* <p>If this network is directed, {@code endpoints} must be ordered.
*
* <p>If either element of {@code endpoints} is removed from the network after this method is
* called, the {@code Set} {@code view} returned by this method will be invalidated, and will
* throw {@code IllegalStateException} if it is accessed in any way, with the following
* exceptions:
*
* <ul>
* <li>{@code view.equals(view)} evaluates to {@code true} (but any other `equals()` expression
* involving {@code view} will throw)
* <li>{@code hashCode()} does not throw
* <li>if either endpoint is re-added to the network after having been removed, {@code view}'s
* behavior is undefined
* </ul>
*
* @throws IllegalArgumentException if either endpoint is not an element of this network
* @throws IllegalArgumentException if the endpoints are unordered and the network is directed
* @since 27.1
*/
Set<E> edgesConnecting(EndpointPair<N> endpoints);
/**
* Returns the single edge that directly connects {@code nodeU} to {@code nodeV}, if one is
* present, or {@code Optional.empty()} if no such edge exists.
*
* <p>In an undirected network, this is equal to {@code edgeConnecting(nodeV, nodeU)}.
*
* @throws IllegalArgumentException if there are multiple parallel edges connecting {@code nodeU}
* to {@code nodeV}
* @throws IllegalArgumentException if {@code nodeU} or {@code nodeV} is not an element of this
* network
* @since 23.0
*/
Optional<E> edgeConnecting(N nodeU, N nodeV);
/**
* Returns the single edge that directly connects {@code endpoints} (in the order, if any,
* specified by {@code endpoints}), if one is present, or {@code Optional.empty()} if no such edge
* exists.
*
* <p>If this network is directed, the endpoints must be ordered.
*
* @throws IllegalArgumentException if there are multiple parallel edges connecting {@code nodeU}
* to {@code nodeV}
* @throws IllegalArgumentException if either endpoint is not an element of this network
* @throws IllegalArgumentException if the endpoints are unordered and the network is directed
* @since 27.1
*/
Optional<E> edgeConnecting(EndpointPair<N> endpoints);
/**
* Returns the single edge that directly connects {@code nodeU} to {@code nodeV}, if one is
* present, or {@code null} if no such edge exists.
*
* <p>In an undirected network, this is equal to {@code edgeConnectingOrNull(nodeV, nodeU)}.
*
* @throws IllegalArgumentException if there are multiple parallel edges connecting {@code nodeU}
* to {@code nodeV}
* @throws IllegalArgumentException if {@code nodeU} or {@code nodeV} is not an element of this
* network
* @since 23.0
*/
@CheckForNull
E edgeConnectingOrNull(N nodeU, N nodeV);
/**
* Returns the single edge that directly connects {@code endpoints} (in the order, if any,
* specified by {@code endpoints}), if one is present, or {@code null} if no such edge exists.
*
* <p>If this network is directed, the endpoints must be ordered.
*
* @throws IllegalArgumentException if there are multiple parallel edges connecting {@code nodeU}
* to {@code nodeV}
* @throws IllegalArgumentException if either endpoint is not an element of this network
* @throws IllegalArgumentException if the endpoints are unordered and the network is directed
* @since 27.1
*/
@CheckForNull
E edgeConnectingOrNull(EndpointPair<N> endpoints);
/**
* Returns true if there is an edge that directly connects {@code nodeU} to {@code nodeV}. This is
* equivalent to {@code nodes().contains(nodeU) && successors(nodeU).contains(nodeV)}, and to
* {@code edgeConnectingOrNull(nodeU, nodeV) != null}.
*
* <p>In an undirected network, this is equal to {@code hasEdgeConnecting(nodeV, nodeU)}.
*
* @since 23.0
*/
boolean hasEdgeConnecting(N nodeU, N nodeV);
/**
* Returns true if there is an edge that directly connects {@code endpoints} (in the order, if
* any, specified by {@code endpoints}).
*
* <p>Unlike the other {@code EndpointPair}-accepting methods, this method does not throw if the
* endpoints are unordered and the network is directed; it simply returns {@code false}. This is
* for consistency with {@link Graph#hasEdgeConnecting(EndpointPair)} and {@link
* ValueGraph#hasEdgeConnecting(EndpointPair)}.
*
* @since 27.1
*/
boolean hasEdgeConnecting(EndpointPair<N> endpoints);
//
// Network identity
//
/**
* Returns {@code true} iff {@code object} is a {@link Network} that has the same elements and the
* same structural relationships as those in this network.
*
* <p>Thus, two networks A and B are equal if <b>all</b> of the following are true:
*
* <ul>
* <li>A and B have equal {@link #isDirected() directedness}.
* <li>A and B have equal {@link #nodes() node sets}.
* <li>A and B have equal {@link #edges() edge sets}.
* <li>Every edge in A and B connects the same nodes in the same direction (if any).
* </ul>
*
* <p>Network properties besides {@link #isDirected() directedness} do <b>not</b> affect equality.
* For example, two networks may be considered equal even if one allows parallel edges and the
* other doesn't. Additionally, the order in which nodes or edges are added to the network, and
* the order in which they are iterated over, are irrelevant.
*
* <p>A reference implementation of this is provided by {@link AbstractNetwork#equals(Object)}.
*/
@Override
boolean equals(@CheckForNull Object object);
/**
* Returns the hash code for this network. The hash code of a network is defined as the hash code
* of a map from each of its {@link #edges() edges} to their {@link #incidentNodes(Object)
* incident nodes}.
*
* <p>A reference implementation of this is provided by {@link AbstractNetwork#hashCode()}.
*/
@Override
int hashCode();
}
| google/guava | guava/src/com/google/common/graph/Network.java |
44,391 | /*
* Copyright (C) 2007 The Guava Authors
*
* 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.google.common.base;
import static com.google.common.base.NullnessCasts.uncheckedCastNullableTToT;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.Map;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Static utility methods pertaining to {@code com.google.common.base.Function} instances; see that
* class for information about migrating to {@code java.util.function}.
*
* <p>All methods return serializable functions as long as they're given serializable parameters.
*
* <p>See the Guava User Guide article on <a
* href="https://github.com/google/guava/wiki/FunctionalExplained">the use of {@code Function}</a>.
*
* @author Mike Bostock
* @author Jared Levy
* @since 2.0
*/
@GwtCompatible
@ElementTypesAreNonnullByDefault
public final class Functions {
private Functions() {}
/**
* A function equivalent to the method reference {@code Object::toString}, for users not yet using
* Java 8. The function simply invokes {@code toString} on its argument and returns the result. It
* throws a {@link NullPointerException} on null input.
*
* <p><b>Warning:</b> The returned function may not be <i>consistent with equals</i> (as
* documented at {@link Function#apply}). For example, this function yields different results for
* the two equal instances {@code ImmutableSet.of(1, 2)} and {@code ImmutableSet.of(2, 1)}.
*
* <p><b>Warning:</b> as with all function types in this package, avoid depending on the specific
* {@code equals}, {@code hashCode} or {@code toString} behavior of the returned function. A
* future migration to {@code java.util.function} will not preserve this behavior.
*
* <p><b>Java 8+ users:</b> use the method reference {@code Object::toString} instead. In the
* future, when this class requires Java 8, this method will be deprecated. See {@link Function}
* for more important information about the Java 8+ transition.
*/
public static Function<Object, String> toStringFunction() {
return ToStringFunction.INSTANCE;
}
// enum singleton pattern
private enum ToStringFunction implements Function<Object, String> {
INSTANCE;
@Override
public String apply(Object o) {
checkNotNull(o); // eager for GWT.
return o.toString();
}
@Override
public String toString() {
return "Functions.toStringFunction()";
}
}
/**
* Returns the identity function.
*
* <p><b>Discouraged:</b> Prefer using a lambda like {@code v -> v}, which is shorter and often
* more readable.
*/
// implementation is "fully variant"; E has become a "pass-through" type
@SuppressWarnings("unchecked")
public static <E extends @Nullable Object> Function<E, E> identity() {
return (Function<E, E>) IdentityFunction.INSTANCE;
}
// enum singleton pattern
private enum IdentityFunction implements Function<@Nullable Object, @Nullable Object> {
INSTANCE;
@Override
@CheckForNull
public Object apply(@CheckForNull Object o) {
return o;
}
@Override
public String toString() {
return "Functions.identity()";
}
}
/**
* Returns a function which performs a map lookup. The returned function throws an {@link
* IllegalArgumentException} if given a key that does not exist in the map. See also {@link
* #forMap(Map, Object)}, which returns a default value in this case.
*
* <p>Note: if {@code map} is a {@link com.google.common.collect.BiMap BiMap} (or can be one), you
* can use {@link com.google.common.collect.Maps#asConverter Maps.asConverter} instead to get a
* function that also supports reverse conversion.
*
* <p><b>Java 8+ users:</b> if you are okay with {@code null} being returned for an unrecognized
* key (instead of an exception being thrown), you can use the method reference {@code map::get}
* instead.
*/
public static <K extends @Nullable Object, V extends @Nullable Object> Function<K, V> forMap(
Map<K, V> map) {
return new FunctionForMapNoDefault<>(map);
}
/**
* Returns a function which performs a map lookup with a default value. The function created by
* this method returns {@code defaultValue} for all inputs that do not belong to the map's key
* set. See also {@link #forMap(Map)}, which throws an exception in this case.
*
* <p><b>Java 8+ users:</b> you can just write the lambda expression {@code k ->
* map.getOrDefault(k, defaultValue)} instead.
*
* @param map source map that determines the function behavior
* @param defaultValue the value to return for inputs that aren't map keys
* @return function that returns {@code map.get(a)} when {@code a} is a key, or {@code
* defaultValue} otherwise
*/
public static <K extends @Nullable Object, V extends @Nullable Object> Function<K, V> forMap(
Map<K, ? extends V> map, @ParametricNullness V defaultValue) {
return new ForMapWithDefault<>(map, defaultValue);
}
private static class FunctionForMapNoDefault<
K extends @Nullable Object, V extends @Nullable Object>
implements Function<K, V>, Serializable {
final Map<K, V> map;
FunctionForMapNoDefault(Map<K, V> map) {
this.map = checkNotNull(map);
}
@Override
@ParametricNullness
public V apply(@ParametricNullness K key) {
V result = map.get(key);
checkArgument(result != null || map.containsKey(key), "Key '%s' not present in map", key);
// The unchecked cast is safe because of the containsKey check.
return uncheckedCastNullableTToT(result);
}
@Override
public boolean equals(@CheckForNull Object o) {
if (o instanceof FunctionForMapNoDefault) {
FunctionForMapNoDefault<?, ?> that = (FunctionForMapNoDefault<?, ?>) o;
return map.equals(that.map);
}
return false;
}
@Override
public int hashCode() {
return map.hashCode();
}
@Override
public String toString() {
return "Functions.forMap(" + map + ")";
}
private static final long serialVersionUID = 0;
}
private static class ForMapWithDefault<K extends @Nullable Object, V extends @Nullable Object>
implements Function<K, V>, Serializable {
final Map<K, ? extends V> map;
@ParametricNullness final V defaultValue;
ForMapWithDefault(Map<K, ? extends V> map, @ParametricNullness V defaultValue) {
this.map = checkNotNull(map);
this.defaultValue = defaultValue;
}
@Override
@ParametricNullness
public V apply(@ParametricNullness K key) {
V result = map.get(key);
// The unchecked cast is safe because of the containsKey check.
return (result != null || map.containsKey(key))
? uncheckedCastNullableTToT(result)
: defaultValue;
}
@Override
public boolean equals(@CheckForNull Object o) {
if (o instanceof ForMapWithDefault) {
ForMapWithDefault<?, ?> that = (ForMapWithDefault<?, ?>) o;
return map.equals(that.map) && Objects.equal(defaultValue, that.defaultValue);
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(map, defaultValue);
}
@Override
public String toString() {
// TODO(cpovirk): maybe remove "defaultValue=" to make this look like the method call does
return "Functions.forMap(" + map + ", defaultValue=" + defaultValue + ")";
}
private static final long serialVersionUID = 0;
}
/**
* Returns the composition of two functions. For {@code f: A->B} and {@code g: B->C}, composition
* is defined as the function h such that {@code h(a) == g(f(a))} for each {@code a}.
*
* <p><b>Java 8+ users:</b> use {@code g.compose(f)} or (probably clearer) {@code f.andThen(g)}
* instead.
*
* @param g the second function to apply
* @param f the first function to apply
* @return the composition of {@code f} and {@code g}
* @see <a href="//en.wikipedia.org/wiki/Function_composition">function composition</a>
*/
public static <A extends @Nullable Object, B extends @Nullable Object, C extends @Nullable Object>
Function<A, C> compose(Function<B, C> g, Function<A, ? extends B> f) {
return new FunctionComposition<>(g, f);
}
private static class FunctionComposition<
A extends @Nullable Object, B extends @Nullable Object, C extends @Nullable Object>
implements Function<A, C>, Serializable {
private final Function<B, C> g;
private final Function<A, ? extends B> f;
public FunctionComposition(Function<B, C> g, Function<A, ? extends B> f) {
this.g = checkNotNull(g);
this.f = checkNotNull(f);
}
@Override
@ParametricNullness
public C apply(@ParametricNullness A a) {
return g.apply(f.apply(a));
}
@Override
public boolean equals(@CheckForNull Object obj) {
if (obj instanceof FunctionComposition) {
FunctionComposition<?, ?, ?> that = (FunctionComposition<?, ?, ?>) obj;
return f.equals(that.f) && g.equals(that.g);
}
return false;
}
@Override
public int hashCode() {
return f.hashCode() ^ g.hashCode();
}
@Override
public String toString() {
// TODO(cpovirk): maybe make this look like the method call does ("Functions.compose(...)")
return g + "(" + f + ")";
}
private static final long serialVersionUID = 0;
}
/**
* Creates a function that returns the same boolean output as the given predicate for all inputs.
*
* <p>The returned function is <i>consistent with equals</i> (as documented at {@link
* Function#apply}) if and only if {@code predicate} is itself consistent with equals.
*
* <p><b>Java 8+ users:</b> use the method reference {@code predicate::test} instead.
*/
public static <T extends @Nullable Object> Function<T, Boolean> forPredicate(
Predicate<T> predicate) {
return new PredicateFunction<>(predicate);
}
/** @see Functions#forPredicate */
private static class PredicateFunction<T extends @Nullable Object>
implements Function<T, Boolean>, Serializable {
private final Predicate<T> predicate;
private PredicateFunction(Predicate<T> predicate) {
this.predicate = checkNotNull(predicate);
}
@Override
public Boolean apply(@ParametricNullness T t) {
return predicate.apply(t);
}
@Override
public boolean equals(@CheckForNull Object obj) {
if (obj instanceof PredicateFunction) {
PredicateFunction<?> that = (PredicateFunction<?>) obj;
return predicate.equals(that.predicate);
}
return false;
}
@Override
public int hashCode() {
return predicate.hashCode();
}
@Override
public String toString() {
return "Functions.forPredicate(" + predicate + ")";
}
private static final long serialVersionUID = 0;
}
/**
* Returns a function that ignores its input and always returns {@code value}.
*
* <p><b>Java 8+ users:</b> use the lambda expression {@code o -> value} instead.
*
* @param value the constant value for the function to return
* @return a function that always returns {@code value}
*/
public static <E extends @Nullable Object> Function<@Nullable Object, E> constant(
@ParametricNullness E value) {
return new ConstantFunction<>(value);
}
private static class ConstantFunction<E extends @Nullable Object>
implements Function<@Nullable Object, E>, Serializable {
@ParametricNullness private final E value;
public ConstantFunction(@ParametricNullness E value) {
this.value = value;
}
@Override
@ParametricNullness
public E apply(@CheckForNull Object from) {
return value;
}
@Override
public boolean equals(@CheckForNull Object obj) {
if (obj instanceof ConstantFunction) {
ConstantFunction<?> that = (ConstantFunction<?>) obj;
return Objects.equal(value, that.value);
}
return false;
}
@Override
public int hashCode() {
return (value == null) ? 0 : value.hashCode();
}
@Override
public String toString() {
return "Functions.constant(" + value + ")";
}
private static final long serialVersionUID = 0;
}
/**
* Returns a function that ignores its input and returns the result of {@code supplier.get()}.
*
* <p><b>Java 8+ users:</b> use the lambda expression {@code o -> supplier.get()} instead.
*
* @since 10.0
*/
public static <F extends @Nullable Object, T extends @Nullable Object> Function<F, T> forSupplier(
Supplier<T> supplier) {
return new SupplierFunction<>(supplier);
}
/** @see Functions#forSupplier */
private static class SupplierFunction<F extends @Nullable Object, T extends @Nullable Object>
implements Function<F, T>, Serializable {
private final Supplier<T> supplier;
private SupplierFunction(Supplier<T> supplier) {
this.supplier = checkNotNull(supplier);
}
@Override
@ParametricNullness
public T apply(@ParametricNullness F input) {
return supplier.get();
}
@Override
public boolean equals(@CheckForNull Object obj) {
if (obj instanceof SupplierFunction) {
SupplierFunction<?, ?> that = (SupplierFunction<?, ?>) obj;
return this.supplier.equals(that.supplier);
}
return false;
}
@Override
public int hashCode() {
return supplier.hashCode();
}
@Override
public String toString() {
return "Functions.forSupplier(" + supplier + ")";
}
private static final long serialVersionUID = 0;
}
}
| google/guava | android/guava/src/com/google/common/base/Functions.java |
44,397 | /*
* Copyright (C) 2011 The Guava Authors
*
* 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.google.common.hash;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Throwables.throwIfUnchecked;
import static java.lang.invoke.MethodType.methodType;
import com.google.errorprone.annotations.Immutable;
import com.google.j2objc.annotations.J2ObjCIncompatible;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.security.Key;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.zip.Adler32;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
import javax.annotation.CheckForNull;
import javax.crypto.spec.SecretKeySpec;
/**
* Static methods to obtain {@link HashFunction} instances, and other static hashing-related
* utilities.
*
* <p>A comparison of the various hash functions can be found <a
* href="http://goo.gl/jS7HH">here</a>.
*
* @author Kevin Bourrillion
* @author Dimitris Andreou
* @author Kurt Alfred Kluever
* @since 11.0
*/
@ElementTypesAreNonnullByDefault
public final class Hashing {
/**
* Returns a general-purpose, <b>temporary-use</b>, non-cryptographic hash function. The algorithm
* the returned function implements is unspecified and subject to change without notice.
*
* <p><b>Warning:</b> a new random seed for these functions is chosen each time the {@code
* Hashing} class is loaded. <b>Do not use this method</b> if hash codes may escape the current
* process in any way, for example being sent over RPC, or saved to disk. For a general-purpose,
* non-cryptographic hash function that will never change behavior, we suggest {@link
* #murmur3_128}.
*
* <p>Repeated calls to this method on the same loaded {@code Hashing} class, using the same value
* for {@code minimumBits}, will return identically-behaving {@link HashFunction} instances.
*
* @param minimumBits a positive integer. This can be arbitrarily large. The returned {@link
* HashFunction} instance may use memory proportional to this integer.
* @return a hash function, described above, that produces hash codes of length {@code
* minimumBits} or greater
*/
public static HashFunction goodFastHash(int minimumBits) {
int bits = checkPositiveAndMakeMultipleOf32(minimumBits);
if (bits == 32) {
return Murmur3_32HashFunction.GOOD_FAST_HASH_32;
}
if (bits <= 128) {
return Murmur3_128HashFunction.GOOD_FAST_HASH_128;
}
// Otherwise, join together some 128-bit murmur3s
int hashFunctionsNeeded = (bits + 127) / 128;
HashFunction[] hashFunctions = new HashFunction[hashFunctionsNeeded];
hashFunctions[0] = Murmur3_128HashFunction.GOOD_FAST_HASH_128;
int seed = GOOD_FAST_HASH_SEED;
for (int i = 1; i < hashFunctionsNeeded; i++) {
seed += 1500450271; // a prime; shouldn't matter
hashFunctions[i] = murmur3_128(seed);
}
return new ConcatenatedHashFunction(hashFunctions);
}
/**
* Used to randomize {@link #goodFastHash} instances, so that programs which persist anything
* dependent on the hash codes they produce will fail sooner.
*/
@SuppressWarnings("GoodTime") // reading system time without TimeSource
static final int GOOD_FAST_HASH_SEED = (int) System.currentTimeMillis();
/**
* Returns a hash function implementing the <a
* href="https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp">32-bit murmur3
* algorithm, x86 variant</a> (little-endian variant), using the given seed value, <b>with a known
* bug</b> as described in the deprecation text.
*
* <p>The C++ equivalent is the MurmurHash3_x86_32 function (Murmur3A), which however does not
* have the bug.
*
* @deprecated This implementation produces incorrect hash values from the {@link
* HashFunction#hashString} method if the string contains non-BMP characters. Use {@link
* #murmur3_32_fixed(int)} instead.
*/
@Deprecated
public static HashFunction murmur3_32(int seed) {
return new Murmur3_32HashFunction(seed, /* supplementaryPlaneFix= */ false);
}
/**
* Returns a hash function implementing the <a
* href="https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp">32-bit murmur3
* algorithm, x86 variant</a> (little-endian variant), using the given seed value, <b>with a known
* bug</b> as described in the deprecation text.
*
* <p>The C++ equivalent is the MurmurHash3_x86_32 function (Murmur3A), which however does not
* have the bug.
*
* @deprecated This implementation produces incorrect hash values from the {@link
* HashFunction#hashString} method if the string contains non-BMP characters. Use {@link
* #murmur3_32_fixed()} instead.
*/
@Deprecated
public static HashFunction murmur3_32() {
return Murmur3_32HashFunction.MURMUR3_32;
}
/**
* Returns a hash function implementing the <a
* href="https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp">32-bit murmur3
* algorithm, x86 variant</a> (little-endian variant), using the given seed value.
*
* <p>The exact C++ equivalent is the MurmurHash3_x86_32 function (Murmur3A).
*
* <p>This method is called {@code murmur3_32_fixed} because it fixes a bug in the {@code
* HashFunction} returned by the original {@code murmur3_32} method.
*
* @since 31.0
*/
public static HashFunction murmur3_32_fixed(int seed) {
return new Murmur3_32HashFunction(seed, /* supplementaryPlaneFix= */ true);
}
/**
* Returns a hash function implementing the <a
* href="https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp">32-bit murmur3
* algorithm, x86 variant</a> (little-endian variant), using a seed value of zero.
*
* <p>The exact C++ equivalent is the MurmurHash3_x86_32 function (Murmur3A).
*
* <p>This method is called {@code murmur3_32_fixed} because it fixes a bug in the {@code
* HashFunction} returned by the original {@code murmur3_32} method.
*
* @since 31.0
*/
public static HashFunction murmur3_32_fixed() {
return Murmur3_32HashFunction.MURMUR3_32_FIXED;
}
/**
* Returns a hash function implementing the <a
* href="https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp">128-bit murmur3
* algorithm, x64 variant</a> (little-endian variant), using the given seed value.
*
* <p>The exact C++ equivalent is the MurmurHash3_x64_128 function (Murmur3F).
*/
public static HashFunction murmur3_128(int seed) {
return new Murmur3_128HashFunction(seed);
}
/**
* Returns a hash function implementing the <a
* href="https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp">128-bit murmur3
* algorithm, x64 variant</a> (little-endian variant), using a seed value of zero.
*
* <p>The exact C++ equivalent is the MurmurHash3_x64_128 function (Murmur3F).
*/
public static HashFunction murmur3_128() {
return Murmur3_128HashFunction.MURMUR3_128;
}
/**
* Returns a hash function implementing the <a href="https://131002.net/siphash/">64-bit
* SipHash-2-4 algorithm</a> using a seed value of {@code k = 00 01 02 ...}.
*
* @since 15.0
*/
public static HashFunction sipHash24() {
return SipHashFunction.SIP_HASH_24;
}
/**
* Returns a hash function implementing the <a href="https://131002.net/siphash/">64-bit
* SipHash-2-4 algorithm</a> using the given seed.
*
* @since 15.0
*/
public static HashFunction sipHash24(long k0, long k1) {
return new SipHashFunction(2, 4, k0, k1);
}
/**
* Returns a hash function implementing the MD5 hash algorithm (128 hash bits).
*
* @deprecated If you must interoperate with a system that requires MD5, then use this method,
* despite its deprecation. But if you can choose your hash function, avoid MD5, which is
* neither fast nor secure. As of January 2017, we suggest:
* <ul>
* <li>For security:
* {@link Hashing#sha256} or a higher-level API.
* <li>For speed: {@link Hashing#goodFastHash}, though see its docs for caveats.
* </ul>
*/
@Deprecated
public static HashFunction md5() {
return Md5Holder.MD5;
}
private static class Md5Holder {
static final HashFunction MD5 = new MessageDigestHashFunction("MD5", "Hashing.md5()");
}
/**
* Returns a hash function implementing the SHA-1 algorithm (160 hash bits).
*
* @deprecated If you must interoperate with a system that requires SHA-1, then use this method,
* despite its deprecation. But if you can choose your hash function, avoid SHA-1, which is
* neither fast nor secure. As of January 2017, we suggest:
* <ul>
* <li>For security:
* {@link Hashing#sha256} or a higher-level API.
* <li>For speed: {@link Hashing#goodFastHash}, though see its docs for caveats.
* </ul>
*/
@Deprecated
public static HashFunction sha1() {
return Sha1Holder.SHA_1;
}
private static class Sha1Holder {
static final HashFunction SHA_1 = new MessageDigestHashFunction("SHA-1", "Hashing.sha1()");
}
/** Returns a hash function implementing the SHA-256 algorithm (256 hash bits). */
public static HashFunction sha256() {
return Sha256Holder.SHA_256;
}
private static class Sha256Holder {
static final HashFunction SHA_256 =
new MessageDigestHashFunction("SHA-256", "Hashing.sha256()");
}
/**
* Returns a hash function implementing the SHA-384 algorithm (384 hash bits).
*
* @since 19.0
*/
public static HashFunction sha384() {
return Sha384Holder.SHA_384;
}
private static class Sha384Holder {
static final HashFunction SHA_384 =
new MessageDigestHashFunction("SHA-384", "Hashing.sha384()");
}
/** Returns a hash function implementing the SHA-512 algorithm (512 hash bits). */
public static HashFunction sha512() {
return Sha512Holder.SHA_512;
}
private static class Sha512Holder {
static final HashFunction SHA_512 =
new MessageDigestHashFunction("SHA-512", "Hashing.sha512()");
}
/**
* Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the
* MD5 (128 hash bits) hash function and the given secret key.
*
* <p>If you are designing a new system that needs HMAC, prefer {@link #hmacSha256} or other
* future-proof algorithms <a
* href="https://datatracker.ietf.org/doc/html/rfc6151#section-2.3">over {@code hmacMd5}</a>.
*
* @param key the secret key
* @throws IllegalArgumentException if the given key is inappropriate for initializing this MAC
* @since 20.0
*/
public static HashFunction hmacMd5(Key key) {
return new MacHashFunction("HmacMD5", key, hmacToString("hmacMd5", key));
}
/**
* Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the
* MD5 (128 hash bits) hash function and a {@link SecretKeySpec} created from the given byte array
* and the MD5 algorithm.
*
* <p>If you are designing a new system that needs HMAC, prefer {@link #hmacSha256} or other
* future-proof algorithms <a
* href="https://datatracker.ietf.org/doc/html/rfc6151#section-2.3">over {@code hmacMd5}</a>.
*
* @param key the key material of the secret key
* @since 20.0
*/
public static HashFunction hmacMd5(byte[] key) {
return hmacMd5(new SecretKeySpec(checkNotNull(key), "HmacMD5"));
}
/**
* Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the
* SHA-1 (160 hash bits) hash function and the given secret key.
*
* @param key the secret key
* @throws IllegalArgumentException if the given key is inappropriate for initializing this MAC
* @since 20.0
*/
public static HashFunction hmacSha1(Key key) {
return new MacHashFunction("HmacSHA1", key, hmacToString("hmacSha1", key));
}
/**
* Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the
* SHA-1 (160 hash bits) hash function and a {@link SecretKeySpec} created from the given byte
* array and the SHA-1 algorithm.
*
* @param key the key material of the secret key
* @since 20.0
*/
public static HashFunction hmacSha1(byte[] key) {
return hmacSha1(new SecretKeySpec(checkNotNull(key), "HmacSHA1"));
}
/**
* Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the
* SHA-256 (256 hash bits) hash function and the given secret key.
*
* @param key the secret key
* @throws IllegalArgumentException if the given key is inappropriate for initializing this MAC
* @since 20.0
*/
public static HashFunction hmacSha256(Key key) {
return new MacHashFunction("HmacSHA256", key, hmacToString("hmacSha256", key));
}
/**
* Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the
* SHA-256 (256 hash bits) hash function and a {@link SecretKeySpec} created from the given byte
* array and the SHA-256 algorithm.
*
* @param key the key material of the secret key
* @since 20.0
*/
public static HashFunction hmacSha256(byte[] key) {
return hmacSha256(new SecretKeySpec(checkNotNull(key), "HmacSHA256"));
}
/**
* Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the
* SHA-512 (512 hash bits) hash function and the given secret key.
*
* @param key the secret key
* @throws IllegalArgumentException if the given key is inappropriate for initializing this MAC
* @since 20.0
*/
public static HashFunction hmacSha512(Key key) {
return new MacHashFunction("HmacSHA512", key, hmacToString("hmacSha512", key));
}
/**
* Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the
* SHA-512 (512 hash bits) hash function and a {@link SecretKeySpec} created from the given byte
* array and the SHA-512 algorithm.
*
* @param key the key material of the secret key
* @since 20.0
*/
public static HashFunction hmacSha512(byte[] key) {
return hmacSha512(new SecretKeySpec(checkNotNull(key), "HmacSHA512"));
}
private static String hmacToString(String methodName, Key key) {
return "Hashing."
+ methodName
+ "(Key[algorithm="
+ key.getAlgorithm()
+ ", format="
+ key.getFormat()
+ "])";
}
/**
* Returns a hash function implementing the CRC32C checksum algorithm (32 hash bits) as described
* by RFC 3720, Section 12.1.
*
* <p>This function is best understood as a <a
* href="https://en.wikipedia.org/wiki/Checksum">checksum</a> rather than a true <a
* href="https://en.wikipedia.org/wiki/Hash_function">hash function</a>.
*
* @since 18.0
*/
public static HashFunction crc32c() {
return Crc32CSupplier.HASH_FUNCTION;
}
@Immutable
private enum Crc32CSupplier implements ImmutableSupplier<HashFunction> {
@J2ObjCIncompatible
JAVA_UTIL_ZIP {
@Override
public HashFunction get() {
return ChecksumType.CRC_32C.hashFunction;
}
},
ABSTRACT_HASH_FUNCTION {
@Override
public HashFunction get() {
return Crc32cHashFunction.CRC_32_C;
}
};
static final HashFunction HASH_FUNCTION = pickFunction().get();
private static Crc32CSupplier pickFunction() {
Crc32CSupplier[] functions = values();
if (functions.length == 1) {
// We're running under J2ObjC.
return functions[0];
}
// We can't refer to JAVA_UTIL_ZIP directly at compile time because of J2ObjC.
Crc32CSupplier javaUtilZip = functions[0];
try {
Class.forName("java.util.zip.CRC32C");
return javaUtilZip;
} catch (ClassNotFoundException runningUnderJava8) {
return ABSTRACT_HASH_FUNCTION;
}
}
}
/**
* Returns a hash function implementing the CRC-32 checksum algorithm (32 hash bits).
*
* <p>To get the {@code long} value equivalent to {@link Checksum#getValue()} for a {@code
* HashCode} produced by this function, use {@link HashCode#padToLong()}.
*
* <p>This function is best understood as a <a
* href="https://en.wikipedia.org/wiki/Checksum">checksum</a> rather than a true <a
* href="https://en.wikipedia.org/wiki/Hash_function">hash function</a>.
*
* @since 14.0
*/
public static HashFunction crc32() {
return ChecksumType.CRC_32.hashFunction;
}
/**
* Returns a hash function implementing the Adler-32 checksum algorithm (32 hash bits).
*
* <p>To get the {@code long} value equivalent to {@link Checksum#getValue()} for a {@code
* HashCode} produced by this function, use {@link HashCode#padToLong()}.
*
* <p>This function is best understood as a <a
* href="https://en.wikipedia.org/wiki/Checksum">checksum</a> rather than a true <a
* href="https://en.wikipedia.org/wiki/Hash_function">hash function</a>.
*
* @since 14.0
*/
public static HashFunction adler32() {
return ChecksumType.ADLER_32.hashFunction;
}
@Immutable
enum ChecksumType implements ImmutableSupplier<Checksum> {
CRC_32("Hashing.crc32()") {
@Override
public Checksum get() {
return new CRC32();
}
},
@J2ObjCIncompatible
CRC_32C("Hashing.crc32c()") {
@Override
public Checksum get() {
return Crc32cMethodHandles.newCrc32c();
}
},
ADLER_32("Hashing.adler32()") {
@Override
public Checksum get() {
return new Adler32();
}
};
public final HashFunction hashFunction;
ChecksumType(String toString) {
this.hashFunction = new ChecksumHashFunction(this, 32, toString);
}
}
@J2ObjCIncompatible
@SuppressWarnings("unused")
private static final class Crc32cMethodHandles {
private static final MethodHandle CONSTRUCTOR = crc32cConstructor();
@IgnoreJRERequirement // https://github.com/mojohaus/animal-sniffer/issues/67
static Checksum newCrc32c() {
try {
return (Checksum) CONSTRUCTOR.invokeExact();
} catch (Throwable e) {
throwIfUnchecked(e);
// That constructor has no `throws` clause.
throw newLinkageError(e);
}
}
private static MethodHandle crc32cConstructor() {
try {
Class<?> clazz = Class.forName("java.util.zip.CRC32C");
/*
* We can't cast to CRC32C at the call site because we support building with Java 8
* (https://github.com/google/guava/issues/6549). So we have to use asType() to change from
* CRC32C to Checksum. This may carry some performance cost
* (https://stackoverflow.com/a/22321671/28465), but I'd have to benchmark more carefully to
* even detect it.
*/
return MethodHandles.lookup()
.findConstructor(clazz, methodType(void.class))
.asType(methodType(Checksum.class));
} catch (ClassNotFoundException e) {
// We check that the class is available before calling this method.
throw new AssertionError(e);
} catch (IllegalAccessException e) {
// That API is public.
throw newLinkageError(e);
} catch (NoSuchMethodException e) {
// That constructor exists.
throw newLinkageError(e);
}
}
private static LinkageError newLinkageError(Throwable cause) {
return new LinkageError(cause.toString(), cause);
}
}
/**
* Returns a hash function implementing FarmHash's Fingerprint64, an open-source algorithm.
*
* <p>This is designed for generating persistent fingerprints of strings. It isn't
* cryptographically secure, but it produces a high-quality hash with fewer collisions than some
* alternatives we've used in the past.
*
* <p>FarmHash fingerprints are encoded by {@link HashCode#asBytes} in little-endian order. This
* means {@link HashCode#asLong} is guaranteed to return the same value that
* farmhash::Fingerprint64() would for the same input (when compared using {@link
* com.google.common.primitives.UnsignedLongs}'s encoding of 64-bit unsigned numbers).
*
* <p>This function is best understood as a <a
* href="https://en.wikipedia.org/wiki/Fingerprint_(computing)">fingerprint</a> rather than a true
* <a href="https://en.wikipedia.org/wiki/Hash_function">hash function</a>.
*
* @since 20.0
*/
public static HashFunction farmHashFingerprint64() {
return FarmHashFingerprint64.FARMHASH_FINGERPRINT_64;
}
/**
* Returns a hash function implementing the Fingerprint2011 hashing function (64 hash bits).
*
* <p>This is designed for generating persistent fingerprints of strings. It isn't
* cryptographically secure, but it produces a high-quality hash with few collisions. Fingerprints
* generated using this are byte-wise identical to those created using the C++ version, but note
* that this uses unsigned integers (see {@link com.google.common.primitives.UnsignedInts}).
* Comparisons between the two should take this into account.
*
* <p>Fingerprint2011() is a form of Murmur2 on strings up to 32 bytes and a form of CityHash for
* longer strings. It could have been one or the other throughout. The main advantage of the
* combination is that CityHash has a bunch of special cases for short strings that don't need to
* be replicated here. The result will never be 0 or 1.
*
* <p>This function is best understood as a <a
* href="https://en.wikipedia.org/wiki/Fingerprint_(computing)">fingerprint</a> rather than a true
* <a href="https://en.wikipedia.org/wiki/Hash_function">hash function</a>.
*
* @since 31.1
*/
public static HashFunction fingerprint2011() {
return Fingerprint2011.FINGERPRINT_2011;
}
/**
* Assigns to {@code hashCode} a "bucket" in the range {@code [0, buckets)}, in a uniform manner
* that minimizes the need for remapping as {@code buckets} grows. That is, {@code
* consistentHash(h, n)} equals:
*
* <ul>
* <li>{@code n - 1}, with approximate probability {@code 1/n}
* <li>{@code consistentHash(h, n - 1)}, otherwise (probability {@code 1 - 1/n})
* </ul>
*
* <p>This method is suitable for the common use case of dividing work among buckets that meet the
* following conditions:
*
* <ul>
* <li>You want to assign the same fraction of inputs to each bucket.
* <li>When you reduce the number of buckets, you can accept that the most recently added
* buckets will be removed first. More concretely, if you are dividing traffic among tasks,
* you can decrease the number of tasks from 15 and 10, killing off the final 5 tasks, and
* {@code consistentHash} will handle it. If, however, you are dividing traffic among
* servers {@code alpha}, {@code bravo}, and {@code charlie} and you occasionally need to
* take each of the servers offline, {@code consistentHash} will be a poor fit: It provides
* no way for you to specify which of the three buckets is disappearing. Thus, if your
* buckets change from {@code [alpha, bravo, charlie]} to {@code [bravo, charlie]}, it will
* assign all the old {@code alpha} traffic to {@code bravo} and all the old {@code bravo}
* traffic to {@code charlie}, rather than letting {@code bravo} keep its traffic.
* </ul>
*
* <p>See the <a href="http://en.wikipedia.org/wiki/Consistent_hashing">Wikipedia article on
* consistent hashing</a> for more information.
*/
public static int consistentHash(HashCode hashCode, int buckets) {
return consistentHash(hashCode.padToLong(), buckets);
}
/**
* Assigns to {@code input} a "bucket" in the range {@code [0, buckets)}, in a uniform manner that
* minimizes the need for remapping as {@code buckets} grows. That is, {@code consistentHash(h,
* n)} equals:
*
* <ul>
* <li>{@code n - 1}, with approximate probability {@code 1/n}
* <li>{@code consistentHash(h, n - 1)}, otherwise (probability {@code 1 - 1/n})
* </ul>
*
* <p>This method is suitable for the common use case of dividing work among buckets that meet the
* following conditions:
*
* <ul>
* <li>You want to assign the same fraction of inputs to each bucket.
* <li>When you reduce the number of buckets, you can accept that the most recently added
* buckets will be removed first. More concretely, if you are dividing traffic among tasks,
* you can decrease the number of tasks from 15 and 10, killing off the final 5 tasks, and
* {@code consistentHash} will handle it. If, however, you are dividing traffic among
* servers {@code alpha}, {@code bravo}, and {@code charlie} and you occasionally need to
* take each of the servers offline, {@code consistentHash} will be a poor fit: It provides
* no way for you to specify which of the three buckets is disappearing. Thus, if your
* buckets change from {@code [alpha, bravo, charlie]} to {@code [bravo, charlie]}, it will
* assign all the old {@code alpha} traffic to {@code bravo} and all the old {@code bravo}
* traffic to {@code charlie}, rather than letting {@code bravo} keep its traffic.
* </ul>
*
* <p>See the <a href="http://en.wikipedia.org/wiki/Consistent_hashing">Wikipedia article on
* consistent hashing</a> for more information.
*/
public static int consistentHash(long input, int buckets) {
checkArgument(buckets > 0, "buckets must be positive: %s", buckets);
LinearCongruentialGenerator generator = new LinearCongruentialGenerator(input);
int candidate = 0;
int next;
// Jump from bucket to bucket until we go out of range
while (true) {
next = (int) ((candidate + 1) / generator.nextDouble());
if (next >= 0 && next < buckets) {
candidate = next;
} else {
return candidate;
}
}
}
/**
* Returns a hash code, having the same bit length as each of the input hash codes, that combines
* the information of these hash codes in an ordered fashion. That is, whenever two equal hash
* codes are produced by two calls to this method, it is <i>as likely as possible</i> that each
* was computed from the <i>same</i> input hash codes in the <i>same</i> order.
*
* @throws IllegalArgumentException if {@code hashCodes} is empty, or the hash codes do not all
* have the same bit length
*/
public static HashCode combineOrdered(Iterable<HashCode> hashCodes) {
Iterator<HashCode> iterator = hashCodes.iterator();
checkArgument(iterator.hasNext(), "Must be at least 1 hash code to combine.");
int bits = iterator.next().bits();
byte[] resultBytes = new byte[bits / 8];
for (HashCode hashCode : hashCodes) {
byte[] nextBytes = hashCode.asBytes();
checkArgument(
nextBytes.length == resultBytes.length, "All hashcodes must have the same bit length.");
for (int i = 0; i < nextBytes.length; i++) {
resultBytes[i] = (byte) (resultBytes[i] * 37 ^ nextBytes[i]);
}
}
return HashCode.fromBytesNoCopy(resultBytes);
}
/**
* Returns a hash code, having the same bit length as each of the input hash codes, that combines
* the information of these hash codes in an unordered fashion. That is, whenever two equal hash
* codes are produced by two calls to this method, it is <i>as likely as possible</i> that each
* was computed from the <i>same</i> input hash codes in <i>some</i> order.
*
* @throws IllegalArgumentException if {@code hashCodes} is empty, or the hash codes do not all
* have the same bit length
*/
public static HashCode combineUnordered(Iterable<HashCode> hashCodes) {
Iterator<HashCode> iterator = hashCodes.iterator();
checkArgument(iterator.hasNext(), "Must be at least 1 hash code to combine.");
byte[] resultBytes = new byte[iterator.next().bits() / 8];
for (HashCode hashCode : hashCodes) {
byte[] nextBytes = hashCode.asBytes();
checkArgument(
nextBytes.length == resultBytes.length, "All hashcodes must have the same bit length.");
for (int i = 0; i < nextBytes.length; i++) {
resultBytes[i] += nextBytes[i];
}
}
return HashCode.fromBytesNoCopy(resultBytes);
}
/** Checks that the passed argument is positive, and ceils it to a multiple of 32. */
static int checkPositiveAndMakeMultipleOf32(int bits) {
checkArgument(bits > 0, "Number of bits must be positive");
return (bits + 31) & ~31;
}
/**
* Returns a hash function which computes its hash code by concatenating the hash codes of the
* underlying hash functions together. This can be useful if you need to generate hash codes of a
* specific length.
*
* <p>For example, if you need 1024-bit hash codes, you could join two {@link Hashing#sha512} hash
* functions together: {@code Hashing.concatenating(Hashing.sha512(), Hashing.sha512())}.
*
* @since 19.0
*/
public static HashFunction concatenating(
HashFunction first, HashFunction second, HashFunction... rest) {
// We can't use Lists.asList() here because there's no hash->collect dependency
List<HashFunction> list = new ArrayList<>();
list.add(first);
list.add(second);
Collections.addAll(list, rest);
return new ConcatenatedHashFunction(list.toArray(new HashFunction[0]));
}
/**
* Returns a hash function which computes its hash code by concatenating the hash codes of the
* underlying hash functions together. This can be useful if you need to generate hash codes of a
* specific length.
*
* <p>For example, if you need 1024-bit hash codes, you could join two {@link Hashing#sha512} hash
* functions together: {@code Hashing.concatenating(Hashing.sha512(), Hashing.sha512())}.
*
* @since 19.0
*/
public static HashFunction concatenating(Iterable<HashFunction> hashFunctions) {
checkNotNull(hashFunctions);
// We can't use Iterables.toArray() here because there's no hash->collect dependency
List<HashFunction> list = new ArrayList<>();
for (HashFunction hashFunction : hashFunctions) {
list.add(hashFunction);
}
checkArgument(!list.isEmpty(), "number of hash functions (%s) must be > 0", list.size());
return new ConcatenatedHashFunction(list.toArray(new HashFunction[0]));
}
private static final class ConcatenatedHashFunction extends AbstractCompositeHashFunction {
private ConcatenatedHashFunction(HashFunction... functions) {
super(functions);
for (HashFunction function : functions) {
checkArgument(
function.bits() % 8 == 0,
"the number of bits (%s) in hashFunction (%s) must be divisible by 8",
function.bits(),
function);
}
}
@Override
HashCode makeHash(Hasher[] hashers) {
byte[] bytes = new byte[bits() / 8];
int i = 0;
for (Hasher hasher : hashers) {
HashCode newHash = hasher.hash();
i += newHash.writeBytesTo(bytes, i, newHash.bits() / 8);
}
return HashCode.fromBytesNoCopy(bytes);
}
@Override
public int bits() {
int bitSum = 0;
for (HashFunction function : functions) {
bitSum += function.bits();
}
return bitSum;
}
@Override
public boolean equals(@CheckForNull Object object) {
if (object instanceof ConcatenatedHashFunction) {
ConcatenatedHashFunction other = (ConcatenatedHashFunction) object;
return Arrays.equals(functions, other.functions);
}
return false;
}
@Override
public int hashCode() {
return Arrays.hashCode(functions);
}
}
/**
* Linear CongruentialGenerator to use for consistent hashing. See
* http://en.wikipedia.org/wiki/Linear_congruential_generator
*/
private static final class LinearCongruentialGenerator {
private long state;
public LinearCongruentialGenerator(long seed) {
this.state = seed;
}
public double nextDouble() {
state = 2862933555777941757L * state + 1;
return ((double) ((int) (state >>> 33) + 1)) / 0x1.0p31;
}
}
private Hashing() {}
}
| google/guava | guava/src/com/google/common/hash/Hashing.java |
44,400 | /*
* Copyright (C) 2009 The Guava Authors
*
* 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.google.common.cache;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Ascii;
import com.google.common.base.Equivalence;
import com.google.common.base.MoreObjects;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.base.Ticker;
import com.google.common.cache.AbstractCache.SimpleStatsCounter;
import com.google.common.cache.AbstractCache.StatsCounter;
import com.google.common.cache.LocalCache.Strength;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.j2objc.annotations.J2ObjCIncompatible;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.ConcurrentModificationException;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.CheckForNull;
/**
* A builder of {@link LoadingCache} and {@link Cache} instances.
*
* <h2>Prefer <a href="https://github.com/ben-manes/caffeine/wiki">Caffeine</a> over Guava's caching
* API</h2>
*
* <p>The successor to Guava's caching API is <a
* href="https://github.com/ben-manes/caffeine/wiki">Caffeine</a>. Its API is designed to make it a
* nearly drop-in replacement. It requires Java 8+, and is not available for Android or GWT/J2CL,
* and may have <a href="https://github.com/ben-manes/caffeine/wiki/Guava">different (usually
* better) behavior</a> when multiple threads attempt concurrent mutations. Its equivalent to {@code
* CacheBuilder} is its <a
* href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/caffeine/latest/com.github.benmanes.caffeine/com/github/benmanes/caffeine/cache/Caffeine.html">{@code
* Caffeine}</a> class. Caffeine offers better performance, more features (including asynchronous
* loading), and fewer <a
* href="https://github.com/google/guava/issues?q=is%3Aopen+is%3Aissue+label%3Apackage%3Dcache+label%3Atype%3Ddefect">bugs</a>.
*
* <p>Caffeine defines its own interfaces (<a
* href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/caffeine/latest/com.github.benmanes.caffeine/com/github/benmanes/caffeine/cache/Cache.html">{@code
* Cache}</a>, <a
* href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/caffeine/latest/com.github.benmanes.caffeine/com/github/benmanes/caffeine/cache/LoadingCache.html">{@code
* LoadingCache}</a>, <a
* href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/caffeine/latest/com.github.benmanes.caffeine/com/github/benmanes/caffeine/cache/CacheLoader.html">{@code
* CacheLoader}</a>, etc.), so you can use Caffeine without needing to use any Guava types.
* Caffeine's types are better than Guava's, especially for <a
* href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/caffeine/latest/com.github.benmanes.caffeine/com/github/benmanes/caffeine/cache/AsyncLoadingCache.html">their
* deep support for asynchronous operations</a>. But if you want to migrate to Caffeine with minimal
* code changes, you can use <a
* href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/guava/latest/com.github.benmanes.caffeine.guava/com/github/benmanes/caffeine/guava/CaffeinatedGuava.html">its
* {@code CaffeinatedGuava} adapter class</a>, which lets you build a Guava {@code Cache} or a Guava
* {@code LoadingCache} backed by a Guava {@code CacheLoader}.
*
* <p>Caffeine's API for asynchronous operations uses {@code CompletableFuture}: <a
* href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/caffeine/latest/com.github.benmanes.caffeine/com/github/benmanes/caffeine/cache/AsyncLoadingCache.html#get(K)">{@code
* AsyncLoadingCache.get}</a> returns a {@code CompletableFuture}, and implementations of <a
* href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/caffeine/latest/com.github.benmanes.caffeine/com/github/benmanes/caffeine/cache/AsyncCacheLoader.html#asyncLoad(K,java.util.concurrent.Executor)">{@code
* AsyncCacheLoader.asyncLoad}</a> must return a {@code CompletableFuture}. Users of Guava's {@link
* com.google.common.util.concurrent.ListenableFuture} can adapt between the two {@code Future}
* types by using <a href="https://github.com/lukas-krecan/future-converter#java8-guava">{@code
* net.javacrumbs.futureconverter.java8guava.FutureConverter}</a>.
*
* <h2>More on {@code CacheBuilder}</h2>
*
* {@code CacheBuilder} builds caches with any combination of the following features:
*
* <ul>
* <li>automatic loading of entries into the cache
* <li>least-recently-used eviction when a maximum size is exceeded (note that the cache is
* divided into segments, each of which does LRU internally)
* <li>time-based expiration of entries, measured since last access or last write
* <li>keys automatically wrapped in {@code WeakReference}
* <li>values automatically wrapped in {@code WeakReference} or {@code SoftReference}
* <li>notification of evicted (or otherwise removed) entries
* <li>accumulation of cache access statistics
* </ul>
*
* <p>These features are all optional; caches can be created using all or none of them. By default,
* cache instances created by {@code CacheBuilder} will not perform any type of eviction.
*
* <p>Usage example:
*
* <pre>{@code
* LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
* .maximumSize(10000)
* .expireAfterWrite(Duration.ofMinutes(10))
* .removalListener(MY_LISTENER)
* .build(
* new CacheLoader<Key, Graph>() {
* public Graph load(Key key) throws AnyException {
* return createExpensiveGraph(key);
* }
* });
* }</pre>
*
* <p>Or equivalently,
*
* <pre>{@code
* // In real life this would come from a command-line flag or config file
* String spec = "maximumSize=10000,expireAfterWrite=10m";
*
* LoadingCache<Key, Graph> graphs = CacheBuilder.from(spec)
* .removalListener(MY_LISTENER)
* .build(
* new CacheLoader<Key, Graph>() {
* public Graph load(Key key) throws AnyException {
* return createExpensiveGraph(key);
* }
* });
* }</pre>
*
* <p>The returned cache implements all optional operations of the {@link LoadingCache} and {@link
* Cache} interfaces. The {@code asMap} view (and its collection views) have <i>weakly consistent
* iterators</i>. This means that they are safe for concurrent use, but if other threads modify the
* cache after the iterator is created, it is undefined which of these changes, if any, are
* reflected in that iterator. These iterators never throw {@link ConcurrentModificationException}.
*
* <p><b>Note:</b> by default, the returned cache uses equality comparisons (the {@link
* Object#equals equals} method) to determine equality for keys or values. However, if {@link
* #weakKeys} was specified, the cache uses identity ({@code ==}) comparisons instead for keys.
* Likewise, if {@link #weakValues} or {@link #softValues} was specified, the cache uses identity
* comparisons for values.
*
* <p>Entries are automatically evicted from the cache when any of {@link #maximumSize(long)
* maximumSize}, {@link #maximumWeight(long) maximumWeight}, {@link #expireAfterWrite
* expireAfterWrite}, {@link #expireAfterAccess expireAfterAccess}, {@link #weakKeys weakKeys},
* {@link #weakValues weakValues}, or {@link #softValues softValues} are requested.
*
* <p>If {@link #maximumSize(long) maximumSize} or {@link #maximumWeight(long) maximumWeight} is
* requested entries may be evicted on each cache modification.
*
* <p>If {@link #expireAfterWrite expireAfterWrite} or {@link #expireAfterAccess expireAfterAccess}
* is requested entries may be evicted on each cache modification, on occasional cache accesses, or
* on calls to {@link Cache#cleanUp}. Expired entries may be counted by {@link Cache#size}, but will
* never be visible to read or write operations.
*
* <p>If {@link #weakKeys weakKeys}, {@link #weakValues weakValues}, or {@link #softValues
* softValues} are requested, it is possible for a key or value present in the cache to be reclaimed
* by the garbage collector. Entries with reclaimed keys or values may be removed from the cache on
* each cache modification, on occasional cache accesses, or on calls to {@link Cache#cleanUp}; such
* entries may be counted in {@link Cache#size}, but will never be visible to read or write
* operations.
*
* <p>Certain cache configurations will result in the accrual of periodic maintenance tasks which
* will be performed during write operations, or during occasional read operations in the absence of
* writes. The {@link Cache#cleanUp} method of the returned cache will also perform maintenance, but
* calling it should not be necessary with a high throughput cache. Only caches built with {@link
* #removalListener removalListener}, {@link #expireAfterWrite expireAfterWrite}, {@link
* #expireAfterAccess expireAfterAccess}, {@link #weakKeys weakKeys}, {@link #weakValues
* weakValues}, or {@link #softValues softValues} perform periodic maintenance.
*
* <p>The caches produced by {@code CacheBuilder} are serializable, and the deserialized caches
* retain all the configuration properties of the original cache. Note that the serialized form does
* <i>not</i> include cache contents, but only configuration.
*
* <p>See the Guava User Guide article on <a
* href="https://github.com/google/guava/wiki/CachesExplained">caching</a> for a higher-level
* explanation.
*
* @param <K> the most general key type this builder will be able to create caches for. This is
* normally {@code Object} unless it is constrained by using a method like {@code
* #removalListener}. Cache keys may not be null.
* @param <V> the most general value type this builder will be able to create caches for. This is
* normally {@code Object} unless it is constrained by using a method like {@code
* #removalListener}. Cache values may not be null.
* @author Charles Fry
* @author Kevin Bourrillion
* @since 10.0
*/
@GwtCompatible(emulated = true)
@ElementTypesAreNonnullByDefault
public final class CacheBuilder<K, V> {
private static final int DEFAULT_INITIAL_CAPACITY = 16;
private static final int DEFAULT_CONCURRENCY_LEVEL = 4;
@SuppressWarnings("GoodTime") // should be a java.time.Duration
private static final int DEFAULT_EXPIRATION_NANOS = 0;
@SuppressWarnings("GoodTime") // should be a java.time.Duration
private static final int DEFAULT_REFRESH_NANOS = 0;
static final Supplier<? extends StatsCounter> NULL_STATS_COUNTER =
Suppliers.ofInstance(
new StatsCounter() {
@Override
public void recordHits(int count) {}
@Override
public void recordMisses(int count) {}
@SuppressWarnings("GoodTime") // b/122668874
@Override
public void recordLoadSuccess(long loadTime) {}
@SuppressWarnings("GoodTime") // b/122668874
@Override
public void recordLoadException(long loadTime) {}
@Override
public void recordEviction() {}
@Override
public CacheStats snapshot() {
return EMPTY_STATS;
}
});
static final CacheStats EMPTY_STATS = new CacheStats(0, 0, 0, 0, 0, 0);
/*
* We avoid using a method reference or lambda here for now:
*
* - method reference: Inside Google, CacheBuilder is used from the implementation of a custom
* ClassLoader that is sometimes used as a system classloader. That's a problem because
* method-reference linking tries to look up the system classloader, and it fails because there
* isn't one yet.
*
* - lambda: Outside Google, we got a report of a similar problem in
* https://github.com/google/guava/issues/6565
*/
@SuppressWarnings("AnonymousToLambda")
static final Supplier<StatsCounter> CACHE_STATS_COUNTER =
new Supplier<StatsCounter>() {
@Override
public StatsCounter get() {
return new SimpleStatsCounter();
}
};
enum NullListener implements RemovalListener<Object, Object> {
INSTANCE;
@Override
public void onRemoval(RemovalNotification<Object, Object> notification) {}
}
enum OneWeigher implements Weigher<Object, Object> {
INSTANCE;
@Override
public int weigh(Object key, Object value) {
return 1;
}
}
static final Ticker NULL_TICKER =
new Ticker() {
@Override
public long read() {
return 0;
}
};
// We use a holder class to delay initialization: https://github.com/google/guava/issues/6566
private static final class LoggerHolder {
static final Logger logger = Logger.getLogger(CacheBuilder.class.getName());
}
static final int UNSET_INT = -1;
boolean strictParsing = true;
int initialCapacity = UNSET_INT;
int concurrencyLevel = UNSET_INT;
long maximumSize = UNSET_INT;
long maximumWeight = UNSET_INT;
@CheckForNull Weigher<? super K, ? super V> weigher;
@CheckForNull Strength keyStrength;
@CheckForNull Strength valueStrength;
@SuppressWarnings("GoodTime") // should be a java.time.Duration
long expireAfterWriteNanos = UNSET_INT;
@SuppressWarnings("GoodTime") // should be a java.time.Duration
long expireAfterAccessNanos = UNSET_INT;
@SuppressWarnings("GoodTime") // should be a java.time.Duration
long refreshNanos = UNSET_INT;
@CheckForNull Equivalence<Object> keyEquivalence;
@CheckForNull Equivalence<Object> valueEquivalence;
@CheckForNull RemovalListener<? super K, ? super V> removalListener;
@CheckForNull Ticker ticker;
Supplier<? extends StatsCounter> statsCounterSupplier = NULL_STATS_COUNTER;
private CacheBuilder() {}
/**
* Constructs a new {@code CacheBuilder} instance with default settings, including strong keys,
* strong values, and no automatic eviction of any kind.
*
* <p>Note that while this return type is {@code CacheBuilder<Object, Object>}, type parameters on
* the {@link #build} methods allow you to create a cache of any key and value type desired.
*/
public static CacheBuilder<Object, Object> newBuilder() {
return new CacheBuilder<>();
}
/**
* Constructs a new {@code CacheBuilder} instance with the settings specified in {@code spec}.
*
* @since 12.0
*/
@GwtIncompatible // To be supported
public static CacheBuilder<Object, Object> from(CacheBuilderSpec spec) {
return spec.toCacheBuilder().lenientParsing();
}
/**
* Constructs a new {@code CacheBuilder} instance with the settings specified in {@code spec}.
* This is especially useful for command-line configuration of a {@code CacheBuilder}.
*
* @param spec a String in the format specified by {@link CacheBuilderSpec}
* @since 12.0
*/
@GwtIncompatible // To be supported
public static CacheBuilder<Object, Object> from(String spec) {
return from(CacheBuilderSpec.parse(spec));
}
/**
* Enables lenient parsing. Useful for tests and spec parsing.
*
* @return this {@code CacheBuilder} instance (for chaining)
*/
@GwtIncompatible // To be supported
@CanIgnoreReturnValue
CacheBuilder<K, V> lenientParsing() {
strictParsing = false;
return this;
}
/**
* Sets a custom {@code Equivalence} strategy for comparing keys.
*
* <p>By default, the cache uses {@link Equivalence#identity} to determine key equality when
* {@link #weakKeys} is specified, and {@link Equivalence#equals()} otherwise.
*
* @return this {@code CacheBuilder} instance (for chaining)
*/
@GwtIncompatible // To be supported
@CanIgnoreReturnValue
CacheBuilder<K, V> keyEquivalence(Equivalence<Object> equivalence) {
checkState(keyEquivalence == null, "key equivalence was already set to %s", keyEquivalence);
keyEquivalence = checkNotNull(equivalence);
return this;
}
Equivalence<Object> getKeyEquivalence() {
return MoreObjects.firstNonNull(keyEquivalence, getKeyStrength().defaultEquivalence());
}
/**
* Sets a custom {@code Equivalence} strategy for comparing values.
*
* <p>By default, the cache uses {@link Equivalence#identity} to determine value equality when
* {@link #weakValues} or {@link #softValues} is specified, and {@link Equivalence#equals()}
* otherwise.
*
* @return this {@code CacheBuilder} instance (for chaining)
*/
@GwtIncompatible // To be supported
@CanIgnoreReturnValue
CacheBuilder<K, V> valueEquivalence(Equivalence<Object> equivalence) {
checkState(
valueEquivalence == null, "value equivalence was already set to %s", valueEquivalence);
this.valueEquivalence = checkNotNull(equivalence);
return this;
}
Equivalence<Object> getValueEquivalence() {
return MoreObjects.firstNonNull(valueEquivalence, getValueStrength().defaultEquivalence());
}
/**
* Sets the minimum total size for the internal hash tables. For example, if the initial capacity
* is {@code 60}, and the concurrency level is {@code 8}, then eight segments are created, each
* having a hash table of size eight. Providing a large enough estimate at construction time
* avoids the need for expensive resizing operations later, but setting this value unnecessarily
* high wastes memory.
*
* @return this {@code CacheBuilder} instance (for chaining)
* @throws IllegalArgumentException if {@code initialCapacity} is negative
* @throws IllegalStateException if an initial capacity was already set
*/
@CanIgnoreReturnValue
public CacheBuilder<K, V> initialCapacity(int initialCapacity) {
checkState(
this.initialCapacity == UNSET_INT,
"initial capacity was already set to %s",
this.initialCapacity);
checkArgument(initialCapacity >= 0);
this.initialCapacity = initialCapacity;
return this;
}
int getInitialCapacity() {
return (initialCapacity == UNSET_INT) ? DEFAULT_INITIAL_CAPACITY : initialCapacity;
}
/**
* Guides the allowed concurrency among update operations. Used as a hint for internal sizing. The
* table is internally partitioned to try to permit the indicated number of concurrent updates
* without contention. Because assignment of entries to these partitions is not necessarily
* uniform, the actual concurrency observed may vary. Ideally, you should choose a value to
* accommodate as many threads as will ever concurrently modify the table. Using a significantly
* higher value than you need can waste space and time, and a significantly lower value can lead
* to thread contention. But overestimates and underestimates within an order of magnitude do not
* usually have much noticeable impact. A value of one permits only one thread to modify the cache
* at a time, but since read operations and cache loading computations can proceed concurrently,
* this still yields higher concurrency than full synchronization.
*
* <p>Defaults to 4. <b>Note:</b>The default may change in the future. If you care about this
* value, you should always choose it explicitly.
*
* <p>The current implementation uses the concurrency level to create a fixed number of hashtable
* segments, each governed by its own write lock. The segment lock is taken once for each explicit
* write, and twice for each cache loading computation (once prior to loading the new value, and
* once after loading completes). Much internal cache management is performed at the segment
* granularity. For example, access queues and write queues are kept per segment when they are
* required by the selected eviction algorithm. As such, when writing unit tests it is not
* uncommon to specify {@code concurrencyLevel(1)} in order to achieve more deterministic eviction
* behavior.
*
* <p>Note that future implementations may abandon segment locking in favor of more advanced
* concurrency controls.
*
* @return this {@code CacheBuilder} instance (for chaining)
* @throws IllegalArgumentException if {@code concurrencyLevel} is nonpositive
* @throws IllegalStateException if a concurrency level was already set
*/
@CanIgnoreReturnValue
public CacheBuilder<K, V> concurrencyLevel(int concurrencyLevel) {
checkState(
this.concurrencyLevel == UNSET_INT,
"concurrency level was already set to %s",
this.concurrencyLevel);
checkArgument(concurrencyLevel > 0);
this.concurrencyLevel = concurrencyLevel;
return this;
}
int getConcurrencyLevel() {
return (concurrencyLevel == UNSET_INT) ? DEFAULT_CONCURRENCY_LEVEL : concurrencyLevel;
}
/**
* Specifies the maximum number of entries the cache may contain.
*
* <p>Note that the cache <b>may evict an entry before this limit is exceeded</b>. For example, in
* the current implementation, when {@code concurrencyLevel} is greater than {@code 1}, each
* resulting segment inside the cache <i>independently</i> limits its own size to approximately
* {@code maximumSize / concurrencyLevel}.
*
* <p>When eviction is necessary, the cache evicts entries that are less likely to be used again.
* For example, the cache may evict an entry because it hasn't been used recently or very often.
*
* <p>If {@code maximumSize} is zero, elements will be evicted immediately after being loaded into
* cache. This can be useful in testing, or to disable caching temporarily.
*
* <p>This feature cannot be used in conjunction with {@link #maximumWeight}.
*
* @param maximumSize the maximum size of the cache
* @return this {@code CacheBuilder} instance (for chaining)
* @throws IllegalArgumentException if {@code maximumSize} is negative
* @throws IllegalStateException if a maximum size or weight was already set
*/
@CanIgnoreReturnValue
public CacheBuilder<K, V> maximumSize(long maximumSize) {
checkState(
this.maximumSize == UNSET_INT, "maximum size was already set to %s", this.maximumSize);
checkState(
this.maximumWeight == UNSET_INT,
"maximum weight was already set to %s",
this.maximumWeight);
checkState(this.weigher == null, "maximum size can not be combined with weigher");
checkArgument(maximumSize >= 0, "maximum size must not be negative");
this.maximumSize = maximumSize;
return this;
}
/**
* Specifies the maximum weight of entries the cache may contain. Weight is determined using the
* {@link Weigher} specified with {@link #weigher}, and use of this method requires a
* corresponding call to {@link #weigher} prior to calling {@link #build}.
*
* <p>Note that the cache <b>may evict an entry before this limit is exceeded</b>. For example, in
* the current implementation, when {@code concurrencyLevel} is greater than {@code 1}, each
* resulting segment inside the cache <i>independently</i> limits its own weight to approximately
* {@code maximumWeight / concurrencyLevel}.
*
* <p>When eviction is necessary, the cache evicts entries that are less likely to be used again.
* For example, the cache may evict an entry because it hasn't been used recently or very often.
*
* <p>If {@code maximumWeight} is zero, elements will be evicted immediately after being loaded
* into cache. This can be useful in testing, or to disable caching temporarily.
*
* <p>Note that weight is only used to determine whether the cache is over capacity; it has no
* effect on selecting which entry should be evicted next.
*
* <p>This feature cannot be used in conjunction with {@link #maximumSize}.
*
* @param maximumWeight the maximum total weight of entries the cache may contain
* @return this {@code CacheBuilder} instance (for chaining)
* @throws IllegalArgumentException if {@code maximumWeight} is negative
* @throws IllegalStateException if a maximum weight or size was already set
* @since 11.0
*/
@GwtIncompatible // To be supported
@CanIgnoreReturnValue
public CacheBuilder<K, V> maximumWeight(long maximumWeight) {
checkState(
this.maximumWeight == UNSET_INT,
"maximum weight was already set to %s",
this.maximumWeight);
checkState(
this.maximumSize == UNSET_INT, "maximum size was already set to %s", this.maximumSize);
checkArgument(maximumWeight >= 0, "maximum weight must not be negative");
this.maximumWeight = maximumWeight;
return this;
}
/**
* Specifies the weigher to use in determining the weight of entries. Entry weight is taken into
* consideration by {@link #maximumWeight(long)} when determining which entries to evict, and use
* of this method requires a corresponding call to {@link #maximumWeight(long)} prior to calling
* {@link #build}. Weights are measured and recorded when entries are inserted into the cache, and
* are thus effectively static during the lifetime of a cache entry.
*
* <p>When the weight of an entry is zero it will not be considered for size-based eviction
* (though it still may be evicted by other means).
*
* <p><b>Important note:</b> Instead of returning <em>this</em> as a {@code CacheBuilder}
* instance, this method returns {@code CacheBuilder<K1, V1>}. From this point on, either the
* original reference or the returned reference may be used to complete configuration and build
* the cache, but only the "generic" one is type-safe. That is, it will properly prevent you from
* building caches whose key or value types are incompatible with the types accepted by the
* weigher already provided; the {@code CacheBuilder} type cannot do this. For best results,
* simply use the standard method-chaining idiom, as illustrated in the documentation at top,
* configuring a {@code CacheBuilder} and building your {@link Cache} all in a single statement.
*
* <p><b>Warning:</b> if you ignore the above advice, and use this {@code CacheBuilder} to build a
* cache whose key or value type is incompatible with the weigher, you will likely experience a
* {@link ClassCastException} at some <i>undefined</i> point in the future.
*
* @param weigher the weigher to use in calculating the weight of cache entries
* @return this {@code CacheBuilder} instance (for chaining)
* @throws IllegalStateException if a weigher was already set or {@link #maximumSize} was
* previously called
* @since 11.0
*/
@GwtIncompatible // To be supported
@CanIgnoreReturnValue // TODO(b/27479612): consider removing this
public <K1 extends K, V1 extends V> CacheBuilder<K1, V1> weigher(
Weigher<? super K1, ? super V1> weigher) {
checkState(this.weigher == null);
if (strictParsing) {
checkState(
this.maximumSize == UNSET_INT,
"weigher can not be combined with maximum size (%s provided)",
this.maximumSize);
}
// safely limiting the kinds of caches this can produce
@SuppressWarnings("unchecked")
CacheBuilder<K1, V1> me = (CacheBuilder<K1, V1>) this;
me.weigher = checkNotNull(weigher);
return me;
}
long getMaximumWeight() {
if (expireAfterWriteNanos == 0 || expireAfterAccessNanos == 0) {
return 0;
}
return (weigher == null) ? maximumSize : maximumWeight;
}
// Make a safe contravariant cast now so we don't have to do it over and over.
@SuppressWarnings("unchecked")
<K1 extends K, V1 extends V> Weigher<K1, V1> getWeigher() {
return (Weigher<K1, V1>) MoreObjects.firstNonNull(weigher, OneWeigher.INSTANCE);
}
/**
* Specifies that each key (not value) stored in the cache should be wrapped in a {@link
* WeakReference} (by default, strong references are used).
*
* <p><b>Warning:</b> when this method is used, the resulting cache will use identity ({@code ==})
* comparison to determine equality of keys. Its {@link Cache#asMap} view will therefore
* technically violate the {@link Map} specification (in the same way that {@link IdentityHashMap}
* does).
*
* <p>Entries with keys that have been garbage collected may be counted in {@link Cache#size}, but
* will never be visible to read or write operations; such entries are cleaned up as part of the
* routine maintenance described in the class javadoc.
*
* @return this {@code CacheBuilder} instance (for chaining)
* @throws IllegalStateException if the key strength was already set
*/
@GwtIncompatible // java.lang.ref.WeakReference
@CanIgnoreReturnValue
public CacheBuilder<K, V> weakKeys() {
return setKeyStrength(Strength.WEAK);
}
@CanIgnoreReturnValue
CacheBuilder<K, V> setKeyStrength(Strength strength) {
checkState(keyStrength == null, "Key strength was already set to %s", keyStrength);
keyStrength = checkNotNull(strength);
return this;
}
Strength getKeyStrength() {
return MoreObjects.firstNonNull(keyStrength, Strength.STRONG);
}
/**
* Specifies that each value (not key) stored in the cache should be wrapped in a {@link
* WeakReference} (by default, strong references are used).
*
* <p>Weak values will be garbage collected once they are weakly reachable. This makes them a poor
* candidate for caching; consider {@link #softValues} instead.
*
* <p><b>Note:</b> when this method is used, the resulting cache will use identity ({@code ==})
* comparison to determine equality of values.
*
* <p>Entries with values that have been garbage collected may be counted in {@link Cache#size},
* but will never be visible to read or write operations; such entries are cleaned up as part of
* the routine maintenance described in the class javadoc.
*
* @return this {@code CacheBuilder} instance (for chaining)
* @throws IllegalStateException if the value strength was already set
*/
@GwtIncompatible // java.lang.ref.WeakReference
@CanIgnoreReturnValue
public CacheBuilder<K, V> weakValues() {
return setValueStrength(Strength.WEAK);
}
/**
* Specifies that each value (not key) stored in the cache should be wrapped in a {@link
* SoftReference} (by default, strong references are used). Softly-referenced objects will be
* garbage-collected in a <i>globally</i> least-recently-used manner, in response to memory
* demand.
*
* <p><b>Warning:</b> in most circumstances it is better to set a per-cache {@linkplain
* #maximumSize(long) maximum size} instead of using soft references. You should only use this
* method if you are well familiar with the practical consequences of soft references.
*
* <p><b>Note:</b> when this method is used, the resulting cache will use identity ({@code ==})
* comparison to determine equality of values.
*
* <p>Entries with values that have been garbage collected may be counted in {@link Cache#size},
* but will never be visible to read or write operations; such entries are cleaned up as part of
* the routine maintenance described in the class javadoc.
*
* @return this {@code CacheBuilder} instance (for chaining)
* @throws IllegalStateException if the value strength was already set
*/
@GwtIncompatible // java.lang.ref.SoftReference
@CanIgnoreReturnValue
public CacheBuilder<K, V> softValues() {
return setValueStrength(Strength.SOFT);
}
@CanIgnoreReturnValue
CacheBuilder<K, V> setValueStrength(Strength strength) {
checkState(valueStrength == null, "Value strength was already set to %s", valueStrength);
valueStrength = checkNotNull(strength);
return this;
}
Strength getValueStrength() {
return MoreObjects.firstNonNull(valueStrength, Strength.STRONG);
}
/**
* Specifies that each entry should be automatically removed from the cache once a fixed duration
* has elapsed after the entry's creation, or the most recent replacement of its value.
*
* <p>When {@code duration} is zero, this method hands off to {@link #maximumSize(long)
* maximumSize}{@code (0)}, ignoring any otherwise-specified maximum size or weight. This can be
* useful in testing, or to disable caching temporarily without a code change.
*
* <p>Expired entries may be counted in {@link Cache#size}, but will never be visible to read or
* write operations. Expired entries are cleaned up as part of the routine maintenance described
* in the class javadoc.
*
* @param duration the length of time after an entry is created that it should be automatically
* removed
* @return this {@code CacheBuilder} instance (for chaining)
* @throws IllegalArgumentException if {@code duration} is negative
* @throws IllegalStateException if {@link #expireAfterWrite} was already set
* @throws ArithmeticException for durations greater than +/- approximately 292 years
* @since 25.0
*/
@J2ObjCIncompatible
@GwtIncompatible // java.time.Duration
@SuppressWarnings("GoodTime") // java.time.Duration decomposition
@CanIgnoreReturnValue
public CacheBuilder<K, V> expireAfterWrite(java.time.Duration duration) {
return expireAfterWrite(toNanosSaturated(duration), TimeUnit.NANOSECONDS);
}
/**
* Specifies that each entry should be automatically removed from the cache once a fixed duration
* has elapsed after the entry's creation, or the most recent replacement of its value.
*
* <p>When {@code duration} is zero, this method hands off to {@link #maximumSize(long)
* maximumSize}{@code (0)}, ignoring any otherwise-specified maximum size or weight. This can be
* useful in testing, or to disable caching temporarily without a code change.
*
* <p>Expired entries may be counted in {@link Cache#size}, but will never be visible to read or
* write operations. Expired entries are cleaned up as part of the routine maintenance described
* in the class javadoc.
*
* <p>If you can represent the duration as a {@link java.time.Duration} (which should be preferred
* when feasible), use {@link #expireAfterWrite(Duration)} instead.
*
* @param duration the length of time after an entry is created that it should be automatically
* removed
* @param unit the unit that {@code duration} is expressed in
* @return this {@code CacheBuilder} instance (for chaining)
* @throws IllegalArgumentException if {@code duration} is negative
* @throws IllegalStateException if {@link #expireAfterWrite} was already set
*/
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
@CanIgnoreReturnValue
public CacheBuilder<K, V> expireAfterWrite(long duration, TimeUnit unit) {
checkState(
expireAfterWriteNanos == UNSET_INT,
"expireAfterWrite was already set to %s ns",
expireAfterWriteNanos);
checkArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit);
this.expireAfterWriteNanos = unit.toNanos(duration);
return this;
}
@SuppressWarnings("GoodTime") // nanos internally, should be Duration
long getExpireAfterWriteNanos() {
return (expireAfterWriteNanos == UNSET_INT) ? DEFAULT_EXPIRATION_NANOS : expireAfterWriteNanos;
}
/**
* Specifies that each entry should be automatically removed from the cache once a fixed duration
* has elapsed after the entry's creation, the most recent replacement of its value, or its last
* access. Access time is reset by all cache read and write operations (including {@code
* Cache.asMap().get(Object)} and {@code Cache.asMap().put(K, V)}), but not by {@code
* containsKey(Object)}, nor by operations on the collection-views of {@link Cache#asMap}}. So,
* for example, iterating through {@code Cache.asMap().entrySet()} does not reset access time for
* the entries you retrieve.
*
* <p>When {@code duration} is zero, this method hands off to {@link #maximumSize(long)
* maximumSize}{@code (0)}, ignoring any otherwise-specified maximum size or weight. This can be
* useful in testing, or to disable caching temporarily without a code change.
*
* <p>Expired entries may be counted in {@link Cache#size}, but will never be visible to read or
* write operations. Expired entries are cleaned up as part of the routine maintenance described
* in the class javadoc.
*
* @param duration the length of time after an entry is last accessed that it should be
* automatically removed
* @return this {@code CacheBuilder} instance (for chaining)
* @throws IllegalArgumentException if {@code duration} is negative
* @throws IllegalStateException if {@link #expireAfterAccess} was already set
* @throws ArithmeticException for durations greater than +/- approximately 292 years
* @since 25.0
*/
@J2ObjCIncompatible
@GwtIncompatible // java.time.Duration
@SuppressWarnings("GoodTime") // java.time.Duration decomposition
@CanIgnoreReturnValue
public CacheBuilder<K, V> expireAfterAccess(java.time.Duration duration) {
return expireAfterAccess(toNanosSaturated(duration), TimeUnit.NANOSECONDS);
}
/**
* Specifies that each entry should be automatically removed from the cache once a fixed duration
* has elapsed after the entry's creation, the most recent replacement of its value, or its last
* access. Access time is reset by all cache read and write operations (including {@code
* Cache.asMap().get(Object)} and {@code Cache.asMap().put(K, V)}), but not by {@code
* containsKey(Object)}, nor by operations on the collection-views of {@link Cache#asMap}. So, for
* example, iterating through {@code Cache.asMap().entrySet()} does not reset access time for the
* entries you retrieve.
*
* <p>When {@code duration} is zero, this method hands off to {@link #maximumSize(long)
* maximumSize}{@code (0)}, ignoring any otherwise-specified maximum size or weight. This can be
* useful in testing, or to disable caching temporarily without a code change.
*
* <p>Expired entries may be counted in {@link Cache#size}, but will never be visible to read or
* write operations. Expired entries are cleaned up as part of the routine maintenance described
* in the class javadoc.
*
* <p>If you can represent the duration as a {@link java.time.Duration} (which should be preferred
* when feasible), use {@link #expireAfterAccess(Duration)} instead.
*
* @param duration the length of time after an entry is last accessed that it should be
* automatically removed
* @param unit the unit that {@code duration} is expressed in
* @return this {@code CacheBuilder} instance (for chaining)
* @throws IllegalArgumentException if {@code duration} is negative
* @throws IllegalStateException if {@link #expireAfterAccess} was already set
*/
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
@CanIgnoreReturnValue
public CacheBuilder<K, V> expireAfterAccess(long duration, TimeUnit unit) {
checkState(
expireAfterAccessNanos == UNSET_INT,
"expireAfterAccess was already set to %s ns",
expireAfterAccessNanos);
checkArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit);
this.expireAfterAccessNanos = unit.toNanos(duration);
return this;
}
@SuppressWarnings("GoodTime") // nanos internally, should be Duration
long getExpireAfterAccessNanos() {
return (expireAfterAccessNanos == UNSET_INT)
? DEFAULT_EXPIRATION_NANOS
: expireAfterAccessNanos;
}
/**
* Specifies that active entries are eligible for automatic refresh once a fixed duration has
* elapsed after the entry's creation, or the most recent replacement of its value. The semantics
* of refreshes are specified in {@link LoadingCache#refresh}, and are performed by calling {@link
* CacheLoader#reload}.
*
* <p>As the default implementation of {@link CacheLoader#reload} is synchronous, it is
* recommended that users of this method override {@link CacheLoader#reload} with an asynchronous
* implementation; otherwise refreshes will be performed during unrelated cache read and write
* operations.
*
* <p>Currently automatic refreshes are performed when the first stale request for an entry
* occurs. The request triggering refresh will make a synchronous call to {@link
* CacheLoader#reload}
* to obtain a future of the new value. If the returned future is already complete, it is returned
* immediately. Otherwise, the old value is returned.
*
* <p><b>Note:</b> <i>all exceptions thrown during refresh will be logged and then swallowed</i>.
*
* @param duration the length of time after an entry is created that it should be considered
* stale, and thus eligible for refresh
* @return this {@code CacheBuilder} instance (for chaining)
* @throws IllegalArgumentException if {@code duration} is negative
* @throws IllegalStateException if {@link #refreshAfterWrite} was already set
* @throws ArithmeticException for durations greater than +/- approximately 292 years
* @since 25.0
*/
@J2ObjCIncompatible
@GwtIncompatible // java.time.Duration
@SuppressWarnings("GoodTime") // java.time.Duration decomposition
@CanIgnoreReturnValue
public CacheBuilder<K, V> refreshAfterWrite(java.time.Duration duration) {
return refreshAfterWrite(toNanosSaturated(duration), TimeUnit.NANOSECONDS);
}
/**
* Specifies that active entries are eligible for automatic refresh once a fixed duration has
* elapsed after the entry's creation, or the most recent replacement of its value. The semantics
* of refreshes are specified in {@link LoadingCache#refresh}, and are performed by calling {@link
* CacheLoader#reload}.
*
* <p>As the default implementation of {@link CacheLoader#reload} is synchronous, it is
* recommended that users of this method override {@link CacheLoader#reload} with an asynchronous
* implementation; otherwise refreshes will be performed during unrelated cache read and write
* operations.
*
* <p>Currently automatic refreshes are performed when the first stale request for an entry
* occurs. The request triggering refresh will make a synchronous call to {@link
* CacheLoader#reload}
* and immediately return the new value if the returned future is complete, and the old value
* otherwise.
*
* <p><b>Note:</b> <i>all exceptions thrown during refresh will be logged and then swallowed</i>.
*
* <p>If you can represent the duration as a {@link java.time.Duration} (which should be preferred
* when feasible), use {@link #refreshAfterWrite(Duration)} instead.
*
* @param duration the length of time after an entry is created that it should be considered
* stale, and thus eligible for refresh
* @param unit the unit that {@code duration} is expressed in
* @return this {@code CacheBuilder} instance (for chaining)
* @throws IllegalArgumentException if {@code duration} is negative
* @throws IllegalStateException if {@link #refreshAfterWrite} was already set
* @since 11.0
*/
@GwtIncompatible // To be supported (synchronously).
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
@CanIgnoreReturnValue
public CacheBuilder<K, V> refreshAfterWrite(long duration, TimeUnit unit) {
checkNotNull(unit);
checkState(refreshNanos == UNSET_INT, "refresh was already set to %s ns", refreshNanos);
checkArgument(duration > 0, "duration must be positive: %s %s", duration, unit);
this.refreshNanos = unit.toNanos(duration);
return this;
}
@SuppressWarnings("GoodTime") // nanos internally, should be Duration
long getRefreshNanos() {
return (refreshNanos == UNSET_INT) ? DEFAULT_REFRESH_NANOS : refreshNanos;
}
/**
* Specifies a nanosecond-precision time source for this cache. By default, {@link
* System#nanoTime} is used.
*
* <p>The primary intent of this method is to facilitate testing of caches with a fake or mock
* time source.
*
* @return this {@code CacheBuilder} instance (for chaining)
* @throws IllegalStateException if a ticker was already set
*/
@CanIgnoreReturnValue
public CacheBuilder<K, V> ticker(Ticker ticker) {
checkState(this.ticker == null);
this.ticker = checkNotNull(ticker);
return this;
}
Ticker getTicker(boolean recordsTime) {
if (ticker != null) {
return ticker;
}
return recordsTime ? Ticker.systemTicker() : NULL_TICKER;
}
/**
* Specifies a listener instance that caches should notify each time an entry is removed for any
* {@linkplain RemovalCause reason}. Each cache created by this builder will invoke this listener
* as part of the routine maintenance described in the class documentation above.
*
* <p><b>Warning:</b> after invoking this method, do not continue to use <i>this</i> cache builder
* reference; instead use the reference this method <i>returns</i>. At runtime, these point to the
* same instance, but only the returned reference has the correct generic type information to
* ensure type safety. For best results, use the standard method-chaining idiom illustrated in the
* class documentation above, configuring a builder and building your cache in a single statement.
* Failure to heed this advice can result in a {@link ClassCastException} being thrown by a cache
* operation at some <i>undefined</i> point in the future.
*
* <p><b>Warning:</b> any exception thrown by {@code listener} will <i>not</i> be propagated to
* the {@code Cache} user, only logged via a {@link Logger}.
*
* @return the cache builder reference that should be used instead of {@code this} for any
* remaining configuration and cache building
* @return this {@code CacheBuilder} instance (for chaining)
* @throws IllegalStateException if a removal listener was already set
*/
public <K1 extends K, V1 extends V> CacheBuilder<K1, V1> removalListener(
RemovalListener<? super K1, ? super V1> listener) {
checkState(this.removalListener == null);
// safely limiting the kinds of caches this can produce
@SuppressWarnings("unchecked")
CacheBuilder<K1, V1> me = (CacheBuilder<K1, V1>) this;
me.removalListener = checkNotNull(listener);
return me;
}
// Make a safe contravariant cast now so we don't have to do it over and over.
@SuppressWarnings("unchecked")
<K1 extends K, V1 extends V> RemovalListener<K1, V1> getRemovalListener() {
return (RemovalListener<K1, V1>)
MoreObjects.firstNonNull(removalListener, NullListener.INSTANCE);
}
/**
* Enable the accumulation of {@link CacheStats} during the operation of the cache. Without this
* {@link Cache#stats} will return zero for all statistics. Note that recording stats requires
* bookkeeping to be performed with each operation, and thus imposes a performance penalty on
* cache operation.
*
* @return this {@code CacheBuilder} instance (for chaining)
* @since 12.0 (previously, stats collection was automatic)
*/
@CanIgnoreReturnValue
public CacheBuilder<K, V> recordStats() {
statsCounterSupplier = CACHE_STATS_COUNTER;
return this;
}
boolean isRecordingStats() {
return statsCounterSupplier == CACHE_STATS_COUNTER;
}
Supplier<? extends StatsCounter> getStatsCounterSupplier() {
return statsCounterSupplier;
}
/**
* Builds a cache, which either returns an already-loaded value for a given key or atomically
* computes or retrieves it using the supplied {@code CacheLoader}. If another thread is currently
* loading the value for this key, simply waits for that thread to finish and returns its loaded
* value. Note that multiple threads can concurrently load values for distinct keys.
*
* <p>This method does not alter the state of this {@code CacheBuilder} instance, so it can be
* invoked again to create multiple independent caches.
*
* @param loader the cache loader used to obtain new values
* @return a cache having the requested features
*/
public <K1 extends K, V1 extends V> LoadingCache<K1, V1> build(
CacheLoader<? super K1, V1> loader) {
checkWeightWithWeigher();
return new LocalCache.LocalLoadingCache<>(this, loader);
}
/**
* Builds a cache which does not automatically load values when keys are requested.
*
* <p>Consider {@link #build(CacheLoader)} instead, if it is feasible to implement a {@code
* CacheLoader}.
*
* <p>This method does not alter the state of this {@code CacheBuilder} instance, so it can be
* invoked again to create multiple independent caches.
*
* @return a cache having the requested features
* @since 11.0
*/
public <K1 extends K, V1 extends V> Cache<K1, V1> build() {
checkWeightWithWeigher();
checkNonLoadingCache();
return new LocalCache.LocalManualCache<>(this);
}
private void checkNonLoadingCache() {
checkState(refreshNanos == UNSET_INT, "refreshAfterWrite requires a LoadingCache");
}
private void checkWeightWithWeigher() {
if (weigher == null) {
checkState(maximumWeight == UNSET_INT, "maximumWeight requires weigher");
} else {
if (strictParsing) {
checkState(maximumWeight != UNSET_INT, "weigher requires maximumWeight");
} else {
if (maximumWeight == UNSET_INT) {
LoggerHolder.logger.log(
Level.WARNING, "ignoring weigher specified without maximumWeight");
}
}
}
}
/**
* Returns a string representation for this CacheBuilder instance. The exact form of the returned
* string is not specified.
*/
@Override
public String toString() {
MoreObjects.ToStringHelper s = MoreObjects.toStringHelper(this);
if (initialCapacity != UNSET_INT) {
s.add("initialCapacity", initialCapacity);
}
if (concurrencyLevel != UNSET_INT) {
s.add("concurrencyLevel", concurrencyLevel);
}
if (maximumSize != UNSET_INT) {
s.add("maximumSize", maximumSize);
}
if (maximumWeight != UNSET_INT) {
s.add("maximumWeight", maximumWeight);
}
if (expireAfterWriteNanos != UNSET_INT) {
s.add("expireAfterWrite", expireAfterWriteNanos + "ns");
}
if (expireAfterAccessNanos != UNSET_INT) {
s.add("expireAfterAccess", expireAfterAccessNanos + "ns");
}
if (keyStrength != null) {
s.add("keyStrength", Ascii.toLowerCase(keyStrength.toString()));
}
if (valueStrength != null) {
s.add("valueStrength", Ascii.toLowerCase(valueStrength.toString()));
}
if (keyEquivalence != null) {
s.addValue("keyEquivalence");
}
if (valueEquivalence != null) {
s.addValue("valueEquivalence");
}
if (removalListener != null) {
s.addValue("removalListener");
}
return s.toString();
}
/**
* Returns the number of nanoseconds of the given duration without throwing or overflowing.
*
* <p>Instead of throwing {@link ArithmeticException}, this method silently saturates to either
* {@link Long#MAX_VALUE} or {@link Long#MIN_VALUE}. This behavior can be useful when decomposing
* a duration in order to call a legacy API which requires a {@code long, TimeUnit} pair.
*/
@GwtIncompatible // java.time.Duration
@SuppressWarnings("GoodTime") // duration decomposition
private static long toNanosSaturated(java.time.Duration duration) {
// Using a try/catch seems lazy, but the catch block will rarely get invoked (except for
// durations longer than approximately +/- 292 years).
try {
return duration.toNanos();
} catch (ArithmeticException tooBig) {
return duration.isNegative() ? Long.MIN_VALUE : Long.MAX_VALUE;
}
}
}
| google/guava | guava/src/com/google/common/cache/CacheBuilder.java |
44,401 | /*
* Copyright (C) 2011 The Guava Authors
*
* 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.google.common.hash;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.errorprone.annotations.Immutable;
import java.security.Key;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.zip.Adler32;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
import javax.annotation.CheckForNull;
import javax.crypto.spec.SecretKeySpec;
/**
* Static methods to obtain {@link HashFunction} instances, and other static hashing-related
* utilities.
*
* <p>A comparison of the various hash functions can be found <a
* href="http://goo.gl/jS7HH">here</a>.
*
* @author Kevin Bourrillion
* @author Dimitris Andreou
* @author Kurt Alfred Kluever
* @since 11.0
*/
@ElementTypesAreNonnullByDefault
public final class Hashing {
/**
* Returns a general-purpose, <b>temporary-use</b>, non-cryptographic hash function. The algorithm
* the returned function implements is unspecified and subject to change without notice.
*
* <p><b>Warning:</b> a new random seed for these functions is chosen each time the {@code
* Hashing} class is loaded. <b>Do not use this method</b> if hash codes may escape the current
* process in any way, for example being sent over RPC, or saved to disk. For a general-purpose,
* non-cryptographic hash function that will never change behavior, we suggest {@link
* #murmur3_128}.
*
* <p>Repeated calls to this method on the same loaded {@code Hashing} class, using the same value
* for {@code minimumBits}, will return identically-behaving {@link HashFunction} instances.
*
* @param minimumBits a positive integer. This can be arbitrarily large. The returned {@link
* HashFunction} instance may use memory proportional to this integer.
* @return a hash function, described above, that produces hash codes of length {@code
* minimumBits} or greater
*/
public static HashFunction goodFastHash(int minimumBits) {
int bits = checkPositiveAndMakeMultipleOf32(minimumBits);
if (bits == 32) {
return Murmur3_32HashFunction.GOOD_FAST_HASH_32;
}
if (bits <= 128) {
return Murmur3_128HashFunction.GOOD_FAST_HASH_128;
}
// Otherwise, join together some 128-bit murmur3s
int hashFunctionsNeeded = (bits + 127) / 128;
HashFunction[] hashFunctions = new HashFunction[hashFunctionsNeeded];
hashFunctions[0] = Murmur3_128HashFunction.GOOD_FAST_HASH_128;
int seed = GOOD_FAST_HASH_SEED;
for (int i = 1; i < hashFunctionsNeeded; i++) {
seed += 1500450271; // a prime; shouldn't matter
hashFunctions[i] = murmur3_128(seed);
}
return new ConcatenatedHashFunction(hashFunctions);
}
/**
* Used to randomize {@link #goodFastHash} instances, so that programs which persist anything
* dependent on the hash codes they produce will fail sooner.
*/
@SuppressWarnings("GoodTime") // reading system time without TimeSource
static final int GOOD_FAST_HASH_SEED = (int) System.currentTimeMillis();
/**
* Returns a hash function implementing the <a
* href="https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp">32-bit murmur3
* algorithm, x86 variant</a> (little-endian variant), using the given seed value, <b>with a known
* bug</b> as described in the deprecation text.
*
* <p>The C++ equivalent is the MurmurHash3_x86_32 function (Murmur3A), which however does not
* have the bug.
*
* @deprecated This implementation produces incorrect hash values from the {@link
* HashFunction#hashString} method if the string contains non-BMP characters. Use {@link
* #murmur3_32_fixed(int)} instead.
*/
@Deprecated
public static HashFunction murmur3_32(int seed) {
return new Murmur3_32HashFunction(seed, /* supplementaryPlaneFix= */ false);
}
/**
* Returns a hash function implementing the <a
* href="https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp">32-bit murmur3
* algorithm, x86 variant</a> (little-endian variant), using the given seed value, <b>with a known
* bug</b> as described in the deprecation text.
*
* <p>The C++ equivalent is the MurmurHash3_x86_32 function (Murmur3A), which however does not
* have the bug.
*
* @deprecated This implementation produces incorrect hash values from the {@link
* HashFunction#hashString} method if the string contains non-BMP characters. Use {@link
* #murmur3_32_fixed()} instead.
*/
@Deprecated
public static HashFunction murmur3_32() {
return Murmur3_32HashFunction.MURMUR3_32;
}
/**
* Returns a hash function implementing the <a
* href="https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp">32-bit murmur3
* algorithm, x86 variant</a> (little-endian variant), using the given seed value.
*
* <p>The exact C++ equivalent is the MurmurHash3_x86_32 function (Murmur3A).
*
* <p>This method is called {@code murmur3_32_fixed} because it fixes a bug in the {@code
* HashFunction} returned by the original {@code murmur3_32} method.
*
* @since 31.0
*/
public static HashFunction murmur3_32_fixed(int seed) {
return new Murmur3_32HashFunction(seed, /* supplementaryPlaneFix= */ true);
}
/**
* Returns a hash function implementing the <a
* href="https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp">32-bit murmur3
* algorithm, x86 variant</a> (little-endian variant), using a seed value of zero.
*
* <p>The exact C++ equivalent is the MurmurHash3_x86_32 function (Murmur3A).
*
* <p>This method is called {@code murmur3_32_fixed} because it fixes a bug in the {@code
* HashFunction} returned by the original {@code murmur3_32} method.
*
* @since 31.0
*/
public static HashFunction murmur3_32_fixed() {
return Murmur3_32HashFunction.MURMUR3_32_FIXED;
}
/**
* Returns a hash function implementing the <a
* href="https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp">128-bit murmur3
* algorithm, x64 variant</a> (little-endian variant), using the given seed value.
*
* <p>The exact C++ equivalent is the MurmurHash3_x64_128 function (Murmur3F).
*/
public static HashFunction murmur3_128(int seed) {
return new Murmur3_128HashFunction(seed);
}
/**
* Returns a hash function implementing the <a
* href="https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp">128-bit murmur3
* algorithm, x64 variant</a> (little-endian variant), using a seed value of zero.
*
* <p>The exact C++ equivalent is the MurmurHash3_x64_128 function (Murmur3F).
*/
public static HashFunction murmur3_128() {
return Murmur3_128HashFunction.MURMUR3_128;
}
/**
* Returns a hash function implementing the <a href="https://131002.net/siphash/">64-bit
* SipHash-2-4 algorithm</a> using a seed value of {@code k = 00 01 02 ...}.
*
* @since 15.0
*/
public static HashFunction sipHash24() {
return SipHashFunction.SIP_HASH_24;
}
/**
* Returns a hash function implementing the <a href="https://131002.net/siphash/">64-bit
* SipHash-2-4 algorithm</a> using the given seed.
*
* @since 15.0
*/
public static HashFunction sipHash24(long k0, long k1) {
return new SipHashFunction(2, 4, k0, k1);
}
/**
* Returns a hash function implementing the MD5 hash algorithm (128 hash bits).
*
* @deprecated If you must interoperate with a system that requires MD5, then use this method,
* despite its deprecation. But if you can choose your hash function, avoid MD5, which is
* neither fast nor secure. As of January 2017, we suggest:
* <ul>
* <li>For security:
* {@link Hashing#sha256} or a higher-level API.
* <li>For speed: {@link Hashing#goodFastHash}, though see its docs for caveats.
* </ul>
*/
@Deprecated
public static HashFunction md5() {
return Md5Holder.MD5;
}
private static class Md5Holder {
static final HashFunction MD5 = new MessageDigestHashFunction("MD5", "Hashing.md5()");
}
/**
* Returns a hash function implementing the SHA-1 algorithm (160 hash bits).
*
* @deprecated If you must interoperate with a system that requires SHA-1, then use this method,
* despite its deprecation. But if you can choose your hash function, avoid SHA-1, which is
* neither fast nor secure. As of January 2017, we suggest:
* <ul>
* <li>For security:
* {@link Hashing#sha256} or a higher-level API.
* <li>For speed: {@link Hashing#goodFastHash}, though see its docs for caveats.
* </ul>
*/
@Deprecated
public static HashFunction sha1() {
return Sha1Holder.SHA_1;
}
private static class Sha1Holder {
static final HashFunction SHA_1 = new MessageDigestHashFunction("SHA-1", "Hashing.sha1()");
}
/** Returns a hash function implementing the SHA-256 algorithm (256 hash bits). */
public static HashFunction sha256() {
return Sha256Holder.SHA_256;
}
private static class Sha256Holder {
static final HashFunction SHA_256 =
new MessageDigestHashFunction("SHA-256", "Hashing.sha256()");
}
/**
* Returns a hash function implementing the SHA-384 algorithm (384 hash bits).
*
* @since 19.0
*/
public static HashFunction sha384() {
return Sha384Holder.SHA_384;
}
private static class Sha384Holder {
static final HashFunction SHA_384 =
new MessageDigestHashFunction("SHA-384", "Hashing.sha384()");
}
/** Returns a hash function implementing the SHA-512 algorithm (512 hash bits). */
public static HashFunction sha512() {
return Sha512Holder.SHA_512;
}
private static class Sha512Holder {
static final HashFunction SHA_512 =
new MessageDigestHashFunction("SHA-512", "Hashing.sha512()");
}
/**
* Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the
* MD5 (128 hash bits) hash function and the given secret key.
*
* <p>If you are designing a new system that needs HMAC, prefer {@link #hmacSha256} or other
* future-proof algorithms <a
* href="https://datatracker.ietf.org/doc/html/rfc6151#section-2.3">over {@code hmacMd5}</a>.
*
* @param key the secret key
* @throws IllegalArgumentException if the given key is inappropriate for initializing this MAC
* @since 20.0
*/
public static HashFunction hmacMd5(Key key) {
return new MacHashFunction("HmacMD5", key, hmacToString("hmacMd5", key));
}
/**
* Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the
* MD5 (128 hash bits) hash function and a {@link SecretKeySpec} created from the given byte array
* and the MD5 algorithm.
*
* <p>If you are designing a new system that needs HMAC, prefer {@link #hmacSha256} or other
* future-proof algorithms <a
* href="https://datatracker.ietf.org/doc/html/rfc6151#section-2.3">over {@code hmacMd5}</a>.
*
* @param key the key material of the secret key
* @since 20.0
*/
public static HashFunction hmacMd5(byte[] key) {
return hmacMd5(new SecretKeySpec(checkNotNull(key), "HmacMD5"));
}
/**
* Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the
* SHA-1 (160 hash bits) hash function and the given secret key.
*
* @param key the secret key
* @throws IllegalArgumentException if the given key is inappropriate for initializing this MAC
* @since 20.0
*/
public static HashFunction hmacSha1(Key key) {
return new MacHashFunction("HmacSHA1", key, hmacToString("hmacSha1", key));
}
/**
* Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the
* SHA-1 (160 hash bits) hash function and a {@link SecretKeySpec} created from the given byte
* array and the SHA-1 algorithm.
*
* @param key the key material of the secret key
* @since 20.0
*/
public static HashFunction hmacSha1(byte[] key) {
return hmacSha1(new SecretKeySpec(checkNotNull(key), "HmacSHA1"));
}
/**
* Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the
* SHA-256 (256 hash bits) hash function and the given secret key.
*
* @param key the secret key
* @throws IllegalArgumentException if the given key is inappropriate for initializing this MAC
* @since 20.0
*/
public static HashFunction hmacSha256(Key key) {
return new MacHashFunction("HmacSHA256", key, hmacToString("hmacSha256", key));
}
/**
* Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the
* SHA-256 (256 hash bits) hash function and a {@link SecretKeySpec} created from the given byte
* array and the SHA-256 algorithm.
*
* @param key the key material of the secret key
* @since 20.0
*/
public static HashFunction hmacSha256(byte[] key) {
return hmacSha256(new SecretKeySpec(checkNotNull(key), "HmacSHA256"));
}
/**
* Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the
* SHA-512 (512 hash bits) hash function and the given secret key.
*
* @param key the secret key
* @throws IllegalArgumentException if the given key is inappropriate for initializing this MAC
* @since 20.0
*/
public static HashFunction hmacSha512(Key key) {
return new MacHashFunction("HmacSHA512", key, hmacToString("hmacSha512", key));
}
/**
* Returns a hash function implementing the Message Authentication Code (MAC) algorithm, using the
* SHA-512 (512 hash bits) hash function and a {@link SecretKeySpec} created from the given byte
* array and the SHA-512 algorithm.
*
* @param key the key material of the secret key
* @since 20.0
*/
public static HashFunction hmacSha512(byte[] key) {
return hmacSha512(new SecretKeySpec(checkNotNull(key), "HmacSHA512"));
}
private static String hmacToString(String methodName, Key key) {
return "Hashing."
+ methodName
+ "(Key[algorithm="
+ key.getAlgorithm()
+ ", format="
+ key.getFormat()
+ "])";
}
/**
* Returns a hash function implementing the CRC32C checksum algorithm (32 hash bits) as described
* by RFC 3720, Section 12.1.
*
* <p>This function is best understood as a <a
* href="https://en.wikipedia.org/wiki/Checksum">checksum</a> rather than a true <a
* href="https://en.wikipedia.org/wiki/Hash_function">hash function</a>.
*
* @since 18.0
*/
public static HashFunction crc32c() {
return Crc32cHashFunction.CRC_32_C;
}
/**
* Returns a hash function implementing the CRC-32 checksum algorithm (32 hash bits).
*
* <p>To get the {@code long} value equivalent to {@link Checksum#getValue()} for a {@code
* HashCode} produced by this function, use {@link HashCode#padToLong()}.
*
* <p>This function is best understood as a <a
* href="https://en.wikipedia.org/wiki/Checksum">checksum</a> rather than a true <a
* href="https://en.wikipedia.org/wiki/Hash_function">hash function</a>.
*
* @since 14.0
*/
public static HashFunction crc32() {
return ChecksumType.CRC_32.hashFunction;
}
/**
* Returns a hash function implementing the Adler-32 checksum algorithm (32 hash bits).
*
* <p>To get the {@code long} value equivalent to {@link Checksum#getValue()} for a {@code
* HashCode} produced by this function, use {@link HashCode#padToLong()}.
*
* <p>This function is best understood as a <a
* href="https://en.wikipedia.org/wiki/Checksum">checksum</a> rather than a true <a
* href="https://en.wikipedia.org/wiki/Hash_function">hash function</a>.
*
* @since 14.0
*/
public static HashFunction adler32() {
return ChecksumType.ADLER_32.hashFunction;
}
@Immutable
enum ChecksumType implements ImmutableSupplier<Checksum> {
CRC_32("Hashing.crc32()") {
@Override
public Checksum get() {
return new CRC32();
}
},
ADLER_32("Hashing.adler32()") {
@Override
public Checksum get() {
return new Adler32();
}
};
public final HashFunction hashFunction;
ChecksumType(String toString) {
this.hashFunction = new ChecksumHashFunction(this, 32, toString);
}
}
/**
* Returns a hash function implementing FarmHash's Fingerprint64, an open-source algorithm.
*
* <p>This is designed for generating persistent fingerprints of strings. It isn't
* cryptographically secure, but it produces a high-quality hash with fewer collisions than some
* alternatives we've used in the past.
*
* <p>FarmHash fingerprints are encoded by {@link HashCode#asBytes} in little-endian order. This
* means {@link HashCode#asLong} is guaranteed to return the same value that
* farmhash::Fingerprint64() would for the same input (when compared using {@link
* com.google.common.primitives.UnsignedLongs}'s encoding of 64-bit unsigned numbers).
*
* <p>This function is best understood as a <a
* href="https://en.wikipedia.org/wiki/Fingerprint_(computing)">fingerprint</a> rather than a true
* <a href="https://en.wikipedia.org/wiki/Hash_function">hash function</a>.
*
* @since 20.0
*/
public static HashFunction farmHashFingerprint64() {
return FarmHashFingerprint64.FARMHASH_FINGERPRINT_64;
}
/**
* Returns a hash function implementing the Fingerprint2011 hashing function (64 hash bits).
*
* <p>This is designed for generating persistent fingerprints of strings. It isn't
* cryptographically secure, but it produces a high-quality hash with few collisions. Fingerprints
* generated using this are byte-wise identical to those created using the C++ version, but note
* that this uses unsigned integers (see {@link com.google.common.primitives.UnsignedInts}).
* Comparisons between the two should take this into account.
*
* <p>Fingerprint2011() is a form of Murmur2 on strings up to 32 bytes and a form of CityHash for
* longer strings. It could have been one or the other throughout. The main advantage of the
* combination is that CityHash has a bunch of special cases for short strings that don't need to
* be replicated here. The result will never be 0 or 1.
*
* <p>This function is best understood as a <a
* href="https://en.wikipedia.org/wiki/Fingerprint_(computing)">fingerprint</a> rather than a true
* <a href="https://en.wikipedia.org/wiki/Hash_function">hash function</a>.
*
* @since 31.1
*/
public static HashFunction fingerprint2011() {
return Fingerprint2011.FINGERPRINT_2011;
}
/**
* Assigns to {@code hashCode} a "bucket" in the range {@code [0, buckets)}, in a uniform manner
* that minimizes the need for remapping as {@code buckets} grows. That is, {@code
* consistentHash(h, n)} equals:
*
* <ul>
* <li>{@code n - 1}, with approximate probability {@code 1/n}
* <li>{@code consistentHash(h, n - 1)}, otherwise (probability {@code 1 - 1/n})
* </ul>
*
* <p>This method is suitable for the common use case of dividing work among buckets that meet the
* following conditions:
*
* <ul>
* <li>You want to assign the same fraction of inputs to each bucket.
* <li>When you reduce the number of buckets, you can accept that the most recently added
* buckets will be removed first. More concretely, if you are dividing traffic among tasks,
* you can decrease the number of tasks from 15 and 10, killing off the final 5 tasks, and
* {@code consistentHash} will handle it. If, however, you are dividing traffic among
* servers {@code alpha}, {@code bravo}, and {@code charlie} and you occasionally need to
* take each of the servers offline, {@code consistentHash} will be a poor fit: It provides
* no way for you to specify which of the three buckets is disappearing. Thus, if your
* buckets change from {@code [alpha, bravo, charlie]} to {@code [bravo, charlie]}, it will
* assign all the old {@code alpha} traffic to {@code bravo} and all the old {@code bravo}
* traffic to {@code charlie}, rather than letting {@code bravo} keep its traffic.
* </ul>
*
* <p>See the <a href="http://en.wikipedia.org/wiki/Consistent_hashing">Wikipedia article on
* consistent hashing</a> for more information.
*/
public static int consistentHash(HashCode hashCode, int buckets) {
return consistentHash(hashCode.padToLong(), buckets);
}
/**
* Assigns to {@code input} a "bucket" in the range {@code [0, buckets)}, in a uniform manner that
* minimizes the need for remapping as {@code buckets} grows. That is, {@code consistentHash(h,
* n)} equals:
*
* <ul>
* <li>{@code n - 1}, with approximate probability {@code 1/n}
* <li>{@code consistentHash(h, n - 1)}, otherwise (probability {@code 1 - 1/n})
* </ul>
*
* <p>This method is suitable for the common use case of dividing work among buckets that meet the
* following conditions:
*
* <ul>
* <li>You want to assign the same fraction of inputs to each bucket.
* <li>When you reduce the number of buckets, you can accept that the most recently added
* buckets will be removed first. More concretely, if you are dividing traffic among tasks,
* you can decrease the number of tasks from 15 and 10, killing off the final 5 tasks, and
* {@code consistentHash} will handle it. If, however, you are dividing traffic among
* servers {@code alpha}, {@code bravo}, and {@code charlie} and you occasionally need to
* take each of the servers offline, {@code consistentHash} will be a poor fit: It provides
* no way for you to specify which of the three buckets is disappearing. Thus, if your
* buckets change from {@code [alpha, bravo, charlie]} to {@code [bravo, charlie]}, it will
* assign all the old {@code alpha} traffic to {@code bravo} and all the old {@code bravo}
* traffic to {@code charlie}, rather than letting {@code bravo} keep its traffic.
* </ul>
*
* <p>See the <a href="http://en.wikipedia.org/wiki/Consistent_hashing">Wikipedia article on
* consistent hashing</a> for more information.
*/
public static int consistentHash(long input, int buckets) {
checkArgument(buckets > 0, "buckets must be positive: %s", buckets);
LinearCongruentialGenerator generator = new LinearCongruentialGenerator(input);
int candidate = 0;
int next;
// Jump from bucket to bucket until we go out of range
while (true) {
next = (int) ((candidate + 1) / generator.nextDouble());
if (next >= 0 && next < buckets) {
candidate = next;
} else {
return candidate;
}
}
}
/**
* Returns a hash code, having the same bit length as each of the input hash codes, that combines
* the information of these hash codes in an ordered fashion. That is, whenever two equal hash
* codes are produced by two calls to this method, it is <i>as likely as possible</i> that each
* was computed from the <i>same</i> input hash codes in the <i>same</i> order.
*
* @throws IllegalArgumentException if {@code hashCodes} is empty, or the hash codes do not all
* have the same bit length
*/
public static HashCode combineOrdered(Iterable<HashCode> hashCodes) {
Iterator<HashCode> iterator = hashCodes.iterator();
checkArgument(iterator.hasNext(), "Must be at least 1 hash code to combine.");
int bits = iterator.next().bits();
byte[] resultBytes = new byte[bits / 8];
for (HashCode hashCode : hashCodes) {
byte[] nextBytes = hashCode.asBytes();
checkArgument(
nextBytes.length == resultBytes.length, "All hashcodes must have the same bit length.");
for (int i = 0; i < nextBytes.length; i++) {
resultBytes[i] = (byte) (resultBytes[i] * 37 ^ nextBytes[i]);
}
}
return HashCode.fromBytesNoCopy(resultBytes);
}
/**
* Returns a hash code, having the same bit length as each of the input hash codes, that combines
* the information of these hash codes in an unordered fashion. That is, whenever two equal hash
* codes are produced by two calls to this method, it is <i>as likely as possible</i> that each
* was computed from the <i>same</i> input hash codes in <i>some</i> order.
*
* @throws IllegalArgumentException if {@code hashCodes} is empty, or the hash codes do not all
* have the same bit length
*/
public static HashCode combineUnordered(Iterable<HashCode> hashCodes) {
Iterator<HashCode> iterator = hashCodes.iterator();
checkArgument(iterator.hasNext(), "Must be at least 1 hash code to combine.");
byte[] resultBytes = new byte[iterator.next().bits() / 8];
for (HashCode hashCode : hashCodes) {
byte[] nextBytes = hashCode.asBytes();
checkArgument(
nextBytes.length == resultBytes.length, "All hashcodes must have the same bit length.");
for (int i = 0; i < nextBytes.length; i++) {
resultBytes[i] += nextBytes[i];
}
}
return HashCode.fromBytesNoCopy(resultBytes);
}
/** Checks that the passed argument is positive, and ceils it to a multiple of 32. */
static int checkPositiveAndMakeMultipleOf32(int bits) {
checkArgument(bits > 0, "Number of bits must be positive");
return (bits + 31) & ~31;
}
/**
* Returns a hash function which computes its hash code by concatenating the hash codes of the
* underlying hash functions together. This can be useful if you need to generate hash codes of a
* specific length.
*
* <p>For example, if you need 1024-bit hash codes, you could join two {@link Hashing#sha512} hash
* functions together: {@code Hashing.concatenating(Hashing.sha512(), Hashing.sha512())}.
*
* @since 19.0
*/
public static HashFunction concatenating(
HashFunction first, HashFunction second, HashFunction... rest) {
// We can't use Lists.asList() here because there's no hash->collect dependency
List<HashFunction> list = new ArrayList<>();
list.add(first);
list.add(second);
Collections.addAll(list, rest);
return new ConcatenatedHashFunction(list.toArray(new HashFunction[0]));
}
/**
* Returns a hash function which computes its hash code by concatenating the hash codes of the
* underlying hash functions together. This can be useful if you need to generate hash codes of a
* specific length.
*
* <p>For example, if you need 1024-bit hash codes, you could join two {@link Hashing#sha512} hash
* functions together: {@code Hashing.concatenating(Hashing.sha512(), Hashing.sha512())}.
*
* @since 19.0
*/
public static HashFunction concatenating(Iterable<HashFunction> hashFunctions) {
checkNotNull(hashFunctions);
// We can't use Iterables.toArray() here because there's no hash->collect dependency
List<HashFunction> list = new ArrayList<>();
for (HashFunction hashFunction : hashFunctions) {
list.add(hashFunction);
}
checkArgument(!list.isEmpty(), "number of hash functions (%s) must be > 0", list.size());
return new ConcatenatedHashFunction(list.toArray(new HashFunction[0]));
}
private static final class ConcatenatedHashFunction extends AbstractCompositeHashFunction {
private ConcatenatedHashFunction(HashFunction... functions) {
super(functions);
for (HashFunction function : functions) {
checkArgument(
function.bits() % 8 == 0,
"the number of bits (%s) in hashFunction (%s) must be divisible by 8",
function.bits(),
function);
}
}
@Override
HashCode makeHash(Hasher[] hashers) {
byte[] bytes = new byte[bits() / 8];
int i = 0;
for (Hasher hasher : hashers) {
HashCode newHash = hasher.hash();
i += newHash.writeBytesTo(bytes, i, newHash.bits() / 8);
}
return HashCode.fromBytesNoCopy(bytes);
}
@Override
public int bits() {
int bitSum = 0;
for (HashFunction function : functions) {
bitSum += function.bits();
}
return bitSum;
}
@Override
public boolean equals(@CheckForNull Object object) {
if (object instanceof ConcatenatedHashFunction) {
ConcatenatedHashFunction other = (ConcatenatedHashFunction) object;
return Arrays.equals(functions, other.functions);
}
return false;
}
@Override
public int hashCode() {
return Arrays.hashCode(functions);
}
}
/**
* Linear CongruentialGenerator to use for consistent hashing. See
* http://en.wikipedia.org/wiki/Linear_congruential_generator
*/
private static final class LinearCongruentialGenerator {
private long state;
public LinearCongruentialGenerator(long seed) {
this.state = seed;
}
public double nextDouble() {
state = 2862933555777941757L * state + 1;
return ((double) ((int) (state >>> 33) + 1)) / 0x1.0p31;
}
}
private Hashing() {}
}
| google/guava | android/guava/src/com/google/common/hash/Hashing.java |
44,402 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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.iluwatar.balking;
import java.util.concurrent.TimeUnit;
/**
* An interface to simulate delay while executing some work.
*/
public interface DelayProvider {
void executeAfterDelay(long interval, TimeUnit timeUnit, Runnable task);
}
| smedals/java-design-patterns | balking/src/main/java/com/iluwatar/balking/DelayProvider.java |
44,404 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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.iluwatar.nullobject;
/**
* Null Object implementation for binary tree node.
*
* <p>Implemented as Singleton, since all the NullNodes are the same.
*/
public final class NullNode implements Node {
private static final NullNode instance = new NullNode();
private NullNode() {
}
public static NullNode getInstance() {
return instance;
}
@Override
public int getTreeSize() {
return 0;
}
@Override
public Node getLeft() {
return null;
}
@Override
public Node getRight() {
return null;
}
@Override
public String getName() {
return null;
}
@Override
public void walk() {
// Do nothing
}
}
| smedals/java-design-patterns | null-object/src/main/java/com/iluwatar/nullobject/NullNode.java |
44,407 | /*
* Copyright (C) 2012 The Guava Authors
*
* 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.google.common.io;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.math.IntMath.divide;
import static com.google.common.math.IntMath.log2;
import static java.math.RoundingMode.CEILING;
import static java.math.RoundingMode.FLOOR;
import static java.math.RoundingMode.UNNECESSARY;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Ascii;
import com.google.errorprone.annotations.concurrent.LazyInit;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.util.Arrays;
import java.util.Objects;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A binary encoding scheme for reversibly translating between byte sequences and printable ASCII
* strings. This class includes several constants for encoding schemes specified by <a
* href="http://tools.ietf.org/html/rfc4648">RFC 4648</a>. For example, the expression:
*
* <pre>{@code
* BaseEncoding.base32().encode("foo".getBytes(Charsets.US_ASCII))
* }</pre>
*
* <p>returns the string {@code "MZXW6==="}, and
*
* <pre>{@code
* byte[] decoded = BaseEncoding.base32().decode("MZXW6===");
* }</pre>
*
* <p>...returns the ASCII bytes of the string {@code "foo"}.
*
* <p>By default, {@code BaseEncoding}'s behavior is relatively strict and in accordance with RFC
* 4648. Decoding rejects characters in the wrong case, though padding is optional. To modify
* encoding and decoding behavior, use configuration methods to obtain a new encoding with modified
* behavior:
*
* <pre>{@code
* BaseEncoding.base16().lowerCase().decode("deadbeef");
* }</pre>
*
* <p>Warning: BaseEncoding instances are immutable. Invoking a configuration method has no effect
* on the receiving instance; you must store and use the new encoding instance it returns, instead.
*
* <pre>{@code
* // Do NOT do this
* BaseEncoding hex = BaseEncoding.base16();
* hex.lowerCase(); // does nothing!
* return hex.decode("deadbeef"); // throws an IllegalArgumentException
* }</pre>
*
* <p>It is guaranteed that {@code encoding.decode(encoding.encode(x))} is always equal to {@code
* x}, but the reverse does not necessarily hold.
*
* <table>
* <caption>Encodings</caption>
* <tr>
* <th>Encoding
* <th>Alphabet
* <th>{@code char:byte} ratio
* <th>Default padding
* <th>Comments
* <tr>
* <td>{@link #base16()}
* <td>0-9 A-F
* <td>2.00
* <td>N/A
* <td>Traditional hexadecimal. Defaults to upper case.
* <tr>
* <td>{@link #base32()}
* <td>A-Z 2-7
* <td>1.60
* <td>=
* <td>Human-readable; no possibility of mixing up 0/O or 1/I. Defaults to upper case.
* <tr>
* <td>{@link #base32Hex()}
* <td>0-9 A-V
* <td>1.60
* <td>=
* <td>"Numerical" base 32; extended from the traditional hex alphabet. Defaults to upper case.
* <tr>
* <td>{@link #base64()}
* <td>A-Z a-z 0-9 + /
* <td>1.33
* <td>=
* <td>
* <tr>
* <td>{@link #base64Url()}
* <td>A-Z a-z 0-9 - _
* <td>1.33
* <td>=
* <td>Safe to use as filenames, or to pass in URLs without escaping
* </table>
*
* <p>All instances of this class are immutable, so they may be stored safely as static constants.
*
* @author Louis Wasserman
* @since 14.0
*/
@GwtCompatible(emulated = true)
@ElementTypesAreNonnullByDefault
public abstract class BaseEncoding {
// TODO(lowasser): consider making encodeTo(Appendable, byte[], int, int) public.
BaseEncoding() {}
/**
* Exception indicating invalid base-encoded input encountered while decoding.
*
* @author Louis Wasserman
* @since 15.0
*/
public static final class DecodingException extends IOException {
DecodingException(@Nullable String message) {
super(message);
}
}
/** Encodes the specified byte array, and returns the encoded {@code String}. */
public String encode(byte[] bytes) {
return encode(bytes, 0, bytes.length);
}
/**
* Encodes the specified range of the specified byte array, and returns the encoded {@code
* String}.
*/
public final String encode(byte[] bytes, int off, int len) {
checkPositionIndexes(off, off + len, bytes.length);
StringBuilder result = new StringBuilder(maxEncodedSize(len));
try {
encodeTo(result, bytes, off, len);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
return result.toString();
}
/**
* Returns an {@code OutputStream} that encodes bytes using this encoding into the specified
* {@code Writer}. When the returned {@code OutputStream} is closed, so is the backing {@code
* Writer}.
*/
@J2ktIncompatible
@GwtIncompatible // Writer,OutputStream
public abstract OutputStream encodingStream(Writer writer);
/**
* Returns a {@code ByteSink} that writes base-encoded bytes to the specified {@code CharSink}.
*/
@J2ktIncompatible
@GwtIncompatible // ByteSink,CharSink
public final ByteSink encodingSink(CharSink encodedSink) {
checkNotNull(encodedSink);
return new ByteSink() {
@Override
public OutputStream openStream() throws IOException {
return encodingStream(encodedSink.openStream());
}
};
}
// TODO(lowasser): document the extent of leniency, probably after adding ignore(CharMatcher)
private static byte[] extract(byte[] result, int length) {
if (length == result.length) {
return result;
}
byte[] trunc = new byte[length];
System.arraycopy(result, 0, trunc, 0, length);
return trunc;
}
/**
* Determines whether the specified character sequence is a valid encoded string according to this
* encoding.
*
* @since 20.0
*/
public abstract boolean canDecode(CharSequence chars);
/**
* Decodes the specified character sequence, and returns the resulting {@code byte[]}. This is the
* inverse operation to {@link #encode(byte[])}.
*
* @throws IllegalArgumentException if the input is not a valid encoded string according to this
* encoding.
*/
public final byte[] decode(CharSequence chars) {
try {
return decodeChecked(chars);
} catch (DecodingException badInput) {
throw new IllegalArgumentException(badInput);
}
}
/**
* Decodes the specified character sequence, and returns the resulting {@code byte[]}. This is the
* inverse operation to {@link #encode(byte[])}.
*
* @throws DecodingException if the input is not a valid encoded string according to this
* encoding.
*/
final byte[] decodeChecked(CharSequence chars)
throws DecodingException {
chars = trimTrailingPadding(chars);
byte[] tmp = new byte[maxDecodedSize(chars.length())];
int len = decodeTo(tmp, chars);
return extract(tmp, len);
}
/**
* Returns an {@code InputStream} that decodes base-encoded input from the specified {@code
* Reader}. The returned stream throws a {@link DecodingException} upon decoding-specific errors.
*/
@J2ktIncompatible
@GwtIncompatible // Reader,InputStream
public abstract InputStream decodingStream(Reader reader);
/**
* Returns a {@code ByteSource} that reads base-encoded bytes from the specified {@code
* CharSource}.
*/
@J2ktIncompatible
@GwtIncompatible // ByteSource,CharSource
public final ByteSource decodingSource(CharSource encodedSource) {
checkNotNull(encodedSource);
return new ByteSource() {
@Override
public InputStream openStream() throws IOException {
return decodingStream(encodedSource.openStream());
}
};
}
// Implementations for encoding/decoding
abstract int maxEncodedSize(int bytes);
abstract void encodeTo(Appendable target, byte[] bytes, int off, int len) throws IOException;
abstract int maxDecodedSize(int chars);
abstract int decodeTo(byte[] target, CharSequence chars) throws DecodingException;
CharSequence trimTrailingPadding(CharSequence chars) {
return checkNotNull(chars);
}
// Modified encoding generators
/**
* Returns an encoding that behaves equivalently to this encoding, but omits any padding
* characters as specified by <a href="http://tools.ietf.org/html/rfc4648#section-3.2">RFC 4648
* section 3.2</a>, Padding of Encoded Data.
*/
public abstract BaseEncoding omitPadding();
/**
* Returns an encoding that behaves equivalently to this encoding, but uses an alternate character
* for padding.
*
* @throws IllegalArgumentException if this padding character is already used in the alphabet or a
* separator
*/
public abstract BaseEncoding withPadChar(char padChar);
/**
* Returns an encoding that behaves equivalently to this encoding, but adds a separator string
* after every {@code n} characters. Any occurrences of any characters that occur in the separator
* are skipped over in decoding.
*
* @throws IllegalArgumentException if any alphabet or padding characters appear in the separator
* string, or if {@code n <= 0}
* @throws UnsupportedOperationException if this encoding already uses a separator
*/
public abstract BaseEncoding withSeparator(String separator, int n);
/**
* Returns an encoding that behaves equivalently to this encoding, but encodes and decodes with
* uppercase letters. Padding and separator characters remain in their original case.
*
* @throws IllegalStateException if the alphabet used by this encoding contains mixed upper- and
* lower-case characters
*/
public abstract BaseEncoding upperCase();
/**
* Returns an encoding that behaves equivalently to this encoding, but encodes and decodes with
* lowercase letters. Padding and separator characters remain in their original case.
*
* @throws IllegalStateException if the alphabet used by this encoding contains mixed upper- and
* lower-case characters
*/
public abstract BaseEncoding lowerCase();
/**
* Returns an encoding that behaves equivalently to this encoding, but decodes letters without
* regard to case.
*
* @throws IllegalStateException if the alphabet used by this encoding contains mixed upper- and
* lower-case characters
* @since 32.0.0
*/
public abstract BaseEncoding ignoreCase();
private static final BaseEncoding BASE64 =
new Base64Encoding(
"base64()", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", '=');
/**
* The "base64" base encoding specified by <a
* href="http://tools.ietf.org/html/rfc4648#section-4">RFC 4648 section 4</a>, Base 64 Encoding.
* (This is the same as the base 64 encoding from <a
* href="http://tools.ietf.org/html/rfc3548#section-3">RFC 3548</a>.)
*
* <p>The character {@code '='} is used for padding, but can be {@linkplain #omitPadding()
* omitted} or {@linkplain #withPadChar(char) replaced}.
*
* <p>No line feeds are added by default, as per <a
* href="http://tools.ietf.org/html/rfc4648#section-3.1">RFC 4648 section 3.1</a>, Line Feeds in
* Encoded Data. Line feeds may be added using {@link #withSeparator(String, int)}.
*/
public static BaseEncoding base64() {
return BASE64;
}
private static final BaseEncoding BASE64_URL =
new Base64Encoding(
"base64Url()", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", '=');
/**
* The "base64url" encoding specified by <a
* href="http://tools.ietf.org/html/rfc4648#section-5">RFC 4648 section 5</a>, Base 64 Encoding
* with URL and Filename Safe Alphabet, also sometimes referred to as the "web safe Base64." (This
* is the same as the base 64 encoding with URL and filename safe alphabet from <a
* href="http://tools.ietf.org/html/rfc3548#section-4">RFC 3548</a>.)
*
* <p>The character {@code '='} is used for padding, but can be {@linkplain #omitPadding()
* omitted} or {@linkplain #withPadChar(char) replaced}.
*
* <p>No line feeds are added by default, as per <a
* href="http://tools.ietf.org/html/rfc4648#section-3.1">RFC 4648 section 3.1</a>, Line Feeds in
* Encoded Data. Line feeds may be added using {@link #withSeparator(String, int)}.
*/
public static BaseEncoding base64Url() {
return BASE64_URL;
}
private static final BaseEncoding BASE32 =
new StandardBaseEncoding("base32()", "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", '=');
/**
* The "base32" encoding specified by <a href="http://tools.ietf.org/html/rfc4648#section-6">RFC
* 4648 section 6</a>, Base 32 Encoding. (This is the same as the base 32 encoding from <a
* href="http://tools.ietf.org/html/rfc3548#section-5">RFC 3548</a>.)
*
* <p>The character {@code '='} is used for padding, but can be {@linkplain #omitPadding()
* omitted} or {@linkplain #withPadChar(char) replaced}.
*
* <p>No line feeds are added by default, as per <a
* href="http://tools.ietf.org/html/rfc4648#section-3.1">RFC 4648 section 3.1</a>, Line Feeds in
* Encoded Data. Line feeds may be added using {@link #withSeparator(String, int)}.
*/
public static BaseEncoding base32() {
return BASE32;
}
private static final BaseEncoding BASE32_HEX =
new StandardBaseEncoding("base32Hex()", "0123456789ABCDEFGHIJKLMNOPQRSTUV", '=');
/**
* The "base32hex" encoding specified by <a
* href="http://tools.ietf.org/html/rfc4648#section-7">RFC 4648 section 7</a>, Base 32 Encoding
* with Extended Hex Alphabet. There is no corresponding encoding in RFC 3548.
*
* <p>The character {@code '='} is used for padding, but can be {@linkplain #omitPadding()
* omitted} or {@linkplain #withPadChar(char) replaced}.
*
* <p>No line feeds are added by default, as per <a
* href="http://tools.ietf.org/html/rfc4648#section-3.1">RFC 4648 section 3.1</a>, Line Feeds in
* Encoded Data. Line feeds may be added using {@link #withSeparator(String, int)}.
*/
public static BaseEncoding base32Hex() {
return BASE32_HEX;
}
private static final BaseEncoding BASE16 = new Base16Encoding("base16()", "0123456789ABCDEF");
/**
* The "base16" encoding specified by <a href="http://tools.ietf.org/html/rfc4648#section-8">RFC
* 4648 section 8</a>, Base 16 Encoding. (This is the same as the base 16 encoding from <a
* href="http://tools.ietf.org/html/rfc3548#section-6">RFC 3548</a>.) This is commonly known as
* "hexadecimal" format.
*
* <p>No padding is necessary in base 16, so {@link #withPadChar(char)} and {@link #omitPadding()}
* have no effect.
*
* <p>No line feeds are added by default, as per <a
* href="http://tools.ietf.org/html/rfc4648#section-3.1">RFC 4648 section 3.1</a>, Line Feeds in
* Encoded Data. Line feeds may be added using {@link #withSeparator(String, int)}.
*/
public static BaseEncoding base16() {
return BASE16;
}
static final class Alphabet {
private final String name;
// this is meant to be immutable -- don't modify it!
private final char[] chars;
final int mask;
final int bitsPerChar;
final int charsPerChunk;
final int bytesPerChunk;
private final byte[] decodabet;
private final boolean[] validPadding;
private final boolean ignoreCase;
Alphabet(String name, char[] chars) {
this(name, chars, decodabetFor(chars), /* ignoreCase= */ false);
}
private Alphabet(String name, char[] chars, byte[] decodabet, boolean ignoreCase) {
this.name = checkNotNull(name);
this.chars = checkNotNull(chars);
try {
this.bitsPerChar = log2(chars.length, UNNECESSARY);
} catch (ArithmeticException e) {
throw new IllegalArgumentException("Illegal alphabet length " + chars.length, e);
}
// Compute how input bytes are chunked. For example, with base64 we chunk every 3 bytes into
// 4 characters. We have bitsPerChar == 6, charsPerChunk == 4, and bytesPerChunk == 3.
// We're looking for the smallest charsPerChunk such that bitsPerChar * charsPerChunk is a
// multiple of 8. A multiple of 8 has 3 low zero bits, so we just need to figure out how many
// extra zero bits we need to add to the end of bitsPerChar to get 3 in total.
// The logic here would be wrong for bitsPerChar > 8, but since we require distinct ASCII
// characters that can't happen.
int zeroesInBitsPerChar = Integer.numberOfTrailingZeros(bitsPerChar);
this.charsPerChunk = 1 << (3 - zeroesInBitsPerChar);
this.bytesPerChunk = bitsPerChar >> zeroesInBitsPerChar;
this.mask = chars.length - 1;
this.decodabet = decodabet;
boolean[] validPadding = new boolean[charsPerChunk];
for (int i = 0; i < bytesPerChunk; i++) {
validPadding[divide(i * 8, bitsPerChar, CEILING)] = true;
}
this.validPadding = validPadding;
this.ignoreCase = ignoreCase;
}
private static byte[] decodabetFor(char[] chars) {
byte[] decodabet = new byte[Ascii.MAX + 1];
Arrays.fill(decodabet, (byte) -1);
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
checkArgument(c < decodabet.length, "Non-ASCII character: %s", c);
checkArgument(decodabet[c] == -1, "Duplicate character: %s", c);
decodabet[c] = (byte) i;
}
return decodabet;
}
/** Returns an equivalent {@code Alphabet} except it ignores case. */
Alphabet ignoreCase() {
if (ignoreCase) {
return this;
}
// We can't use .clone() because of GWT.
byte[] newDecodabet = Arrays.copyOf(decodabet, decodabet.length);
for (int upper = 'A'; upper <= 'Z'; upper++) {
int lower = upper | 0x20;
byte decodeUpper = decodabet[upper];
byte decodeLower = decodabet[lower];
if (decodeUpper == -1) {
newDecodabet[upper] = decodeLower;
} else {
checkState(
decodeLower == -1,
"Can't ignoreCase() since '%s' and '%s' encode different values",
(char) upper,
(char) lower);
newDecodabet[lower] = decodeUpper;
}
}
return new Alphabet(name + ".ignoreCase()", chars, newDecodabet, /* ignoreCase= */ true);
}
char encode(int bits) {
return chars[bits];
}
boolean isValidPaddingStartPosition(int index) {
return validPadding[index % charsPerChunk];
}
boolean canDecode(char ch) {
return ch <= Ascii.MAX && decodabet[ch] != -1;
}
int decode(char ch) throws DecodingException {
if (ch > Ascii.MAX) {
throw new DecodingException("Unrecognized character: 0x" + Integer.toHexString(ch));
}
int result = decodabet[ch];
if (result == -1) {
if (ch <= 0x20 || ch == Ascii.MAX) {
throw new DecodingException("Unrecognized character: 0x" + Integer.toHexString(ch));
} else {
throw new DecodingException("Unrecognized character: " + ch);
}
}
return result;
}
private boolean hasLowerCase() {
for (char c : chars) {
if (Ascii.isLowerCase(c)) {
return true;
}
}
return false;
}
private boolean hasUpperCase() {
for (char c : chars) {
if (Ascii.isUpperCase(c)) {
return true;
}
}
return false;
}
Alphabet upperCase() {
if (!hasLowerCase()) {
return this;
}
checkState(!hasUpperCase(), "Cannot call upperCase() on a mixed-case alphabet");
char[] upperCased = new char[chars.length];
for (int i = 0; i < chars.length; i++) {
upperCased[i] = Ascii.toUpperCase(chars[i]);
}
Alphabet upperCase = new Alphabet(name + ".upperCase()", upperCased);
return ignoreCase ? upperCase.ignoreCase() : upperCase;
}
Alphabet lowerCase() {
if (!hasUpperCase()) {
return this;
}
checkState(!hasLowerCase(), "Cannot call lowerCase() on a mixed-case alphabet");
char[] lowerCased = new char[chars.length];
for (int i = 0; i < chars.length; i++) {
lowerCased[i] = Ascii.toLowerCase(chars[i]);
}
Alphabet lowerCase = new Alphabet(name + ".lowerCase()", lowerCased);
return ignoreCase ? lowerCase.ignoreCase() : lowerCase;
}
public boolean matches(char c) {
return c < decodabet.length && decodabet[c] != -1;
}
@Override
public String toString() {
return name;
}
@Override
public boolean equals(@CheckForNull Object other) {
if (other instanceof Alphabet) {
Alphabet that = (Alphabet) other;
return this.ignoreCase == that.ignoreCase && Arrays.equals(this.chars, that.chars);
}
return false;
}
@Override
public int hashCode() {
return Arrays.hashCode(chars) + (ignoreCase ? 1231 : 1237);
}
}
private static class StandardBaseEncoding extends BaseEncoding {
final Alphabet alphabet;
@CheckForNull final Character paddingChar;
StandardBaseEncoding(String name, String alphabetChars, @CheckForNull Character paddingChar) {
this(new Alphabet(name, alphabetChars.toCharArray()), paddingChar);
}
StandardBaseEncoding(Alphabet alphabet, @CheckForNull Character paddingChar) {
this.alphabet = checkNotNull(alphabet);
checkArgument(
paddingChar == null || !alphabet.matches(paddingChar),
"Padding character %s was already in alphabet",
paddingChar);
this.paddingChar = paddingChar;
}
@Override
int maxEncodedSize(int bytes) {
return alphabet.charsPerChunk * divide(bytes, alphabet.bytesPerChunk, CEILING);
}
@J2ktIncompatible
@GwtIncompatible // Writer,OutputStream
@Override
public OutputStream encodingStream(Writer out) {
checkNotNull(out);
return new OutputStream() {
int bitBuffer = 0;
int bitBufferLength = 0;
int writtenChars = 0;
@Override
public void write(int b) throws IOException {
bitBuffer <<= 8;
bitBuffer |= b & 0xFF;
bitBufferLength += 8;
while (bitBufferLength >= alphabet.bitsPerChar) {
int charIndex = (bitBuffer >> (bitBufferLength - alphabet.bitsPerChar)) & alphabet.mask;
out.write(alphabet.encode(charIndex));
writtenChars++;
bitBufferLength -= alphabet.bitsPerChar;
}
}
@Override
public void flush() throws IOException {
out.flush();
}
@Override
public void close() throws IOException {
if (bitBufferLength > 0) {
int charIndex = (bitBuffer << (alphabet.bitsPerChar - bitBufferLength)) & alphabet.mask;
out.write(alphabet.encode(charIndex));
writtenChars++;
if (paddingChar != null) {
while (writtenChars % alphabet.charsPerChunk != 0) {
out.write(paddingChar.charValue());
writtenChars++;
}
}
}
out.close();
}
};
}
@Override
void encodeTo(Appendable target, byte[] bytes, int off, int len) throws IOException {
checkNotNull(target);
checkPositionIndexes(off, off + len, bytes.length);
for (int i = 0; i < len; i += alphabet.bytesPerChunk) {
encodeChunkTo(target, bytes, off + i, Math.min(alphabet.bytesPerChunk, len - i));
}
}
void encodeChunkTo(Appendable target, byte[] bytes, int off, int len) throws IOException {
checkNotNull(target);
checkPositionIndexes(off, off + len, bytes.length);
checkArgument(len <= alphabet.bytesPerChunk);
long bitBuffer = 0;
for (int i = 0; i < len; ++i) {
bitBuffer |= bytes[off + i] & 0xFF;
bitBuffer <<= 8; // Add additional zero byte in the end.
}
// Position of first character is length of bitBuffer minus bitsPerChar.
int bitOffset = (len + 1) * 8 - alphabet.bitsPerChar;
int bitsProcessed = 0;
while (bitsProcessed < len * 8) {
int charIndex = (int) (bitBuffer >>> (bitOffset - bitsProcessed)) & alphabet.mask;
target.append(alphabet.encode(charIndex));
bitsProcessed += alphabet.bitsPerChar;
}
if (paddingChar != null) {
while (bitsProcessed < alphabet.bytesPerChunk * 8) {
target.append(paddingChar.charValue());
bitsProcessed += alphabet.bitsPerChar;
}
}
}
@Override
int maxDecodedSize(int chars) {
return (int) ((alphabet.bitsPerChar * (long) chars + 7L) / 8L);
}
@Override
CharSequence trimTrailingPadding(CharSequence chars) {
checkNotNull(chars);
if (paddingChar == null) {
return chars;
}
char padChar = paddingChar.charValue();
int l;
for (l = chars.length() - 1; l >= 0; l--) {
if (chars.charAt(l) != padChar) {
break;
}
}
return chars.subSequence(0, l + 1);
}
@Override
public boolean canDecode(CharSequence chars) {
checkNotNull(chars);
chars = trimTrailingPadding(chars);
if (!alphabet.isValidPaddingStartPosition(chars.length())) {
return false;
}
for (int i = 0; i < chars.length(); i++) {
if (!alphabet.canDecode(chars.charAt(i))) {
return false;
}
}
return true;
}
@Override
int decodeTo(byte[] target, CharSequence chars) throws DecodingException {
checkNotNull(target);
chars = trimTrailingPadding(chars);
if (!alphabet.isValidPaddingStartPosition(chars.length())) {
throw new DecodingException("Invalid input length " + chars.length());
}
int bytesWritten = 0;
for (int charIdx = 0; charIdx < chars.length(); charIdx += alphabet.charsPerChunk) {
long chunk = 0;
int charsProcessed = 0;
for (int i = 0; i < alphabet.charsPerChunk; i++) {
chunk <<= alphabet.bitsPerChar;
if (charIdx + i < chars.length()) {
chunk |= alphabet.decode(chars.charAt(charIdx + charsProcessed++));
}
}
int minOffset = alphabet.bytesPerChunk * 8 - charsProcessed * alphabet.bitsPerChar;
for (int offset = (alphabet.bytesPerChunk - 1) * 8; offset >= minOffset; offset -= 8) {
target[bytesWritten++] = (byte) ((chunk >>> offset) & 0xFF);
}
}
return bytesWritten;
}
@Override
@J2ktIncompatible
@GwtIncompatible // Reader,InputStream
public InputStream decodingStream(Reader reader) {
checkNotNull(reader);
return new InputStream() {
int bitBuffer = 0;
int bitBufferLength = 0;
int readChars = 0;
boolean hitPadding = false;
@Override
public int read() throws IOException {
while (true) {
int readChar = reader.read();
if (readChar == -1) {
if (!hitPadding && !alphabet.isValidPaddingStartPosition(readChars)) {
throw new DecodingException("Invalid input length " + readChars);
}
return -1;
}
readChars++;
char ch = (char) readChar;
if (paddingChar != null && paddingChar.charValue() == ch) {
if (!hitPadding
&& (readChars == 1 || !alphabet.isValidPaddingStartPosition(readChars - 1))) {
throw new DecodingException("Padding cannot start at index " + readChars);
}
hitPadding = true;
} else if (hitPadding) {
throw new DecodingException(
"Expected padding character but found '" + ch + "' at index " + readChars);
} else {
bitBuffer <<= alphabet.bitsPerChar;
bitBuffer |= alphabet.decode(ch);
bitBufferLength += alphabet.bitsPerChar;
if (bitBufferLength >= 8) {
bitBufferLength -= 8;
return (bitBuffer >> bitBufferLength) & 0xFF;
}
}
}
}
@Override
public int read(byte[] buf, int off, int len) throws IOException {
// Overriding this to work around the fact that InputStream's default implementation of
// this method will silently swallow exceptions thrown by the single-byte read() method
// (other than on the first call to it), which in this case can cause invalid encoded
// strings to not throw an exception.
// See https://github.com/google/guava/issues/3542
checkPositionIndexes(off, off + len, buf.length);
int i = off;
for (; i < off + len; i++) {
int b = read();
if (b == -1) {
int read = i - off;
return read == 0 ? -1 : read;
}
buf[i] = (byte) b;
}
return i - off;
}
@Override
public void close() throws IOException {
reader.close();
}
};
}
@Override
public BaseEncoding omitPadding() {
return (paddingChar == null) ? this : newInstance(alphabet, null);
}
@Override
public BaseEncoding withPadChar(char padChar) {
if (8 % alphabet.bitsPerChar == 0
|| (paddingChar != null && paddingChar.charValue() == padChar)) {
return this;
} else {
return newInstance(alphabet, padChar);
}
}
@Override
public BaseEncoding withSeparator(String separator, int afterEveryChars) {
for (int i = 0; i < separator.length(); i++) {
checkArgument(
!alphabet.matches(separator.charAt(i)),
"Separator (%s) cannot contain alphabet characters",
separator);
}
if (paddingChar != null) {
checkArgument(
separator.indexOf(paddingChar.charValue()) < 0,
"Separator (%s) cannot contain padding character",
separator);
}
return new SeparatedBaseEncoding(this, separator, afterEveryChars);
}
@LazyInit @CheckForNull private volatile BaseEncoding upperCase;
@LazyInit @CheckForNull private volatile BaseEncoding lowerCase;
@LazyInit @CheckForNull private volatile BaseEncoding ignoreCase;
@Override
public BaseEncoding upperCase() {
BaseEncoding result = upperCase;
if (result == null) {
Alphabet upper = alphabet.upperCase();
result = upperCase = (upper == alphabet) ? this : newInstance(upper, paddingChar);
}
return result;
}
@Override
public BaseEncoding lowerCase() {
BaseEncoding result = lowerCase;
if (result == null) {
Alphabet lower = alphabet.lowerCase();
result = lowerCase = (lower == alphabet) ? this : newInstance(lower, paddingChar);
}
return result;
}
@Override
public BaseEncoding ignoreCase() {
BaseEncoding result = ignoreCase;
if (result == null) {
Alphabet ignore = alphabet.ignoreCase();
result = ignoreCase = (ignore == alphabet) ? this : newInstance(ignore, paddingChar);
}
return result;
}
BaseEncoding newInstance(Alphabet alphabet, @CheckForNull Character paddingChar) {
return new StandardBaseEncoding(alphabet, paddingChar);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("BaseEncoding.");
builder.append(alphabet);
if (8 % alphabet.bitsPerChar != 0) {
if (paddingChar == null) {
builder.append(".omitPadding()");
} else {
builder.append(".withPadChar('").append(paddingChar).append("')");
}
}
return builder.toString();
}
@Override
public boolean equals(@CheckForNull Object other) {
if (other instanceof StandardBaseEncoding) {
StandardBaseEncoding that = (StandardBaseEncoding) other;
return this.alphabet.equals(that.alphabet)
&& Objects.equals(this.paddingChar, that.paddingChar);
}
return false;
}
@Override
public int hashCode() {
return alphabet.hashCode() ^ Objects.hashCode(paddingChar);
}
}
private static final class Base16Encoding extends StandardBaseEncoding {
final char[] encoding = new char[512];
Base16Encoding(String name, String alphabetChars) {
this(new Alphabet(name, alphabetChars.toCharArray()));
}
private Base16Encoding(Alphabet alphabet) {
super(alphabet, null);
checkArgument(alphabet.chars.length == 16);
for (int i = 0; i < 256; ++i) {
encoding[i] = alphabet.encode(i >>> 4);
encoding[i | 0x100] = alphabet.encode(i & 0xF);
}
}
@Override
void encodeTo(Appendable target, byte[] bytes, int off, int len) throws IOException {
checkNotNull(target);
checkPositionIndexes(off, off + len, bytes.length);
for (int i = 0; i < len; ++i) {
int b = bytes[off + i] & 0xFF;
target.append(encoding[b]);
target.append(encoding[b | 0x100]);
}
}
@Override
int decodeTo(byte[] target, CharSequence chars) throws DecodingException {
checkNotNull(target);
if (chars.length() % 2 == 1) {
throw new DecodingException("Invalid input length " + chars.length());
}
int bytesWritten = 0;
for (int i = 0; i < chars.length(); i += 2) {
int decoded = alphabet.decode(chars.charAt(i)) << 4 | alphabet.decode(chars.charAt(i + 1));
target[bytesWritten++] = (byte) decoded;
}
return bytesWritten;
}
@Override
BaseEncoding newInstance(Alphabet alphabet, @CheckForNull Character paddingChar) {
return new Base16Encoding(alphabet);
}
}
private static final class Base64Encoding extends StandardBaseEncoding {
Base64Encoding(String name, String alphabetChars, @CheckForNull Character paddingChar) {
this(new Alphabet(name, alphabetChars.toCharArray()), paddingChar);
}
private Base64Encoding(Alphabet alphabet, @CheckForNull Character paddingChar) {
super(alphabet, paddingChar);
checkArgument(alphabet.chars.length == 64);
}
@Override
void encodeTo(Appendable target, byte[] bytes, int off, int len) throws IOException {
checkNotNull(target);
checkPositionIndexes(off, off + len, bytes.length);
int i = off;
for (int remaining = len; remaining >= 3; remaining -= 3) {
int chunk = (bytes[i++] & 0xFF) << 16 | (bytes[i++] & 0xFF) << 8 | bytes[i++] & 0xFF;
target.append(alphabet.encode(chunk >>> 18));
target.append(alphabet.encode((chunk >>> 12) & 0x3F));
target.append(alphabet.encode((chunk >>> 6) & 0x3F));
target.append(alphabet.encode(chunk & 0x3F));
}
if (i < off + len) {
encodeChunkTo(target, bytes, i, off + len - i);
}
}
@Override
int decodeTo(byte[] target, CharSequence chars) throws DecodingException {
checkNotNull(target);
chars = trimTrailingPadding(chars);
if (!alphabet.isValidPaddingStartPosition(chars.length())) {
throw new DecodingException("Invalid input length " + chars.length());
}
int bytesWritten = 0;
for (int i = 0; i < chars.length(); ) {
int chunk = alphabet.decode(chars.charAt(i++)) << 18;
chunk |= alphabet.decode(chars.charAt(i++)) << 12;
target[bytesWritten++] = (byte) (chunk >>> 16);
if (i < chars.length()) {
chunk |= alphabet.decode(chars.charAt(i++)) << 6;
target[bytesWritten++] = (byte) ((chunk >>> 8) & 0xFF);
if (i < chars.length()) {
chunk |= alphabet.decode(chars.charAt(i++));
target[bytesWritten++] = (byte) (chunk & 0xFF);
}
}
}
return bytesWritten;
}
@Override
BaseEncoding newInstance(Alphabet alphabet, @CheckForNull Character paddingChar) {
return new Base64Encoding(alphabet, paddingChar);
}
}
@J2ktIncompatible
@GwtIncompatible
static Reader ignoringReader(Reader delegate, String toIgnore) {
checkNotNull(delegate);
checkNotNull(toIgnore);
return new Reader() {
@Override
public int read() throws IOException {
int readChar;
do {
readChar = delegate.read();
} while (readChar != -1 && toIgnore.indexOf((char) readChar) >= 0);
return readChar;
}
@Override
public int read(char[] cbuf, int off, int len) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public void close() throws IOException {
delegate.close();
}
};
}
static Appendable separatingAppendable(
Appendable delegate, String separator, int afterEveryChars) {
checkNotNull(delegate);
checkNotNull(separator);
checkArgument(afterEveryChars > 0);
return new Appendable() {
int charsUntilSeparator = afterEveryChars;
@Override
public Appendable append(char c) throws IOException {
if (charsUntilSeparator == 0) {
delegate.append(separator);
charsUntilSeparator = afterEveryChars;
}
delegate.append(c);
charsUntilSeparator--;
return this;
}
@Override
public Appendable append(@CheckForNull CharSequence chars, int off, int len) {
throw new UnsupportedOperationException();
}
@Override
public Appendable append(@CheckForNull CharSequence chars) {
throw new UnsupportedOperationException();
}
};
}
@J2ktIncompatible
@GwtIncompatible // Writer
static Writer separatingWriter(Writer delegate, String separator, int afterEveryChars) {
Appendable separatingAppendable = separatingAppendable(delegate, separator, afterEveryChars);
return new Writer() {
@Override
public void write(int c) throws IOException {
separatingAppendable.append((char) c);
}
@Override
public void write(char[] chars, int off, int len) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public void flush() throws IOException {
delegate.flush();
}
@Override
public void close() throws IOException {
delegate.close();
}
};
}
static final class SeparatedBaseEncoding extends BaseEncoding {
private final BaseEncoding delegate;
private final String separator;
private final int afterEveryChars;
SeparatedBaseEncoding(BaseEncoding delegate, String separator, int afterEveryChars) {
this.delegate = checkNotNull(delegate);
this.separator = checkNotNull(separator);
this.afterEveryChars = afterEveryChars;
checkArgument(
afterEveryChars > 0, "Cannot add a separator after every %s chars", afterEveryChars);
}
@Override
CharSequence trimTrailingPadding(CharSequence chars) {
return delegate.trimTrailingPadding(chars);
}
@Override
int maxEncodedSize(int bytes) {
int unseparatedSize = delegate.maxEncodedSize(bytes);
return unseparatedSize
+ separator.length() * divide(Math.max(0, unseparatedSize - 1), afterEveryChars, FLOOR);
}
@J2ktIncompatible
@GwtIncompatible // Writer,OutputStream
@Override
public OutputStream encodingStream(Writer output) {
return delegate.encodingStream(separatingWriter(output, separator, afterEveryChars));
}
@Override
void encodeTo(Appendable target, byte[] bytes, int off, int len) throws IOException {
delegate.encodeTo(separatingAppendable(target, separator, afterEveryChars), bytes, off, len);
}
@Override
int maxDecodedSize(int chars) {
return delegate.maxDecodedSize(chars);
}
@Override
public boolean canDecode(CharSequence chars) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < chars.length(); i++) {
char c = chars.charAt(i);
if (separator.indexOf(c) < 0) {
builder.append(c);
}
}
return delegate.canDecode(builder);
}
@Override
int decodeTo(byte[] target, CharSequence chars) throws DecodingException {
StringBuilder stripped = new StringBuilder(chars.length());
for (int i = 0; i < chars.length(); i++) {
char c = chars.charAt(i);
if (separator.indexOf(c) < 0) {
stripped.append(c);
}
}
return delegate.decodeTo(target, stripped);
}
@Override
@J2ktIncompatible
@GwtIncompatible // Reader,InputStream
public InputStream decodingStream(Reader reader) {
return delegate.decodingStream(ignoringReader(reader, separator));
}
@Override
public BaseEncoding omitPadding() {
return delegate.omitPadding().withSeparator(separator, afterEveryChars);
}
@Override
public BaseEncoding withPadChar(char padChar) {
return delegate.withPadChar(padChar).withSeparator(separator, afterEveryChars);
}
@Override
public BaseEncoding withSeparator(String separator, int afterEveryChars) {
throw new UnsupportedOperationException("Already have a separator");
}
@Override
public BaseEncoding upperCase() {
return delegate.upperCase().withSeparator(separator, afterEveryChars);
}
@Override
public BaseEncoding lowerCase() {
return delegate.lowerCase().withSeparator(separator, afterEveryChars);
}
@Override
public BaseEncoding ignoreCase() {
return delegate.ignoreCase().withSeparator(separator, afterEveryChars);
}
@Override
public String toString() {
return delegate + ".withSeparator(\"" + separator + "\", " + afterEveryChars + ")";
}
}
}
| google/guava | android/guava/src/com/google/common/io/BaseEncoding.java |
44,409 | /*
* Copyright (C) 2008 The Guava Authors
*
* 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.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Objects;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.CompatibleWith;
import com.google.errorprone.annotations.DoNotMock;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A collection that associates an ordered pair of keys, called a row key and a column key, with a
* single value. A table may be sparse, with only a small fraction of row key / column key pairs
* possessing a corresponding value.
*
* <p>The mappings corresponding to a given row key may be viewed as a {@link Map} whose keys are
* the columns. The reverse is also available, associating a column with a row key / value map. Note
* that, in some implementations, data access by column key may have fewer supported operations or
* worse performance than data access by row key.
*
* <p>The methods returning collections or maps always return views of the underlying table.
* Updating the table can change the contents of those collections, and updating the collections
* will change the table.
*
* <p>All methods that modify the table are optional, and the views returned by the table may or may
* not be modifiable. When modification isn't supported, those methods will throw an {@link
* UnsupportedOperationException}.
*
* <h3>Implementations</h3>
*
* <ul>
* <li>{@link ImmutableTable}
* <li>{@link HashBasedTable}
* <li>{@link TreeBasedTable}
* <li>{@link ArrayTable}
* <li>{@link Tables#newCustomTable Tables.newCustomTable}
* </ul>
*
* <p>See the Guava User Guide article on <a href=
* "https://github.com/google/guava/wiki/NewCollectionTypesExplained#table">{@code Table}</a>.
*
* @author Jared Levy
* @param <R> the type of the table row keys
* @param <C> the type of the table column keys
* @param <V> the type of the mapped values
* @since 7.0
*/
@DoNotMock("Use ImmutableTable, HashBasedTable, or another implementation")
@GwtCompatible
@ElementTypesAreNonnullByDefault
public interface Table<
R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object> {
// TODO(jlevy): Consider adding methods similar to ConcurrentMap methods.
// Accessors
/**
* Returns {@code true} if the table contains a mapping with the specified row and column keys.
*
* @param rowKey key of row to search for
* @param columnKey key of column to search for
*/
boolean contains(
@CompatibleWith("R") @CheckForNull Object rowKey,
@CompatibleWith("C") @CheckForNull Object columnKey);
/**
* Returns {@code true} if the table contains a mapping with the specified row key.
*
* @param rowKey key of row to search for
*/
boolean containsRow(@CompatibleWith("R") @CheckForNull Object rowKey);
/**
* Returns {@code true} if the table contains a mapping with the specified column.
*
* @param columnKey key of column to search for
*/
boolean containsColumn(@CompatibleWith("C") @CheckForNull Object columnKey);
/**
* Returns {@code true} if the table contains a mapping with the specified value.
*
* @param value value to search for
*/
boolean containsValue(@CompatibleWith("V") @CheckForNull Object value);
/**
* Returns the value corresponding to the given row and column keys, or {@code null} if no such
* mapping exists.
*
* @param rowKey key of row to search for
* @param columnKey key of column to search for
*/
@CheckForNull
V get(
@CompatibleWith("R") @CheckForNull Object rowKey,
@CompatibleWith("C") @CheckForNull Object columnKey);
/** Returns {@code true} if the table contains no mappings. */
boolean isEmpty();
/** Returns the number of row key / column key / value mappings in the table. */
int size();
/**
* Compares the specified object with this table for equality. Two tables are equal when their
* cell views, as returned by {@link #cellSet}, are equal.
*/
@Override
boolean equals(@CheckForNull Object obj);
/**
* Returns the hash code for this table. The hash code of a table is defined as the hash code of
* its cell view, as returned by {@link #cellSet}.
*/
@Override
int hashCode();
// Mutators
/** Removes all mappings from the table. */
void clear();
/**
* Associates the specified value with the specified keys. If the table already contained a
* mapping for those keys, the old value is replaced with the specified value.
*
* @param rowKey row key that the value should be associated with
* @param columnKey column key that the value should be associated with
* @param value value to be associated with the specified keys
* @return the value previously associated with the keys, or {@code null} if no mapping existed
* for the keys
*/
@CanIgnoreReturnValue
@CheckForNull
V put(@ParametricNullness R rowKey, @ParametricNullness C columnKey, @ParametricNullness V value);
/**
* Copies all mappings from the specified table to this table. The effect is equivalent to calling
* {@link #put} with each row key / column key / value mapping in {@code table}.
*
* @param table the table to add to this table
*/
void putAll(Table<? extends R, ? extends C, ? extends V> table);
/**
* Removes the mapping, if any, associated with the given keys.
*
* @param rowKey row key of mapping to be removed
* @param columnKey column key of mapping to be removed
* @return the value previously associated with the keys, or {@code null} if no such value existed
*/
@CanIgnoreReturnValue
@CheckForNull
V remove(
@CompatibleWith("R") @CheckForNull Object rowKey,
@CompatibleWith("C") @CheckForNull Object columnKey);
// Views
/**
* Returns a view of all mappings that have the given row key. For each row key / column key /
* value mapping in the table with that row key, the returned map associates the column key with
* the value. If no mappings in the table have the provided row key, an empty map is returned.
*
* <p>Changes to the returned map will update the underlying table, and vice versa.
*
* @param rowKey key of row to search for in the table
* @return the corresponding map from column keys to values
*/
Map<C, V> row(@ParametricNullness R rowKey);
/**
* Returns a view of all mappings that have the given column key. For each row key / column key /
* value mapping in the table with that column key, the returned map associates the row key with
* the value. If no mappings in the table have the provided column key, an empty map is returned.
*
* <p>Changes to the returned map will update the underlying table, and vice versa.
*
* @param columnKey key of column to search for in the table
* @return the corresponding map from row keys to values
*/
Map<R, V> column(@ParametricNullness C columnKey);
/**
* Returns a set of all row key / column key / value triplets. Changes to the returned set will
* update the underlying table, and vice versa. The cell set does not support the {@code add} or
* {@code addAll} methods.
*
* @return set of table cells consisting of row key / column key / value triplets
*/
Set<Cell<R, C, V>> cellSet();
/**
* Returns a set of row keys that have one or more values in the table. Changes to the set will
* update the underlying table, and vice versa.
*
* @return set of row keys
*/
Set<R> rowKeySet();
/**
* Returns a set of column keys that have one or more values in the table. Changes to the set will
* update the underlying table, and vice versa.
*
* @return set of column keys
*/
Set<C> columnKeySet();
/**
* Returns a collection of all values, which may contain duplicates. Changes to the returned
* collection will update the underlying table, and vice versa.
*
* @return collection of values
*/
Collection<V> values();
/**
* Returns a view that associates each row key with the corresponding map from column keys to
* values. Changes to the returned map will update this table. The returned map does not support
* {@code put()} or {@code putAll()}, or {@code setValue()} on its entries.
*
* <p>In contrast, the maps returned by {@code rowMap().get()} have the same behavior as those
* returned by {@link #row}. Those maps may support {@code setValue()}, {@code put()}, and {@code
* putAll()}.
*
* @return a map view from each row key to a secondary map from column keys to values
*/
Map<R, Map<C, V>> rowMap();
/**
* Returns a view that associates each column key with the corresponding map from row keys to
* values. Changes to the returned map will update this table. The returned map does not support
* {@code put()} or {@code putAll()}, or {@code setValue()} on its entries.
*
* <p>In contrast, the maps returned by {@code columnMap().get()} have the same behavior as those
* returned by {@link #column}. Those maps may support {@code setValue()}, {@code put()}, and
* {@code putAll()}.
*
* @return a map view from each column key to a secondary map from row keys to values
*/
Map<C, Map<R, V>> columnMap();
/**
* Row key / column key / value triplet corresponding to a mapping in a table.
*
* @since 7.0
*/
interface Cell<
R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object> {
/** Returns the row key of this cell. */
@ParametricNullness
R getRowKey();
/** Returns the column key of this cell. */
@ParametricNullness
C getColumnKey();
/** Returns the value of this cell. */
@ParametricNullness
V getValue();
/**
* Compares the specified object with this cell for equality. Two cells are equal when they have
* equal row keys, column keys, and values.
*/
@Override
boolean equals(@CheckForNull Object obj);
/**
* Returns the hash code of this cell.
*
* <p>The hash code of a table cell is equal to {@link Objects#hashCode}{@code (e.getRowKey(),
* e.getColumnKey(), e.getValue())}.
*/
@Override
int hashCode();
}
}
| google/guava | guava/src/com/google/common/collect/Table.java |
44,410 | package com.iluwatar.commander;
/**
* Record to hold parameters related to time limit
* for various tasks.
* @param queueTime time limit for queue
* @param queueTaskTime time limit for queuing task
* @param paymentTime time limit for payment error message
* @param messageTime time limit for message time order
* @param employeeTime time limit for employee handle time
*/
public record TimeLimits(long queueTime, long queueTaskTime, long paymentTime,
long messageTime, long employeeTime) {
public static final TimeLimits DEFAULT = new TimeLimits(240000L, 60000L, 120000L, 150000L, 240000L);
} | iluwatar/java-design-patterns | commander/src/main/java/com/iluwatar/commander/TimeLimits.java |
44,414 | /*
* Copyright (C) 2010 The Guava Authors
*
* 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.google.common.base;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.errorprone.annotations.ForOverride;
import java.io.Serializable;
import java.util.function.BiPredicate;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A strategy for determining whether two instances are considered equivalent, and for computing
* hash codes in a manner consistent with that equivalence. Two examples of equivalences are the
* {@linkplain #identity() identity equivalence} and the {@linkplain #equals "equals" equivalence}.
*
* @author Bob Lee
* @author Ben Yu
* @author Gregory Kick
* @since 10.0 (<a href="https://github.com/google/guava/wiki/Compatibility">mostly
* source-compatible</a> since 4.0)
*/
@GwtCompatible
@ElementTypesAreNonnullByDefault
/*
* The type parameter is <T> rather than <T extends @Nullable> so that we can use T in the
* doEquivalent and doHash methods to indicate that the parameter cannot be null.
*/
public abstract class Equivalence<T> implements BiPredicate<@Nullable T, @Nullable T> {
/** Constructor for use by subclasses. */
protected Equivalence() {}
/**
* Returns {@code true} if the given objects are considered equivalent.
*
* <p>This method describes an <i>equivalence relation</i> on object references, meaning that for
* all references {@code x}, {@code y}, and {@code z} (any of which may be null):
*
* <ul>
* <li>{@code equivalent(x, x)} is true (<i>reflexive</i> property)
* <li>{@code equivalent(x, y)} and {@code equivalent(y, x)} each return the same result
* (<i>symmetric</i> property)
* <li>If {@code equivalent(x, y)} and {@code equivalent(y, z)} are both true, then {@code
* equivalent(x, z)} is also true (<i>transitive</i> property)
* </ul>
*
* <p>Note that all calls to {@code equivalent(x, y)} are expected to return the same result as
* long as neither {@code x} nor {@code y} is modified.
*/
public final boolean equivalent(@CheckForNull T a, @CheckForNull T b) {
if (a == b) {
return true;
}
if (a == null || b == null) {
return false;
}
return doEquivalent(a, b);
}
/**
* @deprecated Provided only to satisfy the {@link BiPredicate} interface; use {@link #equivalent}
* instead.
* @since 21.0
*/
@Deprecated
@Override
public final boolean test(@CheckForNull T t, @CheckForNull T u) {
return equivalent(t, u);
}
/**
* Implemented by the user to determine whether {@code a} and {@code b} are considered equivalent,
* subject to the requirements specified in {@link #equivalent}.
*
* <p>This method should not be called except by {@link #equivalent}. When {@link #equivalent}
* calls this method, {@code a} and {@code b} are guaranteed to be distinct, non-null instances.
*
* @since 10.0 (previously, subclasses would override equivalent())
*/
@ForOverride
protected abstract boolean doEquivalent(T a, T b);
/**
* Returns a hash code for {@code t}.
*
* <p>The {@code hash} has the following properties:
*
* <ul>
* <li>It is <i>consistent</i>: for any reference {@code x}, multiple invocations of {@code
* hash(x}} consistently return the same value provided {@code x} remains unchanged
* according to the definition of the equivalence. The hash need not remain consistent from
* one execution of an application to another execution of the same application.
* <li>It is <i>distributable across equivalence</i>: for any references {@code x} and {@code
* y}, if {@code equivalent(x, y)}, then {@code hash(x) == hash(y)}. It is <i>not</i>
* necessary that the hash be distributable across <i>inequivalence</i>. If {@code
* equivalence(x, y)} is false, {@code hash(x) == hash(y)} may still be true.
* <li>{@code hash(null)} is {@code 0}.
* </ul>
*/
public final int hash(@CheckForNull T t) {
if (t == null) {
return 0;
}
return doHash(t);
}
/**
* Implemented by the user to return a hash code for {@code t}, subject to the requirements
* specified in {@link #hash}.
*
* <p>This method should not be called except by {@link #hash}. When {@link #hash} calls this
* method, {@code t} is guaranteed to be non-null.
*
* @since 10.0 (previously, subclasses would override hash())
*/
@ForOverride
protected abstract int doHash(T t);
/**
* Returns a new equivalence relation for {@code F} which evaluates equivalence by first applying
* {@code function} to the argument, then evaluating using {@code this}. That is, for any pair of
* non-null objects {@code x} and {@code y}, {@code equivalence.onResultOf(function).equivalent(a,
* b)} is true if and only if {@code equivalence.equivalent(function.apply(a), function.apply(b))}
* is true.
*
* <p>For example:
*
* <pre>{@code
* Equivalence<Person> SAME_AGE = Equivalence.equals().onResultOf(GET_PERSON_AGE);
* }</pre>
*
* <p>{@code function} will never be invoked with a null value.
*
* <p>Note that {@code function} must be consistent according to {@code this} equivalence
* relation. That is, invoking {@link Function#apply} multiple times for a given value must return
* equivalent results. For example, {@code
* Equivalence.identity().onResultOf(Functions.toStringFunction())} is broken because it's not
* guaranteed that {@link Object#toString}) always returns the same string instance.
*
* @since 10.0
*/
public final <F> Equivalence<F> onResultOf(Function<? super F, ? extends @Nullable T> function) {
return new FunctionalEquivalence<>(function, this);
}
/**
* Returns a wrapper of {@code reference} that implements {@link Wrapper#equals(Object)
* Object.equals()} such that {@code wrap(a).equals(wrap(b))} if and only if {@code equivalent(a,
* b)}.
*
* <p>The returned object is serializable if both this {@code Equivalence} and {@code reference}
* are serializable (including when {@code reference} is null).
*
* @since 10.0
*/
public final <S extends @Nullable T> Wrapper<S> wrap(@ParametricNullness S reference) {
return new Wrapper<>(this, reference);
}
/**
* Wraps an object so that {@link #equals(Object)} and {@link #hashCode()} delegate to an {@link
* Equivalence}.
*
* <p>For example, given an {@link Equivalence} for {@link String strings} named {@code equiv}
* that tests equivalence using their lengths:
*
* <pre>{@code
* equiv.wrap("a").equals(equiv.wrap("b")) // true
* equiv.wrap("a").equals(equiv.wrap("hello")) // false
* }</pre>
*
* <p>Note in particular that an equivalence wrapper is never equal to the object it wraps.
*
* <pre>{@code
* equiv.wrap(obj).equals(obj) // always false
* }</pre>
*
* @since 10.0
*/
public static final class Wrapper<T extends @Nullable Object> implements Serializable {
/*
* Equivalence's type argument is always non-nullable: Equivalence<Number>, never
* Equivalence<@Nullable Number>. That can still produce wrappers of various types --
* Wrapper<Number>, Wrapper<Integer>, Wrapper<@Nullable Integer>, etc. If we used just
* Equivalence<? super T> below, no type could satisfy both that bound and T's own
* bound. With this type, they have some overlap: in our example, Equivalence<Number>
* and Equivalence<Object>.
*/
private final Equivalence<? super @NonNull T> equivalence;
@ParametricNullness private final T reference;
private Wrapper(Equivalence<? super @NonNull T> equivalence, @ParametricNullness T reference) {
this.equivalence = checkNotNull(equivalence);
this.reference = reference;
}
/** Returns the (possibly null) reference wrapped by this instance. */
@ParametricNullness
public T get() {
return reference;
}
/**
* Returns {@code true} if {@link Equivalence#equivalent(Object, Object)} applied to the wrapped
* references is {@code true} and both wrappers use the {@link Object#equals(Object) same}
* equivalence.
*/
@Override
public boolean equals(@CheckForNull Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof Wrapper) {
Wrapper<?> that = (Wrapper<?>) obj; // note: not necessarily a Wrapper<T>
if (this.equivalence.equals(that.equivalence)) {
/*
* We'll accept that as sufficient "proof" that either equivalence should be able to
* handle either reference, so it's safe to circumvent compile-time type checking.
*/
@SuppressWarnings("unchecked")
Equivalence<Object> equivalence = (Equivalence<Object>) this.equivalence;
return equivalence.equivalent(this.reference, that.reference);
}
}
return false;
}
/** Returns the result of {@link Equivalence#hash(Object)} applied to the wrapped reference. */
@Override
public int hashCode() {
return equivalence.hash(reference);
}
/**
* Returns a string representation for this equivalence wrapper. The form of this string
* representation is not specified.
*/
@Override
public String toString() {
return equivalence + ".wrap(" + reference + ")";
}
private static final long serialVersionUID = 0;
}
/**
* Returns an equivalence over iterables based on the equivalence of their elements. More
* specifically, two iterables are considered equivalent if they both contain the same number of
* elements, and each pair of corresponding elements is equivalent according to {@code this}. Null
* iterables are equivalent to one another.
*
* <p>Note that this method performs a similar function for equivalences as {@link
* com.google.common.collect.Ordering#lexicographical} does for orderings.
*
* <p>The returned object is serializable if this object is serializable.
*
* @since 10.0
*/
@GwtCompatible(serializable = true)
public final <S extends @Nullable T> Equivalence<Iterable<S>> pairwise() {
// Ideally, the returned equivalence would support Iterable<? extends T>. However,
// the need for this is so rare that it's not worth making callers deal with the ugly wildcard.
return new PairwiseEquivalence<>(this);
}
/**
* Returns a predicate that evaluates to true if and only if the input is equivalent to {@code
* target} according to this equivalence relation.
*
* @since 10.0
*/
public final Predicate<@Nullable T> equivalentTo(@CheckForNull T target) {
return new EquivalentToPredicate<>(this, target);
}
private static final class EquivalentToPredicate<T>
implements Predicate<@Nullable T>, Serializable {
private final Equivalence<T> equivalence;
@CheckForNull private final T target;
EquivalentToPredicate(Equivalence<T> equivalence, @CheckForNull T target) {
this.equivalence = checkNotNull(equivalence);
this.target = target;
}
@Override
public boolean apply(@CheckForNull T input) {
return equivalence.equivalent(input, target);
}
@Override
public boolean equals(@CheckForNull Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof EquivalentToPredicate) {
EquivalentToPredicate<?> that = (EquivalentToPredicate<?>) obj;
return equivalence.equals(that.equivalence) && Objects.equal(target, that.target);
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(equivalence, target);
}
@Override
public String toString() {
return equivalence + ".equivalentTo(" + target + ")";
}
private static final long serialVersionUID = 0;
}
/**
* Returns an equivalence that delegates to {@link Object#equals} and {@link Object#hashCode}.
* {@link Equivalence#equivalent} returns {@code true} if both values are null, or if neither
* value is null and {@link Object#equals} returns {@code true}. {@link Equivalence#hash} returns
* {@code 0} if passed a null value.
*
* @since 13.0
* @since 8.0 (in Equivalences with null-friendly behavior)
* @since 4.0 (in Equivalences)
*/
public static Equivalence<Object> equals() {
return Equals.INSTANCE;
}
/**
* Returns an equivalence that uses {@code ==} to compare values and {@link
* System#identityHashCode(Object)} to compute the hash code. {@link Equivalence#equivalent}
* returns {@code true} if {@code a == b}, including in the case that a and b are both null.
*
* @since 13.0
* @since 4.0 (in Equivalences)
*/
public static Equivalence<Object> identity() {
return Identity.INSTANCE;
}
static final class Equals extends Equivalence<Object> implements Serializable {
static final Equals INSTANCE = new Equals();
@Override
protected boolean doEquivalent(Object a, Object b) {
return a.equals(b);
}
@Override
protected int doHash(Object o) {
return o.hashCode();
}
private Object readResolve() {
return INSTANCE;
}
private static final long serialVersionUID = 1;
}
static final class Identity extends Equivalence<Object> implements Serializable {
static final Identity INSTANCE = new Identity();
@Override
protected boolean doEquivalent(Object a, Object b) {
return false;
}
@Override
protected int doHash(Object o) {
return System.identityHashCode(o);
}
private Object readResolve() {
return INSTANCE;
}
private static final long serialVersionUID = 1;
}
}
| google/guava | guava/src/com/google/common/base/Equivalence.java |
44,419 | /*
* Copyright (C) 2009 The Guava Authors
*
* 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.google.common.cache;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.cache.CacheBuilder.NULL_TICKER;
import static com.google.common.cache.CacheBuilder.UNSET_INT;
import static com.google.common.util.concurrent.Futures.transform;
import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
import static com.google.common.util.concurrent.Uninterruptibles.getUninterruptibly;
import static java.util.Collections.unmodifiableSet;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Equivalence;
import com.google.common.base.Stopwatch;
import com.google.common.base.Ticker;
import com.google.common.cache.AbstractCache.SimpleStatsCounter;
import com.google.common.cache.AbstractCache.StatsCounter;
import com.google.common.cache.CacheBuilder.NullListener;
import com.google.common.cache.CacheBuilder.OneWeigher;
import com.google.common.cache.CacheLoader.InvalidCacheLoadException;
import com.google.common.cache.CacheLoader.UnsupportedLoadingOperationException;
import com.google.common.collect.AbstractSequentialIterator;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterators;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.primitives.Ints;
import com.google.common.util.concurrent.ExecutionError;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import com.google.common.util.concurrent.UncheckedExecutionException;
import com.google.common.util.concurrent.Uninterruptibles;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.concurrent.GuardedBy;
import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.RetainedWith;
import com.google.j2objc.annotations.Weak;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.AbstractQueue;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* The concurrent hash map implementation built by {@link CacheBuilder}.
*
* <p>This implementation is heavily derived from revision 1.96 of <a
* href="http://tinyurl.com/ConcurrentHashMap">ConcurrentHashMap.java</a>.
*
* @author Charles Fry
* @author Bob Lee ({@code com.google.common.collect.MapMaker})
* @author Doug Lea ({@code ConcurrentHashMap})
*/
@SuppressWarnings({
"GoodTime", // lots of violations (nanosecond math)
"nullness", // too much trouble for the payoff
})
@GwtCompatible(emulated = true)
// TODO(cpovirk): Annotate for nullness.
class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V> {
/*
* The basic strategy is to subdivide the table among Segments, each of which itself is a
* concurrently readable hash table. The map supports non-blocking reads and concurrent writes
* across different segments.
*
* If a maximum size is specified, a best-effort bounding is performed per segment, using a
* page-replacement algorithm to determine which entries to evict when the capacity has been
* exceeded.
*
* The page replacement algorithm's data structures are kept casually consistent with the map. The
* ordering of writes to a segment is sequentially consistent. An update to the map and recording
* of reads may not be immediately reflected on the algorithm's data structures. These structures
* are guarded by a lock and operations are applied in batches to avoid lock contention. The
* penalty of applying the batches is spread across threads so that the amortized cost is slightly
* higher than performing just the operation without enforcing the capacity constraint.
*
* This implementation uses a per-segment queue to record a memento of the additions, removals,
* and accesses that were performed on the map. The queue is drained on writes and when it exceeds
* its capacity threshold.
*
* The Least Recently Used page replacement algorithm was chosen due to its simplicity, high hit
* rate, and ability to be implemented with O(1) time complexity. The initial LRU implementation
* operates per-segment rather than globally for increased implementation simplicity. We expect
* the cache hit rate to be similar to that of a global LRU algorithm.
*/
// Constants
/**
* The maximum capacity, used if a higher value is implicitly specified by either of the
* constructors with arguments. MUST be a power of two {@code <= 1<<30} to ensure that entries are
* indexable using ints.
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/** The maximum number of segments to allow; used to bound constructor arguments. */
static final int MAX_SEGMENTS = 1 << 16; // slightly conservative
/** Number of (unsynchronized) retries in the containsValue method. */
static final int CONTAINS_VALUE_RETRIES = 3;
/**
* Number of cache access operations that can be buffered per segment before the cache's recency
* ordering information is updated. This is used to avoid lock contention by recording a memento
* of reads and delaying a lock acquisition until the threshold is crossed or a mutation occurs.
*
* <p>This must be a (2^n)-1 as it is used as a mask.
*/
static final int DRAIN_THRESHOLD = 0x3F;
/**
* Maximum number of entries to be drained in a single cleanup run. This applies independently to
* the cleanup queue and both reference queues.
*/
// TODO(fry): empirically optimize this
static final int DRAIN_MAX = 16;
// Fields
static final Logger logger = Logger.getLogger(LocalCache.class.getName());
/**
* Mask value for indexing into segments. The upper bits of a key's hash code are used to choose
* the segment.
*/
final int segmentMask;
/**
* Shift value for indexing within segments. Helps prevent entries that end up in the same segment
* from also ending up in the same bucket.
*/
final int segmentShift;
/** The segments, each of which is a specialized hash table. */
final Segment<K, V>[] segments;
/** The concurrency level. */
final int concurrencyLevel;
/** Strategy for comparing keys. */
final Equivalence<Object> keyEquivalence;
/** Strategy for comparing values. */
final Equivalence<Object> valueEquivalence;
/** Strategy for referencing keys. */
final Strength keyStrength;
/** Strategy for referencing values. */
final Strength valueStrength;
/** The maximum weight of this map. UNSET_INT if there is no maximum. */
final long maxWeight;
/** Weigher to weigh cache entries. */
final Weigher<K, V> weigher;
/** How long after the last access to an entry the map will retain that entry. */
final long expireAfterAccessNanos;
/** How long after the last write to an entry the map will retain that entry. */
final long expireAfterWriteNanos;
/** How long after the last write an entry becomes a candidate for refresh. */
final long refreshNanos;
/** Entries waiting to be consumed by the removal listener. */
// TODO(fry): define a new type which creates event objects and automates the clear logic
final Queue<RemovalNotification<K, V>> removalNotificationQueue;
/**
* A listener that is invoked when an entry is removed due to expiration or garbage collection of
* soft/weak entries.
*/
final RemovalListener<K, V> removalListener;
/** Measures time in a testable way. */
final Ticker ticker;
/** Factory used to create new entries. */
final EntryFactory entryFactory;
/**
* Accumulates global cache statistics. Note that there are also per-segments stats counters which
* must be aggregated to obtain a global stats view.
*/
final StatsCounter globalStatsCounter;
/** The default cache loader to use on loading operations. */
@CheckForNull final CacheLoader<? super K, V> defaultLoader;
/**
* Creates a new, empty map with the specified strategy, initial capacity and concurrency level.
*/
LocalCache(
CacheBuilder<? super K, ? super V> builder, @CheckForNull CacheLoader<? super K, V> loader) {
concurrencyLevel = Math.min(builder.getConcurrencyLevel(), MAX_SEGMENTS);
keyStrength = builder.getKeyStrength();
valueStrength = builder.getValueStrength();
keyEquivalence = builder.getKeyEquivalence();
valueEquivalence = builder.getValueEquivalence();
maxWeight = builder.getMaximumWeight();
weigher = builder.getWeigher();
expireAfterAccessNanos = builder.getExpireAfterAccessNanos();
expireAfterWriteNanos = builder.getExpireAfterWriteNanos();
refreshNanos = builder.getRefreshNanos();
removalListener = builder.getRemovalListener();
removalNotificationQueue =
(removalListener == NullListener.INSTANCE)
? LocalCache.discardingQueue()
: new ConcurrentLinkedQueue<>();
ticker = builder.getTicker(recordsTime());
entryFactory = EntryFactory.getFactory(keyStrength, usesAccessEntries(), usesWriteEntries());
globalStatsCounter = builder.getStatsCounterSupplier().get();
defaultLoader = loader;
int initialCapacity = Math.min(builder.getInitialCapacity(), MAXIMUM_CAPACITY);
if (evictsBySize() && !customWeigher()) {
initialCapacity = (int) Math.min(initialCapacity, maxWeight);
}
// Find the lowest power-of-two segmentCount that exceeds concurrencyLevel, unless
// maximumSize/Weight is specified in which case ensure that each segment gets at least 10
// entries. The special casing for size-based eviction is only necessary because that eviction
// happens per segment instead of globally, so too many segments compared to the maximum size
// will result in random eviction behavior.
int segmentShift = 0;
int segmentCount = 1;
while (segmentCount < concurrencyLevel
&& (!evictsBySize() || segmentCount * 20L <= maxWeight)) {
++segmentShift;
segmentCount <<= 1;
}
this.segmentShift = 32 - segmentShift;
segmentMask = segmentCount - 1;
this.segments = newSegmentArray(segmentCount);
int segmentCapacity = initialCapacity / segmentCount;
if (segmentCapacity * segmentCount < initialCapacity) {
++segmentCapacity;
}
int segmentSize = 1;
while (segmentSize < segmentCapacity) {
segmentSize <<= 1;
}
if (evictsBySize()) {
// Ensure sum of segment max weights = overall max weights
long maxSegmentWeight = maxWeight / segmentCount + 1;
long remainder = maxWeight % segmentCount;
for (int i = 0; i < this.segments.length; ++i) {
if (i == remainder) {
maxSegmentWeight--;
}
this.segments[i] =
createSegment(segmentSize, maxSegmentWeight, builder.getStatsCounterSupplier().get());
}
} else {
for (int i = 0; i < this.segments.length; ++i) {
this.segments[i] =
createSegment(segmentSize, UNSET_INT, builder.getStatsCounterSupplier().get());
}
}
}
boolean evictsBySize() {
return maxWeight >= 0;
}
boolean customWeigher() {
return weigher != OneWeigher.INSTANCE;
}
boolean expires() {
return expiresAfterWrite() || expiresAfterAccess();
}
boolean expiresAfterWrite() {
return expireAfterWriteNanos > 0;
}
boolean expiresAfterAccess() {
return expireAfterAccessNanos > 0;
}
boolean refreshes() {
return refreshNanos > 0;
}
boolean usesAccessQueue() {
return expiresAfterAccess() || evictsBySize();
}
boolean usesWriteQueue() {
return expiresAfterWrite();
}
boolean recordsWrite() {
return expiresAfterWrite() || refreshes();
}
boolean recordsAccess() {
return expiresAfterAccess();
}
boolean recordsTime() {
return recordsWrite() || recordsAccess();
}
boolean usesWriteEntries() {
return usesWriteQueue() || recordsWrite();
}
boolean usesAccessEntries() {
return usesAccessQueue() || recordsAccess();
}
boolean usesKeyReferences() {
return keyStrength != Strength.STRONG;
}
boolean usesValueReferences() {
return valueStrength != Strength.STRONG;
}
enum Strength {
/*
* TODO(kevinb): If we strongly reference the value and aren't loading, we needn't wrap the
* value. This could save ~8 bytes per entry.
*/
STRONG {
@Override
<K, V> ValueReference<K, V> referenceValue(
Segment<K, V> segment, ReferenceEntry<K, V> entry, V value, int weight) {
return (weight == 1)
? new StrongValueReference<K, V>(value)
: new WeightedStrongValueReference<K, V>(value, weight);
}
@Override
Equivalence<Object> defaultEquivalence() {
return Equivalence.equals();
}
},
SOFT {
@Override
<K, V> ValueReference<K, V> referenceValue(
Segment<K, V> segment, ReferenceEntry<K, V> entry, V value, int weight) {
return (weight == 1)
? new SoftValueReference<K, V>(segment.valueReferenceQueue, value, entry)
: new WeightedSoftValueReference<K, V>(
segment.valueReferenceQueue, value, entry, weight);
}
@Override
Equivalence<Object> defaultEquivalence() {
return Equivalence.identity();
}
},
WEAK {
@Override
<K, V> ValueReference<K, V> referenceValue(
Segment<K, V> segment, ReferenceEntry<K, V> entry, V value, int weight) {
return (weight == 1)
? new WeakValueReference<K, V>(segment.valueReferenceQueue, value, entry)
: new WeightedWeakValueReference<K, V>(
segment.valueReferenceQueue, value, entry, weight);
}
@Override
Equivalence<Object> defaultEquivalence() {
return Equivalence.identity();
}
};
/** Creates a reference for the given value according to this value strength. */
abstract <K, V> ValueReference<K, V> referenceValue(
Segment<K, V> segment, ReferenceEntry<K, V> entry, V value, int weight);
/**
* Returns the default equivalence strategy used to compare and hash keys or values referenced
* at this strength. This strategy will be used unless the user explicitly specifies an
* alternate strategy.
*/
abstract Equivalence<Object> defaultEquivalence();
}
/** Creates new entries. */
enum EntryFactory {
STRONG {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
return new StrongEntry<>(key, hash, next);
}
},
STRONG_ACCESS {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
return new StrongAccessEntry<>(key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment,
ReferenceEntry<K, V> original,
ReferenceEntry<K, V> newNext,
K key) {
ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext, key);
copyAccessEntry(original, newEntry);
return newEntry;
}
},
STRONG_WRITE {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
return new StrongWriteEntry<>(key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment,
ReferenceEntry<K, V> original,
ReferenceEntry<K, V> newNext,
K key) {
ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext, key);
copyWriteEntry(original, newEntry);
return newEntry;
}
},
STRONG_ACCESS_WRITE {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
return new StrongAccessWriteEntry<>(key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment,
ReferenceEntry<K, V> original,
ReferenceEntry<K, V> newNext,
K key) {
ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext, key);
copyAccessEntry(original, newEntry);
copyWriteEntry(original, newEntry);
return newEntry;
}
},
WEAK {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
return new WeakEntry<>(segment.keyReferenceQueue, key, hash, next);
}
},
WEAK_ACCESS {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
return new WeakAccessEntry<>(segment.keyReferenceQueue, key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment,
ReferenceEntry<K, V> original,
ReferenceEntry<K, V> newNext,
K key) {
ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext, key);
copyAccessEntry(original, newEntry);
return newEntry;
}
},
WEAK_WRITE {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
return new WeakWriteEntry<>(segment.keyReferenceQueue, key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment,
ReferenceEntry<K, V> original,
ReferenceEntry<K, V> newNext,
K key) {
ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext, key);
copyWriteEntry(original, newEntry);
return newEntry;
}
},
WEAK_ACCESS_WRITE {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
return new WeakAccessWriteEntry<>(segment.keyReferenceQueue, key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment,
ReferenceEntry<K, V> original,
ReferenceEntry<K, V> newNext,
K key) {
ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext, key);
copyAccessEntry(original, newEntry);
copyWriteEntry(original, newEntry);
return newEntry;
}
};
// Masks used to compute indices in the following table.
static final int ACCESS_MASK = 1;
static final int WRITE_MASK = 2;
static final int WEAK_MASK = 4;
/** Look-up table for factories. */
static final EntryFactory[] factories = {
STRONG,
STRONG_ACCESS,
STRONG_WRITE,
STRONG_ACCESS_WRITE,
WEAK,
WEAK_ACCESS,
WEAK_WRITE,
WEAK_ACCESS_WRITE,
};
static EntryFactory getFactory(
Strength keyStrength, boolean usesAccessQueue, boolean usesWriteQueue) {
int flags =
((keyStrength == Strength.WEAK) ? WEAK_MASK : 0)
| (usesAccessQueue ? ACCESS_MASK : 0)
| (usesWriteQueue ? WRITE_MASK : 0);
return factories[flags];
}
/**
* Creates a new entry.
*
* @param segment to create the entry for
* @param key of the entry
* @param hash of the key
* @param next entry in the same bucket
*/
abstract <K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @CheckForNull ReferenceEntry<K, V> next);
/**
* Copies an entry, assigning it a new {@code next} entry.
*
* @param original the entry to copy. But avoid calling {@code getKey} on it: Instead, use the
* {@code key} parameter. That way, we prevent the key from being garbage collected in the
* case of weak keys. If we create a new entry with a key that is null at construction time,
* we're not sure if entry will necessarily ever be garbage collected.
* @param newNext entry in the same bucket
* @param key the key to copy from the original entry to the new one. Use this in preference to
* {@code original.getKey()}.
*/
// Guarded By Segment.this
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext, K key) {
return newEntry(segment, key, original.getHash(), newNext);
}
// Guarded By Segment.this
<K, V> void copyAccessEntry(ReferenceEntry<K, V> original, ReferenceEntry<K, V> newEntry) {
// TODO(fry): when we link values instead of entries this method can go
// away, as can connectAccessOrder, nullifyAccessOrder.
newEntry.setAccessTime(original.getAccessTime());
connectAccessOrder(original.getPreviousInAccessQueue(), newEntry);
connectAccessOrder(newEntry, original.getNextInAccessQueue());
nullifyAccessOrder(original);
}
// Guarded By Segment.this
<K, V> void copyWriteEntry(ReferenceEntry<K, V> original, ReferenceEntry<K, V> newEntry) {
// TODO(fry): when we link values instead of entries this method can go
// away, as can connectWriteOrder, nullifyWriteOrder.
newEntry.setWriteTime(original.getWriteTime());
connectWriteOrder(original.getPreviousInWriteQueue(), newEntry);
connectWriteOrder(newEntry, original.getNextInWriteQueue());
nullifyWriteOrder(original);
}
}
/** A reference to a value. */
interface ValueReference<K, V> {
/** Returns the value. Does not block or throw exceptions. */
@CheckForNull
V get();
/**
* Waits for a value that may still be loading. Unlike get(), this method can block (in the case
* of FutureValueReference).
*
* @throws ExecutionException if the loading thread throws an exception
* @throws ExecutionError if the loading thread throws an error
*/
V waitForValue() throws ExecutionException;
/** Returns the weight of this entry. This is assumed to be static between calls to setValue. */
int getWeight();
/**
* Returns the entry associated with this value reference, or {@code null} if this value
* reference is independent of any entry.
*/
@CheckForNull
ReferenceEntry<K, V> getEntry();
/**
* Creates a copy of this reference for the given entry.
*
* <p>{@code value} may be null only for a loading reference.
*/
ValueReference<K, V> copyFor(
ReferenceQueue<V> queue, @CheckForNull V value, ReferenceEntry<K, V> entry);
/**
* Notify pending loads that a new value was set. This is only relevant to loading value
* references.
*/
void notifyNewValue(@CheckForNull V newValue);
/**
* Returns true if a new value is currently loading, regardless of whether there is an existing
* value. It is assumed that the return value of this method is constant for any given
* ValueReference instance.
*/
boolean isLoading();
/**
* Returns true if this reference contains an active value, meaning one that is still considered
* present in the cache. Active values consist of live values, which are returned by cache
* lookups, and dead values, which have been evicted but awaiting removal. Non-active values
* consist strictly of loading values, though during refresh a value may be both active and
* loading.
*/
boolean isActive();
}
/** Placeholder. Indicates that the value hasn't been set yet. */
static final ValueReference<Object, Object> UNSET =
new ValueReference<Object, Object>() {
@CheckForNull
@Override
public Object get() {
return null;
}
@Override
public int getWeight() {
return 0;
}
@CheckForNull
@Override
public ReferenceEntry<Object, Object> getEntry() {
return null;
}
@Override
public ValueReference<Object, Object> copyFor(
ReferenceQueue<Object> queue,
@CheckForNull Object value,
ReferenceEntry<Object, Object> entry) {
return this;
}
@Override
public boolean isLoading() {
return false;
}
@Override
public boolean isActive() {
return false;
}
@CheckForNull
@Override
public Object waitForValue() {
return null;
}
@Override
public void notifyNewValue(Object newValue) {}
};
/** Singleton placeholder that indicates a value is being loaded. */
@SuppressWarnings("unchecked") // impl never uses a parameter or returns any non-null value
static <K, V> ValueReference<K, V> unset() {
return (ValueReference<K, V>) UNSET;
}
private enum NullEntry implements ReferenceEntry<Object, Object> {
INSTANCE;
@CheckForNull
@Override
public ValueReference<Object, Object> getValueReference() {
return null;
}
@Override
public void setValueReference(ValueReference<Object, Object> valueReference) {}
@CheckForNull
@Override
public ReferenceEntry<Object, Object> getNext() {
return null;
}
@Override
public int getHash() {
return 0;
}
@CheckForNull
@Override
public Object getKey() {
return null;
}
@Override
public long getAccessTime() {
return 0;
}
@Override
public void setAccessTime(long time) {}
@Override
public ReferenceEntry<Object, Object> getNextInAccessQueue() {
return this;
}
@Override
public void setNextInAccessQueue(ReferenceEntry<Object, Object> next) {}
@Override
public ReferenceEntry<Object, Object> getPreviousInAccessQueue() {
return this;
}
@Override
public void setPreviousInAccessQueue(ReferenceEntry<Object, Object> previous) {}
@Override
public long getWriteTime() {
return 0;
}
@Override
public void setWriteTime(long time) {}
@Override
public ReferenceEntry<Object, Object> getNextInWriteQueue() {
return this;
}
@Override
public void setNextInWriteQueue(ReferenceEntry<Object, Object> next) {}
@Override
public ReferenceEntry<Object, Object> getPreviousInWriteQueue() {
return this;
}
@Override
public void setPreviousInWriteQueue(ReferenceEntry<Object, Object> previous) {}
}
abstract static class AbstractReferenceEntry<K, V> implements ReferenceEntry<K, V> {
@Override
public ValueReference<K, V> getValueReference() {
throw new UnsupportedOperationException();
}
@Override
public void setValueReference(ValueReference<K, V> valueReference) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getNext() {
throw new UnsupportedOperationException();
}
@Override
public int getHash() {
throw new UnsupportedOperationException();
}
@Override
public K getKey() {
throw new UnsupportedOperationException();
}
@Override
public long getAccessTime() {
throw new UnsupportedOperationException();
}
@Override
public void setAccessTime(long time) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getNextInAccessQueue() {
throw new UnsupportedOperationException();
}
@Override
public void setNextInAccessQueue(ReferenceEntry<K, V> next) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getPreviousInAccessQueue() {
throw new UnsupportedOperationException();
}
@Override
public void setPreviousInAccessQueue(ReferenceEntry<K, V> previous) {
throw new UnsupportedOperationException();
}
@Override
public long getWriteTime() {
throw new UnsupportedOperationException();
}
@Override
public void setWriteTime(long time) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getNextInWriteQueue() {
throw new UnsupportedOperationException();
}
@Override
public void setNextInWriteQueue(ReferenceEntry<K, V> next) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getPreviousInWriteQueue() {
throw new UnsupportedOperationException();
}
@Override
public void setPreviousInWriteQueue(ReferenceEntry<K, V> previous) {
throw new UnsupportedOperationException();
}
}
@SuppressWarnings("unchecked") // impl never uses a parameter or returns any non-null value
static <K, V> ReferenceEntry<K, V> nullEntry() {
return (ReferenceEntry<K, V>) NullEntry.INSTANCE;
}
static final Queue<?> DISCARDING_QUEUE =
new AbstractQueue<Object>() {
@Override
public boolean offer(Object o) {
return true;
}
@CheckForNull
@Override
public Object peek() {
return null;
}
@CheckForNull
@Override
public Object poll() {
return null;
}
@Override
public int size() {
return 0;
}
@Override
public Iterator<Object> iterator() {
return ImmutableSet.of().iterator();
}
};
/** Queue that discards all elements. */
@SuppressWarnings("unchecked") // impl never uses a parameter or returns any non-null value
static <E> Queue<E> discardingQueue() {
return (Queue) DISCARDING_QUEUE;
}
/*
* Note: All of this duplicate code sucks, but it saves a lot of memory. If only Java had mixins!
* To maintain this code, make a change for the strong reference type. Then, cut and paste, and
* replace "Strong" with "Soft" or "Weak" within the pasted text. The primary difference is that
* strong entries store the key reference directly while soft and weak entries delegate to their
* respective superclasses.
*/
/** Used for strongly-referenced keys. */
static class StrongEntry<K, V> extends AbstractReferenceEntry<K, V> {
final K key;
StrongEntry(K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
this.key = key;
this.hash = hash;
this.next = next;
}
@Override
public K getKey() {
return this.key;
}
// The code below is exactly the same for each entry type.
final int hash;
@CheckForNull final ReferenceEntry<K, V> next;
volatile ValueReference<K, V> valueReference = unset();
@Override
public ValueReference<K, V> getValueReference() {
return valueReference;
}
@Override
public void setValueReference(ValueReference<K, V> valueReference) {
this.valueReference = valueReference;
}
@Override
public int getHash() {
return hash;
}
@Override
public ReferenceEntry<K, V> getNext() {
return next;
}
}
static final class StrongAccessEntry<K, V> extends StrongEntry<K, V> {
StrongAccessEntry(K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
super(key, hash, next);
}
// The code below is exactly the same for each access entry type.
volatile long accessTime = Long.MAX_VALUE;
@Override
public long getAccessTime() {
return accessTime;
}
@Override
public void setAccessTime(long time) {
this.accessTime = time;
}
// Guarded By Segment.this
@Weak ReferenceEntry<K, V> nextAccess = nullEntry();
@Override
public ReferenceEntry<K, V> getNextInAccessQueue() {
return nextAccess;
}
@Override
public void setNextInAccessQueue(ReferenceEntry<K, V> next) {
this.nextAccess = next;
}
// Guarded By Segment.this
@Weak ReferenceEntry<K, V> previousAccess = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousInAccessQueue() {
return previousAccess;
}
@Override
public void setPreviousInAccessQueue(ReferenceEntry<K, V> previous) {
this.previousAccess = previous;
}
}
static final class StrongWriteEntry<K, V> extends StrongEntry<K, V> {
StrongWriteEntry(K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
super(key, hash, next);
}
// The code below is exactly the same for each write entry type.
volatile long writeTime = Long.MAX_VALUE;
@Override
public long getWriteTime() {
return writeTime;
}
@Override
public void setWriteTime(long time) {
this.writeTime = time;
}
// Guarded By Segment.this
@Weak ReferenceEntry<K, V> nextWrite = nullEntry();
@Override
public ReferenceEntry<K, V> getNextInWriteQueue() {
return nextWrite;
}
@Override
public void setNextInWriteQueue(ReferenceEntry<K, V> next) {
this.nextWrite = next;
}
// Guarded By Segment.this
@Weak ReferenceEntry<K, V> previousWrite = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousInWriteQueue() {
return previousWrite;
}
@Override
public void setPreviousInWriteQueue(ReferenceEntry<K, V> previous) {
this.previousWrite = previous;
}
}
static final class StrongAccessWriteEntry<K, V> extends StrongEntry<K, V> {
StrongAccessWriteEntry(K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
super(key, hash, next);
}
// The code below is exactly the same for each access entry type.
volatile long accessTime = Long.MAX_VALUE;
@Override
public long getAccessTime() {
return accessTime;
}
@Override
public void setAccessTime(long time) {
this.accessTime = time;
}
// Guarded By Segment.this
@Weak ReferenceEntry<K, V> nextAccess = nullEntry();
@Override
public ReferenceEntry<K, V> getNextInAccessQueue() {
return nextAccess;
}
@Override
public void setNextInAccessQueue(ReferenceEntry<K, V> next) {
this.nextAccess = next;
}
// Guarded By Segment.this
@Weak ReferenceEntry<K, V> previousAccess = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousInAccessQueue() {
return previousAccess;
}
@Override
public void setPreviousInAccessQueue(ReferenceEntry<K, V> previous) {
this.previousAccess = previous;
}
// The code below is exactly the same for each write entry type.
volatile long writeTime = Long.MAX_VALUE;
@Override
public long getWriteTime() {
return writeTime;
}
@Override
public void setWriteTime(long time) {
this.writeTime = time;
}
// Guarded By Segment.this
@Weak ReferenceEntry<K, V> nextWrite = nullEntry();
@Override
public ReferenceEntry<K, V> getNextInWriteQueue() {
return nextWrite;
}
@Override
public void setNextInWriteQueue(ReferenceEntry<K, V> next) {
this.nextWrite = next;
}
// Guarded By Segment.this
@Weak ReferenceEntry<K, V> previousWrite = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousInWriteQueue() {
return previousWrite;
}
@Override
public void setPreviousInWriteQueue(ReferenceEntry<K, V> previous) {
this.previousWrite = previous;
}
}
/** Used for weakly-referenced keys. */
static class WeakEntry<K, V> extends WeakReference<K> implements ReferenceEntry<K, V> {
WeakEntry(ReferenceQueue<K> queue, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
super(key, queue);
this.hash = hash;
this.next = next;
}
@Override
public K getKey() {
return get();
}
/*
* It'd be nice to get these for free from AbstractReferenceEntry, but we're already extending
* WeakReference<K>.
*/
// null access
@Override
public long getAccessTime() {
throw new UnsupportedOperationException();
}
@Override
public void setAccessTime(long time) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getNextInAccessQueue() {
throw new UnsupportedOperationException();
}
@Override
public void setNextInAccessQueue(ReferenceEntry<K, V> next) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getPreviousInAccessQueue() {
throw new UnsupportedOperationException();
}
@Override
public void setPreviousInAccessQueue(ReferenceEntry<K, V> previous) {
throw new UnsupportedOperationException();
}
// null write
@Override
public long getWriteTime() {
throw new UnsupportedOperationException();
}
@Override
public void setWriteTime(long time) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getNextInWriteQueue() {
throw new UnsupportedOperationException();
}
@Override
public void setNextInWriteQueue(ReferenceEntry<K, V> next) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getPreviousInWriteQueue() {
throw new UnsupportedOperationException();
}
@Override
public void setPreviousInWriteQueue(ReferenceEntry<K, V> previous) {
throw new UnsupportedOperationException();
}
// The code below is exactly the same for each entry type.
final int hash;
@CheckForNull final ReferenceEntry<K, V> next;
volatile ValueReference<K, V> valueReference = unset();
@Override
public ValueReference<K, V> getValueReference() {
return valueReference;
}
@Override
public void setValueReference(ValueReference<K, V> valueReference) {
this.valueReference = valueReference;
}
@Override
public int getHash() {
return hash;
}
@Override
public ReferenceEntry<K, V> getNext() {
return next;
}
}
static final class WeakAccessEntry<K, V> extends WeakEntry<K, V> {
WeakAccessEntry(
ReferenceQueue<K> queue, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
super(queue, key, hash, next);
}
// The code below is exactly the same for each access entry type.
volatile long accessTime = Long.MAX_VALUE;
@Override
public long getAccessTime() {
return accessTime;
}
@Override
public void setAccessTime(long time) {
this.accessTime = time;
}
// Guarded By Segment.this
@Weak ReferenceEntry<K, V> nextAccess = nullEntry();
@Override
public ReferenceEntry<K, V> getNextInAccessQueue() {
return nextAccess;
}
@Override
public void setNextInAccessQueue(ReferenceEntry<K, V> next) {
this.nextAccess = next;
}
// Guarded By Segment.this
@Weak ReferenceEntry<K, V> previousAccess = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousInAccessQueue() {
return previousAccess;
}
@Override
public void setPreviousInAccessQueue(ReferenceEntry<K, V> previous) {
this.previousAccess = previous;
}
}
static final class WeakWriteEntry<K, V> extends WeakEntry<K, V> {
WeakWriteEntry(
ReferenceQueue<K> queue, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
super(queue, key, hash, next);
}
// The code below is exactly the same for each write entry type.
volatile long writeTime = Long.MAX_VALUE;
@Override
public long getWriteTime() {
return writeTime;
}
@Override
public void setWriteTime(long time) {
this.writeTime = time;
}
// Guarded By Segment.this
@Weak ReferenceEntry<K, V> nextWrite = nullEntry();
@Override
public ReferenceEntry<K, V> getNextInWriteQueue() {
return nextWrite;
}
@Override
public void setNextInWriteQueue(ReferenceEntry<K, V> next) {
this.nextWrite = next;
}
// Guarded By Segment.this
@Weak ReferenceEntry<K, V> previousWrite = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousInWriteQueue() {
return previousWrite;
}
@Override
public void setPreviousInWriteQueue(ReferenceEntry<K, V> previous) {
this.previousWrite = previous;
}
}
static final class WeakAccessWriteEntry<K, V> extends WeakEntry<K, V> {
WeakAccessWriteEntry(
ReferenceQueue<K> queue, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
super(queue, key, hash, next);
}
// The code below is exactly the same for each access entry type.
volatile long accessTime = Long.MAX_VALUE;
@Override
public long getAccessTime() {
return accessTime;
}
@Override
public void setAccessTime(long time) {
this.accessTime = time;
}
// Guarded By Segment.this
@Weak ReferenceEntry<K, V> nextAccess = nullEntry();
@Override
public ReferenceEntry<K, V> getNextInAccessQueue() {
return nextAccess;
}
@Override
public void setNextInAccessQueue(ReferenceEntry<K, V> next) {
this.nextAccess = next;
}
// Guarded By Segment.this
@Weak ReferenceEntry<K, V> previousAccess = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousInAccessQueue() {
return previousAccess;
}
@Override
public void setPreviousInAccessQueue(ReferenceEntry<K, V> previous) {
this.previousAccess = previous;
}
// The code below is exactly the same for each write entry type.
volatile long writeTime = Long.MAX_VALUE;
@Override
public long getWriteTime() {
return writeTime;
}
@Override
public void setWriteTime(long time) {
this.writeTime = time;
}
// Guarded By Segment.this
@Weak ReferenceEntry<K, V> nextWrite = nullEntry();
@Override
public ReferenceEntry<K, V> getNextInWriteQueue() {
return nextWrite;
}
@Override
public void setNextInWriteQueue(ReferenceEntry<K, V> next) {
this.nextWrite = next;
}
// Guarded By Segment.this
@Weak ReferenceEntry<K, V> previousWrite = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousInWriteQueue() {
return previousWrite;
}
@Override
public void setPreviousInWriteQueue(ReferenceEntry<K, V> previous) {
this.previousWrite = previous;
}
}
/** References a weak value. */
static class WeakValueReference<K, V> extends WeakReference<V> implements ValueReference<K, V> {
final ReferenceEntry<K, V> entry;
WeakValueReference(ReferenceQueue<V> queue, V referent, ReferenceEntry<K, V> entry) {
super(referent, queue);
this.entry = entry;
}
@Override
public int getWeight() {
return 1;
}
@Override
public ReferenceEntry<K, V> getEntry() {
return entry;
}
@Override
public void notifyNewValue(V newValue) {}
@Override
public ValueReference<K, V> copyFor(
ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) {
return new WeakValueReference<>(queue, value, entry);
}
@Override
public boolean isLoading() {
return false;
}
@Override
public boolean isActive() {
return true;
}
@Override
public V waitForValue() {
return get();
}
}
/** References a soft value. */
static class SoftValueReference<K, V> extends SoftReference<V> implements ValueReference<K, V> {
final ReferenceEntry<K, V> entry;
SoftValueReference(ReferenceQueue<V> queue, V referent, ReferenceEntry<K, V> entry) {
super(referent, queue);
this.entry = entry;
}
@Override
public int getWeight() {
return 1;
}
@Override
public ReferenceEntry<K, V> getEntry() {
return entry;
}
@Override
public void notifyNewValue(V newValue) {}
@Override
public ValueReference<K, V> copyFor(
ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) {
return new SoftValueReference<>(queue, value, entry);
}
@Override
public boolean isLoading() {
return false;
}
@Override
public boolean isActive() {
return true;
}
@Override
public V waitForValue() {
return get();
}
}
/** References a strong value. */
static class StrongValueReference<K, V> implements ValueReference<K, V> {
final V referent;
StrongValueReference(V referent) {
this.referent = referent;
}
@Override
public V get() {
return referent;
}
@Override
public int getWeight() {
return 1;
}
@Override
public ReferenceEntry<K, V> getEntry() {
return null;
}
@Override
public ValueReference<K, V> copyFor(
ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) {
return this;
}
@Override
public boolean isLoading() {
return false;
}
@Override
public boolean isActive() {
return true;
}
@Override
public V waitForValue() {
return get();
}
@Override
public void notifyNewValue(V newValue) {}
}
/** References a weak value. */
static final class WeightedWeakValueReference<K, V> extends WeakValueReference<K, V> {
final int weight;
WeightedWeakValueReference(
ReferenceQueue<V> queue, V referent, ReferenceEntry<K, V> entry, int weight) {
super(queue, referent, entry);
this.weight = weight;
}
@Override
public int getWeight() {
return weight;
}
@Override
public ValueReference<K, V> copyFor(
ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) {
return new WeightedWeakValueReference<>(queue, value, entry, weight);
}
}
/** References a soft value. */
static final class WeightedSoftValueReference<K, V> extends SoftValueReference<K, V> {
final int weight;
WeightedSoftValueReference(
ReferenceQueue<V> queue, V referent, ReferenceEntry<K, V> entry, int weight) {
super(queue, referent, entry);
this.weight = weight;
}
@Override
public int getWeight() {
return weight;
}
@Override
public ValueReference<K, V> copyFor(
ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) {
return new WeightedSoftValueReference<>(queue, value, entry, weight);
}
}
/** References a strong value. */
static final class WeightedStrongValueReference<K, V> extends StrongValueReference<K, V> {
final int weight;
WeightedStrongValueReference(V referent, int weight) {
super(referent);
this.weight = weight;
}
@Override
public int getWeight() {
return weight;
}
}
/**
* Applies a supplemental hash function to a given hash code, which defends against poor quality
* hash functions. This is critical when the concurrent hash map uses power-of-two length hash
* tables, that otherwise encounter collisions for hash codes that do not differ in lower or upper
* bits.
*
* @param h hash code
*/
static int rehash(int h) {
// Spread bits to regularize both segment and index locations,
// using variant of single-word Wang/Jenkins hash.
// TODO(kevinb): use Hashing/move this to Hashing?
h += (h << 15) ^ 0xffffcd7d;
h ^= (h >>> 10);
h += (h << 3);
h ^= (h >>> 6);
h += (h << 2) + (h << 14);
return h ^ (h >>> 16);
}
/**
* This method is a convenience for testing. Code should call {@link Segment#newEntry} directly.
*/
@VisibleForTesting
ReferenceEntry<K, V> newEntry(K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
Segment<K, V> segment = segmentFor(hash);
segment.lock();
try {
return segment.newEntry(key, hash, next);
} finally {
segment.unlock();
}
}
/**
* This method is a convenience for testing. Code should call {@link Segment#copyEntry} directly.
*/
// Guarded By Segment.this
@SuppressWarnings("GuardedBy")
@VisibleForTesting
ReferenceEntry<K, V> copyEntry(ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
int hash = original.getHash();
return segmentFor(hash).copyEntry(original, newNext);
}
/**
* This method is a convenience for testing. Code should call {@link Segment#setValue} instead.
*/
// Guarded By Segment.this
@VisibleForTesting
ValueReference<K, V> newValueReference(ReferenceEntry<K, V> entry, V value, int weight) {
int hash = entry.getHash();
return valueStrength.referenceValue(segmentFor(hash), entry, checkNotNull(value), weight);
}
int hash(@CheckForNull Object key) {
int h = keyEquivalence.hash(key);
return rehash(h);
}
void reclaimValue(ValueReference<K, V> valueReference) {
ReferenceEntry<K, V> entry = valueReference.getEntry();
int hash = entry.getHash();
segmentFor(hash).reclaimValue(entry.getKey(), hash, valueReference);
}
void reclaimKey(ReferenceEntry<K, V> entry) {
int hash = entry.getHash();
segmentFor(hash).reclaimKey(entry, hash);
}
/**
* This method is a convenience for testing. Code should call {@link Segment#getLiveValue}
* instead.
*/
@VisibleForTesting
boolean isLive(ReferenceEntry<K, V> entry, long now) {
return segmentFor(entry.getHash()).getLiveValue(entry, now) != null;
}
/**
* Returns the segment that should be used for a key with the given hash.
*
* @param hash the hash code for the key
* @return the segment
*/
Segment<K, V> segmentFor(int hash) {
// TODO(fry): Lazily create segments?
return segments[(hash >>> segmentShift) & segmentMask];
}
Segment<K, V> createSegment(
int initialCapacity, long maxSegmentWeight, StatsCounter statsCounter) {
return new Segment<>(this, initialCapacity, maxSegmentWeight, statsCounter);
}
/**
* Gets the value from an entry. Returns null if the entry is invalid, partially-collected,
* loading, or expired. Unlike {@link Segment#getLiveValue} this method does not attempt to clean
* up stale entries. As such it should only be called outside a segment context, such as during
* iteration.
*/
@CheckForNull
V getLiveValue(ReferenceEntry<K, V> entry, long now) {
if (entry.getKey() == null) {
return null;
}
V value = entry.getValueReference().get();
if (value == null) {
return null;
}
if (isExpired(entry, now)) {
return null;
}
return value;
}
// expiration
/** Returns true if the entry has expired. */
boolean isExpired(ReferenceEntry<K, V> entry, long now) {
checkNotNull(entry);
if (expiresAfterAccess() && (now - entry.getAccessTime() >= expireAfterAccessNanos)) {
return true;
}
if (expiresAfterWrite() && (now - entry.getWriteTime() >= expireAfterWriteNanos)) {
return true;
}
return false;
}
// queues
// Guarded By Segment.this
static <K, V> void connectAccessOrder(ReferenceEntry<K, V> previous, ReferenceEntry<K, V> next) {
previous.setNextInAccessQueue(next);
next.setPreviousInAccessQueue(previous);
}
// Guarded By Segment.this
static <K, V> void nullifyAccessOrder(ReferenceEntry<K, V> nulled) {
ReferenceEntry<K, V> nullEntry = nullEntry();
nulled.setNextInAccessQueue(nullEntry);
nulled.setPreviousInAccessQueue(nullEntry);
}
// Guarded By Segment.this
static <K, V> void connectWriteOrder(ReferenceEntry<K, V> previous, ReferenceEntry<K, V> next) {
previous.setNextInWriteQueue(next);
next.setPreviousInWriteQueue(previous);
}
// Guarded By Segment.this
static <K, V> void nullifyWriteOrder(ReferenceEntry<K, V> nulled) {
ReferenceEntry<K, V> nullEntry = nullEntry();
nulled.setNextInWriteQueue(nullEntry);
nulled.setPreviousInWriteQueue(nullEntry);
}
/**
* Notifies listeners that an entry has been automatically removed due to expiration, eviction, or
* eligibility for garbage collection. This should be called every time expireEntries or
* evictEntry is called (once the lock is released).
*/
void processPendingNotifications() {
RemovalNotification<K, V> notification;
while ((notification = removalNotificationQueue.poll()) != null) {
try {
removalListener.onRemoval(notification);
} catch (Throwable e) {
logger.log(Level.WARNING, "Exception thrown by removal listener", e);
}
}
}
@SuppressWarnings("unchecked")
final Segment<K, V>[] newSegmentArray(int ssize) {
return (Segment<K, V>[]) new Segment<?, ?>[ssize];
}
// Inner Classes
/**
* Segments are specialized versions of hash tables. This subclass inherits from ReentrantLock
* opportunistically, just to simplify some locking and avoid separate construction.
*/
@SuppressWarnings("serial") // This class is never serialized.
static class Segment<K, V> extends ReentrantLock {
/*
* TODO(fry): Consider copying variables (like evictsBySize) from outer class into this class.
* It will require more memory but will reduce indirection.
*/
/*
* Segments maintain a table of entry lists that are ALWAYS kept in a consistent state, so can
* be read without locking. Next fields of nodes are immutable (final). All list additions are
* performed at the front of each bin. This makes it easy to check changes, and also fast to
* traverse. When nodes would otherwise be changed, new nodes are created to replace them. This
* works well for hash tables since the bin lists tend to be short. (The average length is less
* than two.)
*
* Read operations can thus proceed without locking, but rely on selected uses of volatiles to
* ensure that completed write operations performed by other threads are noticed. For most
* purposes, the "count" field, tracking the number of elements, serves as that volatile
* variable ensuring visibility. This is convenient because this field needs to be read in many
* read operations anyway:
*
* - All (unsynchronized) read operations must first read the "count" field, and should not look
* at table entries if it is 0.
*
* - All (synchronized) write operations should write to the "count" field after structurally
* changing any bin. The operations must not take any action that could even momentarily cause a
* concurrent read operation to see inconsistent data. This is made easier by the nature of the
* read operations in Map. For example, no operation can reveal that the table has grown but the
* threshold has not yet been updated, so there are no atomicity requirements for this with
* respect to reads.
*
* As a guide, all critical volatile reads and writes to the count field are marked in code
* comments.
*/
@Weak final LocalCache<K, V> map;
/** The number of live elements in this segment's region. */
volatile int count;
/** The weight of the live elements in this segment's region. */
@GuardedBy("this")
long totalWeight;
/**
* Number of updates that alter the size of the table. This is used during bulk-read methods to
* make sure they see a consistent snapshot: If modCounts change during a traversal of segments
* loading size or checking containsValue, then we might have an inconsistent view of state so
* (usually) must retry.
*/
int modCount;
/**
* The table is expanded when its size exceeds this threshold. (The value of this field is
* always {@code (int) (capacity * 0.75)}.)
*/
int threshold;
/** The per-segment table. */
@CheckForNull volatile AtomicReferenceArray<ReferenceEntry<K, V>> table;
/** The maximum weight of this segment. UNSET_INT if there is no maximum. */
final long maxSegmentWeight;
/**
* The key reference queue contains entries whose keys have been garbage collected, and which
* need to be cleaned up internally.
*/
@CheckForNull final ReferenceQueue<K> keyReferenceQueue;
/**
* The value reference queue contains value references whose values have been garbage collected,
* and which need to be cleaned up internally.
*/
@CheckForNull final ReferenceQueue<V> valueReferenceQueue;
/**
* The recency queue is used to record which entries were accessed for updating the access
* list's ordering. It is drained as a batch operation when either the DRAIN_THRESHOLD is
* crossed or a write occurs on the segment.
*/
final Queue<ReferenceEntry<K, V>> recencyQueue;
/**
* A counter of the number of reads since the last write, used to drain queues on a small
* fraction of read operations.
*/
final AtomicInteger readCount = new AtomicInteger();
/**
* A queue of elements currently in the map, ordered by write time. Elements are added to the
* tail of the queue on write.
*/
@GuardedBy("this")
final Queue<ReferenceEntry<K, V>> writeQueue;
/**
* A queue of elements currently in the map, ordered by access time. Elements are added to the
* tail of the queue on access (note that writes count as accesses).
*/
@GuardedBy("this")
final Queue<ReferenceEntry<K, V>> accessQueue;
/** Accumulates cache statistics. */
final StatsCounter statsCounter;
Segment(
LocalCache<K, V> map,
int initialCapacity,
long maxSegmentWeight,
StatsCounter statsCounter) {
this.map = map;
this.maxSegmentWeight = maxSegmentWeight;
this.statsCounter = checkNotNull(statsCounter);
initTable(newEntryArray(initialCapacity));
keyReferenceQueue = map.usesKeyReferences() ? new ReferenceQueue<>() : null;
valueReferenceQueue = map.usesValueReferences() ? new ReferenceQueue<>() : null;
recencyQueue =
map.usesAccessQueue() ? new ConcurrentLinkedQueue<>() : LocalCache.discardingQueue();
writeQueue = map.usesWriteQueue() ? new WriteQueue<>() : LocalCache.discardingQueue();
accessQueue = map.usesAccessQueue() ? new AccessQueue<>() : LocalCache.discardingQueue();
}
AtomicReferenceArray<ReferenceEntry<K, V>> newEntryArray(int size) {
return new AtomicReferenceArray<>(size);
}
void initTable(AtomicReferenceArray<ReferenceEntry<K, V>> newTable) {
this.threshold = newTable.length() * 3 / 4; // 0.75
if (!map.customWeigher() && this.threshold == maxSegmentWeight) {
// prevent spurious expansion before eviction
this.threshold++;
}
this.table = newTable;
}
@GuardedBy("this")
ReferenceEntry<K, V> newEntry(K key, int hash, @CheckForNull ReferenceEntry<K, V> next) {
return map.entryFactory.newEntry(this, checkNotNull(key), hash, next);
}
/**
* Copies {@code original} into a new entry chained to {@code newNext}. Returns the new entry,
* or {@code null} if {@code original} was already garbage collected.
*/
@CheckForNull
@GuardedBy("this")
ReferenceEntry<K, V> copyEntry(ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
K key = original.getKey();
if (key == null) {
// key collected
return null;
}
ValueReference<K, V> valueReference = original.getValueReference();
V value = valueReference.get();
if ((value == null) && valueReference.isActive()) {
// value collected
return null;
}
ReferenceEntry<K, V> newEntry = map.entryFactory.copyEntry(this, original, newNext, key);
newEntry.setValueReference(valueReference.copyFor(this.valueReferenceQueue, value, newEntry));
return newEntry;
}
/** Sets a new value of an entry. Adds newly created entries at the end of the access queue. */
@GuardedBy("this")
void setValue(ReferenceEntry<K, V> entry, K key, V value, long now) {
ValueReference<K, V> previous = entry.getValueReference();
int weight = map.weigher.weigh(key, value);
checkState(weight >= 0, "Weights must be non-negative");
ValueReference<K, V> valueReference =
map.valueStrength.referenceValue(this, entry, value, weight);
entry.setValueReference(valueReference);
recordWrite(entry, weight, now);
previous.notifyNewValue(value);
}
// loading
@CanIgnoreReturnValue
V get(K key, int hash, CacheLoader<? super K, V> loader) throws ExecutionException {
checkNotNull(key);
checkNotNull(loader);
try {
if (count != 0) { // read-volatile
// don't call getLiveEntry, which would ignore loading values
ReferenceEntry<K, V> e = getEntry(key, hash);
if (e != null) {
long now = map.ticker.read();
V value = getLiveValue(e, now);
if (value != null) {
recordRead(e, now);
statsCounter.recordHits(1);
return scheduleRefresh(e, key, hash, value, now, loader);
}
ValueReference<K, V> valueReference = e.getValueReference();
if (valueReference.isLoading()) {
return waitForLoadingValue(e, key, valueReference);
}
}
}
// at this point e is either null or expired;
return lockedGetOrLoad(key, hash, loader);
} catch (ExecutionException ee) {
Throwable cause = ee.getCause();
if (cause instanceof Error) {
throw new ExecutionError((Error) cause);
} else if (cause instanceof RuntimeException) {
throw new UncheckedExecutionException(cause);
}
throw ee;
} finally {
postReadCleanup();
}
}
@CheckForNull
V get(Object key, int hash) {
try {
if (count != 0) { // read-volatile
long now = map.ticker.read();
ReferenceEntry<K, V> e = getLiveEntry(key, hash, now);
if (e == null) {
return null;
}
V value = e.getValueReference().get();
if (value != null) {
recordRead(e, now);
return scheduleRefresh(e, e.getKey(), hash, value, now, map.defaultLoader);
}
tryDrainReferenceQueues();
}
return null;
} finally {
postReadCleanup();
}
}
V lockedGetOrLoad(K key, int hash, CacheLoader<? super K, V> loader) throws ExecutionException {
ReferenceEntry<K, V> e;
ValueReference<K, V> valueReference = null;
LoadingValueReference<K, V> loadingValueReference = null;
boolean createNewEntry = true;
lock();
try {
// re-read ticker once inside the lock
long now = map.ticker.read();
preWriteCleanup(now);
int newCount = this.count - 1;
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash
&& entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
valueReference = e.getValueReference();
if (valueReference.isLoading()) {
createNewEntry = false;
} else {
V value = valueReference.get();
if (value == null) {
enqueueNotification(
entryKey, hash, value, valueReference.getWeight(), RemovalCause.COLLECTED);
} else if (map.isExpired(e, now)) {
// This is a duplicate check, as preWriteCleanup already purged expired
// entries, but let's accommodate an incorrect expiration queue.
enqueueNotification(
entryKey, hash, value, valueReference.getWeight(), RemovalCause.EXPIRED);
} else {
recordLockedRead(e, now);
statsCounter.recordHits(1);
// we were concurrent with loading; don't consider refresh
return value;
}
// immediately reuse invalid entries
writeQueue.remove(e);
accessQueue.remove(e);
this.count = newCount; // write-volatile
}
break;
}
}
if (createNewEntry) {
loadingValueReference = new LoadingValueReference<>();
if (e == null) {
e = newEntry(key, hash, first);
e.setValueReference(loadingValueReference);
table.set(index, e);
} else {
e.setValueReference(loadingValueReference);
}
}
} finally {
unlock();
postWriteCleanup();
}
if (createNewEntry) {
try {
// Synchronizes on the entry to allow failing fast when a recursive load is
// detected. This may be circumvented when an entry is copied, but will fail fast most
// of the time.
synchronized (e) {
return loadSync(key, hash, loadingValueReference, loader);
}
} finally {
statsCounter.recordMisses(1);
}
} else {
// The entry already exists. Wait for loading.
return waitForLoadingValue(e, key, valueReference);
}
}
V waitForLoadingValue(ReferenceEntry<K, V> e, K key, ValueReference<K, V> valueReference)
throws ExecutionException {
if (!valueReference.isLoading()) {
throw new AssertionError();
}
checkState(!Thread.holdsLock(e), "Recursive load of: %s", key);
// don't consider expiration as we're concurrent with loading
try {
V value = valueReference.waitForValue();
if (value == null) {
throw new InvalidCacheLoadException("CacheLoader returned null for key " + key + ".");
}
// re-read ticker now that loading has completed
long now = map.ticker.read();
recordRead(e, now);
return value;
} finally {
statsCounter.recordMisses(1);
}
}
@CheckForNull
V compute(
K key,
int hash,
BiFunction<? super K, ? super @Nullable V, ? extends @Nullable V> function) {
ReferenceEntry<K, V> e;
ValueReference<K, V> valueReference = null;
ComputingValueReference<K, V> computingValueReference = null;
boolean createNewEntry = true;
V newValue;
lock();
try {
// re-read ticker once inside the lock
long now = map.ticker.read();
preWriteCleanup(now);
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash
&& entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
valueReference = e.getValueReference();
if (map.isExpired(e, now)) {
// This is a duplicate check, as preWriteCleanup already purged expired
// entries, but let's accommodate an incorrect expiration queue.
enqueueNotification(
entryKey,
hash,
valueReference.get(),
valueReference.getWeight(),
RemovalCause.EXPIRED);
}
// immediately reuse invalid entries
writeQueue.remove(e);
accessQueue.remove(e);
createNewEntry = false;
break;
}
}
// note valueReference can be an existing value or even itself another loading value if
// the value for the key is already being computed.
computingValueReference = new ComputingValueReference<>(valueReference);
if (e == null) {
createNewEntry = true;
e = newEntry(key, hash, first);
e.setValueReference(computingValueReference);
table.set(index, e);
} else {
e.setValueReference(computingValueReference);
}
newValue = computingValueReference.compute(key, function);
if (newValue != null) {
if (valueReference != null && newValue == valueReference.get()) {
computingValueReference.set(newValue);
e.setValueReference(valueReference);
recordWrite(e, 0, now); // no change in weight
return newValue;
}
try {
return getAndRecordStats(
key, hash, computingValueReference, Futures.immediateFuture(newValue));
} catch (ExecutionException exception) {
throw new AssertionError("impossible; Futures.immediateFuture can't throw");
}
} else if (createNewEntry || valueReference.isLoading()) {
removeLoadingValue(key, hash, computingValueReference);
return null;
} else {
removeEntry(e, hash, RemovalCause.EXPLICIT);
return null;
}
} finally {
unlock();
postWriteCleanup();
}
}
// at most one of loadSync/loadAsync may be called for any given LoadingValueReference
V loadSync(
K key,
int hash,
LoadingValueReference<K, V> loadingValueReference,
CacheLoader<? super K, V> loader)
throws ExecutionException {
ListenableFuture<V> loadingFuture = loadingValueReference.loadFuture(key, loader);
return getAndRecordStats(key, hash, loadingValueReference, loadingFuture);
}
ListenableFuture<V> loadAsync(
final K key,
final int hash,
final LoadingValueReference<K, V> loadingValueReference,
CacheLoader<? super K, V> loader) {
final ListenableFuture<V> loadingFuture = loadingValueReference.loadFuture(key, loader);
loadingFuture.addListener(
() -> {
try {
getAndRecordStats(key, hash, loadingValueReference, loadingFuture);
} catch (Throwable t) {
logger.log(Level.WARNING, "Exception thrown during refresh", t);
loadingValueReference.setException(t);
}
},
directExecutor());
return loadingFuture;
}
/** Waits uninterruptibly for {@code newValue} to be loaded, and then records loading stats. */
@CanIgnoreReturnValue
V getAndRecordStats(
K key,
int hash,
LoadingValueReference<K, V> loadingValueReference,
ListenableFuture<V> newValue)
throws ExecutionException {
V value = null;
try {
value = getUninterruptibly(newValue);
if (value == null) {
throw new InvalidCacheLoadException("CacheLoader returned null for key " + key + ".");
}
statsCounter.recordLoadSuccess(loadingValueReference.elapsedNanos());
storeLoadedValue(key, hash, loadingValueReference, value);
return value;
} finally {
if (value == null) {
statsCounter.recordLoadException(loadingValueReference.elapsedNanos());
removeLoadingValue(key, hash, loadingValueReference);
}
}
}
V scheduleRefresh(
ReferenceEntry<K, V> entry,
K key,
int hash,
V oldValue,
long now,
CacheLoader<? super K, V> loader) {
if (map.refreshes()
&& (now - entry.getWriteTime() > map.refreshNanos)
&& !entry.getValueReference().isLoading()) {
V newValue = refresh(key, hash, loader, true);
if (newValue != null) {
return newValue;
}
}
return oldValue;
}
/**
* Refreshes the value associated with {@code key}, unless another thread is already doing so.
* Returns the newly refreshed value associated with {@code key} if it was refreshed inline, or
* {@code null} if another thread is performing the refresh or if an error occurs during
* refresh.
*/
@CanIgnoreReturnValue
@CheckForNull
V refresh(K key, int hash, CacheLoader<? super K, V> loader, boolean checkTime) {
final LoadingValueReference<K, V> loadingValueReference =
insertLoadingValueReference(key, hash, checkTime);
if (loadingValueReference == null) {
return null;
}
ListenableFuture<V> result = loadAsync(key, hash, loadingValueReference, loader);
if (result.isDone()) {
try {
return Uninterruptibles.getUninterruptibly(result);
} catch (Throwable t) {
// don't let refresh exceptions propagate; error was already logged
}
}
return null;
}
/**
* Returns a newly inserted {@code LoadingValueReference}, or null if the live value reference
* is already loading.
*/
@CheckForNull
LoadingValueReference<K, V> insertLoadingValueReference(
final K key, final int hash, boolean checkTime) {
ReferenceEntry<K, V> e = null;
lock();
try {
long now = map.ticker.read();
preWriteCleanup(now);
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
// Look for an existing entry.
for (e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash
&& entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
// We found an existing entry.
ValueReference<K, V> valueReference = e.getValueReference();
if (valueReference.isLoading()
|| (checkTime && (now - e.getWriteTime() < map.refreshNanos))) {
// refresh is a no-op if loading is pending
// if checkTime, we want to check *after* acquiring the lock if refresh still needs
// to be scheduled
return null;
}
// continue returning old value while loading
++modCount;
LoadingValueReference<K, V> loadingValueReference =
new LoadingValueReference<>(valueReference);
e.setValueReference(loadingValueReference);
return loadingValueReference;
}
}
++modCount;
LoadingValueReference<K, V> loadingValueReference = new LoadingValueReference<>();
e = newEntry(key, hash, first);
e.setValueReference(loadingValueReference);
table.set(index, e);
return loadingValueReference;
} finally {
unlock();
postWriteCleanup();
}
}
// reference queues, for garbage collection cleanup
/** Cleanup collected entries when the lock is available. */
void tryDrainReferenceQueues() {
if (tryLock()) {
try {
drainReferenceQueues();
} finally {
unlock();
}
}
}
/**
* Drain the key and value reference queues, cleaning up internal entries containing garbage
* collected keys or values.
*/
@GuardedBy("this")
void drainReferenceQueues() {
if (map.usesKeyReferences()) {
drainKeyReferenceQueue();
}
if (map.usesValueReferences()) {
drainValueReferenceQueue();
}
}
@GuardedBy("this")
void drainKeyReferenceQueue() {
Reference<? extends K> ref;
int i = 0;
while ((ref = keyReferenceQueue.poll()) != null) {
@SuppressWarnings("unchecked")
ReferenceEntry<K, V> entry = (ReferenceEntry<K, V>) ref;
map.reclaimKey(entry);
if (++i == DRAIN_MAX) {
break;
}
}
}
@GuardedBy("this")
void drainValueReferenceQueue() {
Reference<? extends V> ref;
int i = 0;
while ((ref = valueReferenceQueue.poll()) != null) {
@SuppressWarnings("unchecked")
ValueReference<K, V> valueReference = (ValueReference<K, V>) ref;
map.reclaimValue(valueReference);
if (++i == DRAIN_MAX) {
break;
}
}
}
/** Clears all entries from the key and value reference queues. */
void clearReferenceQueues() {
if (map.usesKeyReferences()) {
clearKeyReferenceQueue();
}
if (map.usesValueReferences()) {
clearValueReferenceQueue();
}
}
void clearKeyReferenceQueue() {
while (keyReferenceQueue.poll() != null) {}
}
void clearValueReferenceQueue() {
while (valueReferenceQueue.poll() != null) {}
}
// recency queue, shared by expiration and eviction
/**
* Records the relative order in which this read was performed by adding {@code entry} to the
* recency queue. At write-time, or when the queue is full past the threshold, the queue will be
* drained and the entries therein processed.
*
* <p>Note: locked reads should use {@link #recordLockedRead}.
*/
void recordRead(ReferenceEntry<K, V> entry, long now) {
if (map.recordsAccess()) {
entry.setAccessTime(now);
}
recencyQueue.add(entry);
}
/**
* Updates the eviction metadata that {@code entry} was just read. This currently amounts to
* adding {@code entry} to relevant eviction lists.
*
* <p>Note: this method should only be called under lock, as it directly manipulates the
* eviction queues. Unlocked reads should use {@link #recordRead}.
*/
@GuardedBy("this")
void recordLockedRead(ReferenceEntry<K, V> entry, long now) {
if (map.recordsAccess()) {
entry.setAccessTime(now);
}
accessQueue.add(entry);
}
/**
* Updates eviction metadata that {@code entry} was just written. This currently amounts to
* adding {@code entry} to relevant eviction lists.
*/
@GuardedBy("this")
void recordWrite(ReferenceEntry<K, V> entry, int weight, long now) {
// we are already under lock, so drain the recency queue immediately
drainRecencyQueue();
totalWeight += weight;
if (map.recordsAccess()) {
entry.setAccessTime(now);
}
if (map.recordsWrite()) {
entry.setWriteTime(now);
}
accessQueue.add(entry);
writeQueue.add(entry);
}
/**
* Drains the recency queue, updating eviction metadata that the entries therein were read in
* the specified relative order. This currently amounts to adding them to relevant eviction
* lists (accounting for the fact that they could have been removed from the map since being
* added to the recency queue).
*/
@GuardedBy("this")
void drainRecencyQueue() {
ReferenceEntry<K, V> e;
while ((e = recencyQueue.poll()) != null) {
// An entry may be in the recency queue despite it being removed from
// the map . This can occur when the entry was concurrently read while a
// writer is removing it from the segment or after a clear has removed
// all the segment's entries.
if (accessQueue.contains(e)) {
accessQueue.add(e);
}
}
}
// expiration
/** Cleanup expired entries when the lock is available. */
void tryExpireEntries(long now) {
if (tryLock()) {
try {
expireEntries(now);
} finally {
unlock();
// don't call postWriteCleanup as we're in a read
}
}
}
@GuardedBy("this")
void expireEntries(long now) {
drainRecencyQueue();
ReferenceEntry<K, V> e;
while ((e = writeQueue.peek()) != null && map.isExpired(e, now)) {
if (!removeEntry(e, e.getHash(), RemovalCause.EXPIRED)) {
throw new AssertionError();
}
}
while ((e = accessQueue.peek()) != null && map.isExpired(e, now)) {
if (!removeEntry(e, e.getHash(), RemovalCause.EXPIRED)) {
throw new AssertionError();
}
}
}
// eviction
@GuardedBy("this")
void enqueueNotification(
@CheckForNull K key, int hash, @CheckForNull V value, int weight, RemovalCause cause) {
totalWeight -= weight;
if (cause.wasEvicted()) {
statsCounter.recordEviction();
}
if (map.removalNotificationQueue != DISCARDING_QUEUE) {
RemovalNotification<K, V> notification = RemovalNotification.create(key, value, cause);
map.removalNotificationQueue.offer(notification);
}
}
/**
* Performs eviction if the segment is over capacity. Avoids flushing the entire cache if the
* newest entry exceeds the maximum weight all on its own.
*
* @param newest the most recently added entry
*/
@GuardedBy("this")
void evictEntries(ReferenceEntry<K, V> newest) {
if (!map.evictsBySize()) {
return;
}
drainRecencyQueue();
// If the newest entry by itself is too heavy for the segment, don't bother evicting
// anything else, just that
if (newest.getValueReference().getWeight() > maxSegmentWeight) {
if (!removeEntry(newest, newest.getHash(), RemovalCause.SIZE)) {
throw new AssertionError();
}
}
while (totalWeight > maxSegmentWeight) {
ReferenceEntry<K, V> e = getNextEvictable();
if (!removeEntry(e, e.getHash(), RemovalCause.SIZE)) {
throw new AssertionError();
}
}
}
// TODO(fry): instead implement this with an eviction head
@GuardedBy("this")
ReferenceEntry<K, V> getNextEvictable() {
for (ReferenceEntry<K, V> e : accessQueue) {
int weight = e.getValueReference().getWeight();
if (weight > 0) {
return e;
}
}
throw new AssertionError();
}
/** Returns first entry of bin for given hash. */
ReferenceEntry<K, V> getFirst(int hash) {
// read this volatile field only once
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
return table.get(hash & (table.length() - 1));
}
// Specialized implementations of map methods
@CheckForNull
ReferenceEntry<K, V> getEntry(Object key, int hash) {
for (ReferenceEntry<K, V> e = getFirst(hash); e != null; e = e.getNext()) {
if (e.getHash() != hash) {
continue;
}
K entryKey = e.getKey();
if (entryKey == null) {
tryDrainReferenceQueues();
continue;
}
if (map.keyEquivalence.equivalent(key, entryKey)) {
return e;
}
}
return null;
}
@CheckForNull
ReferenceEntry<K, V> getLiveEntry(Object key, int hash, long now) {
ReferenceEntry<K, V> e = getEntry(key, hash);
if (e == null) {
return null;
} else if (map.isExpired(e, now)) {
tryExpireEntries(now);
return null;
}
return e;
}
/**
* Gets the value from an entry. Returns null if the entry is invalid, partially-collected,
* loading, or expired.
*/
V getLiveValue(ReferenceEntry<K, V> entry, long now) {
if (entry.getKey() == null) {
tryDrainReferenceQueues();
return null;
}
V value = entry.getValueReference().get();
if (value == null) {
tryDrainReferenceQueues();
return null;
}
if (map.isExpired(entry, now)) {
tryExpireEntries(now);
return null;
}
return value;
}
boolean containsKey(Object key, int hash) {
try {
if (count != 0) { // read-volatile
long now = map.ticker.read();
ReferenceEntry<K, V> e = getLiveEntry(key, hash, now);
if (e == null) {
return false;
}
return e.getValueReference().get() != null;
}
return false;
} finally {
postReadCleanup();
}
}
/**
* This method is a convenience for testing. Code should call {@link LocalCache#containsValue}
* directly.
*/
@VisibleForTesting
boolean containsValue(Object value) {
try {
if (count != 0) { // read-volatile
long now = map.ticker.read();
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int length = table.length();
for (int i = 0; i < length; ++i) {
for (ReferenceEntry<K, V> e = table.get(i); e != null; e = e.getNext()) {
V entryValue = getLiveValue(e, now);
if (entryValue == null) {
continue;
}
if (map.valueEquivalence.equivalent(value, entryValue)) {
return true;
}
}
}
}
return false;
} finally {
postReadCleanup();
}
}
@CanIgnoreReturnValue
@CheckForNull
V put(K key, int hash, V value, boolean onlyIfAbsent) {
lock();
try {
long now = map.ticker.read();
preWriteCleanup(now);
int newCount = this.count + 1;
if (newCount > this.threshold) { // ensure capacity
expand();
newCount = this.count + 1;
}
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
// Look for an existing entry.
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash
&& entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
// We found an existing entry.
ValueReference<K, V> valueReference = e.getValueReference();
V entryValue = valueReference.get();
if (entryValue == null) {
++modCount;
if (valueReference.isActive()) {
enqueueNotification(
key, hash, entryValue, valueReference.getWeight(), RemovalCause.COLLECTED);
setValue(e, key, value, now);
newCount = this.count; // count remains unchanged
} else {
setValue(e, key, value, now);
newCount = this.count + 1;
}
this.count = newCount; // write-volatile
evictEntries(e);
return null;
} else if (onlyIfAbsent) {
// Mimic
// "if (!map.containsKey(key)) ...
// else return map.get(key);
recordLockedRead(e, now);
return entryValue;
} else {
// clobber existing entry, count remains unchanged
++modCount;
enqueueNotification(
key, hash, entryValue, valueReference.getWeight(), RemovalCause.REPLACED);
setValue(e, key, value, now);
evictEntries(e);
return entryValue;
}
}
}
// Create a new entry.
++modCount;
ReferenceEntry<K, V> newEntry = newEntry(key, hash, first);
setValue(newEntry, key, value, now);
table.set(index, newEntry);
newCount = this.count + 1;
this.count = newCount; // write-volatile
evictEntries(newEntry);
return null;
} finally {
unlock();
postWriteCleanup();
}
}
/** Expands the table if possible. */
@GuardedBy("this")
void expand() {
AtomicReferenceArray<ReferenceEntry<K, V>> oldTable = table;
int oldCapacity = oldTable.length();
if (oldCapacity >= MAXIMUM_CAPACITY) {
return;
}
/*
* Reclassify nodes in each list to new Map. Because we are using power-of-two expansion, the
* elements from each bin must either stay at same index, or move with a power of two offset.
* We eliminate unnecessary node creation by catching cases where old nodes can be reused
* because their next fields won't change. Statistically, at the default threshold, only about
* one-sixth of them need cloning when a table doubles. The nodes they replace will be garbage
* collectable as soon as they are no longer referenced by any reader thread that may be in
* the midst of traversing table right now.
*/
int newCount = count;
AtomicReferenceArray<ReferenceEntry<K, V>> newTable = newEntryArray(oldCapacity << 1);
threshold = newTable.length() * 3 / 4;
int newMask = newTable.length() - 1;
for (int oldIndex = 0; oldIndex < oldCapacity; ++oldIndex) {
// We need to guarantee that any existing reads of old Map can
// proceed. So we cannot yet null out each bin.
ReferenceEntry<K, V> head = oldTable.get(oldIndex);
if (head != null) {
ReferenceEntry<K, V> next = head.getNext();
int headIndex = head.getHash() & newMask;
// Single node on list
if (next == null) {
newTable.set(headIndex, head);
} else {
// Reuse the consecutive sequence of nodes with the same target
// index from the end of the list. tail points to the first
// entry in the reusable list.
ReferenceEntry<K, V> tail = head;
int tailIndex = headIndex;
for (ReferenceEntry<K, V> e = next; e != null; e = e.getNext()) {
int newIndex = e.getHash() & newMask;
if (newIndex != tailIndex) {
// The index changed. We'll need to copy the previous entry.
tailIndex = newIndex;
tail = e;
}
}
newTable.set(tailIndex, tail);
// Clone nodes leading up to the tail.
for (ReferenceEntry<K, V> e = head; e != tail; e = e.getNext()) {
int newIndex = e.getHash() & newMask;
ReferenceEntry<K, V> newNext = newTable.get(newIndex);
ReferenceEntry<K, V> newFirst = copyEntry(e, newNext);
if (newFirst != null) {
newTable.set(newIndex, newFirst);
} else {
removeCollectedEntry(e);
newCount--;
}
}
}
}
}
table = newTable;
this.count = newCount;
}
boolean replace(K key, int hash, V oldValue, V newValue) {
lock();
try {
long now = map.ticker.read();
preWriteCleanup(now);
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash
&& entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
ValueReference<K, V> valueReference = e.getValueReference();
V entryValue = valueReference.get();
if (entryValue == null) {
if (valueReference.isActive()) {
// If the value disappeared, this entry is partially collected.
int newCount = this.count - 1;
++modCount;
ReferenceEntry<K, V> newFirst =
removeValueFromChain(
first,
e,
entryKey,
hash,
entryValue,
valueReference,
RemovalCause.COLLECTED);
newCount = this.count - 1;
table.set(index, newFirst);
this.count = newCount; // write-volatile
}
return false;
}
if (map.valueEquivalence.equivalent(oldValue, entryValue)) {
++modCount;
enqueueNotification(
key, hash, entryValue, valueReference.getWeight(), RemovalCause.REPLACED);
setValue(e, key, newValue, now);
evictEntries(e);
return true;
} else {
// Mimic
// "if (map.containsKey(key) && map.get(key).equals(oldValue))..."
recordLockedRead(e, now);
return false;
}
}
}
return false;
} finally {
unlock();
postWriteCleanup();
}
}
@CheckForNull
V replace(K key, int hash, V newValue) {
lock();
try {
long now = map.ticker.read();
preWriteCleanup(now);
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash
&& entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
ValueReference<K, V> valueReference = e.getValueReference();
V entryValue = valueReference.get();
if (entryValue == null) {
if (valueReference.isActive()) {
// If the value disappeared, this entry is partially collected.
int newCount = this.count - 1;
++modCount;
ReferenceEntry<K, V> newFirst =
removeValueFromChain(
first,
e,
entryKey,
hash,
entryValue,
valueReference,
RemovalCause.COLLECTED);
newCount = this.count - 1;
table.set(index, newFirst);
this.count = newCount; // write-volatile
}
return null;
}
++modCount;
enqueueNotification(
key, hash, entryValue, valueReference.getWeight(), RemovalCause.REPLACED);
setValue(e, key, newValue, now);
evictEntries(e);
return entryValue;
}
}
return null;
} finally {
unlock();
postWriteCleanup();
}
}
@CheckForNull
V remove(Object key, int hash) {
lock();
try {
long now = map.ticker.read();
preWriteCleanup(now);
int newCount = this.count - 1;
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash
&& entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
ValueReference<K, V> valueReference = e.getValueReference();
V entryValue = valueReference.get();
RemovalCause cause;
if (entryValue != null) {
cause = RemovalCause.EXPLICIT;
} else if (valueReference.isActive()) {
cause = RemovalCause.COLLECTED;
} else {
// currently loading
return null;
}
++modCount;
ReferenceEntry<K, V> newFirst =
removeValueFromChain(first, e, entryKey, hash, entryValue, valueReference, cause);
newCount = this.count - 1;
table.set(index, newFirst);
this.count = newCount; // write-volatile
return entryValue;
}
}
return null;
} finally {
unlock();
postWriteCleanup();
}
}
boolean remove(Object key, int hash, Object value) {
lock();
try {
long now = map.ticker.read();
preWriteCleanup(now);
int newCount = this.count - 1;
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash
&& entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
ValueReference<K, V> valueReference = e.getValueReference();
V entryValue = valueReference.get();
RemovalCause cause;
if (map.valueEquivalence.equivalent(value, entryValue)) {
cause = RemovalCause.EXPLICIT;
} else if (entryValue == null && valueReference.isActive()) {
cause = RemovalCause.COLLECTED;
} else {
// currently loading
return false;
}
++modCount;
ReferenceEntry<K, V> newFirst =
removeValueFromChain(first, e, entryKey, hash, entryValue, valueReference, cause);
newCount = this.count - 1;
table.set(index, newFirst);
this.count = newCount; // write-volatile
return (cause == RemovalCause.EXPLICIT);
}
}
return false;
} finally {
unlock();
postWriteCleanup();
}
}
@CanIgnoreReturnValue
boolean storeLoadedValue(
K key, int hash, LoadingValueReference<K, V> oldValueReference, V newValue) {
lock();
try {
long now = map.ticker.read();
preWriteCleanup(now);
int newCount = this.count + 1;
if (newCount > this.threshold) { // ensure capacity
expand();
newCount = this.count + 1;
}
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash
&& entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
ValueReference<K, V> valueReference = e.getValueReference();
V entryValue = valueReference.get();
// replace the old LoadingValueReference if it's live, otherwise
// perform a putIfAbsent
if (oldValueReference == valueReference
|| (entryValue == null && valueReference != UNSET)) {
++modCount;
if (oldValueReference.isActive()) {
RemovalCause cause =
(entryValue == null) ? RemovalCause.COLLECTED : RemovalCause.REPLACED;
enqueueNotification(key, hash, entryValue, oldValueReference.getWeight(), cause);
newCount--;
}
setValue(e, key, newValue, now);
this.count = newCount; // write-volatile
evictEntries(e);
return true;
}
// the loaded value was already clobbered
enqueueNotification(key, hash, newValue, 0, RemovalCause.REPLACED);
return false;
}
}
++modCount;
ReferenceEntry<K, V> newEntry = newEntry(key, hash, first);
setValue(newEntry, key, newValue, now);
table.set(index, newEntry);
this.count = newCount; // write-volatile
evictEntries(newEntry);
return true;
} finally {
unlock();
postWriteCleanup();
}
}
void clear() {
if (count != 0) { // read-volatile
lock();
try {
long now = map.ticker.read();
preWriteCleanup(now);
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
for (int i = 0; i < table.length(); ++i) {
for (ReferenceEntry<K, V> e = table.get(i); e != null; e = e.getNext()) {
// Loading references aren't actually in the map yet.
if (e.getValueReference().isActive()) {
K key = e.getKey();
V value = e.getValueReference().get();
RemovalCause cause =
(key == null || value == null) ? RemovalCause.COLLECTED : RemovalCause.EXPLICIT;
enqueueNotification(
key, e.getHash(), value, e.getValueReference().getWeight(), cause);
}
}
}
for (int i = 0; i < table.length(); ++i) {
table.set(i, null);
}
clearReferenceQueues();
writeQueue.clear();
accessQueue.clear();
readCount.set(0);
++modCount;
count = 0; // write-volatile
} finally {
unlock();
postWriteCleanup();
}
}
}
@GuardedBy("this")
@CheckForNull
ReferenceEntry<K, V> removeValueFromChain(
ReferenceEntry<K, V> first,
ReferenceEntry<K, V> entry,
@CheckForNull K key,
int hash,
V value,
ValueReference<K, V> valueReference,
RemovalCause cause) {
enqueueNotification(key, hash, value, valueReference.getWeight(), cause);
writeQueue.remove(entry);
accessQueue.remove(entry);
if (valueReference.isLoading()) {
valueReference.notifyNewValue(null);
return first;
} else {
return removeEntryFromChain(first, entry);
}
}
@GuardedBy("this")
@CheckForNull
ReferenceEntry<K, V> removeEntryFromChain(
ReferenceEntry<K, V> first, ReferenceEntry<K, V> entry) {
int newCount = count;
ReferenceEntry<K, V> newFirst = entry.getNext();
for (ReferenceEntry<K, V> e = first; e != entry; e = e.getNext()) {
ReferenceEntry<K, V> next = copyEntry(e, newFirst);
if (next != null) {
newFirst = next;
} else {
removeCollectedEntry(e);
newCount--;
}
}
this.count = newCount;
return newFirst;
}
@GuardedBy("this")
void removeCollectedEntry(ReferenceEntry<K, V> entry) {
enqueueNotification(
entry.getKey(),
entry.getHash(),
entry.getValueReference().get(),
entry.getValueReference().getWeight(),
RemovalCause.COLLECTED);
writeQueue.remove(entry);
accessQueue.remove(entry);
}
/** Removes an entry whose key has been garbage collected. */
@CanIgnoreReturnValue
boolean reclaimKey(ReferenceEntry<K, V> entry, int hash) {
lock();
try {
int newCount = count - 1;
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
if (e == entry) {
++modCount;
ReferenceEntry<K, V> newFirst =
removeValueFromChain(
first,
e,
e.getKey(),
hash,
e.getValueReference().get(),
e.getValueReference(),
RemovalCause.COLLECTED);
newCount = this.count - 1;
table.set(index, newFirst);
this.count = newCount; // write-volatile
return true;
}
}
return false;
} finally {
unlock();
postWriteCleanup();
}
}
/** Removes an entry whose value has been garbage collected. */
@CanIgnoreReturnValue
boolean reclaimValue(K key, int hash, ValueReference<K, V> valueReference) {
lock();
try {
int newCount = this.count - 1;
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash
&& entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
ValueReference<K, V> v = e.getValueReference();
if (v == valueReference) {
++modCount;
ReferenceEntry<K, V> newFirst =
removeValueFromChain(
first,
e,
entryKey,
hash,
valueReference.get(),
valueReference,
RemovalCause.COLLECTED);
newCount = this.count - 1;
table.set(index, newFirst);
this.count = newCount; // write-volatile
return true;
}
return false;
}
}
return false;
} finally {
unlock();
if (!isHeldByCurrentThread()) { // don't clean up inside of put
postWriteCleanup();
}
}
}
@CanIgnoreReturnValue
boolean removeLoadingValue(K key, int hash, LoadingValueReference<K, V> valueReference) {
lock();
try {
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash
&& entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
ValueReference<K, V> v = e.getValueReference();
if (v == valueReference) {
if (valueReference.isActive()) {
e.setValueReference(valueReference.getOldValue());
} else {
ReferenceEntry<K, V> newFirst = removeEntryFromChain(first, e);
table.set(index, newFirst);
}
return true;
}
return false;
}
}
return false;
} finally {
unlock();
postWriteCleanup();
}
}
@VisibleForTesting
@GuardedBy("this")
@CanIgnoreReturnValue
boolean removeEntry(ReferenceEntry<K, V> entry, int hash, RemovalCause cause) {
int newCount = this.count - 1;
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
if (e == entry) {
++modCount;
ReferenceEntry<K, V> newFirst =
removeValueFromChain(
first,
e,
e.getKey(),
hash,
e.getValueReference().get(),
e.getValueReference(),
cause);
newCount = this.count - 1;
table.set(index, newFirst);
this.count = newCount; // write-volatile
return true;
}
}
return false;
}
/**
* Performs routine cleanup following a read. Normally cleanup happens during writes. If cleanup
* is not observed after a sufficient number of reads, try cleaning up from the read thread.
*/
void postReadCleanup() {
if ((readCount.incrementAndGet() & DRAIN_THRESHOLD) == 0) {
cleanUp();
}
}
/**
* Performs routine cleanup prior to executing a write. This should be called every time a write
* thread acquires the segment lock, immediately after acquiring the lock.
*
* <p>Post-condition: expireEntries has been run.
*/
@GuardedBy("this")
void preWriteCleanup(long now) {
runLockedCleanup(now);
}
/** Performs routine cleanup following a write. */
void postWriteCleanup() {
runUnlockedCleanup();
}
void cleanUp() {
long now = map.ticker.read();
runLockedCleanup(now);
runUnlockedCleanup();
}
void runLockedCleanup(long now) {
if (tryLock()) {
try {
drainReferenceQueues();
expireEntries(now); // calls drainRecencyQueue
readCount.set(0);
} finally {
unlock();
}
}
}
void runUnlockedCleanup() {
// locked cleanup may generate notifications we can send unlocked
if (!isHeldByCurrentThread()) {
map.processPendingNotifications();
}
}
}
static class LoadingValueReference<K, V> implements ValueReference<K, V> {
volatile ValueReference<K, V> oldValue;
// TODO(fry): rename get, then extend AbstractFuture instead of containing SettableFuture
final SettableFuture<V> futureValue = SettableFuture.create();
final Stopwatch stopwatch = Stopwatch.createUnstarted();
public LoadingValueReference() {
this(null);
}
public LoadingValueReference(@CheckForNull ValueReference<K, V> oldValue) {
this.oldValue = (oldValue == null) ? LocalCache.unset() : oldValue;
}
@Override
public boolean isLoading() {
return true;
}
@Override
public boolean isActive() {
return oldValue.isActive();
}
@Override
public int getWeight() {
return oldValue.getWeight();
}
@CanIgnoreReturnValue
public boolean set(@CheckForNull V newValue) {
return futureValue.set(newValue);
}
@CanIgnoreReturnValue
public boolean setException(Throwable t) {
return futureValue.setException(t);
}
private ListenableFuture<V> fullyFailedFuture(Throwable t) {
return Futures.immediateFailedFuture(t);
}
@Override
public void notifyNewValue(@CheckForNull V newValue) {
if (newValue != null) {
// The pending load was clobbered by a manual write.
// Unblock all pending gets, and have them return the new value.
set(newValue);
} else {
// The pending load was removed. Delay notifications until loading completes.
oldValue = unset();
}
// TODO(fry): could also cancel loading if we had a handle on its future
}
public ListenableFuture<V> loadFuture(K key, CacheLoader<? super K, V> loader) {
try {
stopwatch.start();
V previousValue = oldValue.get();
if (previousValue == null) {
V newValue = loader.load(key);
return set(newValue) ? futureValue : Futures.immediateFuture(newValue);
}
ListenableFuture<V> newValue = loader.reload(key, previousValue);
if (newValue == null) {
return Futures.immediateFuture(null);
}
// To avoid a race, make sure the refreshed value is set into loadingValueReference
// *before* returning newValue from the cache query.
return transform(
newValue,
newResult -> {
LoadingValueReference.this.set(newResult);
return newResult;
},
directExecutor());
} catch (Throwable t) {
ListenableFuture<V> result = setException(t) ? futureValue : fullyFailedFuture(t);
if (t instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
return result;
}
}
@CheckForNull
public V compute(
K key, BiFunction<? super K, ? super @Nullable V, ? extends @Nullable V> function) {
stopwatch.start();
V previousValue;
try {
previousValue = oldValue.waitForValue();
} catch (ExecutionException e) {
previousValue = null;
}
V newValue;
try {
newValue = function.apply(key, previousValue);
} catch (Throwable th) {
this.setException(th);
throw th;
}
this.set(newValue);
return newValue;
}
public long elapsedNanos() {
return stopwatch.elapsed(NANOSECONDS);
}
@Override
public V waitForValue() throws ExecutionException {
return getUninterruptibly(futureValue);
}
@Override
public V get() {
return oldValue.get();
}
public ValueReference<K, V> getOldValue() {
return oldValue;
}
@Override
public ReferenceEntry<K, V> getEntry() {
return null;
}
@Override
public ValueReference<K, V> copyFor(
ReferenceQueue<V> queue, @CheckForNull V value, ReferenceEntry<K, V> entry) {
return this;
}
}
static class ComputingValueReference<K, V> extends LoadingValueReference<K, V> {
ComputingValueReference(ValueReference<K, V> oldValue) {
super(oldValue);
}
@Override
public boolean isLoading() {
return false;
}
}
// Queues
/**
* A custom queue for managing eviction order. Note that this is tightly integrated with {@code
* ReferenceEntry}, upon which it relies to perform its linking.
*
* <p>Note that this entire implementation makes the assumption that all elements which are in the
* map are also in this queue, and that all elements not in the queue are not in the map.
*
* <p>The benefits of creating our own queue are that (1) we can replace elements in the middle of
* the queue as part of copyWriteEntry, and (2) the contains method is highly optimized for the
* current model.
*/
static final class WriteQueue<K, V> extends AbstractQueue<ReferenceEntry<K, V>> {
final ReferenceEntry<K, V> head =
new AbstractReferenceEntry<K, V>() {
@Override
public long getWriteTime() {
return Long.MAX_VALUE;
}
@Override
public void setWriteTime(long time) {}
@Weak ReferenceEntry<K, V> nextWrite = this;
@Override
public ReferenceEntry<K, V> getNextInWriteQueue() {
return nextWrite;
}
@Override
public void setNextInWriteQueue(ReferenceEntry<K, V> next) {
this.nextWrite = next;
}
@Weak ReferenceEntry<K, V> previousWrite = this;
@Override
public ReferenceEntry<K, V> getPreviousInWriteQueue() {
return previousWrite;
}
@Override
public void setPreviousInWriteQueue(ReferenceEntry<K, V> previous) {
this.previousWrite = previous;
}
};
// implements Queue
@Override
public boolean offer(ReferenceEntry<K, V> entry) {
// unlink
connectWriteOrder(entry.getPreviousInWriteQueue(), entry.getNextInWriteQueue());
// add to tail
connectWriteOrder(head.getPreviousInWriteQueue(), entry);
connectWriteOrder(entry, head);
return true;
}
@CheckForNull
@Override
public ReferenceEntry<K, V> peek() {
ReferenceEntry<K, V> next = head.getNextInWriteQueue();
return (next == head) ? null : next;
}
@CheckForNull
@Override
public ReferenceEntry<K, V> poll() {
ReferenceEntry<K, V> next = head.getNextInWriteQueue();
if (next == head) {
return null;
}
remove(next);
return next;
}
@Override
@SuppressWarnings("unchecked")
@CanIgnoreReturnValue
public boolean remove(Object o) {
ReferenceEntry<K, V> e = (ReferenceEntry<K, V>) o;
ReferenceEntry<K, V> previous = e.getPreviousInWriteQueue();
ReferenceEntry<K, V> next = e.getNextInWriteQueue();
connectWriteOrder(previous, next);
nullifyWriteOrder(e);
return next != NullEntry.INSTANCE;
}
@Override
@SuppressWarnings("unchecked")
public boolean contains(Object o) {
ReferenceEntry<K, V> e = (ReferenceEntry<K, V>) o;
return e.getNextInWriteQueue() != NullEntry.INSTANCE;
}
@Override
public boolean isEmpty() {
return head.getNextInWriteQueue() == head;
}
@Override
public int size() {
int size = 0;
for (ReferenceEntry<K, V> e = head.getNextInWriteQueue();
e != head;
e = e.getNextInWriteQueue()) {
size++;
}
return size;
}
@Override
public void clear() {
ReferenceEntry<K, V> e = head.getNextInWriteQueue();
while (e != head) {
ReferenceEntry<K, V> next = e.getNextInWriteQueue();
nullifyWriteOrder(e);
e = next;
}
head.setNextInWriteQueue(head);
head.setPreviousInWriteQueue(head);
}
@Override
public Iterator<ReferenceEntry<K, V>> iterator() {
return new AbstractSequentialIterator<ReferenceEntry<K, V>>(peek()) {
@CheckForNull
@Override
protected ReferenceEntry<K, V> computeNext(ReferenceEntry<K, V> previous) {
ReferenceEntry<K, V> next = previous.getNextInWriteQueue();
return (next == head) ? null : next;
}
};
}
}
/**
* A custom queue for managing access order. Note that this is tightly integrated with {@code
* ReferenceEntry}, upon which it relies to perform its linking.
*
* <p>Note that this entire implementation makes the assumption that all elements which are in the
* map are also in this queue, and that all elements not in the queue are not in the map.
*
* <p>The benefits of creating our own queue are that (1) we can replace elements in the middle of
* the queue as part of copyWriteEntry, and (2) the contains method is highly optimized for the
* current model.
*/
static final class AccessQueue<K, V> extends AbstractQueue<ReferenceEntry<K, V>> {
final ReferenceEntry<K, V> head =
new AbstractReferenceEntry<K, V>() {
@Override
public long getAccessTime() {
return Long.MAX_VALUE;
}
@Override
public void setAccessTime(long time) {}
@Weak ReferenceEntry<K, V> nextAccess = this;
@Override
public ReferenceEntry<K, V> getNextInAccessQueue() {
return nextAccess;
}
@Override
public void setNextInAccessQueue(ReferenceEntry<K, V> next) {
this.nextAccess = next;
}
@Weak ReferenceEntry<K, V> previousAccess = this;
@Override
public ReferenceEntry<K, V> getPreviousInAccessQueue() {
return previousAccess;
}
@Override
public void setPreviousInAccessQueue(ReferenceEntry<K, V> previous) {
this.previousAccess = previous;
}
};
// implements Queue
@Override
public boolean offer(ReferenceEntry<K, V> entry) {
// unlink
connectAccessOrder(entry.getPreviousInAccessQueue(), entry.getNextInAccessQueue());
// add to tail
connectAccessOrder(head.getPreviousInAccessQueue(), entry);
connectAccessOrder(entry, head);
return true;
}
@CheckForNull
@Override
public ReferenceEntry<K, V> peek() {
ReferenceEntry<K, V> next = head.getNextInAccessQueue();
return (next == head) ? null : next;
}
@CheckForNull
@Override
public ReferenceEntry<K, V> poll() {
ReferenceEntry<K, V> next = head.getNextInAccessQueue();
if (next == head) {
return null;
}
remove(next);
return next;
}
@Override
@SuppressWarnings("unchecked")
@CanIgnoreReturnValue
public boolean remove(Object o) {
ReferenceEntry<K, V> e = (ReferenceEntry<K, V>) o;
ReferenceEntry<K, V> previous = e.getPreviousInAccessQueue();
ReferenceEntry<K, V> next = e.getNextInAccessQueue();
connectAccessOrder(previous, next);
nullifyAccessOrder(e);
return next != NullEntry.INSTANCE;
}
@Override
@SuppressWarnings("unchecked")
public boolean contains(Object o) {
ReferenceEntry<K, V> e = (ReferenceEntry<K, V>) o;
return e.getNextInAccessQueue() != NullEntry.INSTANCE;
}
@Override
public boolean isEmpty() {
return head.getNextInAccessQueue() == head;
}
@Override
public int size() {
int size = 0;
for (ReferenceEntry<K, V> e = head.getNextInAccessQueue();
e != head;
e = e.getNextInAccessQueue()) {
size++;
}
return size;
}
@Override
public void clear() {
ReferenceEntry<K, V> e = head.getNextInAccessQueue();
while (e != head) {
ReferenceEntry<K, V> next = e.getNextInAccessQueue();
nullifyAccessOrder(e);
e = next;
}
head.setNextInAccessQueue(head);
head.setPreviousInAccessQueue(head);
}
@Override
public Iterator<ReferenceEntry<K, V>> iterator() {
return new AbstractSequentialIterator<ReferenceEntry<K, V>>(peek()) {
@CheckForNull
@Override
protected ReferenceEntry<K, V> computeNext(ReferenceEntry<K, V> previous) {
ReferenceEntry<K, V> next = previous.getNextInAccessQueue();
return (next == head) ? null : next;
}
};
}
}
// Cache support
public void cleanUp() {
for (Segment<?, ?> segment : segments) {
segment.cleanUp();
}
}
// ConcurrentMap methods
@Override
public boolean isEmpty() {
/*
* Sum per-segment modCounts to avoid mis-reporting when elements are concurrently added and
* removed in one segment while checking another, in which case the table was never actually
* empty at any point. (The sum ensures accuracy up through at least 1<<31 per-segment
* modifications before recheck.) Method containsValue() uses similar constructions for
* stability checks.
*/
long sum = 0L;
Segment<K, V>[] segments = this.segments;
for (Segment<K, V> segment : segments) {
if (segment.count != 0) {
return false;
}
sum += segment.modCount;
}
if (sum != 0L) { // recheck unless no modifications
for (Segment<K, V> segment : segments) {
if (segment.count != 0) {
return false;
}
sum -= segment.modCount;
}
return sum == 0L;
}
return true;
}
long longSize() {
Segment<K, V>[] segments = this.segments;
long sum = 0;
for (Segment<K, V> segment : segments) {
sum += segment.count;
}
return sum;
}
@Override
public int size() {
return Ints.saturatedCast(longSize());
}
@CanIgnoreReturnValue // TODO(b/27479612): consider removing this
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
if (key == null) {
return null;
}
int hash = hash(key);
return segmentFor(hash).get(key, hash);
}
@CanIgnoreReturnValue // TODO(b/27479612): consider removing this
V get(K key, CacheLoader<? super K, V> loader) throws ExecutionException {
int hash = hash(checkNotNull(key));
return segmentFor(hash).get(key, hash, loader);
}
@CheckForNull
public V getIfPresent(Object key) {
int hash = hash(checkNotNull(key));
V value = segmentFor(hash).get(key, hash);
if (value == null) {
globalStatsCounter.recordMisses(1);
} else {
globalStatsCounter.recordHits(1);
}
return value;
}
@Override
@CheckForNull
public V getOrDefault(@CheckForNull Object key, @CheckForNull V defaultValue) {
V result = get(key);
return (result != null) ? result : defaultValue;
}
V getOrLoad(K key) throws ExecutionException {
return get(key, defaultLoader);
}
ImmutableMap<K, V> getAllPresent(Iterable<?> keys) {
int hits = 0;
int misses = 0;
ImmutableMap.Builder<K, V> result = ImmutableMap.builder();
for (Object key : keys) {
V value = get(key);
if (value == null) {
misses++;
} else {
// TODO(fry): store entry key instead of query key
@SuppressWarnings("unchecked")
K castKey = (K) key;
result.put(castKey, value);
hits++;
}
}
globalStatsCounter.recordHits(hits);
globalStatsCounter.recordMisses(misses);
return result.buildKeepingLast();
}
ImmutableMap<K, V> getAll(Iterable<? extends K> keys) throws ExecutionException {
int hits = 0;
int misses = 0;
Map<K, V> result = Maps.newLinkedHashMap();
Set<K> keysToLoad = Sets.newLinkedHashSet();
for (K key : keys) {
V value = get(key);
if (!result.containsKey(key)) {
result.put(key, value);
if (value == null) {
misses++;
keysToLoad.add(key);
} else {
hits++;
}
}
}
try {
if (!keysToLoad.isEmpty()) {
try {
Map<K, V> newEntries = loadAll(unmodifiableSet(keysToLoad), defaultLoader);
for (K key : keysToLoad) {
V value = newEntries.get(key);
if (value == null) {
throw new InvalidCacheLoadException("loadAll failed to return a value for " + key);
}
result.put(key, value);
}
} catch (UnsupportedLoadingOperationException e) {
// loadAll not implemented, fallback to load
for (K key : keysToLoad) {
misses--; // get will count this miss
result.put(key, get(key, defaultLoader));
}
}
}
return ImmutableMap.copyOf(result);
} finally {
globalStatsCounter.recordHits(hits);
globalStatsCounter.recordMisses(misses);
}
}
/**
* Returns the result of calling {@link CacheLoader#loadAll}, or null if {@code loader} doesn't
* implement {@code loadAll}.
*/
@CheckForNull
Map<K, V> loadAll(Set<? extends K> keys, CacheLoader<? super K, V> loader)
throws ExecutionException {
checkNotNull(loader);
checkNotNull(keys);
Stopwatch stopwatch = Stopwatch.createStarted();
Map<K, V> result;
boolean success = false;
try {
@SuppressWarnings("unchecked") // safe since all keys extend K
Map<K, V> map = (Map<K, V>) loader.loadAll(keys);
result = map;
success = true;
} catch (UnsupportedLoadingOperationException e) {
success = true;
throw e;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new ExecutionException(e);
} catch (RuntimeException e) {
throw new UncheckedExecutionException(e);
} catch (Exception e) {
throw new ExecutionException(e);
} catch (Error e) {
throw new ExecutionError(e);
} finally {
if (!success) {
globalStatsCounter.recordLoadException(stopwatch.elapsed(NANOSECONDS));
}
}
if (result == null) {
globalStatsCounter.recordLoadException(stopwatch.elapsed(NANOSECONDS));
throw new InvalidCacheLoadException(loader + " returned null map from loadAll");
}
stopwatch.stop();
// TODO(fry): batch by segment
boolean nullsPresent = false;
for (Entry<K, V> entry : result.entrySet()) {
K key = entry.getKey();
V value = entry.getValue();
if (key == null || value == null) {
// delay failure until non-null entries are stored
nullsPresent = true;
} else {
put(key, value);
}
}
if (nullsPresent) {
globalStatsCounter.recordLoadException(stopwatch.elapsed(NANOSECONDS));
throw new InvalidCacheLoadException(loader + " returned null keys or values from loadAll");
}
// TODO(fry): record count of loaded entries
globalStatsCounter.recordLoadSuccess(stopwatch.elapsed(NANOSECONDS));
return result;
}
/**
* Returns the internal entry for the specified key. The entry may be loading, expired, or
* partially collected.
*/
@CheckForNull
ReferenceEntry<K, V> getEntry(@CheckForNull Object key) {
// does not impact recency ordering
if (key == null) {
return null;
}
int hash = hash(key);
return segmentFor(hash).getEntry(key, hash);
}
void refresh(K key) {
int hash = hash(checkNotNull(key));
segmentFor(hash).refresh(key, hash, defaultLoader, false);
}
@Override
public boolean containsKey(@CheckForNull Object key) {
// does not impact recency ordering
if (key == null) {
return false;
}
int hash = hash(key);
return segmentFor(hash).containsKey(key, hash);
}
@Override
public boolean containsValue(@CheckForNull Object value) {
// does not impact recency ordering
if (value == null) {
return false;
}
// This implementation is patterned after ConcurrentHashMap, but without the locking. The only
// way for it to return a false negative would be for the target value to jump around in the map
// such that none of the subsequent iterations observed it, despite the fact that at every point
// in time it was present somewhere int the map. This becomes increasingly unlikely as
// CONTAINS_VALUE_RETRIES increases, though without locking it is theoretically possible.
long now = ticker.read();
final Segment<K, V>[] segments = this.segments;
long last = -1L;
for (int i = 0; i < CONTAINS_VALUE_RETRIES; i++) {
long sum = 0L;
for (Segment<K, V> segment : segments) {
// ensure visibility of most recent completed write
int unused = segment.count; // read-volatile
AtomicReferenceArray<ReferenceEntry<K, V>> table = segment.table;
for (int j = 0; j < table.length(); j++) {
for (ReferenceEntry<K, V> e = table.get(j); e != null; e = e.getNext()) {
V v = segment.getLiveValue(e, now);
if (v != null && valueEquivalence.equivalent(value, v)) {
return true;
}
}
}
sum += segment.modCount;
}
if (sum == last) {
break;
}
last = sum;
}
return false;
}
@CheckForNull
@CanIgnoreReturnValue
@Override
public V put(K key, V value) {
checkNotNull(key);
checkNotNull(value);
int hash = hash(key);
return segmentFor(hash).put(key, hash, value, false);
}
@CheckForNull
@Override
public V putIfAbsent(K key, V value) {
checkNotNull(key);
checkNotNull(value);
int hash = hash(key);
return segmentFor(hash).put(key, hash, value, true);
}
@Override
@CheckForNull
public V compute(
K key, BiFunction<? super K, ? super @Nullable V, ? extends @Nullable V> function) {
checkNotNull(key);
checkNotNull(function);
int hash = hash(key);
return segmentFor(hash).compute(key, hash, function);
}
@Override
public V computeIfAbsent(K key, Function<? super K, ? extends V> function) {
checkNotNull(key);
checkNotNull(function);
return compute(key, (k, oldValue) -> (oldValue == null) ? function.apply(key) : oldValue);
}
@Override
@CheckForNull
public V computeIfPresent(
K key, BiFunction<? super K, ? super V, ? extends @Nullable V> function) {
checkNotNull(key);
checkNotNull(function);
return compute(key, (k, oldValue) -> (oldValue == null) ? null : function.apply(k, oldValue));
}
@Override
@CheckForNull
public V merge(
K key, V newValue, BiFunction<? super V, ? super V, ? extends @Nullable V> function) {
checkNotNull(key);
checkNotNull(newValue);
checkNotNull(function);
return compute(
key, (k, oldValue) -> (oldValue == null) ? newValue : function.apply(oldValue, newValue));
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
for (Entry<? extends K, ? extends V> e : m.entrySet()) {
put(e.getKey(), e.getValue());
}
}
@CheckForNull
@CanIgnoreReturnValue
@Override
public V remove(@CheckForNull Object key) {
if (key == null) {
return null;
}
int hash = hash(key);
return segmentFor(hash).remove(key, hash);
}
@CanIgnoreReturnValue
@Override
public boolean remove(@CheckForNull Object key, @CheckForNull Object value) {
if (key == null || value == null) {
return false;
}
int hash = hash(key);
return segmentFor(hash).remove(key, hash, value);
}
@CanIgnoreReturnValue
@Override
public boolean replace(K key, @CheckForNull V oldValue, V newValue) {
checkNotNull(key);
checkNotNull(newValue);
if (oldValue == null) {
return false;
}
int hash = hash(key);
return segmentFor(hash).replace(key, hash, oldValue, newValue);
}
@CheckForNull
@CanIgnoreReturnValue
@Override
public V replace(K key, V value) {
checkNotNull(key);
checkNotNull(value);
int hash = hash(key);
return segmentFor(hash).replace(key, hash, value);
}
@Override
public void clear() {
for (Segment<K, V> segment : segments) {
segment.clear();
}
}
void invalidateAll(Iterable<?> keys) {
// TODO(fry): batch by segment
for (Object key : keys) {
remove(key);
}
}
@LazyInit @RetainedWith @CheckForNull Set<K> keySet;
@Override
public Set<K> keySet() {
// does not impact recency ordering
Set<K> ks = keySet;
return (ks != null) ? ks : (keySet = new KeySet());
}
@LazyInit @RetainedWith @CheckForNull Collection<V> values;
@Override
public Collection<V> values() {
// does not impact recency ordering
Collection<V> vs = values;
return (vs != null) ? vs : (values = new Values());
}
@LazyInit @RetainedWith @CheckForNull Set<Entry<K, V>> entrySet;
@Override
@GwtIncompatible // Not supported.
public Set<Entry<K, V>> entrySet() {
// does not impact recency ordering
Set<Entry<K, V>> es = entrySet;
return (es != null) ? es : (entrySet = new EntrySet());
}
// Iterator Support
abstract class HashIterator<T> implements Iterator<T> {
int nextSegmentIndex;
int nextTableIndex;
@CheckForNull Segment<K, V> currentSegment;
@CheckForNull AtomicReferenceArray<ReferenceEntry<K, V>> currentTable;
@CheckForNull ReferenceEntry<K, V> nextEntry;
@CheckForNull WriteThroughEntry nextExternal;
@CheckForNull WriteThroughEntry lastReturned;
HashIterator() {
nextSegmentIndex = segments.length - 1;
nextTableIndex = -1;
advance();
}
@Override
public abstract T next();
final void advance() {
nextExternal = null;
if (nextInChain()) {
return;
}
if (nextInTable()) {
return;
}
while (nextSegmentIndex >= 0) {
currentSegment = segments[nextSegmentIndex--];
if (currentSegment.count != 0) {
currentTable = currentSegment.table;
nextTableIndex = currentTable.length() - 1;
if (nextInTable()) {
return;
}
}
}
}
/** Finds the next entry in the current chain. Returns true if an entry was found. */
boolean nextInChain() {
if (nextEntry != null) {
for (nextEntry = nextEntry.getNext(); nextEntry != null; nextEntry = nextEntry.getNext()) {
if (advanceTo(nextEntry)) {
return true;
}
}
}
return false;
}
/** Finds the next entry in the current table. Returns true if an entry was found. */
boolean nextInTable() {
while (nextTableIndex >= 0) {
if ((nextEntry = currentTable.get(nextTableIndex--)) != null) {
if (advanceTo(nextEntry) || nextInChain()) {
return true;
}
}
}
return false;
}
/**
* Advances to the given entry. Returns true if the entry was valid, false if it should be
* skipped.
*/
boolean advanceTo(ReferenceEntry<K, V> entry) {
try {
long now = ticker.read();
K key = entry.getKey();
V value = getLiveValue(entry, now);
if (value != null) {
nextExternal = new WriteThroughEntry(key, value);
return true;
} else {
// Skip stale entry.
return false;
}
} finally {
currentSegment.postReadCleanup();
}
}
@Override
public boolean hasNext() {
return nextExternal != null;
}
WriteThroughEntry nextEntry() {
if (nextExternal == null) {
throw new NoSuchElementException();
}
lastReturned = nextExternal;
advance();
return lastReturned;
}
@Override
public void remove() {
checkState(lastReturned != null);
LocalCache.this.remove(lastReturned.getKey());
lastReturned = null;
}
}
final class KeyIterator extends HashIterator<K> {
@Override
public K next() {
return nextEntry().getKey();
}
}
final class ValueIterator extends HashIterator<V> {
@Override
public V next() {
return nextEntry().getValue();
}
}
/**
* Custom Entry class used by EntryIterator.next(), that relays setValue changes to the underlying
* map.
*/
final class WriteThroughEntry implements Entry<K, V> {
final K key; // non-null
V value; // non-null
WriteThroughEntry(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@Override
public boolean equals(@CheckForNull Object object) {
// Cannot use key and value equivalence
if (object instanceof Entry) {
Entry<?, ?> that = (Entry<?, ?>) object;
return key.equals(that.getKey()) && value.equals(that.getValue());
}
return false;
}
@Override
public int hashCode() {
// Cannot use key and value equivalence
return key.hashCode() ^ value.hashCode();
}
@Override
public V setValue(V newValue) {
V oldValue = put(key, newValue);
value = newValue; // only if put succeeds
return oldValue;
}
@Override
public String toString() {
return getKey() + "=" + getValue();
}
}
final class EntryIterator extends HashIterator<Entry<K, V>> {
@Override
public Entry<K, V> next() {
return nextEntry();
}
}
abstract class AbstractCacheSet<T> extends AbstractSet<T> {
@Override
public int size() {
return LocalCache.this.size();
}
@Override
public boolean isEmpty() {
return LocalCache.this.isEmpty();
}
@Override
public void clear() {
LocalCache.this.clear();
}
// super.toArray() may misbehave if size() is inaccurate, at least on old versions of Android.
// https://code.google.com/p/android/issues/detail?id=36519 / http://r.android.com/47508
@Override
public Object[] toArray() {
return toArrayList(this).toArray();
}
@Override
public <E> E[] toArray(E[] a) {
return toArrayList(this).toArray(a);
}
}
private static <E> ArrayList<E> toArrayList(Collection<E> c) {
// Avoid calling ArrayList(Collection), which may call back into toArray.
ArrayList<E> result = new ArrayList<>(c.size());
Iterators.addAll(result, c.iterator());
return result;
}
boolean removeIf(BiPredicate<? super K, ? super V> filter) {
checkNotNull(filter);
boolean changed = false;
for (K key : keySet()) {
while (true) {
V value = get(key);
if (value == null || !filter.test(key, value)) {
break;
} else if (LocalCache.this.remove(key, value)) {
changed = true;
break;
}
}
}
return changed;
}
final class KeySet extends AbstractCacheSet<K> {
@Override
public Iterator<K> iterator() {
return new KeyIterator();
}
@Override
public boolean contains(Object o) {
return LocalCache.this.containsKey(o);
}
@Override
public boolean remove(Object o) {
return LocalCache.this.remove(o) != null;
}
}
final class Values extends AbstractCollection<V> {
@Override
public int size() {
return LocalCache.this.size();
}
@Override
public boolean isEmpty() {
return LocalCache.this.isEmpty();
}
@Override
public void clear() {
LocalCache.this.clear();
}
@Override
public Iterator<V> iterator() {
return new ValueIterator();
}
@Override
public boolean removeIf(Predicate<? super V> filter) {
checkNotNull(filter);
return LocalCache.this.removeIf((k, v) -> filter.test(v));
}
@Override
public boolean contains(Object o) {
return LocalCache.this.containsValue(o);
}
// super.toArray() may misbehave if size() is inaccurate, at least on old versions of Android.
// https://code.google.com/p/android/issues/detail?id=36519 / http://r.android.com/47508
@Override
public Object[] toArray() {
return toArrayList(this).toArray();
}
@Override
public <E> E[] toArray(E[] a) {
return toArrayList(this).toArray(a);
}
}
final class EntrySet extends AbstractCacheSet<Entry<K, V>> {
@Override
public Iterator<Entry<K, V>> iterator() {
return new EntryIterator();
}
@Override
public boolean removeIf(Predicate<? super Entry<K, V>> filter) {
checkNotNull(filter);
return LocalCache.this.removeIf((k, v) -> filter.test(Maps.immutableEntry(k, v)));
}
@Override
public boolean contains(Object o) {
if (!(o instanceof Entry)) {
return false;
}
Entry<?, ?> e = (Entry<?, ?>) o;
Object key = e.getKey();
if (key == null) {
return false;
}
V v = LocalCache.this.get(key);
return v != null && valueEquivalence.equivalent(e.getValue(), v);
}
@Override
public boolean remove(Object o) {
if (!(o instanceof Entry)) {
return false;
}
Entry<?, ?> e = (Entry<?, ?>) o;
Object key = e.getKey();
return key != null && LocalCache.this.remove(key, e.getValue());
}
}
// Serialization Support
/**
* Serializes the configuration of a LocalCache, reconstituting it as a Cache using CacheBuilder
* upon deserialization. An instance of this class is fit for use by the writeReplace of
* LocalManualCache.
*
* <p>Unfortunately, readResolve() doesn't get called when a circular dependency is present, so
* the proxy must be able to behave as the cache itself.
*/
static class ManualSerializationProxy<K, V> extends ForwardingCache<K, V>
implements Serializable {
private static final long serialVersionUID = 1;
final Strength keyStrength;
final Strength valueStrength;
final Equivalence<Object> keyEquivalence;
final Equivalence<Object> valueEquivalence;
final long expireAfterWriteNanos;
final long expireAfterAccessNanos;
final long maxWeight;
final Weigher<K, V> weigher;
final int concurrencyLevel;
final RemovalListener<? super K, ? super V> removalListener;
@CheckForNull final Ticker ticker;
final CacheLoader<? super K, V> loader;
@CheckForNull transient Cache<K, V> delegate;
ManualSerializationProxy(LocalCache<K, V> cache) {
this(
cache.keyStrength,
cache.valueStrength,
cache.keyEquivalence,
cache.valueEquivalence,
cache.expireAfterWriteNanos,
cache.expireAfterAccessNanos,
cache.maxWeight,
cache.weigher,
cache.concurrencyLevel,
cache.removalListener,
cache.ticker,
cache.defaultLoader);
}
private ManualSerializationProxy(
Strength keyStrength,
Strength valueStrength,
Equivalence<Object> keyEquivalence,
Equivalence<Object> valueEquivalence,
long expireAfterWriteNanos,
long expireAfterAccessNanos,
long maxWeight,
Weigher<K, V> weigher,
int concurrencyLevel,
RemovalListener<? super K, ? super V> removalListener,
Ticker ticker,
CacheLoader<? super K, V> loader) {
this.keyStrength = keyStrength;
this.valueStrength = valueStrength;
this.keyEquivalence = keyEquivalence;
this.valueEquivalence = valueEquivalence;
this.expireAfterWriteNanos = expireAfterWriteNanos;
this.expireAfterAccessNanos = expireAfterAccessNanos;
this.maxWeight = maxWeight;
this.weigher = weigher;
this.concurrencyLevel = concurrencyLevel;
this.removalListener = removalListener;
this.ticker = (ticker == Ticker.systemTicker() || ticker == NULL_TICKER) ? null : ticker;
this.loader = loader;
}
CacheBuilder<K, V> recreateCacheBuilder() {
CacheBuilder<K, V> builder =
CacheBuilder.newBuilder()
.setKeyStrength(keyStrength)
.setValueStrength(valueStrength)
.keyEquivalence(keyEquivalence)
.valueEquivalence(valueEquivalence)
.concurrencyLevel(concurrencyLevel)
.removalListener(removalListener);
builder.strictParsing = false;
if (expireAfterWriteNanos > 0) {
builder.expireAfterWrite(expireAfterWriteNanos, TimeUnit.NANOSECONDS);
}
if (expireAfterAccessNanos > 0) {
builder.expireAfterAccess(expireAfterAccessNanos, TimeUnit.NANOSECONDS);
}
if (weigher != OneWeigher.INSTANCE) {
Object unused = builder.weigher(weigher);
if (maxWeight != UNSET_INT) {
builder.maximumWeight(maxWeight);
}
} else {
if (maxWeight != UNSET_INT) {
builder.maximumSize(maxWeight);
}
}
if (ticker != null) {
builder.ticker(ticker);
}
return builder;
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
CacheBuilder<K, V> builder = recreateCacheBuilder();
this.delegate = builder.build();
}
private Object readResolve() {
return delegate;
}
@Override
protected Cache<K, V> delegate() {
return delegate;
}
}
/**
* Serializes the configuration of a LocalCache, reconstituting it as an LoadingCache using
* CacheBuilder upon deserialization. An instance of this class is fit for use by the writeReplace
* of LocalLoadingCache.
*
* <p>Unfortunately, readResolve() doesn't get called when a circular dependency is present, so
* the proxy must be able to behave as the cache itself.
*/
static final class LoadingSerializationProxy<K, V> extends ManualSerializationProxy<K, V>
implements LoadingCache<K, V>, Serializable {
private static final long serialVersionUID = 1;
@CheckForNull transient LoadingCache<K, V> autoDelegate;
LoadingSerializationProxy(LocalCache<K, V> cache) {
super(cache);
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
CacheBuilder<K, V> builder = recreateCacheBuilder();
this.autoDelegate = builder.build(loader);
}
@Override
public V get(K key) throws ExecutionException {
return autoDelegate.get(key);
}
@Override
public V getUnchecked(K key) {
return autoDelegate.getUnchecked(key);
}
@Override
public ImmutableMap<K, V> getAll(Iterable<? extends K> keys) throws ExecutionException {
return autoDelegate.getAll(keys);
}
@Override
public V apply(K key) {
return autoDelegate.apply(key);
}
@Override
public void refresh(K key) {
autoDelegate.refresh(key);
}
private Object readResolve() {
return autoDelegate;
}
}
static class LocalManualCache<K, V> implements Cache<K, V>, Serializable {
final LocalCache<K, V> localCache;
LocalManualCache(CacheBuilder<? super K, ? super V> builder) {
this(new LocalCache<>(builder, null));
}
private LocalManualCache(LocalCache<K, V> localCache) {
this.localCache = localCache;
}
// Cache methods
@Override
@CheckForNull
public V getIfPresent(Object key) {
return localCache.getIfPresent(key);
}
@Override
public V get(K key, final Callable<? extends V> valueLoader) throws ExecutionException {
checkNotNull(valueLoader);
return localCache.get(
key,
new CacheLoader<Object, V>() {
@Override
public V load(Object key) throws Exception {
return valueLoader.call();
}
});
}
@Override
public ImmutableMap<K, V> getAllPresent(Iterable<?> keys) {
return localCache.getAllPresent(keys);
}
@Override
public void put(K key, V value) {
localCache.put(key, value);
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
localCache.putAll(m);
}
@Override
public void invalidate(Object key) {
checkNotNull(key);
localCache.remove(key);
}
@Override
public void invalidateAll(Iterable<?> keys) {
localCache.invalidateAll(keys);
}
@Override
public void invalidateAll() {
localCache.clear();
}
@Override
public long size() {
return localCache.longSize();
}
@Override
public ConcurrentMap<K, V> asMap() {
return localCache;
}
@Override
public CacheStats stats() {
SimpleStatsCounter aggregator = new SimpleStatsCounter();
aggregator.incrementBy(localCache.globalStatsCounter);
for (Segment<K, V> segment : localCache.segments) {
aggregator.incrementBy(segment.statsCounter);
}
return aggregator.snapshot();
}
@Override
public void cleanUp() {
localCache.cleanUp();
}
// Serialization Support
private static final long serialVersionUID = 1;
Object writeReplace() {
return new ManualSerializationProxy<>(localCache);
}
private void readObject(ObjectInputStream in) throws InvalidObjectException {
throw new InvalidObjectException("Use ManualSerializationProxy");
}
}
static class LocalLoadingCache<K, V> extends LocalManualCache<K, V>
implements LoadingCache<K, V> {
LocalLoadingCache(
CacheBuilder<? super K, ? super V> builder, CacheLoader<? super K, V> loader) {
super(new LocalCache<>(builder, checkNotNull(loader)));
}
// LoadingCache methods
@Override
public V get(K key) throws ExecutionException {
return localCache.getOrLoad(key);
}
@CanIgnoreReturnValue // TODO(b/27479612): consider removing this
@Override
public V getUnchecked(K key) {
try {
return get(key);
} catch (ExecutionException e) {
throw new UncheckedExecutionException(e.getCause());
}
}
@Override
public ImmutableMap<K, V> getAll(Iterable<? extends K> keys) throws ExecutionException {
return localCache.getAll(keys);
}
@Override
public void refresh(K key) {
localCache.refresh(key);
}
@Override
public final V apply(K key) {
return getUnchecked(key);
}
// Serialization Support
private static final long serialVersionUID = 1;
@Override
Object writeReplace() {
return new LoadingSerializationProxy<>(localCache);
}
private void readObject(ObjectInputStream in) throws InvalidObjectException {
throw new InvalidObjectException("Use LoadingSerializationProxy");
}
}
}
| google/guava | guava/src/com/google/common/cache/LocalCache.java |
44,423 | /*
* Copyright (C) 2008 The Guava Authors
*
* 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.google.common.primitives;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Converter;
import java.io.Serializable;
import java.util.AbstractList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.RandomAccess;
import java.util.Spliterator;
import java.util.Spliterators;
import javax.annotation.CheckForNull;
/**
* Static utility methods pertaining to {@code long} primitives, that are not already found in
* either {@link Long} or {@link Arrays}.
*
* <p>See the Guava User Guide article on <a
* href="https://github.com/google/guava/wiki/PrimitivesExplained">primitive utilities</a>.
*
* @author Kevin Bourrillion
* @since 1.0
*/
@GwtCompatible
@ElementTypesAreNonnullByDefault
public final class Longs {
private Longs() {}
/**
* The number of bytes required to represent a primitive {@code long} value.
*
* <p><b>Java 8+ users:</b> use {@link Long#BYTES} instead.
*/
public static final int BYTES = Long.SIZE / Byte.SIZE;
/**
* The largest power of two that can be represented as a {@code long}.
*
* @since 10.0
*/
public static final long MAX_POWER_OF_TWO = 1L << (Long.SIZE - 2);
/**
* Returns a hash code for {@code value}; equal to the result of invoking {@code ((Long)
* value).hashCode()}.
*
* <p>This method always return the value specified by {@link Long#hashCode()} in java, which
* might be different from {@code ((Long) value).hashCode()} in GWT because {@link
* Long#hashCode()} in GWT does not obey the JRE contract.
*
* <p><b>Java 8+ users:</b> use {@link Long#hashCode(long)} instead.
*
* @param value a primitive {@code long} value
* @return a hash code for the value
*/
public static int hashCode(long value) {
return (int) (value ^ (value >>> 32));
}
/**
* Compares the two specified {@code long} values. The sign of the value returned is the same as
* that of {@code ((Long) a).compareTo(b)}.
*
* <p><b>Java 7+ users:</b> this method should be treated as deprecated; use the equivalent {@link
* Long#compare} method instead.
*
* @param a the first {@code long} to compare
* @param b the second {@code long} to compare
* @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is
* greater than {@code b}; or zero if they are equal
*/
public static int compare(long a, long b) {
return (a < b) ? -1 : ((a > b) ? 1 : 0);
}
/**
* Returns {@code true} if {@code target} is present as an element anywhere in {@code array}.
*
* @param array an array of {@code long} values, possibly empty
* @param target a primitive {@code long} value
* @return {@code true} if {@code array[i] == target} for some value of {@code i}
*/
public static boolean contains(long[] array, long target) {
for (long value : array) {
if (value == target) {
return true;
}
}
return false;
}
/**
* Returns the index of the first appearance of the value {@code target} in {@code array}.
*
* @param array an array of {@code long} values, possibly empty
* @param target a primitive {@code long} value
* @return the least index {@code i} for which {@code array[i] == target}, or {@code -1} if no
* such index exists.
*/
public static int indexOf(long[] array, long target) {
return indexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int indexOf(long[] array, long target, int start, int end) {
for (int i = start; i < end; i++) {
if (array[i] == target) {
return i;
}
}
return -1;
}
/**
* Returns the start position of the first occurrence of the specified {@code target} within
* {@code array}, or {@code -1} if there is no such occurrence.
*
* <p>More formally, returns the lowest index {@code i} such that {@code Arrays.copyOfRange(array,
* i, i + target.length)} contains exactly the same elements as {@code target}.
*
* @param array the array to search for the sequence {@code target}
* @param target the array to search for as a sub-sequence of {@code array}
*/
public static int indexOf(long[] array, long[] target) {
checkNotNull(array, "array");
checkNotNull(target, "target");
if (target.length == 0) {
return 0;
}
outer:
for (int i = 0; i < array.length - target.length + 1; i++) {
for (int j = 0; j < target.length; j++) {
if (array[i + j] != target[j]) {
continue outer;
}
}
return i;
}
return -1;
}
/**
* Returns the index of the last appearance of the value {@code target} in {@code array}.
*
* @param array an array of {@code long} values, possibly empty
* @param target a primitive {@code long} value
* @return the greatest index {@code i} for which {@code array[i] == target}, or {@code -1} if no
* such index exists.
*/
public static int lastIndexOf(long[] array, long target) {
return lastIndexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int lastIndexOf(long[] array, long target, int start, int end) {
for (int i = end - 1; i >= start; i--) {
if (array[i] == target) {
return i;
}
}
return -1;
}
/**
* Returns the least value present in {@code array}.
*
* @param array a <i>nonempty</i> array of {@code long} values
* @return the value present in {@code array} that is less than or equal to every other value in
* the array
* @throws IllegalArgumentException if {@code array} is empty
*/
public static long min(long... array) {
checkArgument(array.length > 0);
long min = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] < min) {
min = array[i];
}
}
return min;
}
/**
* Returns the greatest value present in {@code array}.
*
* @param array a <i>nonempty</i> array of {@code long} values
* @return the value present in {@code array} that is greater than or equal to every other value
* in the array
* @throws IllegalArgumentException if {@code array} is empty
*/
public static long max(long... array) {
checkArgument(array.length > 0);
long max = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
/**
* Returns the value nearest to {@code value} which is within the closed range {@code [min..max]}.
*
* <p>If {@code value} is within the range {@code [min..max]}, {@code value} is returned
* unchanged. If {@code value} is less than {@code min}, {@code min} is returned, and if {@code
* value} is greater than {@code max}, {@code max} is returned.
*
* @param value the {@code long} value to constrain
* @param min the lower bound (inclusive) of the range to constrain {@code value} to
* @param max the upper bound (inclusive) of the range to constrain {@code value} to
* @throws IllegalArgumentException if {@code min > max}
* @since 21.0
*/
public static long constrainToRange(long value, long min, long max) {
checkArgument(min <= max, "min (%s) must be less than or equal to max (%s)", min, max);
return Math.min(Math.max(value, min), max);
}
/**
* Returns the values from each provided array combined into a single array. For example, {@code
* concat(new long[] {a, b}, new long[] {}, new long[] {c}} returns the array {@code {a, b, c}}.
*
* @param arrays zero or more {@code long} arrays
* @return a single array containing all the values from the source arrays, in order
* @throws IllegalArgumentException if the total number of elements in {@code arrays} does not fit
* in an {@code int}
*/
public static long[] concat(long[]... arrays) {
long length = 0;
for (long[] array : arrays) {
length += array.length;
}
long[] result = new long[checkNoOverflow(length)];
int pos = 0;
for (long[] array : arrays) {
System.arraycopy(array, 0, result, pos, array.length);
pos += array.length;
}
return result;
}
private static int checkNoOverflow(long result) {
checkArgument(
result == (int) result,
"the total number of elements (%s) in the arrays must fit in an int",
result);
return (int) result;
}
/**
* Returns a big-endian representation of {@code value} in an 8-element byte array; equivalent to
* {@code ByteBuffer.allocate(8).putLong(value).array()}. For example, the input value {@code
* 0x1213141516171819L} would yield the byte array {@code {0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
* 0x18, 0x19}}.
*
* <p>If you need to convert and concatenate several values (possibly even of different types),
* use a shared {@link java.nio.ByteBuffer} instance, or use {@link
* com.google.common.io.ByteStreams#newDataOutput()} to get a growable buffer.
*/
public static byte[] toByteArray(long value) {
// Note that this code needs to stay compatible with GWT, which has known
// bugs when narrowing byte casts of long values occur.
byte[] result = new byte[8];
for (int i = 7; i >= 0; i--) {
result[i] = (byte) (value & 0xffL);
value >>= 8;
}
return result;
}
/**
* Returns the {@code long} value whose big-endian representation is stored in the first 8 bytes
* of {@code bytes}; equivalent to {@code ByteBuffer.wrap(bytes).getLong()}. For example, the
* input byte array {@code {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19}} would yield the
* {@code long} value {@code 0x1213141516171819L}.
*
* <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that library exposes much more
* flexibility at little cost in readability.
*
* @throws IllegalArgumentException if {@code bytes} has fewer than 8 elements
*/
public static long fromByteArray(byte[] bytes) {
checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES);
return fromBytes(
bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7]);
}
/**
* Returns the {@code long} value whose byte representation is the given 8 bytes, in big-endian
* order; equivalent to {@code Longs.fromByteArray(new byte[] {b1, b2, b3, b4, b5, b6, b7, b8})}.
*
* @since 7.0
*/
public static long fromBytes(
byte b1, byte b2, byte b3, byte b4, byte b5, byte b6, byte b7, byte b8) {
return (b1 & 0xFFL) << 56
| (b2 & 0xFFL) << 48
| (b3 & 0xFFL) << 40
| (b4 & 0xFFL) << 32
| (b5 & 0xFFL) << 24
| (b6 & 0xFFL) << 16
| (b7 & 0xFFL) << 8
| (b8 & 0xFFL);
}
/*
* Moving asciiDigits into this static holder class lets ProGuard eliminate and inline the Longs
* class.
*/
static final class AsciiDigits {
private AsciiDigits() {}
private static final byte[] asciiDigits;
static {
byte[] result = new byte[128];
Arrays.fill(result, (byte) -1);
for (int i = 0; i < 10; i++) {
result['0' + i] = (byte) i;
}
for (int i = 0; i < 26; i++) {
result['A' + i] = (byte) (10 + i);
result['a' + i] = (byte) (10 + i);
}
asciiDigits = result;
}
static int digit(char c) {
return (c < 128) ? asciiDigits[c] : -1;
}
}
/**
* Parses the specified string as a signed decimal long value. The ASCII character {@code '-'} (
* <code>'\u002D'</code>) is recognized as the minus sign.
*
* <p>Unlike {@link Long#parseLong(String)}, this method returns {@code null} instead of throwing
* an exception if parsing fails. Additionally, this method only accepts ASCII digits, and returns
* {@code null} if non-ASCII digits are present in the string.
*
* <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even under JDK 7, despite
* the change to {@link Long#parseLong(String)} for that version.
*
* @param string the string representation of a long value
* @return the long value represented by {@code string}, or {@code null} if {@code string} has a
* length of zero or cannot be parsed as a long value
* @throws NullPointerException if {@code string} is {@code null}
* @since 14.0
*/
@CheckForNull
public static Long tryParse(String string) {
return tryParse(string, 10);
}
/**
* Parses the specified string as a signed long value using the specified radix. The ASCII
* character {@code '-'} (<code>'\u002D'</code>) is recognized as the minus sign.
*
* <p>Unlike {@link Long#parseLong(String, int)}, this method returns {@code null} instead of
* throwing an exception if parsing fails. Additionally, this method only accepts ASCII digits,
* and returns {@code null} if non-ASCII digits are present in the string.
*
* <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even under JDK 7, despite
* the change to {@link Long#parseLong(String, int)} for that version.
*
* @param string the string representation of a long value
* @param radix the radix to use when parsing
* @return the long value represented by {@code string} using {@code radix}, or {@code null} if
* {@code string} has a length of zero or cannot be parsed as a long value
* @throws IllegalArgumentException if {@code radix < Character.MIN_RADIX} or {@code radix >
* Character.MAX_RADIX}
* @throws NullPointerException if {@code string} is {@code null}
* @since 19.0
*/
@CheckForNull
public static Long tryParse(String string, int radix) {
if (checkNotNull(string).isEmpty()) {
return null;
}
if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
throw new IllegalArgumentException(
"radix must be between MIN_RADIX and MAX_RADIX but was " + radix);
}
boolean negative = string.charAt(0) == '-';
int index = negative ? 1 : 0;
if (index == string.length()) {
return null;
}
int digit = AsciiDigits.digit(string.charAt(index++));
if (digit < 0 || digit >= radix) {
return null;
}
long accum = -digit;
long cap = Long.MIN_VALUE / radix;
while (index < string.length()) {
digit = AsciiDigits.digit(string.charAt(index++));
if (digit < 0 || digit >= radix || accum < cap) {
return null;
}
accum *= radix;
if (accum < Long.MIN_VALUE + digit) {
return null;
}
accum -= digit;
}
if (negative) {
return accum;
} else if (accum == Long.MIN_VALUE) {
return null;
} else {
return -accum;
}
}
private static final class LongConverter extends Converter<String, Long> implements Serializable {
static final Converter<String, Long> INSTANCE = new LongConverter();
@Override
protected Long doForward(String value) {
return Long.decode(value);
}
@Override
protected String doBackward(Long value) {
return value.toString();
}
@Override
public String toString() {
return "Longs.stringConverter()";
}
private Object readResolve() {
return INSTANCE;
}
private static final long serialVersionUID = 1;
}
/**
* Returns a serializable converter object that converts between strings and longs using {@link
* Long#decode} and {@link Long#toString()}. The returned converter throws {@link
* NumberFormatException} if the input string is invalid.
*
* <p><b>Warning:</b> please see {@link Long#decode} to understand exactly how strings are parsed.
* For example, the string {@code "0123"} is treated as <i>octal</i> and converted to the value
* {@code 83L}.
*
* @since 16.0
*/
public static Converter<String, Long> stringConverter() {
return LongConverter.INSTANCE;
}
/**
* Returns an array containing the same values as {@code array}, but guaranteed to be of a
* specified minimum length. If {@code array} already has a length of at least {@code minLength},
* it is returned directly. Otherwise, a new array of size {@code minLength + padding} is
* returned, containing the values of {@code array}, and zeroes in the remaining places.
*
* @param array the source array
* @param minLength the minimum length the returned array must guarantee
* @param padding an extra amount to "grow" the array by if growth is necessary
* @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative
* @return an array containing the values of {@code array}, with guaranteed minimum length {@code
* minLength}
*/
public static long[] ensureCapacity(long[] array, int minLength, int padding) {
checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
checkArgument(padding >= 0, "Invalid padding: %s", padding);
return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array;
}
/**
* Returns a string containing the supplied {@code long} values separated by {@code separator}.
* For example, {@code join("-", 1L, 2L, 3L)} returns the string {@code "1-2-3"}.
*
* @param separator the text that should appear between consecutive values in the resulting string
* (but not at the start or end)
* @param array an array of {@code long} values, possibly empty
*/
public static String join(String separator, long... array) {
checkNotNull(separator);
if (array.length == 0) {
return "";
}
// For pre-sizing a builder, just get the right order of magnitude
StringBuilder builder = new StringBuilder(array.length * 10);
builder.append(array[0]);
for (int i = 1; i < array.length; i++) {
builder.append(separator).append(array[i]);
}
return builder.toString();
}
/**
* Returns a comparator that compares two {@code long} arrays <a
* href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>. That is, it
* compares, using {@link #compare(long, long)}), the first pair of values that follow any common
* prefix, or when one array is a prefix of the other, treats the shorter array as the lesser. For
* example, {@code [] < [1L] < [1L, 2L] < [2L]}.
*
* <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays
* support only identity equality), but it is consistent with {@link Arrays#equals(long[],
* long[])}.
*
* @since 2.0
*/
public static Comparator<long[]> lexicographicalComparator() {
return LexicographicalComparator.INSTANCE;
}
private enum LexicographicalComparator implements Comparator<long[]> {
INSTANCE;
@Override
public int compare(long[] left, long[] right) {
int minLength = Math.min(left.length, right.length);
for (int i = 0; i < minLength; i++) {
int result = Longs.compare(left[i], right[i]);
if (result != 0) {
return result;
}
}
return left.length - right.length;
}
@Override
public String toString() {
return "Longs.lexicographicalComparator()";
}
}
/**
* Sorts the elements of {@code array} in descending order.
*
* @since 23.1
*/
public static void sortDescending(long[] array) {
checkNotNull(array);
sortDescending(array, 0, array.length);
}
/**
* Sorts the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex}
* exclusive in descending order.
*
* @since 23.1
*/
public static void sortDescending(long[] array, int fromIndex, int toIndex) {
checkNotNull(array);
checkPositionIndexes(fromIndex, toIndex, array.length);
Arrays.sort(array, fromIndex, toIndex);
reverse(array, fromIndex, toIndex);
}
/**
* Reverses the elements of {@code array}. This is equivalent to {@code
* Collections.reverse(Longs.asList(array))}, but is likely to be more efficient.
*
* @since 23.1
*/
public static void reverse(long[] array) {
checkNotNull(array);
reverse(array, 0, array.length);
}
/**
* Reverses the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex}
* exclusive. This is equivalent to {@code
* Collections.reverse(Longs.asList(array).subList(fromIndex, toIndex))}, but is likely to be more
* efficient.
*
* @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
* {@code toIndex > fromIndex}
* @since 23.1
*/
public static void reverse(long[] array, int fromIndex, int toIndex) {
checkNotNull(array);
checkPositionIndexes(fromIndex, toIndex, array.length);
for (int i = fromIndex, j = toIndex - 1; i < j; i++, j--) {
long tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
}
/**
* Performs a right rotation of {@code array} of "distance" places, so that the first element is
* moved to index "distance", and the element at index {@code i} ends up at index {@code (distance
* + i) mod array.length}. This is equivalent to {@code Collections.rotate(Longs.asList(array),
* distance)}, but is considerably faster and avoids allocation and garbage collection.
*
* <p>The provided "distance" may be negative, which will rotate left.
*
* @since 32.0.0
*/
public static void rotate(long[] array, int distance) {
rotate(array, distance, 0, array.length);
}
/**
* Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code
* toIndex} exclusive. This is equivalent to {@code
* Collections.rotate(Longs.asList(array).subList(fromIndex, toIndex), distance)}, but is
* considerably faster and avoids allocations and garbage collection.
*
* <p>The provided "distance" may be negative, which will rotate left.
*
* @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
* {@code toIndex > fromIndex}
* @since 32.0.0
*/
public static void rotate(long[] array, int distance, int fromIndex, int toIndex) {
// See Ints.rotate for more details about possible algorithms here.
checkNotNull(array);
checkPositionIndexes(fromIndex, toIndex, array.length);
if (array.length <= 1) {
return;
}
int length = toIndex - fromIndex;
// Obtain m = (-distance mod length), a non-negative value less than "length". This is how many
// places left to rotate.
int m = -distance % length;
m = (m < 0) ? m + length : m;
// The current index of what will become the first element of the rotated section.
int newFirstIndex = m + fromIndex;
if (newFirstIndex == fromIndex) {
return;
}
reverse(array, fromIndex, newFirstIndex);
reverse(array, newFirstIndex, toIndex);
reverse(array, fromIndex, toIndex);
}
/**
* Returns an array containing each value of {@code collection}, converted to a {@code long} value
* in the manner of {@link Number#longValue}.
*
* <p>Elements are copied from the argument collection as if by {@code collection.toArray()}.
* Calling this method is as thread-safe as calling that method.
*
* @param collection a collection of {@code Number} instances
* @return an array containing the same values as {@code collection}, in the same order, converted
* to primitives
* @throws NullPointerException if {@code collection} or any of its elements is null
* @since 1.0 (parameter was {@code Collection<Long>} before 12.0)
*/
public static long[] toArray(Collection<? extends Number> collection) {
if (collection instanceof LongArrayAsList) {
return ((LongArrayAsList) collection).toLongArray();
}
Object[] boxedArray = collection.toArray();
int len = boxedArray.length;
long[] array = new long[len];
for (int i = 0; i < len; i++) {
// checkNotNull for GWT (do not optimize)
array[i] = ((Number) checkNotNull(boxedArray[i])).longValue();
}
return array;
}
/**
* Returns a fixed-size list backed by the specified array, similar to {@link
* Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to
* set a value to {@code null} will result in a {@link NullPointerException}.
*
* <p>The returned list maintains the values, but not the identities, of {@code Long} objects
* written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for
* the returned list is unspecified.
*
* <p>The returned list is serializable.
*
* <p><b>Note:</b> when possible, you should represent your data as an {@link ImmutableLongArray}
* instead, which has an {@link ImmutableLongArray#asList asList} view.
*
* @param backingArray the array to back the list
* @return a list view of the array
*/
public static List<Long> asList(long... backingArray) {
if (backingArray.length == 0) {
return Collections.emptyList();
}
return new LongArrayAsList(backingArray);
}
@GwtCompatible
private static class LongArrayAsList extends AbstractList<Long>
implements RandomAccess, Serializable {
final long[] array;
final int start;
final int end;
LongArrayAsList(long[] array) {
this(array, 0, array.length);
}
LongArrayAsList(long[] array, int start, int end) {
this.array = array;
this.start = start;
this.end = end;
}
@Override
public int size() {
return end - start;
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public Long get(int index) {
checkElementIndex(index, size());
return array[start + index];
}
@Override
public Spliterator.OfLong spliterator() {
return Spliterators.spliterator(array, start, end, 0);
}
@Override
public boolean contains(@CheckForNull Object target) {
// Overridden to prevent a ton of boxing
return (target instanceof Long) && Longs.indexOf(array, (Long) target, start, end) != -1;
}
@Override
public int indexOf(@CheckForNull Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Long) {
int i = Longs.indexOf(array, (Long) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override
public int lastIndexOf(@CheckForNull Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Long) {
int i = Longs.lastIndexOf(array, (Long) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override
public Long set(int index, Long element) {
checkElementIndex(index, size());
long oldValue = array[start + index];
// checkNotNull for GWT (do not optimize)
array[start + index] = checkNotNull(element);
return oldValue;
}
@Override
public List<Long> subList(int fromIndex, int toIndex) {
int size = size();
checkPositionIndexes(fromIndex, toIndex, size);
if (fromIndex == toIndex) {
return Collections.emptyList();
}
return new LongArrayAsList(array, start + fromIndex, start + toIndex);
}
@Override
public boolean equals(@CheckForNull Object object) {
if (object == this) {
return true;
}
if (object instanceof LongArrayAsList) {
LongArrayAsList that = (LongArrayAsList) object;
int size = size();
if (that.size() != size) {
return false;
}
for (int i = 0; i < size; i++) {
if (array[start + i] != that.array[that.start + i]) {
return false;
}
}
return true;
}
return super.equals(object);
}
@Override
public int hashCode() {
int result = 1;
for (int i = start; i < end; i++) {
result = 31 * result + Longs.hashCode(array[i]);
}
return result;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder(size() * 10);
builder.append('[').append(array[start]);
for (int i = start + 1; i < end; i++) {
builder.append(", ").append(array[i]);
}
return builder.append(']').toString();
}
long[] toLongArray() {
return Arrays.copyOfRange(array, start, end);
}
private static final long serialVersionUID = 0;
}
}
| google/guava | guava/src/com/google/common/primitives/Longs.java |
44,436 | /*
* Copyright (C) 2008 The Guava Authors
*
* 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.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.base.Supplier;
import com.google.common.collect.Table.Cell;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.Spliterator;
import java.util.function.BinaryOperator;
import java.util.stream.Collector;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Provides static methods that involve a {@code Table}.
*
* <p>See the Guava User Guide article on <a href=
* "https://github.com/google/guava/wiki/CollectionUtilitiesExplained#tables">{@code Tables}</a>.
*
* @author Jared Levy
* @author Louis Wasserman
* @since 7.0
*/
@GwtCompatible
@ElementTypesAreNonnullByDefault
public final class Tables {
private Tables() {}
/**
* Returns a {@link Collector} that accumulates elements into a {@code Table} created using the
* specified supplier, whose cells are generated by applying the provided mapping functions to the
* input elements. Cells are inserted into the generated {@code Table} in encounter order.
*
* <p>If multiple input elements map to the same row and column, an {@code IllegalStateException}
* is thrown when the collection operation is performed.
*
* <p>To collect to an {@link ImmutableTable}, use {@link ImmutableTable#toImmutableTable}.
*
* @since 21.0
*/
public static <
T extends @Nullable Object,
R extends @Nullable Object,
C extends @Nullable Object,
V,
I extends Table<R, C, V>>
Collector<T, ?, I> toTable(
java.util.function.Function<? super T, ? extends R> rowFunction,
java.util.function.Function<? super T, ? extends C> columnFunction,
java.util.function.Function<? super T, ? extends V> valueFunction,
java.util.function.Supplier<I> tableSupplier) {
return TableCollectors.<T, R, C, V, I>toTable(
rowFunction, columnFunction, valueFunction, tableSupplier);
}
/**
* Returns a {@link Collector} that accumulates elements into a {@code Table} created using the
* specified supplier, whose cells are generated by applying the provided mapping functions to the
* input elements. Cells are inserted into the generated {@code Table} in encounter order.
*
* <p>If multiple input elements map to the same row and column, the specified merging function is
* used to combine the values. Like {@link
* java.util.stream.Collectors#toMap(java.util.function.Function, java.util.function.Function,
* BinaryOperator, java.util.function.Supplier)}, this Collector throws a {@code
* NullPointerException} on null values returned from {@code valueFunction}, and treats nulls
* returned from {@code mergeFunction} as removals of that row/column pair.
*
* @since 21.0
*/
public static <
T extends @Nullable Object,
R extends @Nullable Object,
C extends @Nullable Object,
V,
I extends Table<R, C, V>>
Collector<T, ?, I> toTable(
java.util.function.Function<? super T, ? extends R> rowFunction,
java.util.function.Function<? super T, ? extends C> columnFunction,
java.util.function.Function<? super T, ? extends V> valueFunction,
BinaryOperator<V> mergeFunction,
java.util.function.Supplier<I> tableSupplier) {
return TableCollectors.<T, R, C, V, I>toTable(
rowFunction, columnFunction, valueFunction, mergeFunction, tableSupplier);
}
/**
* Returns an immutable cell with the specified row key, column key, and value.
*
* <p>The returned cell is serializable.
*
* @param rowKey the row key to be associated with the returned cell
* @param columnKey the column key to be associated with the returned cell
* @param value the value to be associated with the returned cell
*/
public static <R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object>
Cell<R, C, V> immutableCell(
@ParametricNullness R rowKey,
@ParametricNullness C columnKey,
@ParametricNullness V value) {
return new ImmutableCell<>(rowKey, columnKey, value);
}
static final class ImmutableCell<
R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object>
extends AbstractCell<R, C, V> implements Serializable {
@ParametricNullness private final R rowKey;
@ParametricNullness private final C columnKey;
@ParametricNullness private final V value;
ImmutableCell(
@ParametricNullness R rowKey,
@ParametricNullness C columnKey,
@ParametricNullness V value) {
this.rowKey = rowKey;
this.columnKey = columnKey;
this.value = value;
}
@Override
@ParametricNullness
public R getRowKey() {
return rowKey;
}
@Override
@ParametricNullness
public C getColumnKey() {
return columnKey;
}
@Override
@ParametricNullness
public V getValue() {
return value;
}
private static final long serialVersionUID = 0;
}
abstract static class AbstractCell<
R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object>
implements Cell<R, C, V> {
// needed for serialization
AbstractCell() {}
@Override
public boolean equals(@CheckForNull Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof Cell) {
Cell<?, ?, ?> other = (Cell<?, ?, ?>) obj;
return Objects.equal(getRowKey(), other.getRowKey())
&& Objects.equal(getColumnKey(), other.getColumnKey())
&& Objects.equal(getValue(), other.getValue());
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(getRowKey(), getColumnKey(), getValue());
}
@Override
public String toString() {
return "(" + getRowKey() + "," + getColumnKey() + ")=" + getValue();
}
}
/**
* Creates a transposed view of a given table that flips its row and column keys. In other words,
* calling {@code get(columnKey, rowKey)} on the generated table always returns the same value as
* calling {@code get(rowKey, columnKey)} on the original table. Updating the original table
* changes the contents of the transposed table and vice versa.
*
* <p>The returned table supports update operations as long as the input table supports the
* analogous operation with swapped rows and columns. For example, in a {@link HashBasedTable}
* instance, {@code rowKeySet().iterator()} supports {@code remove()} but {@code
* columnKeySet().iterator()} doesn't. With a transposed {@link HashBasedTable}, it's the other
* way around.
*/
public static <R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object>
Table<C, R, V> transpose(Table<R, C, V> table) {
return (table instanceof TransposeTable)
? ((TransposeTable<R, C, V>) table).original
: new TransposeTable<C, R, V>(table);
}
private static class TransposeTable<
C extends @Nullable Object, R extends @Nullable Object, V extends @Nullable Object>
extends AbstractTable<C, R, V> {
final Table<R, C, V> original;
TransposeTable(Table<R, C, V> original) {
this.original = checkNotNull(original);
}
@Override
public void clear() {
original.clear();
}
@Override
public Map<C, V> column(@ParametricNullness R columnKey) {
return original.row(columnKey);
}
@Override
public Set<R> columnKeySet() {
return original.rowKeySet();
}
@Override
public Map<R, Map<C, V>> columnMap() {
return original.rowMap();
}
@Override
public boolean contains(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
return original.contains(columnKey, rowKey);
}
@Override
public boolean containsColumn(@CheckForNull Object columnKey) {
return original.containsRow(columnKey);
}
@Override
public boolean containsRow(@CheckForNull Object rowKey) {
return original.containsColumn(rowKey);
}
@Override
public boolean containsValue(@CheckForNull Object value) {
return original.containsValue(value);
}
@Override
@CheckForNull
public V get(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
return original.get(columnKey, rowKey);
}
@Override
@CheckForNull
public V put(
@ParametricNullness C rowKey,
@ParametricNullness R columnKey,
@ParametricNullness V value) {
return original.put(columnKey, rowKey, value);
}
@Override
public void putAll(Table<? extends C, ? extends R, ? extends V> table) {
original.putAll(transpose(table));
}
@Override
@CheckForNull
public V remove(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
return original.remove(columnKey, rowKey);
}
@Override
public Map<R, V> row(@ParametricNullness C rowKey) {
return original.column(rowKey);
}
@Override
public Set<C> rowKeySet() {
return original.columnKeySet();
}
@Override
public Map<C, Map<R, V>> rowMap() {
return original.columnMap();
}
@Override
public int size() {
return original.size();
}
@Override
public Collection<V> values() {
return original.values();
}
@Override
Iterator<Cell<C, R, V>> cellIterator() {
return Iterators.transform(original.cellSet().iterator(), Tables::transposeCell);
}
@Override
Spliterator<Cell<C, R, V>> cellSpliterator() {
return CollectSpliterators.map(original.cellSet().spliterator(), Tables::transposeCell);
}
}
private static <
R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object>
Cell<C, R, V> transposeCell(Cell<R, C, V> cell) {
return immutableCell(cell.getColumnKey(), cell.getRowKey(), cell.getValue());
}
/**
* Creates a table that uses the specified backing map and factory. It can generate a table based
* on arbitrary {@link Map} classes.
*
* <p>The {@code factory}-generated and {@code backingMap} classes determine the table iteration
* order. However, the table's {@code row()} method returns instances of a different class than
* {@code factory.get()} does.
*
* <p>Call this method only when the simpler factory methods in classes like {@link
* HashBasedTable} and {@link TreeBasedTable} won't suffice.
*
* <p>The views returned by the {@code Table} methods {@link Table#column}, {@link
* Table#columnKeySet}, and {@link Table#columnMap} have iterators that don't support {@code
* remove()}. Otherwise, all optional operations are supported. Null row keys, columns keys, and
* values are not supported.
*
* <p>Lookups by row key are often faster than lookups by column key, because the data is stored
* in a {@code Map<R, Map<C, V>>}. A method call like {@code column(columnKey).get(rowKey)} still
* runs quickly, since the row key is provided. However, {@code column(columnKey).size()} takes
* longer, since an iteration across all row keys occurs.
*
* <p>Note that this implementation is not synchronized. If multiple threads access this table
* concurrently and one of the threads modifies the table, it must be synchronized externally.
*
* <p>The table is serializable if {@code backingMap}, {@code factory}, the maps generated by
* {@code factory}, and the table contents are all serializable.
*
* <p>Note: the table assumes complete ownership over of {@code backingMap} and the maps returned
* by {@code factory}. Those objects should not be manually updated and they should not use soft,
* weak, or phantom references.
*
* @param backingMap place to store the mapping from each row key to its corresponding column key
* / value map
* @param factory supplier of new, empty maps that will each hold all column key / value mappings
* for a given row key
* @throws IllegalArgumentException if {@code backingMap} is not empty
* @since 10.0
*/
public static <R, C, V> Table<R, C, V> newCustomTable(
Map<R, Map<C, V>> backingMap, Supplier<? extends Map<C, V>> factory) {
checkArgument(backingMap.isEmpty());
checkNotNull(factory);
// TODO(jlevy): Wrap factory to validate that the supplied maps are empty?
return new StandardTable<>(backingMap, factory);
}
/**
* Returns a view of a table where each value is transformed by a function. All other properties
* of the table, such as iteration order, are left intact.
*
* <p>Changes in the underlying table are reflected in this view. Conversely, this view supports
* removal operations, and these are reflected in the underlying table.
*
* <p>It's acceptable for the underlying table to contain null keys, and even null values provided
* that the function is capable of accepting null input. The transformed table might contain null
* values, if the function sometimes gives a null result.
*
* <p>The returned table is not thread-safe or serializable, even if the underlying table is.
*
* <p>The function is applied lazily, invoked when needed. This is necessary for the returned
* table to be a view, but it means that the function will be applied many times for bulk
* operations like {@link Table#containsValue} and {@code Table.toString()}. For this to perform
* well, {@code function} should be fast. To avoid lazy evaluation when the returned table doesn't
* need to be a view, copy the returned table into a new table of your choosing.
*
* @since 10.0
*/
public static <
R extends @Nullable Object,
C extends @Nullable Object,
V1 extends @Nullable Object,
V2 extends @Nullable Object>
Table<R, C, V2> transformValues(
Table<R, C, V1> fromTable, Function<? super V1, V2> function) {
return new TransformedTable<>(fromTable, function);
}
private static class TransformedTable<
R extends @Nullable Object,
C extends @Nullable Object,
V1 extends @Nullable Object,
V2 extends @Nullable Object>
extends AbstractTable<R, C, V2> {
final Table<R, C, V1> fromTable;
final Function<? super V1, V2> function;
TransformedTable(Table<R, C, V1> fromTable, Function<? super V1, V2> function) {
this.fromTable = checkNotNull(fromTable);
this.function = checkNotNull(function);
}
@Override
public boolean contains(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
return fromTable.contains(rowKey, columnKey);
}
@Override
@CheckForNull
public V2 get(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
// The function is passed a null input only when the table contains a null
// value.
// The cast is safe because of the contains() check.
return contains(rowKey, columnKey)
? function.apply(uncheckedCastNullableTToT(fromTable.get(rowKey, columnKey)))
: null;
}
@Override
public int size() {
return fromTable.size();
}
@Override
public void clear() {
fromTable.clear();
}
@Override
@CheckForNull
public V2 put(
@ParametricNullness R rowKey,
@ParametricNullness C columnKey,
@ParametricNullness V2 value) {
throw new UnsupportedOperationException();
}
@Override
public void putAll(Table<? extends R, ? extends C, ? extends V2> table) {
throw new UnsupportedOperationException();
}
@Override
@CheckForNull
public V2 remove(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
return contains(rowKey, columnKey)
// The cast is safe because of the contains() check.
? function.apply(uncheckedCastNullableTToT(fromTable.remove(rowKey, columnKey)))
: null;
}
@Override
public Map<C, V2> row(@ParametricNullness R rowKey) {
return Maps.transformValues(fromTable.row(rowKey), function);
}
@Override
public Map<R, V2> column(@ParametricNullness C columnKey) {
return Maps.transformValues(fromTable.column(columnKey), function);
}
Function<Cell<R, C, V1>, Cell<R, C, V2>> cellFunction() {
return new Function<Cell<R, C, V1>, Cell<R, C, V2>>() {
@Override
public Cell<R, C, V2> apply(Cell<R, C, V1> cell) {
return immutableCell(
cell.getRowKey(), cell.getColumnKey(), function.apply(cell.getValue()));
}
};
}
@Override
Iterator<Cell<R, C, V2>> cellIterator() {
return Iterators.transform(fromTable.cellSet().iterator(), cellFunction());
}
@Override
Spliterator<Cell<R, C, V2>> cellSpliterator() {
return CollectSpliterators.map(fromTable.cellSet().spliterator(), cellFunction());
}
@Override
public Set<R> rowKeySet() {
return fromTable.rowKeySet();
}
@Override
public Set<C> columnKeySet() {
return fromTable.columnKeySet();
}
@Override
Collection<V2> createValues() {
return Collections2.transform(fromTable.values(), function);
}
@Override
public Map<R, Map<C, V2>> rowMap() {
Function<Map<C, V1>, Map<C, V2>> rowFunction =
new Function<Map<C, V1>, Map<C, V2>>() {
@Override
public Map<C, V2> apply(Map<C, V1> row) {
return Maps.transformValues(row, function);
}
};
return Maps.transformValues(fromTable.rowMap(), rowFunction);
}
@Override
public Map<C, Map<R, V2>> columnMap() {
Function<Map<R, V1>, Map<R, V2>> columnFunction =
new Function<Map<R, V1>, Map<R, V2>>() {
@Override
public Map<R, V2> apply(Map<R, V1> column) {
return Maps.transformValues(column, function);
}
};
return Maps.transformValues(fromTable.columnMap(), columnFunction);
}
}
/**
* Returns an unmodifiable view of the specified table. This method allows modules to provide
* users with "read-only" access to internal tables. Query operations on the returned table "read
* through" to the specified table, and attempts to modify the returned table, whether direct or
* via its collection views, result in an {@code UnsupportedOperationException}.
*
* <p>The returned table will be serializable if the specified table is serializable.
*
* <p>Consider using an {@link ImmutableTable}, which is guaranteed never to change.
*
* @since 11.0
*/
public static <R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object>
Table<R, C, V> unmodifiableTable(Table<? extends R, ? extends C, ? extends V> table) {
return new UnmodifiableTable<>(table);
}
private static class UnmodifiableTable<
R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object>
extends ForwardingTable<R, C, V> implements Serializable {
final Table<? extends R, ? extends C, ? extends V> delegate;
UnmodifiableTable(Table<? extends R, ? extends C, ? extends V> delegate) {
this.delegate = checkNotNull(delegate);
}
@SuppressWarnings("unchecked") // safe, covariant cast
@Override
protected Table<R, C, V> delegate() {
return (Table<R, C, V>) delegate;
}
@Override
public Set<Cell<R, C, V>> cellSet() {
return Collections.unmodifiableSet(super.cellSet());
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
@Override
public Map<R, V> column(@ParametricNullness C columnKey) {
return Collections.unmodifiableMap(super.column(columnKey));
}
@Override
public Set<C> columnKeySet() {
return Collections.unmodifiableSet(super.columnKeySet());
}
@Override
public Map<C, Map<R, V>> columnMap() {
Function<Map<R, V>, Map<R, V>> wrapper = unmodifiableWrapper();
return Collections.unmodifiableMap(Maps.transformValues(super.columnMap(), wrapper));
}
@Override
@CheckForNull
public V put(
@ParametricNullness R rowKey,
@ParametricNullness C columnKey,
@ParametricNullness V value) {
throw new UnsupportedOperationException();
}
@Override
public void putAll(Table<? extends R, ? extends C, ? extends V> table) {
throw new UnsupportedOperationException();
}
@Override
@CheckForNull
public V remove(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
throw new UnsupportedOperationException();
}
@Override
public Map<C, V> row(@ParametricNullness R rowKey) {
return Collections.unmodifiableMap(super.row(rowKey));
}
@Override
public Set<R> rowKeySet() {
return Collections.unmodifiableSet(super.rowKeySet());
}
@Override
public Map<R, Map<C, V>> rowMap() {
Function<Map<C, V>, Map<C, V>> wrapper = unmodifiableWrapper();
return Collections.unmodifiableMap(Maps.transformValues(super.rowMap(), wrapper));
}
@Override
public Collection<V> values() {
return Collections.unmodifiableCollection(super.values());
}
private static final long serialVersionUID = 0;
}
/**
* Returns an unmodifiable view of the specified row-sorted table. This method allows modules to
* provide users with "read-only" access to internal tables. Query operations on the returned
* table "read through" to the specified table, and attempts to modify the returned table, whether
* direct or via its collection views, result in an {@code UnsupportedOperationException}.
*
* <p>The returned table will be serializable if the specified table is serializable.
*
* @param table the row-sorted table for which an unmodifiable view is to be returned
* @return an unmodifiable view of the specified table
* @since 11.0
*/
public static <R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object>
RowSortedTable<R, C, V> unmodifiableRowSortedTable(
RowSortedTable<R, ? extends C, ? extends V> table) {
/*
* It's not ? extends R, because it's technically not covariant in R. Specifically,
* table.rowMap().comparator() could return a comparator that only works for the ? extends R.
* Collections.unmodifiableSortedMap makes the same distinction.
*/
return new UnmodifiableRowSortedMap<>(table);
}
private static final class UnmodifiableRowSortedMap<
R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object>
extends UnmodifiableTable<R, C, V> implements RowSortedTable<R, C, V> {
public UnmodifiableRowSortedMap(RowSortedTable<R, ? extends C, ? extends V> delegate) {
super(delegate);
}
@Override
protected RowSortedTable<R, C, V> delegate() {
return (RowSortedTable<R, C, V>) super.delegate();
}
@Override
public SortedMap<R, Map<C, V>> rowMap() {
Function<Map<C, V>, Map<C, V>> wrapper = unmodifiableWrapper();
return Collections.unmodifiableSortedMap(Maps.transformValues(delegate().rowMap(), wrapper));
}
@Override
public SortedSet<R> rowKeySet() {
return Collections.unmodifiableSortedSet(delegate().rowKeySet());
}
private static final long serialVersionUID = 0;
}
@SuppressWarnings("unchecked")
private static <K extends @Nullable Object, V extends @Nullable Object>
Function<Map<K, V>, Map<K, V>> unmodifiableWrapper() {
return (Function) UNMODIFIABLE_WRAPPER;
}
private static final Function<? extends Map<?, ?>, ? extends Map<?, ?>> UNMODIFIABLE_WRAPPER =
new Function<Map<Object, Object>, Map<Object, Object>>() {
@Override
public Map<Object, Object> apply(Map<Object, Object> input) {
return Collections.unmodifiableMap(input);
}
};
/**
* Returns a synchronized (thread-safe) table backed by the specified table. In order to guarantee
* serial access, it is critical that <b>all</b> access to the backing table is accomplished
* through the returned table.
*
* <p>It is imperative that the user manually synchronize on the returned table when accessing any
* of its collection views:
*
* <pre>{@code
* Table<R, C, V> table = Tables.synchronizedTable(HashBasedTable.<R, C, V>create());
* ...
* Map<C, V> row = table.row(rowKey); // Needn't be in synchronized block
* ...
* synchronized (table) { // Synchronizing on table, not row!
* Iterator<Entry<C, V>> i = row.entrySet().iterator(); // Must be in synchronized block
* while (i.hasNext()) {
* foo(i.next());
* }
* }
* }</pre>
*
* <p>Failure to follow this advice may result in non-deterministic behavior.
*
* <p>The returned table will be serializable if the specified table is serializable.
*
* @param table the table to be wrapped in a synchronized view
* @return a synchronized view of the specified table
* @since 22.0
*/
public static <R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object>
Table<R, C, V> synchronizedTable(Table<R, C, V> table) {
return Synchronized.table(table, null);
}
static boolean equalsImpl(Table<?, ?, ?> table, @CheckForNull Object obj) {
if (obj == table) {
return true;
} else if (obj instanceof Table) {
Table<?, ?, ?> that = (Table<?, ?, ?>) obj;
return table.cellSet().equals(that.cellSet());
} else {
return false;
}
}
}
| google/guava | guava/src/com/google/common/collect/Tables.java |
44,437 | /*
* Copyright (C) 2010 The Guava Authors
*
* 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.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.RandomAccess;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Static methods pertaining to sorted {@link List} instances.
*
* <p>In this documentation, the terms <i>greatest</i>, <i>greater</i>, <i>least</i>, and
* <i>lesser</i> are considered to refer to the comparator on the elements, and the terms
* <i>first</i> and <i>last</i> are considered to refer to the elements' ordering in a list.
*
* @author Louis Wasserman
*/
@GwtCompatible
@ElementTypesAreNonnullByDefault
final class SortedLists {
private SortedLists() {}
/**
* A specification for which index to return if the list contains at least one element that
* compares as equal to the key.
*/
enum KeyPresentBehavior {
/**
* Return the index of any list element that compares as equal to the key. No guarantees are
* made as to which index is returned, if more than one element compares as equal to the key.
*/
ANY_PRESENT {
@Override
<E extends @Nullable Object> int resultIndex(
Comparator<? super E> comparator,
@ParametricNullness E key,
List<? extends E> list,
int foundIndex) {
return foundIndex;
}
},
/** Return the index of the last list element that compares as equal to the key. */
LAST_PRESENT {
@Override
<E extends @Nullable Object> int resultIndex(
Comparator<? super E> comparator,
@ParametricNullness E key,
List<? extends E> list,
int foundIndex) {
// Of course, we have to use binary search to find the precise
// breakpoint...
int lower = foundIndex;
int upper = list.size() - 1;
// Everything between lower and upper inclusive compares at >= 0.
while (lower < upper) {
int middle = (lower + upper + 1) >>> 1;
int c = comparator.compare(list.get(middle), key);
if (c > 0) {
upper = middle - 1;
} else { // c == 0
lower = middle;
}
}
return lower;
}
},
/** Return the index of the first list element that compares as equal to the key. */
FIRST_PRESENT {
@Override
<E extends @Nullable Object> int resultIndex(
Comparator<? super E> comparator,
@ParametricNullness E key,
List<? extends E> list,
int foundIndex) {
// Of course, we have to use binary search to find the precise
// breakpoint...
int lower = 0;
int upper = foundIndex;
// Of course, we have to use binary search to find the precise breakpoint...
// Everything between lower and upper inclusive compares at <= 0.
while (lower < upper) {
int middle = (lower + upper) >>> 1;
int c = comparator.compare(list.get(middle), key);
if (c < 0) {
lower = middle + 1;
} else { // c == 0
upper = middle;
}
}
return lower;
}
},
/**
* Return the index of the first list element that compares as greater than the key, or {@code
* list.size()} if there is no such element.
*/
FIRST_AFTER {
@Override
public <E extends @Nullable Object> int resultIndex(
Comparator<? super E> comparator,
@ParametricNullness E key,
List<? extends E> list,
int foundIndex) {
return LAST_PRESENT.resultIndex(comparator, key, list, foundIndex) + 1;
}
},
/**
* Return the index of the last list element that compares as less than the key, or {@code -1}
* if there is no such element.
*/
LAST_BEFORE {
@Override
public <E extends @Nullable Object> int resultIndex(
Comparator<? super E> comparator,
@ParametricNullness E key,
List<? extends E> list,
int foundIndex) {
return FIRST_PRESENT.resultIndex(comparator, key, list, foundIndex) - 1;
}
};
abstract <E extends @Nullable Object> int resultIndex(
Comparator<? super E> comparator,
@ParametricNullness E key,
List<? extends E> list,
int foundIndex);
}
/**
* A specification for which index to return if the list contains no elements that compare as
* equal to the key.
*/
enum KeyAbsentBehavior {
/**
* Return the index of the next lower element in the list, or {@code -1} if there is no such
* element.
*/
NEXT_LOWER {
@Override
int resultIndex(int higherIndex) {
return higherIndex - 1;
}
},
/**
* Return the index of the next higher element in the list, or {@code list.size()} if there is
* no such element.
*/
NEXT_HIGHER {
@Override
public int resultIndex(int higherIndex) {
return higherIndex;
}
},
/**
* Return {@code ~insertionIndex}, where {@code insertionIndex} is defined as the point at which
* the key would be inserted into the list: the index of the next higher element in the list, or
* {@code list.size()} if there is no such element.
*
* <p>Note that the return value will be {@code >= 0} if and only if there is an element of the
* list that compares as equal to the key.
*
* <p>This is equivalent to the behavior of {@link java.util.Collections#binarySearch(List,
* Object)} when the key isn't present, since {@code ~insertionIndex} is equal to {@code -1 -
* insertionIndex}.
*/
INVERTED_INSERTION_INDEX {
@Override
public int resultIndex(int higherIndex) {
return ~higherIndex;
}
};
abstract int resultIndex(int higherIndex);
}
/**
* Searches the specified naturally ordered list for the specified object using the binary search
* algorithm.
*
* <p>Equivalent to {@link #binarySearch(List, Function, Object, Comparator, KeyPresentBehavior,
* KeyAbsentBehavior)} using {@link Ordering#natural}.
*/
@SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989
public static <E extends Comparable> int binarySearch(
List<? extends E> list,
E e,
KeyPresentBehavior presentBehavior,
KeyAbsentBehavior absentBehavior) {
checkNotNull(e);
return binarySearch(list, e, Ordering.natural(), presentBehavior, absentBehavior);
}
/**
* Binary searches the list for the specified key, using the specified key function.
*
* <p>Equivalent to {@link #binarySearch(List, Function, Object, Comparator, KeyPresentBehavior,
* KeyAbsentBehavior)} using {@link Ordering#natural}.
*/
@SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989
public static <E extends @Nullable Object, K extends Comparable> int binarySearch(
List<E> list,
Function<? super E, K> keyFunction,
K key,
KeyPresentBehavior presentBehavior,
KeyAbsentBehavior absentBehavior) {
checkNotNull(key);
return binarySearch(
list, keyFunction, key, Ordering.natural(), presentBehavior, absentBehavior);
}
/**
* Binary searches the list for the specified key, using the specified key function.
*
* <p>Equivalent to {@link #binarySearch(List, Object, Comparator, KeyPresentBehavior,
* KeyAbsentBehavior)} using {@link Lists#transform(List, Function) Lists.transform(list,
* keyFunction)}.
*/
public static <E extends @Nullable Object, K extends @Nullable Object> int binarySearch(
List<E> list,
Function<? super E, K> keyFunction,
@ParametricNullness K key,
Comparator<? super K> keyComparator,
KeyPresentBehavior presentBehavior,
KeyAbsentBehavior absentBehavior) {
return binarySearch(
Lists.transform(list, keyFunction), key, keyComparator, presentBehavior, absentBehavior);
}
/**
* Searches the specified list for the specified object using the binary search algorithm. The
* list must be sorted into ascending order according to the specified comparator (as by the
* {@link Collections#sort(List, Comparator) Collections.sort(List, Comparator)} method), prior to
* making this call. If it is not sorted, the results are undefined.
*
* <p>If there are elements in the list which compare as equal to the key, the choice of {@link
* KeyPresentBehavior} decides which index is returned. If no elements compare as equal to the
* key, the choice of {@link KeyAbsentBehavior} decides which index is returned.
*
* <p>This method runs in log(n) time on random-access lists, which offer near-constant-time
* access to each list element.
*
* @param list the list to be searched.
* @param key the value to be searched for.
* @param comparator the comparator by which the list is ordered.
* @param presentBehavior the specification for what to do if at least one element of the list
* compares as equal to the key.
* @param absentBehavior the specification for what to do if no elements of the list compare as
* equal to the key.
* @return the index determined by the {@code KeyPresentBehavior}, if the key is in the list;
* otherwise the index determined by the {@code KeyAbsentBehavior}.
*/
public static <E extends @Nullable Object> int binarySearch(
List<? extends E> list,
@ParametricNullness E key,
Comparator<? super E> comparator,
KeyPresentBehavior presentBehavior,
KeyAbsentBehavior absentBehavior) {
checkNotNull(comparator);
checkNotNull(list);
checkNotNull(presentBehavior);
checkNotNull(absentBehavior);
if (!(list instanceof RandomAccess)) {
list = Lists.newArrayList(list);
}
// TODO(lowasser): benchmark when it's best to do a linear search
int lower = 0;
int upper = list.size() - 1;
while (lower <= upper) {
int middle = (lower + upper) >>> 1;
int c = comparator.compare(key, list.get(middle));
if (c < 0) {
upper = middle - 1;
} else if (c > 0) {
lower = middle + 1;
} else {
return lower
+ presentBehavior.resultIndex(
comparator, key, list.subList(lower, upper + 1), middle - lower);
}
}
return absentBehavior.resultIndex(lower);
}
}
| google/guava | android/guava/src/com/google/common/collect/SortedLists.java |
44,438 | /*
* Copyright (C) 2008 The Guava Authors
*
* 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.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Equivalence;
import com.google.common.base.Predicate;
import com.google.errorprone.annotations.Immutable;
import java.io.Serializable;
import java.util.Comparator;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.SortedSet;
import javax.annotation.CheckForNull;
/**
* A range (or "interval") defines the <i>boundaries</i> around a contiguous span of values of some
* {@code Comparable} type; for example, "integers from 1 to 100 inclusive." Note that it is not
* possible to <i>iterate</i> over these contained values. To do so, pass this range instance and an
* appropriate {@link DiscreteDomain} to {@link ContiguousSet#create}.
*
* <h3>Types of ranges</h3>
*
* <p>Each end of the range may be bounded or unbounded. If bounded, there is an associated
* <i>endpoint</i> value, and the range is considered to be either <i>open</i> (does not include the
* endpoint) or <i>closed</i> (includes the endpoint) on that side. With three possibilities on each
* side, this yields nine basic types of ranges, enumerated below. (Notation: a square bracket
* ({@code [ ]}) indicates that the range is closed on that side; a parenthesis ({@code ( )}) means
* it is either open or unbounded. The construct {@code {x | statement}} is read "the set of all
* <i>x</i> such that <i>statement</i>.")
*
* <blockquote>
*
* <table>
* <caption>Range Types</caption>
* <tr><th>Notation <th>Definition <th>Factory method
* <tr><td>{@code (a..b)} <td>{@code {x | a < x < b}} <td>{@link Range#open open}
* <tr><td>{@code [a..b]} <td>{@code {x | a <= x <= b}}<td>{@link Range#closed closed}
* <tr><td>{@code (a..b]} <td>{@code {x | a < x <= b}} <td>{@link Range#openClosed openClosed}
* <tr><td>{@code [a..b)} <td>{@code {x | a <= x < b}} <td>{@link Range#closedOpen closedOpen}
* <tr><td>{@code (a..+∞)} <td>{@code {x | x > a}} <td>{@link Range#greaterThan greaterThan}
* <tr><td>{@code [a..+∞)} <td>{@code {x | x >= a}} <td>{@link Range#atLeast atLeast}
* <tr><td>{@code (-∞..b)} <td>{@code {x | x < b}} <td>{@link Range#lessThan lessThan}
* <tr><td>{@code (-∞..b]} <td>{@code {x | x <= b}} <td>{@link Range#atMost atMost}
* <tr><td>{@code (-∞..+∞)}<td>{@code {x}} <td>{@link Range#all all}
* </table>
*
* </blockquote>
*
* <p>When both endpoints exist, the upper endpoint may not be less than the lower. The endpoints
* may be equal only if at least one of the bounds is closed:
*
* <ul>
* <li>{@code [a..a]} : a singleton range
* <li>{@code [a..a); (a..a]} : {@linkplain #isEmpty empty} ranges; also valid
* <li>{@code (a..a)} : <b>invalid</b>; an exception will be thrown
* </ul>
*
* <h3>Warnings</h3>
*
* <ul>
* <li>Use immutable value types only, if at all possible. If you must use a mutable type, <b>do
* not</b> allow the endpoint instances to mutate after the range is created!
* <li>Your value type's comparison method should be {@linkplain Comparable consistent with
* equals} if at all possible. Otherwise, be aware that concepts used throughout this
* documentation such as "equal", "same", "unique" and so on actually refer to whether {@link
* Comparable#compareTo compareTo} returns zero, not whether {@link Object#equals equals}
* returns {@code true}.
* <li>A class which implements {@code Comparable<UnrelatedType>} is very broken, and will cause
* undefined horrible things to happen in {@code Range}. For now, the Range API does not
* prevent its use, because this would also rule out all ungenerified (pre-JDK1.5) data types.
* <b>This may change in the future.</b>
* </ul>
*
* <h3>Other notes</h3>
*
* <ul>
* <li>All ranges are shallow-immutable.
* <li>Instances of this type are obtained using the static factory methods in this class.
* <li>Ranges are <i>convex</i>: whenever two values are contained, all values in between them
* must also be contained. More formally, for any {@code c1 <= c2 <= c3} of type {@code C},
* {@code r.contains(c1) && r.contains(c3)} implies {@code r.contains(c2)}). This means that a
* {@code Range<Integer>} can never be used to represent, say, "all <i>prime</i> numbers from
* 1 to 100."
* <li>When evaluated as a {@link Predicate}, a range yields the same result as invoking {@link
* #contains}.
* <li>Terminology note: a range {@code a} is said to be the <i>maximal</i> range having property
* <i>P</i> if, for all ranges {@code b} also having property <i>P</i>, {@code a.encloses(b)}.
* Likewise, {@code a} is <i>minimal</i> when {@code b.encloses(a)} for all {@code b} having
* property <i>P</i>. See, for example, the definition of {@link #intersection intersection}.
* <li>A {@code Range} is serializable if it has no bounds, or if each bound is serializable.
* </ul>
*
* <h3>Further reading</h3>
*
* <p>See the Guava User Guide article on <a
* href="https://github.com/google/guava/wiki/RangesExplained">{@code Range}</a>.
*
* @author Kevin Bourrillion
* @author Gregory Kick
* @since 10.0
*/
@GwtCompatible
@SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989
@Immutable(containerOf = "C")
@ElementTypesAreNonnullByDefault
public final class Range<C extends Comparable> extends RangeGwtSerializationDependencies
implements Predicate<C>, Serializable {
@SuppressWarnings("unchecked")
static <C extends Comparable<?>> Ordering<Range<C>> rangeLexOrdering() {
return (Ordering<Range<C>>) RangeLexOrdering.INSTANCE;
}
static <C extends Comparable<?>> Range<C> create(Cut<C> lowerBound, Cut<C> upperBound) {
return new Range<>(lowerBound, upperBound);
}
/**
* Returns a range that contains all values strictly greater than {@code lower} and strictly less
* than {@code upper}.
*
* @throws IllegalArgumentException if {@code lower} is greater than <i>or equal to</i> {@code
* upper}
* @throws ClassCastException if {@code lower} and {@code upper} are not mutually comparable
* @since 14.0
*/
public static <C extends Comparable<?>> Range<C> open(C lower, C upper) {
return create(Cut.aboveValue(lower), Cut.belowValue(upper));
}
/**
* Returns a range that contains all values greater than or equal to {@code lower} and less than
* or equal to {@code upper}.
*
* @throws IllegalArgumentException if {@code lower} is greater than {@code upper}
* @throws ClassCastException if {@code lower} and {@code upper} are not mutually comparable
* @since 14.0
*/
public static <C extends Comparable<?>> Range<C> closed(C lower, C upper) {
return create(Cut.belowValue(lower), Cut.aboveValue(upper));
}
/**
* Returns a range that contains all values greater than or equal to {@code lower} and strictly
* less than {@code upper}.
*
* @throws IllegalArgumentException if {@code lower} is greater than {@code upper}
* @throws ClassCastException if {@code lower} and {@code upper} are not mutually comparable
* @since 14.0
*/
public static <C extends Comparable<?>> Range<C> closedOpen(C lower, C upper) {
return create(Cut.belowValue(lower), Cut.belowValue(upper));
}
/**
* Returns a range that contains all values strictly greater than {@code lower} and less than or
* equal to {@code upper}.
*
* @throws IllegalArgumentException if {@code lower} is greater than {@code upper}
* @throws ClassCastException if {@code lower} and {@code upper} are not mutually comparable
* @since 14.0
*/
public static <C extends Comparable<?>> Range<C> openClosed(C lower, C upper) {
return create(Cut.aboveValue(lower), Cut.aboveValue(upper));
}
/**
* Returns a range that contains any value from {@code lower} to {@code upper}, where each
* endpoint may be either inclusive (closed) or exclusive (open).
*
* @throws IllegalArgumentException if {@code lower} is greater than {@code upper}
* @throws ClassCastException if {@code lower} and {@code upper} are not mutually comparable
* @since 14.0
*/
public static <C extends Comparable<?>> Range<C> range(
C lower, BoundType lowerType, C upper, BoundType upperType) {
checkNotNull(lowerType);
checkNotNull(upperType);
Cut<C> lowerBound =
(lowerType == BoundType.OPEN) ? Cut.aboveValue(lower) : Cut.belowValue(lower);
Cut<C> upperBound =
(upperType == BoundType.OPEN) ? Cut.belowValue(upper) : Cut.aboveValue(upper);
return create(lowerBound, upperBound);
}
/**
* Returns a range that contains all values strictly less than {@code endpoint}.
*
* @since 14.0
*/
public static <C extends Comparable<?>> Range<C> lessThan(C endpoint) {
return create(Cut.<C>belowAll(), Cut.belowValue(endpoint));
}
/**
* Returns a range that contains all values less than or equal to {@code endpoint}.
*
* @since 14.0
*/
public static <C extends Comparable<?>> Range<C> atMost(C endpoint) {
return create(Cut.<C>belowAll(), Cut.aboveValue(endpoint));
}
/**
* Returns a range with no lower bound up to the given endpoint, which may be either inclusive
* (closed) or exclusive (open).
*
* @since 14.0
*/
public static <C extends Comparable<?>> Range<C> upTo(C endpoint, BoundType boundType) {
switch (boundType) {
case OPEN:
return lessThan(endpoint);
case CLOSED:
return atMost(endpoint);
default:
throw new AssertionError();
}
}
/**
* Returns a range that contains all values strictly greater than {@code endpoint}.
*
* @since 14.0
*/
public static <C extends Comparable<?>> Range<C> greaterThan(C endpoint) {
return create(Cut.aboveValue(endpoint), Cut.<C>aboveAll());
}
/**
* Returns a range that contains all values greater than or equal to {@code endpoint}.
*
* @since 14.0
*/
public static <C extends Comparable<?>> Range<C> atLeast(C endpoint) {
return create(Cut.belowValue(endpoint), Cut.<C>aboveAll());
}
/**
* Returns a range from the given endpoint, which may be either inclusive (closed) or exclusive
* (open), with no upper bound.
*
* @since 14.0
*/
public static <C extends Comparable<?>> Range<C> downTo(C endpoint, BoundType boundType) {
switch (boundType) {
case OPEN:
return greaterThan(endpoint);
case CLOSED:
return atLeast(endpoint);
default:
throw new AssertionError();
}
}
private static final Range<Comparable> ALL = new Range<>(Cut.belowAll(), Cut.aboveAll());
/**
* Returns a range that contains every value of type {@code C}.
*
* @since 14.0
*/
@SuppressWarnings("unchecked")
public static <C extends Comparable<?>> Range<C> all() {
return (Range) ALL;
}
/**
* Returns a range that {@linkplain Range#contains(Comparable) contains} only the given value. The
* returned range is {@linkplain BoundType#CLOSED closed} on both ends.
*
* @since 14.0
*/
public static <C extends Comparable<?>> Range<C> singleton(C value) {
return closed(value, value);
}
/**
* Returns the minimal range that {@linkplain Range#contains(Comparable) contains} all of the
* given values. The returned range is {@linkplain BoundType#CLOSED closed} on both ends.
*
* @throws ClassCastException if the values are not mutually comparable
* @throws NoSuchElementException if {@code values} is empty
* @throws NullPointerException if any of {@code values} is null
* @since 14.0
*/
public static <C extends Comparable<?>> Range<C> encloseAll(Iterable<C> values) {
checkNotNull(values);
if (values instanceof SortedSet) {
SortedSet<C> set = (SortedSet<C>) values;
Comparator<?> comparator = set.comparator();
if (Ordering.<C>natural().equals(comparator) || comparator == null) {
return closed(set.first(), set.last());
}
}
Iterator<C> valueIterator = values.iterator();
C min = checkNotNull(valueIterator.next());
C max = min;
while (valueIterator.hasNext()) {
C value = checkNotNull(valueIterator.next());
min = Ordering.<C>natural().min(min, value);
max = Ordering.<C>natural().max(max, value);
}
return closed(min, max);
}
final Cut<C> lowerBound;
final Cut<C> upperBound;
private Range(Cut<C> lowerBound, Cut<C> upperBound) {
this.lowerBound = checkNotNull(lowerBound);
this.upperBound = checkNotNull(upperBound);
if (lowerBound.compareTo(upperBound) > 0
|| lowerBound == Cut.<C>aboveAll()
|| upperBound == Cut.<C>belowAll()) {
throw new IllegalArgumentException("Invalid range: " + toString(lowerBound, upperBound));
}
}
/** Returns {@code true} if this range has a lower endpoint. */
public boolean hasLowerBound() {
return lowerBound != Cut.belowAll();
}
/**
* Returns the lower endpoint of this range.
*
* @throws IllegalStateException if this range is unbounded below (that is, {@link
* #hasLowerBound()} returns {@code false})
*/
public C lowerEndpoint() {
return lowerBound.endpoint();
}
/**
* Returns the type of this range's lower bound: {@link BoundType#CLOSED} if the range includes
* its lower endpoint, {@link BoundType#OPEN} if it does not.
*
* @throws IllegalStateException if this range is unbounded below (that is, {@link
* #hasLowerBound()} returns {@code false})
*/
public BoundType lowerBoundType() {
return lowerBound.typeAsLowerBound();
}
/** Returns {@code true} if this range has an upper endpoint. */
public boolean hasUpperBound() {
return upperBound != Cut.aboveAll();
}
/**
* Returns the upper endpoint of this range.
*
* @throws IllegalStateException if this range is unbounded above (that is, {@link
* #hasUpperBound()} returns {@code false})
*/
public C upperEndpoint() {
return upperBound.endpoint();
}
/**
* Returns the type of this range's upper bound: {@link BoundType#CLOSED} if the range includes
* its upper endpoint, {@link BoundType#OPEN} if it does not.
*
* @throws IllegalStateException if this range is unbounded above (that is, {@link
* #hasUpperBound()} returns {@code false})
*/
public BoundType upperBoundType() {
return upperBound.typeAsUpperBound();
}
/**
* Returns {@code true} if this range is of the form {@code [v..v)} or {@code (v..v]}. (This does
* not encompass ranges of the form {@code (v..v)}, because such ranges are <i>invalid</i> and
* can't be constructed at all.)
*
* <p>Note that certain discrete ranges such as the integer range {@code (3..4)} are <b>not</b>
* considered empty, even though they contain no actual values. In these cases, it may be helpful
* to preprocess ranges with {@link #canonical(DiscreteDomain)}.
*/
public boolean isEmpty() {
return lowerBound.equals(upperBound);
}
/**
* Returns {@code true} if {@code value} is within the bounds of this range. For example, on the
* range {@code [0..2)}, {@code contains(1)} returns {@code true}, while {@code contains(2)}
* returns {@code false}.
*/
public boolean contains(C value) {
checkNotNull(value);
// let this throw CCE if there is some trickery going on
return lowerBound.isLessThan(value) && !upperBound.isLessThan(value);
}
/**
* @deprecated Provided only to satisfy the {@link Predicate} interface; use {@link #contains}
* instead.
*/
@Deprecated
@Override
public boolean apply(C input) {
return contains(input);
}
/**
* Returns {@code true} if every element in {@code values} is {@linkplain #contains contained} in
* this range.
*/
public boolean containsAll(Iterable<? extends C> values) {
if (Iterables.isEmpty(values)) {
return true;
}
// this optimizes testing equality of two range-backed sets
if (values instanceof SortedSet) {
SortedSet<? extends C> set = (SortedSet<? extends C>) values;
Comparator<?> comparator = set.comparator();
if (Ordering.natural().equals(comparator) || comparator == null) {
return contains(set.first()) && contains(set.last());
}
}
for (C value : values) {
if (!contains(value)) {
return false;
}
}
return true;
}
/**
* Returns {@code true} if the bounds of {@code other} do not extend outside the bounds of this
* range. Examples:
*
* <ul>
* <li>{@code [3..6]} encloses {@code [4..5]}
* <li>{@code (3..6)} encloses {@code (3..6)}
* <li>{@code [3..6]} encloses {@code [4..4)} (even though the latter is empty)
* <li>{@code (3..6]} does not enclose {@code [3..6]}
* <li>{@code [4..5]} does not enclose {@code (3..6)} (even though it contains every value
* contained by the latter range)
* <li>{@code [3..6]} does not enclose {@code (1..1]} (even though it contains every value
* contained by the latter range)
* </ul>
*
* <p>Note that if {@code a.encloses(b)}, then {@code b.contains(v)} implies {@code
* a.contains(v)}, but as the last two examples illustrate, the converse is not always true.
*
* <p>Being reflexive, antisymmetric and transitive, the {@code encloses} relation defines a
* <i>partial order</i> over ranges. There exists a unique {@linkplain Range#all maximal} range
* according to this relation, and also numerous {@linkplain #isEmpty minimal} ranges. Enclosure
* also implies {@linkplain #isConnected connectedness}.
*/
public boolean encloses(Range<C> other) {
return lowerBound.compareTo(other.lowerBound) <= 0
&& upperBound.compareTo(other.upperBound) >= 0;
}
/**
* Returns {@code true} if there exists a (possibly empty) range which is {@linkplain #encloses
* enclosed} by both this range and {@code other}.
*
* <p>For example,
*
* <ul>
* <li>{@code [2, 4)} and {@code [5, 7)} are not connected
* <li>{@code [2, 4)} and {@code [3, 5)} are connected, because both enclose {@code [3, 4)}
* <li>{@code [2, 4)} and {@code [4, 6)} are connected, because both enclose the empty range
* {@code [4, 4)}
* </ul>
*
* <p>Note that this range and {@code other} have a well-defined {@linkplain #span union} and
* {@linkplain #intersection intersection} (as a single, possibly-empty range) if and only if this
* method returns {@code true}.
*
* <p>The connectedness relation is both reflexive and symmetric, but does not form an {@linkplain
* Equivalence equivalence relation} as it is not transitive.
*
* <p>Note that certain discrete ranges are not considered connected, even though there are no
* elements "between them." For example, {@code [3, 5]} is not considered connected to {@code [6,
* 10]}. In these cases, it may be desirable for both input ranges to be preprocessed with {@link
* #canonical(DiscreteDomain)} before testing for connectedness.
*/
public boolean isConnected(Range<C> other) {
return lowerBound.compareTo(other.upperBound) <= 0
&& other.lowerBound.compareTo(upperBound) <= 0;
}
/**
* Returns the maximal range {@linkplain #encloses enclosed} by both this range and {@code
* connectedRange}, if such a range exists.
*
* <p>For example, the intersection of {@code [1..5]} and {@code (3..7)} is {@code (3..5]}. The
* resulting range may be empty; for example, {@code [1..5)} intersected with {@code [5..7)}
* yields the empty range {@code [5..5)}.
*
* <p>The intersection exists if and only if the two ranges are {@linkplain #isConnected
* connected}.
*
* <p>The intersection operation is commutative, associative and idempotent, and its identity
* element is {@link Range#all}).
*
* @throws IllegalArgumentException if {@code isConnected(connectedRange)} is {@code false}
*/
public Range<C> intersection(Range<C> connectedRange) {
int lowerCmp = lowerBound.compareTo(connectedRange.lowerBound);
int upperCmp = upperBound.compareTo(connectedRange.upperBound);
if (lowerCmp >= 0 && upperCmp <= 0) {
return this;
} else if (lowerCmp <= 0 && upperCmp >= 0) {
return connectedRange;
} else {
Cut<C> newLower = (lowerCmp >= 0) ? lowerBound : connectedRange.lowerBound;
Cut<C> newUpper = (upperCmp <= 0) ? upperBound : connectedRange.upperBound;
// create() would catch this, but give a confusing error message
checkArgument(
newLower.compareTo(newUpper) <= 0,
"intersection is undefined for disconnected ranges %s and %s",
this,
connectedRange);
// TODO(kevinb): all the precondition checks in the constructor are redundant...
return create(newLower, newUpper);
}
}
/**
* Returns the maximal range lying between this range and {@code otherRange}, if such a range
* exists. The resulting range may be empty if the two ranges are adjacent but non-overlapping.
*
* <p>For example, the gap of {@code [1..5]} and {@code (7..10)} is {@code (5..7]}. The resulting
* range may be empty; for example, the gap between {@code [1..5)} {@code [5..7)} yields the empty
* range {@code [5..5)}.
*
* <p>The gap exists if and only if the two ranges are either disconnected or immediately adjacent
* (any intersection must be an empty range).
*
* <p>The gap operation is commutative.
*
* @throws IllegalArgumentException if this range and {@code otherRange} have a nonempty
* intersection
* @since 27.0
*/
public Range<C> gap(Range<C> otherRange) {
/*
* For an explanation of the basic principle behind this check, see
* https://stackoverflow.com/a/35754308/28465
*
* In that explanation's notation, our `overlap` check would be `x1 < y2 && y1 < x2`. We've
* flipped one part of the check so that we're using "less than" in both cases (rather than a
* mix of "less than" and "greater than"). We've also switched to "strictly less than" rather
* than "less than or equal to" because of *handwave* the difference between "endpoints of
* inclusive ranges" and "Cuts."
*/
if (lowerBound.compareTo(otherRange.upperBound) < 0
&& otherRange.lowerBound.compareTo(upperBound) < 0) {
throw new IllegalArgumentException(
"Ranges have a nonempty intersection: " + this + ", " + otherRange);
}
boolean isThisFirst = this.lowerBound.compareTo(otherRange.lowerBound) < 0;
Range<C> firstRange = isThisFirst ? this : otherRange;
Range<C> secondRange = isThisFirst ? otherRange : this;
return create(firstRange.upperBound, secondRange.lowerBound);
}
/**
* Returns the minimal range that {@linkplain #encloses encloses} both this range and {@code
* other}. For example, the span of {@code [1..3]} and {@code (5..7)} is {@code [1..7)}.
*
* <p><i>If</i> the input ranges are {@linkplain #isConnected connected}, the returned range can
* also be called their <i>union</i>. If they are not, note that the span might contain values
* that are not contained in either input range.
*
* <p>Like {@link #intersection(Range) intersection}, this operation is commutative, associative
* and idempotent. Unlike it, it is always well-defined for any two input ranges.
*/
public Range<C> span(Range<C> other) {
int lowerCmp = lowerBound.compareTo(other.lowerBound);
int upperCmp = upperBound.compareTo(other.upperBound);
if (lowerCmp <= 0 && upperCmp >= 0) {
return this;
} else if (lowerCmp >= 0 && upperCmp <= 0) {
return other;
} else {
Cut<C> newLower = (lowerCmp <= 0) ? lowerBound : other.lowerBound;
Cut<C> newUpper = (upperCmp >= 0) ? upperBound : other.upperBound;
return create(newLower, newUpper);
}
}
/**
* Returns the canonical form of this range in the given domain. The canonical form has the
* following properties:
*
* <ul>
* <li>equivalence: {@code a.canonical().contains(v) == a.contains(v)} for all {@code v} (in
* other words, {@code ContiguousSet.create(a.canonical(domain), domain).equals(
* ContiguousSet.create(a, domain))}
* <li>uniqueness: unless {@code a.isEmpty()}, {@code ContiguousSet.create(a,
* domain).equals(ContiguousSet.create(b, domain))} implies {@code
* a.canonical(domain).equals(b.canonical(domain))}
* <li>idempotence: {@code a.canonical(domain).canonical(domain).equals(a.canonical(domain))}
* </ul>
*
* <p>Furthermore, this method guarantees that the range returned will be one of the following
* canonical forms:
*
* <ul>
* <li>[start..end)
* <li>[start..+∞)
* <li>(-∞..end) (only if type {@code C} is unbounded below)
* <li>(-∞..+∞) (only if type {@code C} is unbounded below)
* </ul>
*/
public Range<C> canonical(DiscreteDomain<C> domain) {
checkNotNull(domain);
Cut<C> lower = lowerBound.canonical(domain);
Cut<C> upper = upperBound.canonical(domain);
return (lower == lowerBound && upper == upperBound) ? this : create(lower, upper);
}
/**
* Returns {@code true} if {@code object} is a range having the same endpoints and bound types as
* this range. Note that discrete ranges such as {@code (1..4)} and {@code [2..3]} are <b>not</b>
* equal to one another, despite the fact that they each contain precisely the same set of values.
* Similarly, empty ranges are not equal unless they have exactly the same representation, so
* {@code [3..3)}, {@code (3..3]}, {@code (4..4]} are all unequal.
*/
@Override
public boolean equals(@CheckForNull Object object) {
if (object instanceof Range) {
Range<?> other = (Range<?>) object;
return lowerBound.equals(other.lowerBound) && upperBound.equals(other.upperBound);
}
return false;
}
/** Returns a hash code for this range. */
@Override
public int hashCode() {
return lowerBound.hashCode() * 31 + upperBound.hashCode();
}
/**
* Returns a string representation of this range, such as {@code "[3..5)"} (other examples are
* listed in the class documentation).
*/
@Override
public String toString() {
return toString(lowerBound, upperBound);
}
// We declare accessors so that we can use method references like `Range::lowerBound`.
Cut<C> lowerBound() {
return lowerBound;
}
Cut<C> upperBound() {
return upperBound;
}
private static String toString(Cut<?> lowerBound, Cut<?> upperBound) {
StringBuilder sb = new StringBuilder(16);
lowerBound.describeAsLowerBound(sb);
sb.append("..");
upperBound.describeAsUpperBound(sb);
return sb.toString();
}
Object readResolve() {
if (this.equals(ALL)) {
return all();
} else {
return this;
}
}
@SuppressWarnings("unchecked") // this method may throw CCE
static int compareOrThrow(Comparable left, Comparable right) {
return left.compareTo(right);
}
/** Needed to serialize sorted collections of Ranges. */
private static class RangeLexOrdering extends Ordering<Range<?>> implements Serializable {
static final Ordering<?> INSTANCE = new RangeLexOrdering();
@Override
public int compare(Range<?> left, Range<?> right) {
return ComparisonChain.start()
.compare(left.lowerBound, right.lowerBound)
.compare(left.upperBound, right.upperBound)
.result();
}
private static final long serialVersionUID = 0;
}
private static final long serialVersionUID = 0;
}
| google/guava | guava/src/com/google/common/collect/Range.java |
44,439 | /*
* Copyright (C) 2011 The Guava Authors
*
* 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.google.common.math;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.math.MathPreconditions.checkNoOverflow;
import static com.google.common.math.MathPreconditions.checkNonNegative;
import static com.google.common.math.MathPreconditions.checkPositive;
import static com.google.common.math.MathPreconditions.checkRoundingUnnecessary;
import static java.lang.Math.abs;
import static java.lang.Math.min;
import static java.math.RoundingMode.HALF_EVEN;
import static java.math.RoundingMode.HALF_UP;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.primitives.Ints;
import java.math.BigInteger;
import java.math.RoundingMode;
/**
* A class for arithmetic on values of type {@code int}. Where possible, methods are defined and
* named analogously to their {@code BigInteger} counterparts.
*
* <p>The implementations of many methods in this class are based on material from Henry S. Warren,
* Jr.'s <i>Hacker's Delight</i>, (Addison Wesley, 2002).
*
* <p>Similar functionality for {@code long} and for {@link BigInteger} can be found in {@link
* LongMath} and {@link BigIntegerMath} respectively. For other common operations on {@code int}
* values, see {@link com.google.common.primitives.Ints}.
*
* @author Louis Wasserman
* @since 11.0
*/
@GwtCompatible(emulated = true)
@ElementTypesAreNonnullByDefault
public final class IntMath {
// NOTE: Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, ||
@VisibleForTesting static final int MAX_SIGNED_POWER_OF_TWO = 1 << (Integer.SIZE - 2);
/**
* Returns the smallest power of two greater than or equal to {@code x}. This is equivalent to
* {@code checkedPow(2, log2(x, CEILING))}.
*
* @throws IllegalArgumentException if {@code x <= 0}
* @throws ArithmeticException of the next-higher power of two is not representable as an {@code
* int}, i.e. when {@code x > 2^30}
* @since 20.0
*/
public static int ceilingPowerOfTwo(int x) {
checkPositive("x", x);
if (x > MAX_SIGNED_POWER_OF_TWO) {
throw new ArithmeticException("ceilingPowerOfTwo(" + x + ") not representable as an int");
}
return 1 << -Integer.numberOfLeadingZeros(x - 1);
}
/**
* Returns the largest power of two less than or equal to {@code x}. This is equivalent to {@code
* checkedPow(2, log2(x, FLOOR))}.
*
* @throws IllegalArgumentException if {@code x <= 0}
* @since 20.0
*/
public static int floorPowerOfTwo(int x) {
checkPositive("x", x);
return Integer.highestOneBit(x);
}
/**
* Returns {@code true} if {@code x} represents a power of two.
*
* <p>This differs from {@code Integer.bitCount(x) == 1}, because {@code
* Integer.bitCount(Integer.MIN_VALUE) == 1}, but {@link Integer#MIN_VALUE} is not a power of two.
*/
public static boolean isPowerOfTwo(int x) {
return x > 0 & (x & (x - 1)) == 0;
}
/**
* Returns 1 if {@code x < y} as unsigned integers, and 0 otherwise. Assumes that x - y fits into
* a signed int. The implementation is branch-free, and benchmarks suggest it is measurably (if
* narrowly) faster than the straightforward ternary expression.
*/
@VisibleForTesting
static int lessThanBranchFree(int x, int y) {
// The double negation is optimized away by normal Java, but is necessary for GWT
// to make sure bit twiddling works as expected.
return ~~(x - y) >>> (Integer.SIZE - 1);
}
/**
* Returns the base-2 logarithm of {@code x}, rounded according to the specified rounding mode.
*
* @throws IllegalArgumentException if {@code x <= 0}
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
* is not a power of two
*/
@SuppressWarnings("fallthrough")
// TODO(kevinb): remove after this warning is disabled globally
public static int log2(int x, RoundingMode mode) {
checkPositive("x", x);
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(isPowerOfTwo(x));
// fall through
case DOWN:
case FLOOR:
return (Integer.SIZE - 1) - Integer.numberOfLeadingZeros(x);
case UP:
case CEILING:
return Integer.SIZE - Integer.numberOfLeadingZeros(x - 1);
case HALF_DOWN:
case HALF_UP:
case HALF_EVEN:
// Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5
int leadingZeros = Integer.numberOfLeadingZeros(x);
int cmp = MAX_POWER_OF_SQRT2_UNSIGNED >>> leadingZeros;
// floor(2^(logFloor + 0.5))
int logFloor = (Integer.SIZE - 1) - leadingZeros;
return logFloor + lessThanBranchFree(cmp, x);
default:
throw new AssertionError();
}
}
/** The biggest half power of two that can fit in an unsigned int. */
@VisibleForTesting static final int MAX_POWER_OF_SQRT2_UNSIGNED = 0xB504F333;
/**
* Returns the base-10 logarithm of {@code x}, rounded according to the specified rounding mode.
*
* @throws IllegalArgumentException if {@code x <= 0}
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
* is not a power of ten
*/
@GwtIncompatible // need BigIntegerMath to adequately test
@SuppressWarnings("fallthrough")
public static int log10(int x, RoundingMode mode) {
checkPositive("x", x);
int logFloor = log10Floor(x);
int floorPow = powersOf10[logFloor];
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(x == floorPow);
// fall through
case FLOOR:
case DOWN:
return logFloor;
case CEILING:
case UP:
return logFloor + lessThanBranchFree(floorPow, x);
case HALF_DOWN:
case HALF_UP:
case HALF_EVEN:
// sqrt(10) is irrational, so log10(x) - logFloor is never exactly 0.5
return logFloor + lessThanBranchFree(halfPowersOf10[logFloor], x);
default:
throw new AssertionError();
}
}
private static int log10Floor(int x) {
/*
* Based on Hacker's Delight Fig. 11-5, the two-table-lookup, branch-free implementation.
*
* The key idea is that based on the number of leading zeros (equivalently, floor(log2(x))), we
* can narrow the possible floor(log10(x)) values to two. For example, if floor(log2(x)) is 6,
* then 64 <= x < 128, so floor(log10(x)) is either 1 or 2.
*/
int y = maxLog10ForLeadingZeros[Integer.numberOfLeadingZeros(x)];
/*
* y is the higher of the two possible values of floor(log10(x)). If x < 10^y, then we want the
* lower of the two possible values, or y - 1, otherwise, we want y.
*/
return y - lessThanBranchFree(x, powersOf10[y]);
}
// maxLog10ForLeadingZeros[i] == floor(log10(2^(Long.SIZE - i)))
@VisibleForTesting
static final byte[] maxLog10ForLeadingZeros = {
9, 9, 9, 8, 8, 8, 7, 7, 7, 6, 6, 6, 6, 5, 5, 5, 4, 4, 4, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1, 0, 0, 0,
0
};
@VisibleForTesting
static final int[] powersOf10 = {
1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000
};
// halfPowersOf10[i] = largest int less than 10^(i + 0.5)
@VisibleForTesting
static final int[] halfPowersOf10 = {
3, 31, 316, 3162, 31622, 316227, 3162277, 31622776, 316227766, Integer.MAX_VALUE
};
/**
* Returns {@code b} to the {@code k}th power. Even if the result overflows, it will be equal to
* {@code BigInteger.valueOf(b).pow(k).intValue()}. This implementation runs in {@code O(log k)}
* time.
*
* <p>Compare {@link #checkedPow}, which throws an {@link ArithmeticException} upon overflow.
*
* @throws IllegalArgumentException if {@code k < 0}
*/
@GwtIncompatible // failing tests
public static int pow(int b, int k) {
checkNonNegative("exponent", k);
switch (b) {
case 0:
return (k == 0) ? 1 : 0;
case 1:
return 1;
case (-1):
return ((k & 1) == 0) ? 1 : -1;
case 2:
return (k < Integer.SIZE) ? (1 << k) : 0;
case (-2):
if (k < Integer.SIZE) {
return ((k & 1) == 0) ? (1 << k) : -(1 << k);
} else {
return 0;
}
default:
// continue below to handle the general case
}
for (int accum = 1; ; k >>= 1) {
switch (k) {
case 0:
return accum;
case 1:
return b * accum;
default:
accum *= ((k & 1) == 0) ? 1 : b;
b *= b;
}
}
}
/**
* Returns the square root of {@code x}, rounded with the specified rounding mode.
*
* @throws IllegalArgumentException if {@code x < 0}
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code
* sqrt(x)} is not an integer
*/
@GwtIncompatible // need BigIntegerMath to adequately test
@SuppressWarnings("fallthrough")
public static int sqrt(int x, RoundingMode mode) {
checkNonNegative("x", x);
int sqrtFloor = sqrtFloor(x);
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(sqrtFloor * sqrtFloor == x); // fall through
case FLOOR:
case DOWN:
return sqrtFloor;
case CEILING:
case UP:
return sqrtFloor + lessThanBranchFree(sqrtFloor * sqrtFloor, x);
case HALF_DOWN:
case HALF_UP:
case HALF_EVEN:
int halfSquare = sqrtFloor * sqrtFloor + sqrtFloor;
/*
* We wish to test whether or not x <= (sqrtFloor + 0.5)^2 = halfSquare + 0.25. Since both x
* and halfSquare are integers, this is equivalent to testing whether or not x <=
* halfSquare. (We have to deal with overflow, though.)
*
* If we treat halfSquare as an unsigned int, we know that
* sqrtFloor^2 <= x < (sqrtFloor + 1)^2
* halfSquare - sqrtFloor <= x < halfSquare + sqrtFloor + 1
* so |x - halfSquare| <= sqrtFloor. Therefore, it's safe to treat x - halfSquare as a
* signed int, so lessThanBranchFree is safe for use.
*/
return sqrtFloor + lessThanBranchFree(halfSquare, x);
default:
throw new AssertionError();
}
}
private static int sqrtFloor(int x) {
// There is no loss of precision in converting an int to a double, according to
// http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.2
return (int) Math.sqrt(x);
}
/**
* Returns the result of dividing {@code p} by {@code q}, rounding using the specified {@code
* RoundingMode}.
*
* @throws ArithmeticException if {@code q == 0}, or if {@code mode == UNNECESSARY} and {@code a}
* is not an integer multiple of {@code b}
*/
@SuppressWarnings("fallthrough")
public static int divide(int p, int q, RoundingMode mode) {
checkNotNull(mode);
if (q == 0) {
throw new ArithmeticException("/ by zero"); // for GWT
}
int div = p / q;
int rem = p - q * div; // equal to p % q
if (rem == 0) {
return div;
}
/*
* Normal Java division rounds towards 0, consistently with RoundingMode.DOWN. We just have to
* deal with the cases where rounding towards 0 is wrong, which typically depends on the sign of
* p / q.
*
* signum is 1 if p and q are both nonnegative or both negative, and -1 otherwise.
*/
int signum = 1 | ((p ^ q) >> (Integer.SIZE - 1));
boolean increment;
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(rem == 0);
// fall through
case DOWN:
increment = false;
break;
case UP:
increment = true;
break;
case CEILING:
increment = signum > 0;
break;
case FLOOR:
increment = signum < 0;
break;
case HALF_EVEN:
case HALF_DOWN:
case HALF_UP:
int absRem = abs(rem);
int cmpRemToHalfDivisor = absRem - (abs(q) - absRem);
// subtracting two nonnegative ints can't overflow
// cmpRemToHalfDivisor has the same sign as compare(abs(rem), abs(q) / 2).
if (cmpRemToHalfDivisor == 0) { // exactly on the half mark
increment = (mode == HALF_UP || (mode == HALF_EVEN & (div & 1) != 0));
} else {
increment = cmpRemToHalfDivisor > 0; // closer to the UP value
}
break;
default:
throw new AssertionError();
}
return increment ? div + signum : div;
}
/**
* Returns {@code x mod m}, a non-negative value less than {@code m}. This differs from {@code x %
* m}, which might be negative.
*
* <p>For example:
*
* <pre>{@code
* mod(7, 4) == 3
* mod(-7, 4) == 1
* mod(-1, 4) == 3
* mod(-8, 4) == 0
* mod(8, 4) == 0
* }</pre>
*
* @throws ArithmeticException if {@code m <= 0}
* @see <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17.3">
* Remainder Operator</a>
*/
public static int mod(int x, int m) {
if (m <= 0) {
throw new ArithmeticException("Modulus " + m + " must be > 0");
}
int result = x % m;
return (result >= 0) ? result : result + m;
}
/**
* Returns the greatest common divisor of {@code a, b}. Returns {@code 0} if {@code a == 0 && b ==
* 0}.
*
* @throws IllegalArgumentException if {@code a < 0} or {@code b < 0}
*/
public static int gcd(int a, int b) {
/*
* The reason we require both arguments to be >= 0 is because otherwise, what do you return on
* gcd(0, Integer.MIN_VALUE)? BigInteger.gcd would return positive 2^31, but positive 2^31 isn't
* an int.
*/
checkNonNegative("a", a);
checkNonNegative("b", b);
if (a == 0) {
// 0 % b == 0, so b divides a, but the converse doesn't hold.
// BigInteger.gcd is consistent with this decision.
return b;
} else if (b == 0) {
return a; // similar logic
}
/*
* Uses the binary GCD algorithm; see http://en.wikipedia.org/wiki/Binary_GCD_algorithm. This is
* >40% faster than the Euclidean algorithm in benchmarks.
*/
int aTwos = Integer.numberOfTrailingZeros(a);
a >>= aTwos; // divide out all 2s
int bTwos = Integer.numberOfTrailingZeros(b);
b >>= bTwos; // divide out all 2s
while (a != b) { // both a, b are odd
// The key to the binary GCD algorithm is as follows:
// Both a and b are odd. Assume a > b; then gcd(a - b, b) = gcd(a, b).
// But in gcd(a - b, b), a - b is even and b is odd, so we can divide out powers of two.
// We bend over backwards to avoid branching, adapting a technique from
// http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax
int delta = a - b; // can't overflow, since a and b are nonnegative
int minDeltaOrZero = delta & (delta >> (Integer.SIZE - 1));
// equivalent to Math.min(delta, 0)
a = delta - minDeltaOrZero - minDeltaOrZero; // sets a to Math.abs(a - b)
// a is now nonnegative and even
b += minDeltaOrZero; // sets b to min(old a, b)
a >>= Integer.numberOfTrailingZeros(a); // divide out all 2s, since 2 doesn't divide b
}
return a << min(aTwos, bTwos);
}
/**
* Returns the sum of {@code a} and {@code b}, provided it does not overflow.
*
* @throws ArithmeticException if {@code a + b} overflows in signed {@code int} arithmetic
*/
public static int checkedAdd(int a, int b) {
long result = (long) a + b;
checkNoOverflow(result == (int) result, "checkedAdd", a, b);
return (int) result;
}
/**
* Returns the difference of {@code a} and {@code b}, provided it does not overflow.
*
* @throws ArithmeticException if {@code a - b} overflows in signed {@code int} arithmetic
*/
public static int checkedSubtract(int a, int b) {
long result = (long) a - b;
checkNoOverflow(result == (int) result, "checkedSubtract", a, b);
return (int) result;
}
/**
* Returns the product of {@code a} and {@code b}, provided it does not overflow.
*
* @throws ArithmeticException if {@code a * b} overflows in signed {@code int} arithmetic
*/
public static int checkedMultiply(int a, int b) {
long result = (long) a * b;
checkNoOverflow(result == (int) result, "checkedMultiply", a, b);
return (int) result;
}
/**
* Returns the {@code b} to the {@code k}th power, provided it does not overflow.
*
* <p>{@link #pow} may be faster, but does not check for overflow.
*
* @throws ArithmeticException if {@code b} to the {@code k}th power overflows in signed {@code
* int} arithmetic
*/
public static int checkedPow(int b, int k) {
checkNonNegative("exponent", k);
switch (b) {
case 0:
return (k == 0) ? 1 : 0;
case 1:
return 1;
case (-1):
return ((k & 1) == 0) ? 1 : -1;
case 2:
checkNoOverflow(k < Integer.SIZE - 1, "checkedPow", b, k);
return 1 << k;
case (-2):
checkNoOverflow(k < Integer.SIZE, "checkedPow", b, k);
return ((k & 1) == 0) ? 1 << k : -1 << k;
default:
// continue below to handle the general case
}
int accum = 1;
while (true) {
switch (k) {
case 0:
return accum;
case 1:
return checkedMultiply(accum, b);
default:
if ((k & 1) != 0) {
accum = checkedMultiply(accum, b);
}
k >>= 1;
if (k > 0) {
checkNoOverflow(-FLOOR_SQRT_MAX_INT <= b & b <= FLOOR_SQRT_MAX_INT, "checkedPow", b, k);
b *= b;
}
}
}
}
/**
* Returns the sum of {@code a} and {@code b} unless it would overflow or underflow in which case
* {@code Integer.MAX_VALUE} or {@code Integer.MIN_VALUE} is returned, respectively.
*
* @since 20.0
*/
public static int saturatedAdd(int a, int b) {
return Ints.saturatedCast((long) a + b);
}
/**
* Returns the difference of {@code a} and {@code b} unless it would overflow or underflow in
* which case {@code Integer.MAX_VALUE} or {@code Integer.MIN_VALUE} is returned, respectively.
*
* @since 20.0
*/
public static int saturatedSubtract(int a, int b) {
return Ints.saturatedCast((long) a - b);
}
/**
* Returns the product of {@code a} and {@code b} unless it would overflow or underflow in which
* case {@code Integer.MAX_VALUE} or {@code Integer.MIN_VALUE} is returned, respectively.
*
* @since 20.0
*/
public static int saturatedMultiply(int a, int b) {
return Ints.saturatedCast((long) a * b);
}
/**
* Returns the {@code b} to the {@code k}th power, unless it would overflow or underflow in which
* case {@code Integer.MAX_VALUE} or {@code Integer.MIN_VALUE} is returned, respectively.
*
* @since 20.0
*/
public static int saturatedPow(int b, int k) {
checkNonNegative("exponent", k);
switch (b) {
case 0:
return (k == 0) ? 1 : 0;
case 1:
return 1;
case (-1):
return ((k & 1) == 0) ? 1 : -1;
case 2:
if (k >= Integer.SIZE - 1) {
return Integer.MAX_VALUE;
}
return 1 << k;
case (-2):
if (k >= Integer.SIZE) {
return Integer.MAX_VALUE + (k & 1);
}
return ((k & 1) == 0) ? 1 << k : -1 << k;
default:
// continue below to handle the general case
}
int accum = 1;
// if b is negative and k is odd then the limit is MIN otherwise the limit is MAX
int limit = Integer.MAX_VALUE + ((b >>> Integer.SIZE - 1) & (k & 1));
while (true) {
switch (k) {
case 0:
return accum;
case 1:
return saturatedMultiply(accum, b);
default:
if ((k & 1) != 0) {
accum = saturatedMultiply(accum, b);
}
k >>= 1;
if (k > 0) {
if (-FLOOR_SQRT_MAX_INT > b | b > FLOOR_SQRT_MAX_INT) {
return limit;
}
b *= b;
}
}
}
}
@VisibleForTesting static final int FLOOR_SQRT_MAX_INT = 46340;
/**
* Returns {@code n!}, that is, the product of the first {@code n} positive integers, {@code 1} if
* {@code n == 0}, or {@link Integer#MAX_VALUE} if the result does not fit in a {@code int}.
*
* @throws IllegalArgumentException if {@code n < 0}
*/
public static int factorial(int n) {
checkNonNegative("n", n);
return (n < factorials.length) ? factorials[n] : Integer.MAX_VALUE;
}
private static final int[] factorials = {
1,
1,
1 * 2,
1 * 2 * 3,
1 * 2 * 3 * 4,
1 * 2 * 3 * 4 * 5,
1 * 2 * 3 * 4 * 5 * 6,
1 * 2 * 3 * 4 * 5 * 6 * 7,
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8,
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9,
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10,
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11,
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12
};
/**
* Returns {@code n} choose {@code k}, also known as the binomial coefficient of {@code n} and
* {@code k}, or {@link Integer#MAX_VALUE} if the result does not fit in an {@code int}.
*
* @throws IllegalArgumentException if {@code n < 0}, {@code k < 0} or {@code k > n}
*/
public static int binomial(int n, int k) {
checkNonNegative("n", n);
checkNonNegative("k", k);
checkArgument(k <= n, "k (%s) > n (%s)", k, n);
if (k > (n >> 1)) {
k = n - k;
}
if (k >= biggestBinomials.length || n > biggestBinomials[k]) {
return Integer.MAX_VALUE;
}
switch (k) {
case 0:
return 1;
case 1:
return n;
default:
long result = 1;
for (int i = 0; i < k; i++) {
result *= n - i;
result /= i + 1;
}
return (int) result;
}
}
// binomial(biggestBinomials[k], k) fits in an int, but not binomial(biggestBinomials[k]+1,k).
@VisibleForTesting
static int[] biggestBinomials = {
Integer.MAX_VALUE,
Integer.MAX_VALUE,
65536,
2345,
477,
193,
110,
75,
58,
49,
43,
39,
37,
35,
34,
34,
33
};
/**
* Returns the arithmetic mean of {@code x} and {@code y}, rounded towards negative infinity. This
* method is overflow resilient.
*
* @since 14.0
*/
public static int mean(int x, int y) {
// Efficient method for computing the arithmetic mean.
// The alternative (x + y) / 2 fails for large values.
// The alternative (x + y) >>> 1 fails for negative values.
return (x & y) + ((x ^ y) >> 1);
}
/**
* Returns {@code true} if {@code n} is a <a
* href="http://mathworld.wolfram.com/PrimeNumber.html">prime number</a>: an integer <i>greater
* than one</i> that cannot be factored into a product of <i>smaller</i> positive integers.
* Returns {@code false} if {@code n} is zero, one, or a composite number (one which <i>can</i> be
* factored into smaller positive integers).
*
* <p>To test larger numbers, use {@link LongMath#isPrime} or {@link BigInteger#isProbablePrime}.
*
* @throws IllegalArgumentException if {@code n} is negative
* @since 20.0
*/
@GwtIncompatible // TODO
public static boolean isPrime(int n) {
return LongMath.isPrime(n);
}
private IntMath() {}
}
| google/guava | android/guava/src/com/google/common/math/IntMath.java |
44,440 | /*
* Copyright (C) 2007 The Guava Authors
*
* 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.google.common.io;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.io.FileWriteMode.APPEND;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.graph.SuccessorsFunction;
import com.google.common.graph.Traverser;
import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.InlineMe;
import com.google.j2objc.annotations.J2ObjCIncompatible;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Provides utility methods for working with {@linkplain File files}.
*
* <p>{@link java.nio.file.Path} users will find similar utilities in {@link MoreFiles} and the
* JDK's {@link java.nio.file.Files} class.
*
* @author Chris Nokleberg
* @author Colin Decker
* @since 1.0
*/
@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class Files {
private Files() {}
/**
* Returns a buffered reader that reads from a file using the given character set.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link
* java.nio.file.Files#newBufferedReader(java.nio.file.Path, Charset)}.
*
* @param file the file to read from
* @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
* helpful predefined constants
* @return the buffered reader
*/
public static BufferedReader newReader(File file, Charset charset) throws FileNotFoundException {
checkNotNull(file);
checkNotNull(charset);
return new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
}
/**
* Returns a buffered writer that writes to a file using the given character set.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link
* java.nio.file.Files#newBufferedWriter(java.nio.file.Path, Charset,
* java.nio.file.OpenOption...)}.
*
* @param file the file to write to
* @param charset the charset used to encode the output stream; see {@link StandardCharsets} for
* helpful predefined constants
* @return the buffered writer
*/
public static BufferedWriter newWriter(File file, Charset charset) throws FileNotFoundException {
checkNotNull(file);
checkNotNull(charset);
return new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset));
}
/**
* Returns a new {@link ByteSource} for reading bytes from the given file.
*
* @since 14.0
*/
public static ByteSource asByteSource(File file) {
return new FileByteSource(file);
}
private static final class FileByteSource extends
ByteSource
{
private final File file;
private FileByteSource(File file) {
this.file = checkNotNull(file);
}
@Override
public FileInputStream openStream() throws IOException {
return new FileInputStream(file);
}
@Override
public Optional<Long> sizeIfKnown() {
if (file.isFile()) {
return Optional.of(file.length());
} else {
return Optional.absent();
}
}
@Override
public long size() throws IOException {
if (!file.isFile()) {
throw new FileNotFoundException(file.toString());
}
return file.length();
}
@Override
public byte[] read() throws IOException {
Closer closer = Closer.create();
try {
FileInputStream in = closer.register(openStream());
return ByteStreams.toByteArray(in, in.getChannel().size());
} catch (Throwable e) {
throw closer.rethrow(e);
} finally {
closer.close();
}
}
@Override
public String toString() {
return "Files.asByteSource(" + file + ")";
}
}
/**
* Returns a new {@link ByteSink} for writing bytes to the given file. The given {@code modes}
* control how the file is opened for writing. When no mode is provided, the file will be
* truncated before writing. When the {@link FileWriteMode#APPEND APPEND} mode is provided, writes
* will append to the end of the file without truncating it.
*
* @since 14.0
*/
public static ByteSink asByteSink(File file, FileWriteMode... modes) {
return new FileByteSink(file, modes);
}
private static final class FileByteSink extends ByteSink {
private final File file;
private final ImmutableSet<FileWriteMode> modes;
private FileByteSink(File file, FileWriteMode... modes) {
this.file = checkNotNull(file);
this.modes = ImmutableSet.copyOf(modes);
}
@Override
public FileOutputStream openStream() throws IOException {
return new FileOutputStream(file, modes.contains(APPEND));
}
@Override
public String toString() {
return "Files.asByteSink(" + file + ", " + modes + ")";
}
}
/**
* Returns a new {@link CharSource} for reading character data from the given file using the given
* character set.
*
* @since 14.0
*/
public static CharSource asCharSource(File file, Charset charset) {
return asByteSource(file).asCharSource(charset);
}
/**
* Returns a new {@link CharSink} for writing character data to the given file using the given
* character set. The given {@code modes} control how the file is opened for writing. When no mode
* is provided, the file will be truncated before writing. When the {@link FileWriteMode#APPEND
* APPEND} mode is provided, writes will append to the end of the file without truncating it.
*
* @since 14.0
*/
public static CharSink asCharSink(File file, Charset charset, FileWriteMode... modes) {
return asByteSink(file, modes).asCharSink(charset);
}
/**
* Reads all bytes from a file into a byte array.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link java.nio.file.Files#readAllBytes}.
*
* @param file the file to read from
* @return a byte array containing all the bytes from file
* @throws IllegalArgumentException if the file is bigger than the largest possible byte array
* (2^31 - 1)
* @throws IOException if an I/O error occurs
*/
public static byte[] toByteArray(File file) throws IOException {
return asByteSource(file).read();
}
/**
* Reads all characters from a file into a {@link String}, using the given character set.
*
* @param file the file to read from
* @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
* helpful predefined constants
* @return a string containing all the characters from the file
* @throws IOException if an I/O error occurs
* @deprecated Prefer {@code asCharSource(file, charset).read()}.
*/
@Deprecated
@InlineMe(
replacement = "Files.asCharSource(file, charset).read()",
imports = "com.google.common.io.Files")
public static String toString(File file, Charset charset) throws IOException {
return asCharSource(file, charset).read();
}
/**
* Overwrites a file with the contents of a byte array.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link
* java.nio.file.Files#write(java.nio.file.Path, byte[], java.nio.file.OpenOption...)}.
*
* @param from the bytes to write
* @param to the destination file
* @throws IOException if an I/O error occurs
*/
public static void write(byte[] from, File to) throws IOException {
asByteSink(to).write(from);
}
/**
* Writes a character sequence (such as a string) to a file using the given character set.
*
* @param from the character sequence to write
* @param to the destination file
* @param charset the charset used to encode the output stream; see {@link StandardCharsets} for
* helpful predefined constants
* @throws IOException if an I/O error occurs
* @deprecated Prefer {@code asCharSink(to, charset).write(from)}.
*/
@Deprecated
@InlineMe(
replacement = "Files.asCharSink(to, charset).write(from)",
imports = "com.google.common.io.Files")
public static void write(CharSequence from, File to, Charset charset) throws IOException {
asCharSink(to, charset).write(from);
}
/**
* Copies all bytes from a file to an output stream.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link
* java.nio.file.Files#copy(java.nio.file.Path, OutputStream)}.
*
* @param from the source file
* @param to the output stream
* @throws IOException if an I/O error occurs
*/
public static void copy(File from, OutputStream to) throws IOException {
asByteSource(from).copyTo(to);
}
/**
* Copies all the bytes from one file to another.
*
* <p>Copying is not an atomic operation - in the case of an I/O error, power loss, process
* termination, or other problems, {@code to} may not be a complete copy of {@code from}. If you
* need to guard against those conditions, you should employ other file-level synchronization.
*
* <p><b>Warning:</b> If {@code to} represents an existing file, that file will be overwritten
* with the contents of {@code from}. If {@code to} and {@code from} refer to the <i>same</i>
* file, the contents of that file will be deleted.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link
* java.nio.file.Files#copy(java.nio.file.Path, java.nio.file.Path, java.nio.file.CopyOption...)}.
*
* @param from the source file
* @param to the destination file
* @throws IOException if an I/O error occurs
* @throws IllegalArgumentException if {@code from.equals(to)}
*/
public static void copy(File from, File to) throws IOException {
checkArgument(!from.equals(to), "Source %s and destination %s must be different", from, to);
asByteSource(from).copyTo(asByteSink(to));
}
/**
* Copies all characters from a file to an appendable object, using the given character set.
*
* @param from the source file
* @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
* helpful predefined constants
* @param to the appendable object
* @throws IOException if an I/O error occurs
* @deprecated Prefer {@code asCharSource(from, charset).copyTo(to)}.
*/
@Deprecated
@InlineMe(
replacement = "Files.asCharSource(from, charset).copyTo(to)",
imports = "com.google.common.io.Files")
public
static void copy(File from, Charset charset, Appendable to) throws IOException {
asCharSource(from, charset).copyTo(to);
}
/**
* Appends a character sequence (such as a string) to a file using the given character set.
*
* @param from the character sequence to append
* @param to the destination file
* @param charset the charset used to encode the output stream; see {@link StandardCharsets} for
* helpful predefined constants
* @throws IOException if an I/O error occurs
* @deprecated Prefer {@code asCharSink(to, charset, FileWriteMode.APPEND).write(from)}. This
* method is scheduled to be removed in October 2019.
*/
@Deprecated
@InlineMe(
replacement = "Files.asCharSink(to, charset, FileWriteMode.APPEND).write(from)",
imports = {"com.google.common.io.FileWriteMode", "com.google.common.io.Files"})
public
static void append(CharSequence from, File to, Charset charset) throws IOException {
asCharSink(to, charset, FileWriteMode.APPEND).write(from);
}
/**
* Returns true if the given files exist, are not directories, and contain the same bytes.
*
* @throws IOException if an I/O error occurs
*/
public static boolean equal(File file1, File file2) throws IOException {
checkNotNull(file1);
checkNotNull(file2);
if (file1 == file2 || file1.equals(file2)) {
return true;
}
/*
* Some operating systems may return zero as the length for files denoting system-dependent
* entities such as devices or pipes, in which case we must fall back on comparing the bytes
* directly.
*/
long len1 = file1.length();
long len2 = file2.length();
if (len1 != 0 && len2 != 0 && len1 != len2) {
return false;
}
return asByteSource(file1).contentEquals(asByteSource(file2));
}
/**
* Atomically creates a new directory somewhere beneath the system's temporary directory (as
* defined by the {@code java.io.tmpdir} system property), and returns its name.
*
* <p>The temporary directory is created with permissions restricted to the current user or, in
* the case of Android, the current app. If that is not possible (as is the case under the very
* old Android Ice Cream Sandwich release), then this method throws an exception instead of
* creating a directory that would be more accessible. (This behavior is new in Guava 32.0.0.
* Previous versions would create a directory that is more accessible, as discussed in <a
* href="https://github.com/google/guava/issues/4011">CVE-2020-8908</a>.)
*
* <p>Use this method instead of {@link File#createTempFile(String, String)} when you wish to
* create a directory, not a regular file. A common pitfall is to call {@code createTempFile},
* delete the file and create a directory in its place, but this leads a race condition which can
* be exploited to create security vulnerabilities, especially when executable files are to be
* written into the directory.
*
* <p>This method assumes that the temporary volume is writable, has free inodes and free blocks,
* and that it will not be called thousands of times per second.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link
* java.nio.file.Files#createTempDirectory}.
*
* @return the newly-created directory
* @throws IllegalStateException if the directory could not be created, such as if the system does
* not support creating temporary directories securely
* @deprecated For Android users, see the <a
* href="https://developer.android.com/training/data-storage" target="_blank">Data and File
* Storage overview</a> to select an appropriate temporary directory (perhaps {@code
* context.getCacheDir()}), and create your own directory under that. (For example, you might
* use {@code new File(context.getCacheDir(), "directoryname").mkdir()}, or, if you need an
* arbitrary number of temporary directories, you might have to generate multiple directory
* names in a loop until {@code mkdir()} returns {@code true}.) For Java 7+ users, prefer
* {@link java.nio.file.Files#createTempDirectory}, transforming it to a {@link File} using
* {@link java.nio.file.Path#toFile() toFile()} if needed. To restrict permissions as this
* method does, pass {@code
* PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------"))} to your
* call to {@code createTempDirectory}.
*/
@Beta
@Deprecated
@J2ObjCIncompatible
public static File createTempDir() {
return TempFileCreator.INSTANCE.createTempDir();
}
/**
* Creates an empty file or updates the last updated timestamp on the same as the unix command of
* the same name.
*
* @param file the file to create or update
* @throws IOException if an I/O error occurs
*/
@SuppressWarnings("GoodTime") // reading system time without TimeSource
public static void touch(File file) throws IOException {
checkNotNull(file);
if (!file.createNewFile() && !file.setLastModified(System.currentTimeMillis())) {
throw new IOException("Unable to update modification time of " + file);
}
}
/**
* Creates any necessary but nonexistent parent directories of the specified file. Note that if
* this operation fails it may have succeeded in creating some (but not all) of the necessary
* parent directories.
*
* @throws IOException if an I/O error occurs, or if any necessary but nonexistent parent
* directories of the specified file could not be created.
* @since 4.0
*/
public static void createParentDirs(File file) throws IOException {
checkNotNull(file);
File parent = file.getCanonicalFile().getParentFile();
if (parent == null) {
/*
* The given directory is a filesystem root. All zero of its ancestors exist. This doesn't
* mean that the root itself exists -- consider x:\ on a Windows machine without such a drive
* -- or even that the caller can create it, but this method makes no such guarantees even for
* non-root files.
*/
return;
}
parent.mkdirs();
if (!parent.isDirectory()) {
throw new IOException("Unable to create parent directories of " + file);
}
}
/**
* Moves a file from one path to another. This method can rename a file and/or move it to a
* different directory. In either case {@code to} must be the target path for the file itself; not
* just the new name for the file or the path to the new parent directory.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link java.nio.file.Files#move}.
*
* @param from the source file
* @param to the destination file
* @throws IOException if an I/O error occurs
* @throws IllegalArgumentException if {@code from.equals(to)}
*/
public static void move(File from, File to) throws IOException {
checkNotNull(from);
checkNotNull(to);
checkArgument(!from.equals(to), "Source %s and destination %s must be different", from, to);
if (!from.renameTo(to)) {
copy(from, to);
if (!from.delete()) {
if (!to.delete()) {
throw new IOException("Unable to delete " + to);
}
throw new IOException("Unable to delete " + from);
}
}
}
/**
* Reads the first line from a file. The line does not include line-termination characters, but
* does include other leading and trailing whitespace.
*
* @param file the file to read from
* @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
* helpful predefined constants
* @return the first line, or null if the file is empty
* @throws IOException if an I/O error occurs
* @deprecated Prefer {@code asCharSource(file, charset).readFirstLine()}.
*/
@Deprecated
@InlineMe(
replacement = "Files.asCharSource(file, charset).readFirstLine()",
imports = "com.google.common.io.Files")
@CheckForNull
public
static String readFirstLine(File file, Charset charset) throws IOException {
return asCharSource(file, charset).readFirstLine();
}
/**
* Reads all of the lines from a file. The lines do not include line-termination characters, but
* do include other leading and trailing whitespace.
*
* <p>This method returns a mutable {@code List}. For an {@code ImmutableList}, use {@code
* Files.asCharSource(file, charset).readLines()}.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link
* java.nio.file.Files#readAllLines(java.nio.file.Path, Charset)}.
*
* @param file the file to read from
* @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
* helpful predefined constants
* @return a mutable {@link List} containing all the lines
* @throws IOException if an I/O error occurs
*/
public static List<String> readLines(File file, Charset charset) throws IOException {
// don't use asCharSource(file, charset).readLines() because that returns
// an immutable list, which would change the behavior of this method
return asCharSource(file, charset)
.readLines(
new LineProcessor<List<String>>() {
final List<String> result = Lists.newArrayList();
@Override
public boolean processLine(String line) {
result.add(line);
return true;
}
@Override
public List<String> getResult() {
return result;
}
});
}
/**
* Streams lines from a {@link File}, stopping when our callback returns false, or we have read
* all of the lines.
*
* @param file the file to read from
* @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
* helpful predefined constants
* @param callback the {@link LineProcessor} to use to handle the lines
* @return the output of processing the lines
* @throws IOException if an I/O error occurs
* @deprecated Prefer {@code asCharSource(file, charset).readLines(callback)}.
*/
@Deprecated
@InlineMe(
replacement = "Files.asCharSource(file, charset).readLines(callback)",
imports = "com.google.common.io.Files")
@CanIgnoreReturnValue // some processors won't return a useful result
@ParametricNullness
public
static <T extends @Nullable Object> T readLines(
File file, Charset charset, LineProcessor<T> callback) throws IOException {
return asCharSource(file, charset).readLines(callback);
}
/**
* Process the bytes of a file.
*
* <p>(If this seems too complicated, maybe you're looking for {@link #toByteArray}.)
*
* @param file the file to read
* @param processor the object to which the bytes of the file are passed.
* @return the result of the byte processor
* @throws IOException if an I/O error occurs
* @deprecated Prefer {@code asByteSource(file).read(processor)}.
*/
@Deprecated
@InlineMe(
replacement = "Files.asByteSource(file).read(processor)",
imports = "com.google.common.io.Files")
@CanIgnoreReturnValue // some processors won't return a useful result
@ParametricNullness
public
static <T extends @Nullable Object> T readBytes(File file, ByteProcessor<T> processor)
throws IOException {
return asByteSource(file).read(processor);
}
/**
* Computes the hash code of the {@code file} using {@code hashFunction}.
*
* @param file the file to read
* @param hashFunction the hash function to use to hash the data
* @return the {@link HashCode} of all of the bytes in the file
* @throws IOException if an I/O error occurs
* @since 12.0
* @deprecated Prefer {@code asByteSource(file).hash(hashFunction)}.
*/
@Deprecated
@InlineMe(
replacement = "Files.asByteSource(file).hash(hashFunction)",
imports = "com.google.common.io.Files")
public
static HashCode hash(File file, HashFunction hashFunction) throws IOException {
return asByteSource(file).hash(hashFunction);
}
/**
* Fully maps a file read-only in to memory as per {@link
* FileChannel#map(java.nio.channels.FileChannel.MapMode, long, long)}.
*
* <p>Files are mapped from offset 0 to its length.
*
* <p>This only works for files ≤ {@link Integer#MAX_VALUE} bytes.
*
* @param file the file to map
* @return a read-only buffer reflecting {@code file}
* @throws FileNotFoundException if the {@code file} does not exist
* @throws IOException if an I/O error occurs
* @see FileChannel#map(MapMode, long, long)
* @since 2.0
*/
public static MappedByteBuffer map(File file) throws IOException {
checkNotNull(file);
return map(file, MapMode.READ_ONLY);
}
/**
* Fully maps a file in to memory as per {@link
* FileChannel#map(java.nio.channels.FileChannel.MapMode, long, long)} using the requested {@link
* MapMode}.
*
* <p>Files are mapped from offset 0 to its length.
*
* <p>This only works for files ≤ {@link Integer#MAX_VALUE} bytes.
*
* @param file the file to map
* @param mode the mode to use when mapping {@code file}
* @return a buffer reflecting {@code file}
* @throws FileNotFoundException if the {@code file} does not exist
* @throws IOException if an I/O error occurs
* @see FileChannel#map(MapMode, long, long)
* @since 2.0
*/
public static MappedByteBuffer map(File file, MapMode mode) throws IOException {
return mapInternal(file, mode, -1);
}
/**
* Maps a file in to memory as per {@link FileChannel#map(java.nio.channels.FileChannel.MapMode,
* long, long)} using the requested {@link MapMode}.
*
* <p>Files are mapped from offset 0 to {@code size}.
*
* <p>If the mode is {@link MapMode#READ_WRITE} and the file does not exist, it will be created
* with the requested {@code size}. Thus this method is useful for creating memory mapped files
* which do not yet exist.
*
* <p>This only works for files ≤ {@link Integer#MAX_VALUE} bytes.
*
* @param file the file to map
* @param mode the mode to use when mapping {@code file}
* @return a buffer reflecting {@code file}
* @throws IOException if an I/O error occurs
* @see FileChannel#map(MapMode, long, long)
* @since 2.0
*/
public static MappedByteBuffer map(File file, MapMode mode, long size) throws IOException {
checkArgument(size >= 0, "size (%s) may not be negative", size);
return mapInternal(file, mode, size);
}
private static MappedByteBuffer mapInternal(File file, MapMode mode, long size)
throws IOException {
checkNotNull(file);
checkNotNull(mode);
Closer closer = Closer.create();
try {
RandomAccessFile raf =
closer.register(new RandomAccessFile(file, mode == MapMode.READ_ONLY ? "r" : "rw"));
FileChannel channel = closer.register(raf.getChannel());
return channel.map(mode, 0, size == -1 ? channel.size() : size);
} catch (Throwable e) {
throw closer.rethrow(e);
} finally {
closer.close();
}
}
/**
* Returns the lexically cleaned form of the path name, <i>usually</i> (but not always) equivalent
* to the original. The following heuristics are used:
*
* <ul>
* <li>empty string becomes .
* <li>. stays as .
* <li>fold out ./
* <li>fold out ../ when possible
* <li>collapse multiple slashes
* <li>delete trailing slashes (unless the path is just "/")
* </ul>
*
* <p>These heuristics do not always match the behavior of the filesystem. In particular, consider
* the path {@code a/../b}, which {@code simplifyPath} will change to {@code b}. If {@code a} is a
* symlink to {@code x}, {@code a/../b} may refer to a sibling of {@code x}, rather than the
* sibling of {@code a} referred to by {@code b}.
*
* @since 11.0
*/
public static String simplifyPath(String pathname) {
checkNotNull(pathname);
if (pathname.length() == 0) {
return ".";
}
// split the path apart
Iterable<String> components = Splitter.on('/').omitEmptyStrings().split(pathname);
List<String> path = new ArrayList<>();
// resolve ., .., and //
for (String component : components) {
switch (component) {
case ".":
continue;
case "..":
if (path.size() > 0 && !path.get(path.size() - 1).equals("..")) {
path.remove(path.size() - 1);
} else {
path.add("..");
}
break;
default:
path.add(component);
break;
}
}
// put it back together
String result = Joiner.on('/').join(path);
if (pathname.charAt(0) == '/') {
result = "/" + result;
}
while (result.startsWith("/../")) {
result = result.substring(3);
}
if (result.equals("/..")) {
result = "/";
} else if ("".equals(result)) {
result = ".";
}
return result;
}
/**
* Returns the <a href="http://en.wikipedia.org/wiki/Filename_extension">file extension</a> for
* the given file name, or the empty string if the file has no extension. The result does not
* include the '{@code .}'.
*
* <p><b>Note:</b> This method simply returns everything after the last '{@code .}' in the file's
* name as determined by {@link File#getName}. It does not account for any filesystem-specific
* behavior that the {@link File} API does not already account for. For example, on NTFS it will
* report {@code "txt"} as the extension for the filename {@code "foo.exe:.txt"} even though NTFS
* will drop the {@code ":.txt"} part of the name when the file is actually created on the
* filesystem due to NTFS's <a href="https://goo.gl/vTpJi4">Alternate Data Streams</a>.
*
* @since 11.0
*/
public static String getFileExtension(String fullName) {
checkNotNull(fullName);
String fileName = new File(fullName).getName();
int dotIndex = fileName.lastIndexOf('.');
return (dotIndex == -1) ? "" : fileName.substring(dotIndex + 1);
}
/**
* Returns the file name without its <a
* href="http://en.wikipedia.org/wiki/Filename_extension">file extension</a> or path. This is
* similar to the {@code basename} unix command. The result does not include the '{@code .}'.
*
* @param file The name of the file to trim the extension from. This can be either a fully
* qualified file name (including a path) or just a file name.
* @return The file name without its path or extension.
* @since 14.0
*/
public static String getNameWithoutExtension(String file) {
checkNotNull(file);
String fileName = new File(file).getName();
int dotIndex = fileName.lastIndexOf('.');
return (dotIndex == -1) ? fileName : fileName.substring(0, dotIndex);
}
/**
* Returns a {@link Traverser} instance for the file and directory tree. The returned traverser
* starts from a {@link File} and will return all files and directories it encounters.
*
* <p><b>Warning:</b> {@code File} provides no support for symbolic links, and as such there is no
* way to ensure that a symbolic link to a directory is not followed when traversing the tree. In
* this case, iterables created by this traverser could contain files that are outside of the
* given directory or even be infinite if there is a symbolic link loop.
*
* <p>If available, consider using {@link MoreFiles#fileTraverser()} instead. It behaves the same
* except that it doesn't follow symbolic links and returns {@code Path} instances.
*
* <p>If the {@link File} passed to one of the {@link Traverser} methods does not exist or is not
* a directory, no exception will be thrown and the returned {@link Iterable} will contain a
* single element: that file.
*
* <p>Example: {@code Files.fileTraverser().depthFirstPreOrder(new File("/"))} may return files
* with the following paths: {@code ["/", "/etc", "/etc/config.txt", "/etc/fonts", "/home",
* "/home/alice", ...]}
*
* @since 23.5
*/
public static Traverser<File> fileTraverser() {
return Traverser.forTree(FILE_TREE);
}
private static final SuccessorsFunction<File> FILE_TREE =
new SuccessorsFunction<File>() {
@Override
public Iterable<File> successors(File file) {
// check isDirectory() just because it may be faster than listFiles() on a non-directory
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null) {
return Collections.unmodifiableList(Arrays.asList(files));
}
}
return ImmutableList.of();
}
};
/**
* Returns a predicate that returns the result of {@link File#isDirectory} on input files.
*
* @since 15.0
*/
public static Predicate<File> isDirectory() {
return FilePredicate.IS_DIRECTORY;
}
/**
* Returns a predicate that returns the result of {@link File#isFile} on input files.
*
* @since 15.0
*/
public static Predicate<File> isFile() {
return FilePredicate.IS_FILE;
}
private enum FilePredicate implements Predicate<File> {
IS_DIRECTORY {
@Override
public boolean apply(File file) {
return file.isDirectory();
}
@Override
public String toString() {
return "Files.isDirectory()";
}
},
IS_FILE {
@Override
public boolean apply(File file) {
return file.isFile();
}
@Override
public String toString() {
return "Files.isFile()";
}
}
}
}
| google/guava | guava/src/com/google/common/io/Files.java |
44,441 | /*
* Copyright (C) 2008 The Guava Authors
*
* 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.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.base.Supplier;
import com.google.common.collect.Table.Cell;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.function.BinaryOperator;
import java.util.stream.Collector;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Provides static methods that involve a {@code Table}.
*
* <p>See the Guava User Guide article on <a href=
* "https://github.com/google/guava/wiki/CollectionUtilitiesExplained#tables">{@code Tables}</a>.
*
* @author Jared Levy
* @author Louis Wasserman
* @since 7.0
*/
@GwtCompatible
@ElementTypesAreNonnullByDefault
public final class Tables {
private Tables() {}
/**
* Returns a {@link Collector} that accumulates elements into a {@code Table} created using the
* specified supplier, whose cells are generated by applying the provided mapping functions to the
* input elements. Cells are inserted into the generated {@code Table} in encounter order.
*
* <p>If multiple input elements map to the same row and column, an {@code IllegalStateException}
* is thrown when the collection operation is performed.
*
* <p>To collect to an {@link ImmutableTable}, use {@link ImmutableTable#toImmutableTable}.
*
* @since 33.2.0 (available since 21.0 in guava-jre)
*/
@SuppressWarnings({"AndroidJdkLibsChecker", "Java7ApiChecker"})
@IgnoreJRERequirement // Users will use this only if they're already using streams.
@Beta // TODO: b/288085449 - Remove.
public static <
T extends @Nullable Object,
R extends @Nullable Object,
C extends @Nullable Object,
V,
I extends Table<R, C, V>>
Collector<T, ?, I> toTable(
java.util.function.Function<? super T, ? extends R> rowFunction,
java.util.function.Function<? super T, ? extends C> columnFunction,
java.util.function.Function<? super T, ? extends V> valueFunction,
java.util.function.Supplier<I> tableSupplier) {
return TableCollectors.<T, R, C, V, I>toTable(
rowFunction, columnFunction, valueFunction, tableSupplier);
}
/**
* Returns a {@link Collector} that accumulates elements into a {@code Table} created using the
* specified supplier, whose cells are generated by applying the provided mapping functions to the
* input elements. Cells are inserted into the generated {@code Table} in encounter order.
*
* <p>If multiple input elements map to the same row and column, the specified merging function is
* used to combine the values. Like {@link
* java.util.stream.Collectors#toMap(java.util.function.Function, java.util.function.Function,
* BinaryOperator, java.util.function.Supplier)}, this Collector throws a {@code
* NullPointerException} on null values returned from {@code valueFunction}, and treats nulls
* returned from {@code mergeFunction} as removals of that row/column pair.
*
* @since 33.2.0 (available since 21.0 in guava-jre)
*/
@SuppressWarnings({"AndroidJdkLibsChecker", "Java7ApiChecker"})
@IgnoreJRERequirement // Users will use this only if they're already using streams.
@Beta // TODO: b/288085449 - Remove.
public static <
T extends @Nullable Object,
R extends @Nullable Object,
C extends @Nullable Object,
V,
I extends Table<R, C, V>>
Collector<T, ?, I> toTable(
java.util.function.Function<? super T, ? extends R> rowFunction,
java.util.function.Function<? super T, ? extends C> columnFunction,
java.util.function.Function<? super T, ? extends V> valueFunction,
BinaryOperator<V> mergeFunction,
java.util.function.Supplier<I> tableSupplier) {
return TableCollectors.<T, R, C, V, I>toTable(
rowFunction, columnFunction, valueFunction, mergeFunction, tableSupplier);
}
/**
* Returns an immutable cell with the specified row key, column key, and value.
*
* <p>The returned cell is serializable.
*
* @param rowKey the row key to be associated with the returned cell
* @param columnKey the column key to be associated with the returned cell
* @param value the value to be associated with the returned cell
*/
public static <R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object>
Cell<R, C, V> immutableCell(
@ParametricNullness R rowKey,
@ParametricNullness C columnKey,
@ParametricNullness V value) {
return new ImmutableCell<>(rowKey, columnKey, value);
}
static final class ImmutableCell<
R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object>
extends AbstractCell<R, C, V> implements Serializable {
@ParametricNullness private final R rowKey;
@ParametricNullness private final C columnKey;
@ParametricNullness private final V value;
ImmutableCell(
@ParametricNullness R rowKey,
@ParametricNullness C columnKey,
@ParametricNullness V value) {
this.rowKey = rowKey;
this.columnKey = columnKey;
this.value = value;
}
@Override
@ParametricNullness
public R getRowKey() {
return rowKey;
}
@Override
@ParametricNullness
public C getColumnKey() {
return columnKey;
}
@Override
@ParametricNullness
public V getValue() {
return value;
}
private static final long serialVersionUID = 0;
}
abstract static class AbstractCell<
R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object>
implements Cell<R, C, V> {
// needed for serialization
AbstractCell() {}
@Override
public boolean equals(@CheckForNull Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof Cell) {
Cell<?, ?, ?> other = (Cell<?, ?, ?>) obj;
return Objects.equal(getRowKey(), other.getRowKey())
&& Objects.equal(getColumnKey(), other.getColumnKey())
&& Objects.equal(getValue(), other.getValue());
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(getRowKey(), getColumnKey(), getValue());
}
@Override
public String toString() {
return "(" + getRowKey() + "," + getColumnKey() + ")=" + getValue();
}
}
/**
* Creates a transposed view of a given table that flips its row and column keys. In other words,
* calling {@code get(columnKey, rowKey)} on the generated table always returns the same value as
* calling {@code get(rowKey, columnKey)} on the original table. Updating the original table
* changes the contents of the transposed table and vice versa.
*
* <p>The returned table supports update operations as long as the input table supports the
* analogous operation with swapped rows and columns. For example, in a {@link HashBasedTable}
* instance, {@code rowKeySet().iterator()} supports {@code remove()} but {@code
* columnKeySet().iterator()} doesn't. With a transposed {@link HashBasedTable}, it's the other
* way around.
*/
public static <R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object>
Table<C, R, V> transpose(Table<R, C, V> table) {
return (table instanceof TransposeTable)
? ((TransposeTable<R, C, V>) table).original
: new TransposeTable<C, R, V>(table);
}
private static class TransposeTable<
C extends @Nullable Object, R extends @Nullable Object, V extends @Nullable Object>
extends AbstractTable<C, R, V> {
final Table<R, C, V> original;
TransposeTable(Table<R, C, V> original) {
this.original = checkNotNull(original);
}
@Override
public void clear() {
original.clear();
}
@Override
public Map<C, V> column(@ParametricNullness R columnKey) {
return original.row(columnKey);
}
@Override
public Set<R> columnKeySet() {
return original.rowKeySet();
}
@Override
public Map<R, Map<C, V>> columnMap() {
return original.rowMap();
}
@Override
public boolean contains(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
return original.contains(columnKey, rowKey);
}
@Override
public boolean containsColumn(@CheckForNull Object columnKey) {
return original.containsRow(columnKey);
}
@Override
public boolean containsRow(@CheckForNull Object rowKey) {
return original.containsColumn(rowKey);
}
@Override
public boolean containsValue(@CheckForNull Object value) {
return original.containsValue(value);
}
@Override
@CheckForNull
public V get(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
return original.get(columnKey, rowKey);
}
@Override
@CheckForNull
public V put(
@ParametricNullness C rowKey,
@ParametricNullness R columnKey,
@ParametricNullness V value) {
return original.put(columnKey, rowKey, value);
}
@Override
public void putAll(Table<? extends C, ? extends R, ? extends V> table) {
original.putAll(transpose(table));
}
@Override
@CheckForNull
public V remove(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
return original.remove(columnKey, rowKey);
}
@Override
public Map<R, V> row(@ParametricNullness C rowKey) {
return original.column(rowKey);
}
@Override
public Set<C> rowKeySet() {
return original.columnKeySet();
}
@Override
public Map<C, Map<R, V>> rowMap() {
return original.columnMap();
}
@Override
public int size() {
return original.size();
}
@Override
public Collection<V> values() {
return original.values();
}
@Override
Iterator<Cell<C, R, V>> cellIterator() {
return Iterators.transform(original.cellSet().iterator(), Tables::transposeCell);
}
}
private static <
R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object>
Cell<C, R, V> transposeCell(Cell<R, C, V> cell) {
return immutableCell(cell.getColumnKey(), cell.getRowKey(), cell.getValue());
}
/**
* Creates a table that uses the specified backing map and factory. It can generate a table based
* on arbitrary {@link Map} classes.
*
* <p>The {@code factory}-generated and {@code backingMap} classes determine the table iteration
* order. However, the table's {@code row()} method returns instances of a different class than
* {@code factory.get()} does.
*
* <p>Call this method only when the simpler factory methods in classes like {@link
* HashBasedTable} and {@link TreeBasedTable} won't suffice.
*
* <p>The views returned by the {@code Table} methods {@link Table#column}, {@link
* Table#columnKeySet}, and {@link Table#columnMap} have iterators that don't support {@code
* remove()}. Otherwise, all optional operations are supported. Null row keys, columns keys, and
* values are not supported.
*
* <p>Lookups by row key are often faster than lookups by column key, because the data is stored
* in a {@code Map<R, Map<C, V>>}. A method call like {@code column(columnKey).get(rowKey)} still
* runs quickly, since the row key is provided. However, {@code column(columnKey).size()} takes
* longer, since an iteration across all row keys occurs.
*
* <p>Note that this implementation is not synchronized. If multiple threads access this table
* concurrently and one of the threads modifies the table, it must be synchronized externally.
*
* <p>The table is serializable if {@code backingMap}, {@code factory}, the maps generated by
* {@code factory}, and the table contents are all serializable.
*
* <p>Note: the table assumes complete ownership over of {@code backingMap} and the maps returned
* by {@code factory}. Those objects should not be manually updated and they should not use soft,
* weak, or phantom references.
*
* @param backingMap place to store the mapping from each row key to its corresponding column key
* / value map
* @param factory supplier of new, empty maps that will each hold all column key / value mappings
* for a given row key
* @throws IllegalArgumentException if {@code backingMap} is not empty
* @since 10.0
*/
public static <R, C, V> Table<R, C, V> newCustomTable(
Map<R, Map<C, V>> backingMap, Supplier<? extends Map<C, V>> factory) {
checkArgument(backingMap.isEmpty());
checkNotNull(factory);
// TODO(jlevy): Wrap factory to validate that the supplied maps are empty?
return new StandardTable<>(backingMap, factory);
}
/**
* Returns a view of a table where each value is transformed by a function. All other properties
* of the table, such as iteration order, are left intact.
*
* <p>Changes in the underlying table are reflected in this view. Conversely, this view supports
* removal operations, and these are reflected in the underlying table.
*
* <p>It's acceptable for the underlying table to contain null keys, and even null values provided
* that the function is capable of accepting null input. The transformed table might contain null
* values, if the function sometimes gives a null result.
*
* <p>The returned table is not thread-safe or serializable, even if the underlying table is.
*
* <p>The function is applied lazily, invoked when needed. This is necessary for the returned
* table to be a view, but it means that the function will be applied many times for bulk
* operations like {@link Table#containsValue} and {@code Table.toString()}. For this to perform
* well, {@code function} should be fast. To avoid lazy evaluation when the returned table doesn't
* need to be a view, copy the returned table into a new table of your choosing.
*
* @since 10.0
*/
public static <
R extends @Nullable Object,
C extends @Nullable Object,
V1 extends @Nullable Object,
V2 extends @Nullable Object>
Table<R, C, V2> transformValues(
Table<R, C, V1> fromTable, Function<? super V1, V2> function) {
return new TransformedTable<>(fromTable, function);
}
private static class TransformedTable<
R extends @Nullable Object,
C extends @Nullable Object,
V1 extends @Nullable Object,
V2 extends @Nullable Object>
extends AbstractTable<R, C, V2> {
final Table<R, C, V1> fromTable;
final Function<? super V1, V2> function;
TransformedTable(Table<R, C, V1> fromTable, Function<? super V1, V2> function) {
this.fromTable = checkNotNull(fromTable);
this.function = checkNotNull(function);
}
@Override
public boolean contains(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
return fromTable.contains(rowKey, columnKey);
}
@Override
@CheckForNull
public V2 get(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
// The function is passed a null input only when the table contains a null
// value.
// The cast is safe because of the contains() check.
return contains(rowKey, columnKey)
? function.apply(uncheckedCastNullableTToT(fromTable.get(rowKey, columnKey)))
: null;
}
@Override
public int size() {
return fromTable.size();
}
@Override
public void clear() {
fromTable.clear();
}
@Override
@CheckForNull
public V2 put(
@ParametricNullness R rowKey,
@ParametricNullness C columnKey,
@ParametricNullness V2 value) {
throw new UnsupportedOperationException();
}
@Override
public void putAll(Table<? extends R, ? extends C, ? extends V2> table) {
throw new UnsupportedOperationException();
}
@Override
@CheckForNull
public V2 remove(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
return contains(rowKey, columnKey)
// The cast is safe because of the contains() check.
? function.apply(uncheckedCastNullableTToT(fromTable.remove(rowKey, columnKey)))
: null;
}
@Override
public Map<C, V2> row(@ParametricNullness R rowKey) {
return Maps.transformValues(fromTable.row(rowKey), function);
}
@Override
public Map<R, V2> column(@ParametricNullness C columnKey) {
return Maps.transformValues(fromTable.column(columnKey), function);
}
Function<Cell<R, C, V1>, Cell<R, C, V2>> cellFunction() {
return new Function<Cell<R, C, V1>, Cell<R, C, V2>>() {
@Override
public Cell<R, C, V2> apply(Cell<R, C, V1> cell) {
return immutableCell(
cell.getRowKey(), cell.getColumnKey(), function.apply(cell.getValue()));
}
};
}
@Override
Iterator<Cell<R, C, V2>> cellIterator() {
return Iterators.transform(fromTable.cellSet().iterator(), cellFunction());
}
@Override
public Set<R> rowKeySet() {
return fromTable.rowKeySet();
}
@Override
public Set<C> columnKeySet() {
return fromTable.columnKeySet();
}
@Override
Collection<V2> createValues() {
return Collections2.transform(fromTable.values(), function);
}
@Override
public Map<R, Map<C, V2>> rowMap() {
Function<Map<C, V1>, Map<C, V2>> rowFunction =
new Function<Map<C, V1>, Map<C, V2>>() {
@Override
public Map<C, V2> apply(Map<C, V1> row) {
return Maps.transformValues(row, function);
}
};
return Maps.transformValues(fromTable.rowMap(), rowFunction);
}
@Override
public Map<C, Map<R, V2>> columnMap() {
Function<Map<R, V1>, Map<R, V2>> columnFunction =
new Function<Map<R, V1>, Map<R, V2>>() {
@Override
public Map<R, V2> apply(Map<R, V1> column) {
return Maps.transformValues(column, function);
}
};
return Maps.transformValues(fromTable.columnMap(), columnFunction);
}
}
/**
* Returns an unmodifiable view of the specified table. This method allows modules to provide
* users with "read-only" access to internal tables. Query operations on the returned table "read
* through" to the specified table, and attempts to modify the returned table, whether direct or
* via its collection views, result in an {@code UnsupportedOperationException}.
*
* <p>The returned table will be serializable if the specified table is serializable.
*
* <p>Consider using an {@link ImmutableTable}, which is guaranteed never to change.
*
* @since 11.0
*/
public static <R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object>
Table<R, C, V> unmodifiableTable(Table<? extends R, ? extends C, ? extends V> table) {
return new UnmodifiableTable<>(table);
}
private static class UnmodifiableTable<
R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object>
extends ForwardingTable<R, C, V> implements Serializable {
final Table<? extends R, ? extends C, ? extends V> delegate;
UnmodifiableTable(Table<? extends R, ? extends C, ? extends V> delegate) {
this.delegate = checkNotNull(delegate);
}
@SuppressWarnings("unchecked") // safe, covariant cast
@Override
protected Table<R, C, V> delegate() {
return (Table<R, C, V>) delegate;
}
@Override
public Set<Cell<R, C, V>> cellSet() {
return Collections.unmodifiableSet(super.cellSet());
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
@Override
public Map<R, V> column(@ParametricNullness C columnKey) {
return Collections.unmodifiableMap(super.column(columnKey));
}
@Override
public Set<C> columnKeySet() {
return Collections.unmodifiableSet(super.columnKeySet());
}
@Override
public Map<C, Map<R, V>> columnMap() {
Function<Map<R, V>, Map<R, V>> wrapper = unmodifiableWrapper();
return Collections.unmodifiableMap(Maps.transformValues(super.columnMap(), wrapper));
}
@Override
@CheckForNull
public V put(
@ParametricNullness R rowKey,
@ParametricNullness C columnKey,
@ParametricNullness V value) {
throw new UnsupportedOperationException();
}
@Override
public void putAll(Table<? extends R, ? extends C, ? extends V> table) {
throw new UnsupportedOperationException();
}
@Override
@CheckForNull
public V remove(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
throw new UnsupportedOperationException();
}
@Override
public Map<C, V> row(@ParametricNullness R rowKey) {
return Collections.unmodifiableMap(super.row(rowKey));
}
@Override
public Set<R> rowKeySet() {
return Collections.unmodifiableSet(super.rowKeySet());
}
@Override
public Map<R, Map<C, V>> rowMap() {
Function<Map<C, V>, Map<C, V>> wrapper = unmodifiableWrapper();
return Collections.unmodifiableMap(Maps.transformValues(super.rowMap(), wrapper));
}
@Override
public Collection<V> values() {
return Collections.unmodifiableCollection(super.values());
}
private static final long serialVersionUID = 0;
}
/**
* Returns an unmodifiable view of the specified row-sorted table. This method allows modules to
* provide users with "read-only" access to internal tables. Query operations on the returned
* table "read through" to the specified table, and attempts to modify the returned table, whether
* direct or via its collection views, result in an {@code UnsupportedOperationException}.
*
* <p>The returned table will be serializable if the specified table is serializable.
*
* @param table the row-sorted table for which an unmodifiable view is to be returned
* @return an unmodifiable view of the specified table
* @since 11.0
*/
public static <R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object>
RowSortedTable<R, C, V> unmodifiableRowSortedTable(
RowSortedTable<R, ? extends C, ? extends V> table) {
/*
* It's not ? extends R, because it's technically not covariant in R. Specifically,
* table.rowMap().comparator() could return a comparator that only works for the ? extends R.
* Collections.unmodifiableSortedMap makes the same distinction.
*/
return new UnmodifiableRowSortedMap<>(table);
}
private static final class UnmodifiableRowSortedMap<
R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object>
extends UnmodifiableTable<R, C, V> implements RowSortedTable<R, C, V> {
public UnmodifiableRowSortedMap(RowSortedTable<R, ? extends C, ? extends V> delegate) {
super(delegate);
}
@Override
protected RowSortedTable<R, C, V> delegate() {
return (RowSortedTable<R, C, V>) super.delegate();
}
@Override
public SortedMap<R, Map<C, V>> rowMap() {
Function<Map<C, V>, Map<C, V>> wrapper = unmodifiableWrapper();
return Collections.unmodifiableSortedMap(Maps.transformValues(delegate().rowMap(), wrapper));
}
@Override
public SortedSet<R> rowKeySet() {
return Collections.unmodifiableSortedSet(delegate().rowKeySet());
}
private static final long serialVersionUID = 0;
}
@SuppressWarnings("unchecked")
private static <K extends @Nullable Object, V extends @Nullable Object>
Function<Map<K, V>, Map<K, V>> unmodifiableWrapper() {
return (Function) UNMODIFIABLE_WRAPPER;
}
private static final Function<? extends Map<?, ?>, ? extends Map<?, ?>> UNMODIFIABLE_WRAPPER =
new Function<Map<Object, Object>, Map<Object, Object>>() {
@Override
public Map<Object, Object> apply(Map<Object, Object> input) {
return Collections.unmodifiableMap(input);
}
};
/**
* Returns a synchronized (thread-safe) table backed by the specified table. In order to guarantee
* serial access, it is critical that <b>all</b> access to the backing table is accomplished
* through the returned table.
*
* <p>It is imperative that the user manually synchronize on the returned table when accessing any
* of its collection views:
*
* <pre>{@code
* Table<R, C, V> table = Tables.synchronizedTable(HashBasedTable.<R, C, V>create());
* ...
* Map<C, V> row = table.row(rowKey); // Needn't be in synchronized block
* ...
* synchronized (table) { // Synchronizing on table, not row!
* Iterator<Entry<C, V>> i = row.entrySet().iterator(); // Must be in synchronized block
* while (i.hasNext()) {
* foo(i.next());
* }
* }
* }</pre>
*
* <p>Failure to follow this advice may result in non-deterministic behavior.
*
* <p>The returned table will be serializable if the specified table is serializable.
*
* @param table the table to be wrapped in a synchronized view
* @return a synchronized view of the specified table
* @since 22.0
*/
public static <R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object>
Table<R, C, V> synchronizedTable(Table<R, C, V> table) {
return Synchronized.table(table, null);
}
static boolean equalsImpl(Table<?, ?, ?> table, @CheckForNull Object obj) {
if (obj == table) {
return true;
} else if (obj instanceof Table) {
Table<?, ?, ?> that = (Table<?, ?, ?>) obj;
return table.cellSet().equals(that.cellSet());
} else {
return false;
}
}
}
| google/guava | android/guava/src/com/google/common/collect/Tables.java |
44,442 | /*
* Copyright (C) 2011 The Guava Authors
*
* 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.google.common.collect;
import com.google.common.annotations.GwtIncompatible;
import com.google.errorprone.annotations.DoNotMock;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.annotation.CheckForNull;
/**
* A set comprising zero or more {@linkplain Range#isEmpty nonempty}, {@linkplain
* Range#isConnected(Range) disconnected} ranges of type {@code C}.
*
* <p>Implementations that choose to support the {@link #add(Range)} operation are required to
* ignore empty ranges and coalesce connected ranges. For example:
*
* <pre>{@code
* RangeSet<Integer> rangeSet = TreeRangeSet.create();
* rangeSet.add(Range.closed(1, 10)); // {[1, 10]}
* rangeSet.add(Range.closedOpen(11, 15)); // disconnected range; {[1, 10], [11, 15)}
* rangeSet.add(Range.closedOpen(15, 20)); // connected range; {[1, 10], [11, 20)}
* rangeSet.add(Range.openClosed(0, 0)); // empty range; {[1, 10], [11, 20)}
* rangeSet.remove(Range.open(5, 10)); // splits [1, 10]; {[1, 5], [10, 10], [11, 20)}
* }</pre>
*
* <p>Note that the behavior of {@link Range#isEmpty()} and {@link Range#isConnected(Range)} may not
* be as expected on discrete ranges. See the Javadoc of those methods for details.
*
* <p>For a {@link Set} whose contents are specified by a {@link Range}, see {@link ContiguousSet}.
*
* <p>See the Guava User Guide article on <a href=
* "https://github.com/google/guava/wiki/NewCollectionTypesExplained#rangeset">RangeSets</a>.
*
* @author Kevin Bourrillion
* @author Louis Wasserman
* @since 14.0
*/
@SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989
@DoNotMock("Use ImmutableRangeSet or TreeRangeSet")
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public interface RangeSet<C extends Comparable> {
// TODO(lowasser): consider adding default implementations of some of these methods
// Query methods
/** Determines whether any of this range set's member ranges contains {@code value}. */
boolean contains(C value);
/**
* Returns the unique range from this range set that {@linkplain Range#contains contains} {@code
* value}, or {@code null} if this range set does not contain {@code value}.
*/
@CheckForNull
Range<C> rangeContaining(C value);
/**
* Returns {@code true} if there exists a non-empty range enclosed by both a member range in this
* range set and the specified range. This is equivalent to calling {@code
* subRangeSet(otherRange)} and testing whether the resulting range set is non-empty.
*
* @since 20.0
*/
boolean intersects(Range<C> otherRange);
/**
* Returns {@code true} if there exists a member range in this range set which {@linkplain
* Range#encloses encloses} the specified range.
*/
boolean encloses(Range<C> otherRange);
/**
* Returns {@code true} if for each member range in {@code other} there exists a member range in
* this range set which {@linkplain Range#encloses encloses} it. It follows that {@code
* this.contains(value)} whenever {@code other.contains(value)}. Returns {@code true} if {@code
* other} is empty.
*
* <p>This is equivalent to checking if this range set {@link #encloses} each of the ranges in
* {@code other}.
*/
boolean enclosesAll(RangeSet<C> other);
/**
* Returns {@code true} if for each range in {@code other} there exists a member range in this
* range set which {@linkplain Range#encloses encloses} it. Returns {@code true} if {@code other}
* is empty.
*
* <p>This is equivalent to checking if this range set {@link #encloses} each range in {@code
* other}.
*
* @since 21.0
*/
default boolean enclosesAll(Iterable<Range<C>> other) {
for (Range<C> range : other) {
if (!encloses(range)) {
return false;
}
}
return true;
}
/** Returns {@code true} if this range set contains no ranges. */
boolean isEmpty();
/**
* Returns the minimal range which {@linkplain Range#encloses(Range) encloses} all ranges in this
* range set.
*
* @throws NoSuchElementException if this range set is {@linkplain #isEmpty() empty}
*/
Range<C> span();
// Views
/**
* Returns a view of the {@linkplain Range#isConnected disconnected} ranges that make up this
* range set. The returned set may be empty. The iterators returned by its {@link
* Iterable#iterator} method return the ranges in increasing order of lower bound (equivalently,
* of upper bound).
*/
Set<Range<C>> asRanges();
/**
* Returns a descending view of the {@linkplain Range#isConnected disconnected} ranges that make
* up this range set. The returned set may be empty. The iterators returned by its {@link
* Iterable#iterator} method return the ranges in decreasing order of lower bound (equivalently,
* of upper bound).
*
* @since 19.0
*/
Set<Range<C>> asDescendingSetOfRanges();
/**
* Returns a view of the complement of this {@code RangeSet}.
*
* <p>The returned view supports the {@link #add} operation if this {@code RangeSet} supports
* {@link #remove}, and vice versa.
*/
RangeSet<C> complement();
/**
* Returns a view of the intersection of this {@code RangeSet} with the specified range.
*
* <p>The returned view supports all optional operations supported by this {@code RangeSet}, with
* the caveat that an {@link IllegalArgumentException} is thrown on an attempt to {@linkplain
* #add(Range) add} any range not {@linkplain Range#encloses(Range) enclosed} by {@code view}.
*/
RangeSet<C> subRangeSet(Range<C> view);
// Modification
/**
* Adds the specified range to this {@code RangeSet} (optional operation). That is, for equal
* range sets a and b, the result of {@code a.add(range)} is that {@code a} will be the minimal
* range set for which both {@code a.enclosesAll(b)} and {@code a.encloses(range)}.
*
* <p>Note that {@code range} will be {@linkplain Range#span(Range) coalesced} with any ranges in
* the range set that are {@linkplain Range#isConnected(Range) connected} with it. Moreover, if
* {@code range} is empty, this is a no-op.
*
* @throws UnsupportedOperationException if this range set does not support the {@code add}
* operation
*/
void add(Range<C> range);
/**
* Removes the specified range from this {@code RangeSet} (optional operation). After this
* operation, if {@code range.contains(c)}, {@code this.contains(c)} will return {@code false}.
*
* <p>If {@code range} is empty, this is a no-op.
*
* @throws UnsupportedOperationException if this range set does not support the {@code remove}
* operation
*/
void remove(Range<C> range);
/**
* Removes all ranges from this {@code RangeSet} (optional operation). After this operation,
* {@code this.contains(c)} will return false for all {@code c}.
*
* <p>This is equivalent to {@code remove(Range.all())}.
*
* @throws UnsupportedOperationException if this range set does not support the {@code clear}
* operation
*/
void clear();
/**
* Adds all of the ranges from the specified range set to this range set (optional operation).
* After this operation, this range set is the minimal range set that {@linkplain
* #enclosesAll(RangeSet) encloses} both the original range set and {@code other}.
*
* <p>This is equivalent to calling {@link #add} on each of the ranges in {@code other} in turn.
*
* @throws UnsupportedOperationException if this range set does not support the {@code addAll}
* operation
*/
void addAll(RangeSet<C> other);
/**
* Adds all of the specified ranges to this range set (optional operation). After this operation,
* this range set is the minimal range set that {@linkplain #enclosesAll(RangeSet) encloses} both
* the original range set and each range in {@code other}.
*
* <p>This is equivalent to calling {@link #add} on each of the ranges in {@code other} in turn.
*
* @throws UnsupportedOperationException if this range set does not support the {@code addAll}
* operation
* @since 21.0
*/
default void addAll(Iterable<Range<C>> ranges) {
for (Range<C> range : ranges) {
add(range);
}
}
/**
* Removes all of the ranges from the specified range set from this range set (optional
* operation). After this operation, if {@code other.contains(c)}, {@code this.contains(c)} will
* return {@code false}.
*
* <p>This is equivalent to calling {@link #remove} on each of the ranges in {@code other} in
* turn.
*
* @throws UnsupportedOperationException if this range set does not support the {@code removeAll}
* operation
*/
void removeAll(RangeSet<C> other);
/**
* Removes all of the specified ranges from this range set (optional operation).
*
* <p>This is equivalent to calling {@link #remove} on each of the ranges in {@code other} in
* turn.
*
* @throws UnsupportedOperationException if this range set does not support the {@code removeAll}
* operation
* @since 21.0
*/
default void removeAll(Iterable<Range<C>> ranges) {
for (Range<C> range : ranges) {
remove(range);
}
}
// Object methods
/**
* Returns {@code true} if {@code obj} is another {@code RangeSet} that contains the same ranges
* according to {@link Range#equals(Object)}.
*/
@Override
boolean equals(@CheckForNull Object obj);
/** Returns {@code asRanges().hashCode()}. */
@Override
int hashCode();
/**
* Returns a readable string representation of this range set. For example, if this {@code
* RangeSet} consisted of {@code Range.closed(1, 3)} and {@code Range.greaterThan(4)}, this might
* return {@code " [1..3](4..+∞)}"}.
*/
@Override
String toString();
}
| google/guava | guava/src/com/google/common/collect/RangeSet.java |
44,444 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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.iluwatar.nullobject;
/**
* Interface for binary tree node.
*/
public interface Node {
String getName();
int getTreeSize();
Node getLeft();
Node getRight();
void walk();
}
| smedals/java-design-patterns | null-object/src/main/java/com/iluwatar/nullobject/Node.java |
44,445 | /*
* Copyright (C) 2015 The Guava Authors
*
* 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.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT;
import static java.lang.Math.min;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.math.LongMath;
import com.google.errorprone.annotations.InlineMe;
import com.google.errorprone.annotations.InlineMeValidationDisabled;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Deque;
import java.util.Iterator;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.OptionalLong;
import java.util.PrimitiveIterator;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.Spliterators.AbstractSpliterator;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.DoubleConsumer;
import java.util.function.IntConsumer;
import java.util.function.LongConsumer;
import java.util.stream.BaseStream;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Static utility methods related to {@code Stream} instances.
*
* @since 21.0
*/
@GwtCompatible
@ElementTypesAreNonnullByDefault
public final class Streams {
/**
* Returns a sequential {@link Stream} of the contents of {@code iterable}, delegating to {@link
* Collection#stream} if possible.
*/
public static <T extends @Nullable Object> Stream<T> stream(Iterable<T> iterable) {
return (iterable instanceof Collection)
? ((Collection<T>) iterable).stream()
: StreamSupport.stream(iterable.spliterator(), false);
}
/**
* Returns {@link Collection#stream}.
*
* @deprecated There is no reason to use this; just invoke {@code collection.stream()} directly.
*/
@Deprecated
@InlineMe(replacement = "collection.stream()")
public static <T extends @Nullable Object> Stream<T> stream(Collection<T> collection) {
return collection.stream();
}
/**
* Returns a sequential {@link Stream} of the remaining contents of {@code iterator}. Do not use
* {@code iterator} directly after passing it to this method.
*/
public static <T extends @Nullable Object> Stream<T> stream(Iterator<T> iterator) {
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, 0), false);
}
/**
* If a value is present in {@code optional}, returns a stream containing only that element,
* otherwise returns an empty stream.
*/
public static <T> Stream<T> stream(com.google.common.base.Optional<T> optional) {
return optional.isPresent() ? Stream.of(optional.get()) : Stream.empty();
}
/**
* If a value is present in {@code optional}, returns a stream containing only that element,
* otherwise returns an empty stream.
*
* <p><b>Java 9 users:</b> use {@code optional.stream()} instead.
*/
@Beta
@InlineMe(replacement = "optional.stream()")
@InlineMeValidationDisabled("Java 9+ API only")
public static <T> Stream<T> stream(java.util.Optional<T> optional) {
return optional.isPresent() ? Stream.of(optional.get()) : Stream.empty();
}
/**
* If a value is present in {@code optional}, returns a stream containing only that element,
* otherwise returns an empty stream.
*
* <p><b>Java 9 users:</b> use {@code optional.stream()} instead.
*/
@Beta
@InlineMe(replacement = "optional.stream()")
@InlineMeValidationDisabled("Java 9+ API only")
public static IntStream stream(OptionalInt optional) {
return optional.isPresent() ? IntStream.of(optional.getAsInt()) : IntStream.empty();
}
/**
* If a value is present in {@code optional}, returns a stream containing only that element,
* otherwise returns an empty stream.
*
* <p><b>Java 9 users:</b> use {@code optional.stream()} instead.
*/
@Beta
@InlineMe(replacement = "optional.stream()")
@InlineMeValidationDisabled("Java 9+ API only")
public static LongStream stream(OptionalLong optional) {
return optional.isPresent() ? LongStream.of(optional.getAsLong()) : LongStream.empty();
}
/**
* If a value is present in {@code optional}, returns a stream containing only that element,
* otherwise returns an empty stream.
*
* <p><b>Java 9 users:</b> use {@code optional.stream()} instead.
*/
@Beta
@InlineMe(replacement = "optional.stream()")
@InlineMeValidationDisabled("Java 9+ API only")
public static DoubleStream stream(OptionalDouble optional) {
return optional.isPresent() ? DoubleStream.of(optional.getAsDouble()) : DoubleStream.empty();
}
@SuppressWarnings("CatchingUnchecked") // sneaky checked exception
private static void closeAll(BaseStream<?, ?>[] toClose) {
// If one of the streams throws an exception, continue closing the others, then throw the
// exception later. If more than one stream throws an exception, the later ones are added to the
// first as suppressed exceptions. We don't catch Error on the grounds that it should be allowed
// to propagate immediately.
Exception exception = null;
for (BaseStream<?, ?> stream : toClose) {
try {
stream.close();
} catch (Exception e) { // sneaky checked exception
if (exception == null) {
exception = e;
} else {
exception.addSuppressed(e);
}
}
}
if (exception != null) {
// Normally this is a RuntimeException that doesn't need sneakyThrow.
// But theoretically we could see sneaky checked exception
sneakyThrow(exception);
}
}
/** Throws an undeclared checked exception. */
private static void sneakyThrow(Throwable t) {
class SneakyThrower<T extends Throwable> {
@SuppressWarnings("unchecked") // not really safe, but that's the point
void throwIt(Throwable t) throws T {
throw (T) t;
}
}
new SneakyThrower<Error>().throwIt(t);
}
/**
* Returns a {@link Stream} containing the elements of the first stream, followed by the elements
* of the second stream, and so on.
*
* <p>This is equivalent to {@code Stream.of(streams).flatMap(stream -> stream)}, but the returned
* stream may perform better.
*
* @see Stream#concat(Stream, Stream)
*/
@SuppressWarnings("unchecked") // could probably be avoided with a forwarding Spliterator
@SafeVarargs
public static <T extends @Nullable Object> Stream<T> concat(Stream<? extends T>... streams) {
// TODO(lowasser): consider an implementation that can support SUBSIZED
boolean isParallel = false;
int characteristics = Spliterator.ORDERED | Spliterator.SIZED | Spliterator.NONNULL;
long estimatedSize = 0L;
ImmutableList.Builder<Spliterator<? extends T>> splitrsBuilder =
new ImmutableList.Builder<>(streams.length);
for (Stream<? extends T> stream : streams) {
isParallel |= stream.isParallel();
Spliterator<? extends T> splitr = stream.spliterator();
splitrsBuilder.add(splitr);
characteristics &= splitr.characteristics();
estimatedSize = LongMath.saturatedAdd(estimatedSize, splitr.estimateSize());
}
return StreamSupport.stream(
CollectSpliterators.flatMap(
splitrsBuilder.build().spliterator(),
splitr -> (Spliterator<T>) splitr,
characteristics,
estimatedSize),
isParallel)
.onClose(() -> closeAll(streams));
}
/**
* Returns an {@link IntStream} containing the elements of the first stream, followed by the
* elements of the second stream, and so on.
*
* <p>This is equivalent to {@code Stream.of(streams).flatMapToInt(stream -> stream)}, but the
* returned stream may perform better.
*
* @see IntStream#concat(IntStream, IntStream)
*/
public static IntStream concat(IntStream... streams) {
boolean isParallel = false;
int characteristics = Spliterator.ORDERED | Spliterator.SIZED | Spliterator.NONNULL;
long estimatedSize = 0L;
ImmutableList.Builder<Spliterator.OfInt> splitrsBuilder =
new ImmutableList.Builder<>(streams.length);
for (IntStream stream : streams) {
isParallel |= stream.isParallel();
Spliterator.OfInt splitr = stream.spliterator();
splitrsBuilder.add(splitr);
characteristics &= splitr.characteristics();
estimatedSize = LongMath.saturatedAdd(estimatedSize, splitr.estimateSize());
}
return StreamSupport.intStream(
CollectSpliterators.flatMapToInt(
splitrsBuilder.build().spliterator(),
splitr -> splitr,
characteristics,
estimatedSize),
isParallel)
.onClose(() -> closeAll(streams));
}
/**
* Returns a {@link LongStream} containing the elements of the first stream, followed by the
* elements of the second stream, and so on.
*
* <p>This is equivalent to {@code Stream.of(streams).flatMapToLong(stream -> stream)}, but the
* returned stream may perform better.
*
* @see LongStream#concat(LongStream, LongStream)
*/
public static LongStream concat(LongStream... streams) {
boolean isParallel = false;
int characteristics = Spliterator.ORDERED | Spliterator.SIZED | Spliterator.NONNULL;
long estimatedSize = 0L;
ImmutableList.Builder<Spliterator.OfLong> splitrsBuilder =
new ImmutableList.Builder<>(streams.length);
for (LongStream stream : streams) {
isParallel |= stream.isParallel();
Spliterator.OfLong splitr = stream.spliterator();
splitrsBuilder.add(splitr);
characteristics &= splitr.characteristics();
estimatedSize = LongMath.saturatedAdd(estimatedSize, splitr.estimateSize());
}
return StreamSupport.longStream(
CollectSpliterators.flatMapToLong(
splitrsBuilder.build().spliterator(),
splitr -> splitr,
characteristics,
estimatedSize),
isParallel)
.onClose(() -> closeAll(streams));
}
/**
* Returns a {@link DoubleStream} containing the elements of the first stream, followed by the
* elements of the second stream, and so on.
*
* <p>This is equivalent to {@code Stream.of(streams).flatMapToDouble(stream -> stream)}, but the
* returned stream may perform better.
*
* @see DoubleStream#concat(DoubleStream, DoubleStream)
*/
public static DoubleStream concat(DoubleStream... streams) {
boolean isParallel = false;
int characteristics = Spliterator.ORDERED | Spliterator.SIZED | Spliterator.NONNULL;
long estimatedSize = 0L;
ImmutableList.Builder<Spliterator.OfDouble> splitrsBuilder =
new ImmutableList.Builder<>(streams.length);
for (DoubleStream stream : streams) {
isParallel |= stream.isParallel();
Spliterator.OfDouble splitr = stream.spliterator();
splitrsBuilder.add(splitr);
characteristics &= splitr.characteristics();
estimatedSize = LongMath.saturatedAdd(estimatedSize, splitr.estimateSize());
}
return StreamSupport.doubleStream(
CollectSpliterators.flatMapToDouble(
splitrsBuilder.build().spliterator(),
splitr -> splitr,
characteristics,
estimatedSize),
isParallel)
.onClose(() -> closeAll(streams));
}
/**
* Returns a stream in which each element is the result of passing the corresponding element of
* each of {@code streamA} and {@code streamB} to {@code function}.
*
* <p>For example:
*
* <pre>{@code
* Streams.zip(
* Stream.of("foo1", "foo2", "foo3"),
* Stream.of("bar1", "bar2"),
* (arg1, arg2) -> arg1 + ":" + arg2)
* }</pre>
*
* <p>will return {@code Stream.of("foo1:bar1", "foo2:bar2")}.
*
* <p>The resulting stream will only be as long as the shorter of the two input streams; if one
* stream is longer, its extra elements will be ignored.
*
* <p>Note that if you are calling {@link Stream#forEach} on the resulting stream, you might want
* to consider using {@link #forEachPair} instead of this method.
*
* <p><b>Performance note:</b> The resulting stream is not <a
* href="http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html">efficiently splittable</a>.
* This may harm parallel performance.
*/
@Beta
public static <A extends @Nullable Object, B extends @Nullable Object, R extends @Nullable Object>
Stream<R> zip(
Stream<A> streamA, Stream<B> streamB, BiFunction<? super A, ? super B, R> function) {
checkNotNull(streamA);
checkNotNull(streamB);
checkNotNull(function);
boolean isParallel = streamA.isParallel() || streamB.isParallel(); // same as Stream.concat
Spliterator<A> splitrA = streamA.spliterator();
Spliterator<B> splitrB = streamB.spliterator();
int characteristics =
splitrA.characteristics()
& splitrB.characteristics()
& (Spliterator.SIZED | Spliterator.ORDERED);
Iterator<A> itrA = Spliterators.iterator(splitrA);
Iterator<B> itrB = Spliterators.iterator(splitrB);
return StreamSupport.stream(
new AbstractSpliterator<R>(
min(splitrA.estimateSize(), splitrB.estimateSize()), characteristics) {
@Override
public boolean tryAdvance(Consumer<? super R> action) {
if (itrA.hasNext() && itrB.hasNext()) {
action.accept(function.apply(itrA.next(), itrB.next()));
return true;
}
return false;
}
},
isParallel)
.onClose(streamA::close)
.onClose(streamB::close);
}
/**
* Invokes {@code consumer} once for each pair of <i>corresponding</i> elements in {@code streamA}
* and {@code streamB}. If one stream is longer than the other, the extra elements are silently
* ignored. Elements passed to the consumer are guaranteed to come from the same position in their
* respective source streams. For example:
*
* <pre>{@code
* Streams.forEachPair(
* Stream.of("foo1", "foo2", "foo3"),
* Stream.of("bar1", "bar2"),
* (arg1, arg2) -> System.out.println(arg1 + ":" + arg2)
* }</pre>
*
* <p>will print:
*
* <pre>{@code
* foo1:bar1
* foo2:bar2
* }</pre>
*
* <p><b>Warning:</b> If either supplied stream is a parallel stream, the same correspondence
* between elements will be made, but the order in which those pairs of elements are passed to the
* consumer is <i>not</i> defined.
*
* <p>Note that many usages of this method can be replaced with simpler calls to {@link #zip}.
* This method behaves equivalently to {@linkplain #zip zipping} the stream elements into
* temporary pair objects and then using {@link Stream#forEach} on that stream.
*
* @since 22.0
*/
@Beta
public static <A extends @Nullable Object, B extends @Nullable Object> void forEachPair(
Stream<A> streamA, Stream<B> streamB, BiConsumer<? super A, ? super B> consumer) {
checkNotNull(consumer);
if (streamA.isParallel() || streamB.isParallel()) {
zip(streamA, streamB, TemporaryPair::new).forEach(pair -> consumer.accept(pair.a, pair.b));
} else {
Iterator<A> iterA = streamA.iterator();
Iterator<B> iterB = streamB.iterator();
while (iterA.hasNext() && iterB.hasNext()) {
consumer.accept(iterA.next(), iterB.next());
}
}
}
// Use this carefully - it doesn't implement value semantics
private static class TemporaryPair<A extends @Nullable Object, B extends @Nullable Object> {
@ParametricNullness final A a;
@ParametricNullness final B b;
TemporaryPair(@ParametricNullness A a, @ParametricNullness B b) {
this.a = a;
this.b = b;
}
}
/**
* Returns a stream consisting of the results of applying the given function to the elements of
* {@code stream} and their indices in the stream. For example,
*
* <pre>{@code
* mapWithIndex(
* Stream.of("a", "b", "c"),
* (e, index) -> index + ":" + e)
* }</pre>
*
* <p>would return {@code Stream.of("0:a", "1:b", "2:c")}.
*
* <p>The resulting stream is <a
* href="http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html">efficiently splittable</a>
* if and only if {@code stream} was efficiently splittable and its underlying spliterator
* reported {@link Spliterator#SUBSIZED}. This is generally the case if the underlying stream
* comes from a data structure supporting efficient indexed random access, typically an array or
* list.
*
* <p>The order of the resulting stream is defined if and only if the order of the original stream
* was defined.
*/
public static <T extends @Nullable Object, R extends @Nullable Object> Stream<R> mapWithIndex(
Stream<T> stream, FunctionWithIndex<? super T, ? extends R> function) {
checkNotNull(stream);
checkNotNull(function);
boolean isParallel = stream.isParallel();
Spliterator<T> fromSpliterator = stream.spliterator();
if (!fromSpliterator.hasCharacteristics(Spliterator.SUBSIZED)) {
Iterator<T> fromIterator = Spliterators.iterator(fromSpliterator);
return StreamSupport.stream(
new AbstractSpliterator<R>(
fromSpliterator.estimateSize(),
fromSpliterator.characteristics() & (Spliterator.ORDERED | Spliterator.SIZED)) {
long index = 0;
@Override
public boolean tryAdvance(Consumer<? super R> action) {
if (fromIterator.hasNext()) {
action.accept(function.apply(fromIterator.next(), index++));
return true;
}
return false;
}
},
isParallel)
.onClose(stream::close);
}
class Splitr extends MapWithIndexSpliterator<Spliterator<T>, R, Splitr> implements Consumer<T> {
@CheckForNull T holder;
Splitr(Spliterator<T> splitr, long index) {
super(splitr, index);
}
@Override
public void accept(@ParametricNullness T t) {
this.holder = t;
}
@Override
public boolean tryAdvance(Consumer<? super R> action) {
if (fromSpliterator.tryAdvance(this)) {
try {
// The cast is safe because tryAdvance puts a T into `holder`.
action.accept(function.apply(uncheckedCastNullableTToT(holder), index++));
return true;
} finally {
holder = null;
}
}
return false;
}
@Override
Splitr createSplit(Spliterator<T> from, long i) {
return new Splitr(from, i);
}
}
return StreamSupport.stream(new Splitr(fromSpliterator, 0), isParallel).onClose(stream::close);
}
/**
* Returns a stream consisting of the results of applying the given function to the elements of
* {@code stream} and their indexes in the stream. For example,
*
* <pre>{@code
* mapWithIndex(
* IntStream.of(10, 11, 12),
* (e, index) -> index + ":" + e)
* }</pre>
*
* <p>...would return {@code Stream.of("0:10", "1:11", "2:12")}.
*
* <p>The resulting stream is <a
* href="http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html">efficiently splittable</a>
* if and only if {@code stream} was efficiently splittable and its underlying spliterator
* reported {@link Spliterator#SUBSIZED}. This is generally the case if the underlying stream
* comes from a data structure supporting efficient indexed random access, typically an array or
* list.
*
* <p>The order of the resulting stream is defined if and only if the order of the original stream
* was defined.
*/
public static <R extends @Nullable Object> Stream<R> mapWithIndex(
IntStream stream, IntFunctionWithIndex<R> function) {
checkNotNull(stream);
checkNotNull(function);
boolean isParallel = stream.isParallel();
Spliterator.OfInt fromSpliterator = stream.spliterator();
if (!fromSpliterator.hasCharacteristics(Spliterator.SUBSIZED)) {
PrimitiveIterator.OfInt fromIterator = Spliterators.iterator(fromSpliterator);
return StreamSupport.stream(
new AbstractSpliterator<R>(
fromSpliterator.estimateSize(),
fromSpliterator.characteristics() & (Spliterator.ORDERED | Spliterator.SIZED)) {
long index = 0;
@Override
public boolean tryAdvance(Consumer<? super R> action) {
if (fromIterator.hasNext()) {
action.accept(function.apply(fromIterator.nextInt(), index++));
return true;
}
return false;
}
},
isParallel)
.onClose(stream::close);
}
class Splitr extends MapWithIndexSpliterator<Spliterator.OfInt, R, Splitr>
implements IntConsumer, Spliterator<R> {
int holder;
Splitr(Spliterator.OfInt splitr, long index) {
super(splitr, index);
}
@Override
public void accept(int t) {
this.holder = t;
}
@Override
public boolean tryAdvance(Consumer<? super R> action) {
if (fromSpliterator.tryAdvance(this)) {
action.accept(function.apply(holder, index++));
return true;
}
return false;
}
@Override
Splitr createSplit(Spliterator.OfInt from, long i) {
return new Splitr(from, i);
}
}
return StreamSupport.stream(new Splitr(fromSpliterator, 0), isParallel).onClose(stream::close);
}
/**
* Returns a stream consisting of the results of applying the given function to the elements of
* {@code stream} and their indexes in the stream. For example,
*
* <pre>{@code
* mapWithIndex(
* LongStream.of(10, 11, 12),
* (e, index) -> index + ":" + e)
* }</pre>
*
* <p>...would return {@code Stream.of("0:10", "1:11", "2:12")}.
*
* <p>The resulting stream is <a
* href="http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html">efficiently splittable</a>
* if and only if {@code stream} was efficiently splittable and its underlying spliterator
* reported {@link Spliterator#SUBSIZED}. This is generally the case if the underlying stream
* comes from a data structure supporting efficient indexed random access, typically an array or
* list.
*
* <p>The order of the resulting stream is defined if and only if the order of the original stream
* was defined.
*/
public static <R extends @Nullable Object> Stream<R> mapWithIndex(
LongStream stream, LongFunctionWithIndex<R> function) {
checkNotNull(stream);
checkNotNull(function);
boolean isParallel = stream.isParallel();
Spliterator.OfLong fromSpliterator = stream.spliterator();
if (!fromSpliterator.hasCharacteristics(Spliterator.SUBSIZED)) {
PrimitiveIterator.OfLong fromIterator = Spliterators.iterator(fromSpliterator);
return StreamSupport.stream(
new AbstractSpliterator<R>(
fromSpliterator.estimateSize(),
fromSpliterator.characteristics() & (Spliterator.ORDERED | Spliterator.SIZED)) {
long index = 0;
@Override
public boolean tryAdvance(Consumer<? super R> action) {
if (fromIterator.hasNext()) {
action.accept(function.apply(fromIterator.nextLong(), index++));
return true;
}
return false;
}
},
isParallel)
.onClose(stream::close);
}
class Splitr extends MapWithIndexSpliterator<Spliterator.OfLong, R, Splitr>
implements LongConsumer, Spliterator<R> {
long holder;
Splitr(Spliterator.OfLong splitr, long index) {
super(splitr, index);
}
@Override
public void accept(long t) {
this.holder = t;
}
@Override
public boolean tryAdvance(Consumer<? super R> action) {
if (fromSpliterator.tryAdvance(this)) {
action.accept(function.apply(holder, index++));
return true;
}
return false;
}
@Override
Splitr createSplit(Spliterator.OfLong from, long i) {
return new Splitr(from, i);
}
}
return StreamSupport.stream(new Splitr(fromSpliterator, 0), isParallel).onClose(stream::close);
}
/**
* Returns a stream consisting of the results of applying the given function to the elements of
* {@code stream} and their indexes in the stream. For example,
*
* <pre>{@code
* mapWithIndex(
* DoubleStream.of(0.0, 1.0, 2.0)
* (e, index) -> index + ":" + e)
* }</pre>
*
* <p>...would return {@code Stream.of("0:0.0", "1:1.0", "2:2.0")}.
*
* <p>The resulting stream is <a
* href="http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html">efficiently splittable</a>
* if and only if {@code stream} was efficiently splittable and its underlying spliterator
* reported {@link Spliterator#SUBSIZED}. This is generally the case if the underlying stream
* comes from a data structure supporting efficient indexed random access, typically an array or
* list.
*
* <p>The order of the resulting stream is defined if and only if the order of the original stream
* was defined.
*/
public static <R extends @Nullable Object> Stream<R> mapWithIndex(
DoubleStream stream, DoubleFunctionWithIndex<R> function) {
checkNotNull(stream);
checkNotNull(function);
boolean isParallel = stream.isParallel();
Spliterator.OfDouble fromSpliterator = stream.spliterator();
if (!fromSpliterator.hasCharacteristics(Spliterator.SUBSIZED)) {
PrimitiveIterator.OfDouble fromIterator = Spliterators.iterator(fromSpliterator);
return StreamSupport.stream(
new AbstractSpliterator<R>(
fromSpliterator.estimateSize(),
fromSpliterator.characteristics() & (Spliterator.ORDERED | Spliterator.SIZED)) {
long index = 0;
@Override
public boolean tryAdvance(Consumer<? super R> action) {
if (fromIterator.hasNext()) {
action.accept(function.apply(fromIterator.nextDouble(), index++));
return true;
}
return false;
}
},
isParallel)
.onClose(stream::close);
}
class Splitr extends MapWithIndexSpliterator<Spliterator.OfDouble, R, Splitr>
implements DoubleConsumer, Spliterator<R> {
double holder;
Splitr(Spliterator.OfDouble splitr, long index) {
super(splitr, index);
}
@Override
public void accept(double t) {
this.holder = t;
}
@Override
public boolean tryAdvance(Consumer<? super R> action) {
if (fromSpliterator.tryAdvance(this)) {
action.accept(function.apply(holder, index++));
return true;
}
return false;
}
@Override
Splitr createSplit(Spliterator.OfDouble from, long i) {
return new Splitr(from, i);
}
}
return StreamSupport.stream(new Splitr(fromSpliterator, 0), isParallel).onClose(stream::close);
}
/**
* An analogue of {@link java.util.function.Function} also accepting an index.
*
* <p>This interface is only intended for use by callers of {@link #mapWithIndex(Stream,
* FunctionWithIndex)}.
*
* @since 21.0
*/
public interface FunctionWithIndex<T extends @Nullable Object, R extends @Nullable Object> {
/** Applies this function to the given argument and its index within a stream. */
@ParametricNullness
R apply(@ParametricNullness T from, long index);
}
private abstract static class MapWithIndexSpliterator<
F extends Spliterator<?>,
R extends @Nullable Object,
S extends MapWithIndexSpliterator<F, R, S>>
implements Spliterator<R> {
final F fromSpliterator;
long index;
MapWithIndexSpliterator(F fromSpliterator, long index) {
this.fromSpliterator = fromSpliterator;
this.index = index;
}
abstract S createSplit(F from, long i);
@Override
@CheckForNull
public S trySplit() {
Spliterator<?> splitOrNull = fromSpliterator.trySplit();
if (splitOrNull == null) {
return null;
}
@SuppressWarnings("unchecked")
F split = (F) splitOrNull;
S result = createSplit(split, index);
this.index += split.getExactSizeIfKnown();
return result;
}
@Override
public long estimateSize() {
return fromSpliterator.estimateSize();
}
@Override
public int characteristics() {
return fromSpliterator.characteristics()
& (Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED);
}
}
/**
* An analogue of {@link java.util.function.IntFunction} also accepting an index.
*
* <p>This interface is only intended for use by callers of {@link #mapWithIndex(IntStream,
* IntFunctionWithIndex)}.
*
* @since 21.0
*/
public interface IntFunctionWithIndex<R extends @Nullable Object> {
/** Applies this function to the given argument and its index within a stream. */
@ParametricNullness
R apply(int from, long index);
}
/**
* An analogue of {@link java.util.function.LongFunction} also accepting an index.
*
* <p>This interface is only intended for use by callers of {@link #mapWithIndex(LongStream,
* LongFunctionWithIndex)}.
*
* @since 21.0
*/
public interface LongFunctionWithIndex<R extends @Nullable Object> {
/** Applies this function to the given argument and its index within a stream. */
@ParametricNullness
R apply(long from, long index);
}
/**
* An analogue of {@link java.util.function.DoubleFunction} also accepting an index.
*
* <p>This interface is only intended for use by callers of {@link #mapWithIndex(DoubleStream,
* DoubleFunctionWithIndex)}.
*
* @since 21.0
*/
public interface DoubleFunctionWithIndex<R extends @Nullable Object> {
/** Applies this function to the given argument and its index within a stream. */
@ParametricNullness
R apply(double from, long index);
}
/**
* Returns the last element of the specified stream, or {@link java.util.Optional#empty} if the
* stream is empty.
*
* <p>Equivalent to {@code stream.reduce((a, b) -> b)}, but may perform significantly better. This
* method's runtime will be between O(log n) and O(n), performing better on <a
* href="http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html">efficiently splittable</a>
* streams.
*
* <p>If the stream has nondeterministic order, this has equivalent semantics to {@link
* Stream#findAny} (which you might as well use).
*
* @see Stream#findFirst()
* @throws NullPointerException if the last element of the stream is null
*/
/*
* By declaring <T> instead of <T extends @Nullable Object>, we declare this method as requiring a
* stream whose elements are non-null. However, the method goes out of its way to still handle
* nulls in the stream. This means that the method can safely be used with a stream that contains
* nulls as long as the *last* element is *not* null.
*
* (To "go out of its way," the method tracks a `set` bit so that it can distinguish "the final
* split has a last element of null, so throw NPE" from "the final split was empty, so look for an
* element in the prior one.")
*/
public static <T> java.util.Optional<T> findLast(Stream<T> stream) {
class OptionalState {
boolean set = false;
@CheckForNull T value = null;
void set(T value) {
this.set = true;
this.value = value;
}
T get() {
/*
* requireNonNull is safe because we call get() only if we've previously called set().
*
* (For further discussion of nullness, see the comment above the method.)
*/
return requireNonNull(value);
}
}
OptionalState state = new OptionalState();
Deque<Spliterator<T>> splits = new ArrayDeque<>();
splits.addLast(stream.spliterator());
while (!splits.isEmpty()) {
Spliterator<T> spliterator = splits.removeLast();
if (spliterator.getExactSizeIfKnown() == 0) {
continue; // drop this split
}
// Many spliterators will have trySplits that are SUBSIZED even if they are not themselves
// SUBSIZED.
if (spliterator.hasCharacteristics(Spliterator.SUBSIZED)) {
// we can drill down to exactly the smallest nonempty spliterator
while (true) {
Spliterator<T> prefix = spliterator.trySplit();
if (prefix == null || prefix.getExactSizeIfKnown() == 0) {
break;
} else if (spliterator.getExactSizeIfKnown() == 0) {
spliterator = prefix;
break;
}
}
// spliterator is known to be nonempty now
spliterator.forEachRemaining(state::set);
return java.util.Optional.of(state.get());
}
Spliterator<T> prefix = spliterator.trySplit();
if (prefix == null || prefix.getExactSizeIfKnown() == 0) {
// we can't split this any further
spliterator.forEachRemaining(state::set);
if (state.set) {
return java.util.Optional.of(state.get());
}
// fall back to the last split
continue;
}
splits.addLast(prefix);
splits.addLast(spliterator);
}
return java.util.Optional.empty();
}
/**
* Returns the last element of the specified stream, or {@link OptionalInt#empty} if the stream is
* empty.
*
* <p>Equivalent to {@code stream.reduce((a, b) -> b)}, but may perform significantly better. This
* method's runtime will be between O(log n) and O(n), performing better on <a
* href="http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html">efficiently splittable</a>
* streams.
*
* @see IntStream#findFirst()
* @throws NullPointerException if the last element of the stream is null
*/
public static OptionalInt findLast(IntStream stream) {
// findLast(Stream) does some allocation, so we might as well box some more
java.util.Optional<Integer> boxedLast = findLast(stream.boxed());
return boxedLast.map(OptionalInt::of).orElse(OptionalInt.empty());
}
/**
* Returns the last element of the specified stream, or {@link OptionalLong#empty} if the stream
* is empty.
*
* <p>Equivalent to {@code stream.reduce((a, b) -> b)}, but may perform significantly better. This
* method's runtime will be between O(log n) and O(n), performing better on <a
* href="http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html">efficiently splittable</a>
* streams.
*
* @see LongStream#findFirst()
* @throws NullPointerException if the last element of the stream is null
*/
public static OptionalLong findLast(LongStream stream) {
// findLast(Stream) does some allocation, so we might as well box some more
java.util.Optional<Long> boxedLast = findLast(stream.boxed());
return boxedLast.map(OptionalLong::of).orElse(OptionalLong.empty());
}
/**
* Returns the last element of the specified stream, or {@link OptionalDouble#empty} if the stream
* is empty.
*
* <p>Equivalent to {@code stream.reduce((a, b) -> b)}, but may perform significantly better. This
* method's runtime will be between O(log n) and O(n), performing better on <a
* href="http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html">efficiently splittable</a>
* streams.
*
* @see DoubleStream#findFirst()
* @throws NullPointerException if the last element of the stream is null
*/
public static OptionalDouble findLast(DoubleStream stream) {
// findLast(Stream) does some allocation, so we might as well box some more
java.util.Optional<Double> boxedLast = findLast(stream.boxed());
return boxedLast.map(OptionalDouble::of).orElse(OptionalDouble.empty());
}
private Streams() {}
}
| google/guava | guava/src/com/google/common/collect/Streams.java |
44,446 | /*
* Copyright (C) 2007 The Guava Authors
*
* 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.google.common.io;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndex;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import static java.lang.Math.max;
import static java.lang.Math.min;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import com.google.common.math.IntMath;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Queue;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Provides utility methods for working with byte arrays and I/O streams.
*
* @author Chris Nokleberg
* @author Colin Decker
* @since 1.0
*/
@J2ktIncompatible
@GwtIncompatible
@ElementTypesAreNonnullByDefault
public final class ByteStreams {
private static final int BUFFER_SIZE = 8192;
/** Creates a new byte array for buffering reads or writes. */
static byte[] createBuffer() {
return new byte[BUFFER_SIZE];
}
/**
* There are three methods to implement {@link FileChannel#transferTo(long, long,
* WritableByteChannel)}:
*
* <ol>
* <li>Use sendfile(2) or equivalent. Requires that both the input channel and the output
* channel have their own file descriptors. Generally this only happens when both channels
* are files or sockets. This performs zero copies - the bytes never enter userspace.
* <li>Use mmap(2) or equivalent. Requires that either the input channel or the output channel
* have file descriptors. Bytes are copied from the file into a kernel buffer, then directly
* into the other buffer (userspace). Note that if the file is very large, a naive
* implementation will effectively put the whole file in memory. On many systems with paging
* and virtual memory, this is not a problem - because it is mapped read-only, the kernel
* can always page it to disk "for free". However, on systems where killing processes
* happens all the time in normal conditions (i.e., android) the OS must make a tradeoff
* between paging memory and killing other processes - so allocating a gigantic buffer and
* then sequentially accessing it could result in other processes dying. This is solvable
* via madvise(2), but that obviously doesn't exist in java.
* <li>Ordinary copy. Kernel copies bytes into a kernel buffer, from a kernel buffer into a
* userspace buffer (byte[] or ByteBuffer), then copies them from that buffer into the
* destination channel.
* </ol>
*
* This value is intended to be large enough to make the overhead of system calls negligible,
* without being so large that it causes problems for systems with atypical memory management if
* approaches 2 or 3 are used.
*/
private static final int ZERO_COPY_CHUNK_SIZE = 512 * 1024;
private ByteStreams() {}
/**
* Copies all bytes from the input stream to the output stream. Does not close or flush either
* stream.
*
* <p><b>Java 9 users and later:</b> this method should be treated as deprecated; use the
* equivalent {@link InputStream#transferTo} method instead.
*
* @param from the input stream to read from
* @param to the output stream to write to
* @return the number of bytes copied
* @throws IOException if an I/O error occurs
*/
@CanIgnoreReturnValue
public static long copy(InputStream from, OutputStream to) throws IOException {
checkNotNull(from);
checkNotNull(to);
byte[] buf = createBuffer();
long total = 0;
while (true) {
int r = from.read(buf);
if (r == -1) {
break;
}
to.write(buf, 0, r);
total += r;
}
return total;
}
/**
* Copies all bytes from the readable channel to the writable channel. Does not close or flush
* either channel.
*
* @param from the readable channel to read from
* @param to the writable channel to write to
* @return the number of bytes copied
* @throws IOException if an I/O error occurs
*/
@CanIgnoreReturnValue
public static long copy(ReadableByteChannel from, WritableByteChannel to) throws IOException {
checkNotNull(from);
checkNotNull(to);
if (from instanceof FileChannel) {
FileChannel sourceChannel = (FileChannel) from;
long oldPosition = sourceChannel.position();
long position = oldPosition;
long copied;
do {
copied = sourceChannel.transferTo(position, ZERO_COPY_CHUNK_SIZE, to);
position += copied;
sourceChannel.position(position);
} while (copied > 0 || position < sourceChannel.size());
return position - oldPosition;
}
ByteBuffer buf = ByteBuffer.wrap(createBuffer());
long total = 0;
while (from.read(buf) != -1) {
Java8Compatibility.flip(buf);
while (buf.hasRemaining()) {
total += to.write(buf);
}
Java8Compatibility.clear(buf);
}
return total;
}
/** Max array length on JVM. */
private static final int MAX_ARRAY_LEN = Integer.MAX_VALUE - 8;
/** Large enough to never need to expand, given the geometric progression of buffer sizes. */
private static final int TO_BYTE_ARRAY_DEQUE_SIZE = 20;
/**
* Returns a byte array containing the bytes from the buffers already in {@code bufs} (which have
* a total combined length of {@code totalLen} bytes) followed by all bytes remaining in the given
* input stream.
*/
private static byte[] toByteArrayInternal(InputStream in, Queue<byte[]> bufs, int totalLen)
throws IOException {
// Roughly size to match what has been read already. Some file systems, such as procfs, return 0
// as their length. These files are very small, so it's wasteful to allocate an 8KB buffer.
int initialBufferSize = min(BUFFER_SIZE, max(128, Integer.highestOneBit(totalLen) * 2));
// Starting with an 8k buffer, double the size of each successive buffer. Smaller buffers
// quadruple in size until they reach 8k, to minimize the number of small reads for longer
// streams. Buffers are retained in a deque so that there's no copying between buffers while
// reading and so all of the bytes in each new allocated buffer are available for reading from
// the stream.
for (int bufSize = initialBufferSize;
totalLen < MAX_ARRAY_LEN;
bufSize = IntMath.saturatedMultiply(bufSize, bufSize < 4096 ? 4 : 2)) {
byte[] buf = new byte[min(bufSize, MAX_ARRAY_LEN - totalLen)];
bufs.add(buf);
int off = 0;
while (off < buf.length) {
// always OK to fill buf; its size plus the rest of bufs is never more than MAX_ARRAY_LEN
int r = in.read(buf, off, buf.length - off);
if (r == -1) {
return combineBuffers(bufs, totalLen);
}
off += r;
totalLen += r;
}
}
// read MAX_ARRAY_LEN bytes without seeing end of stream
if (in.read() == -1) {
// oh, there's the end of the stream
return combineBuffers(bufs, MAX_ARRAY_LEN);
} else {
throw new OutOfMemoryError("input is too large to fit in a byte array");
}
}
private static byte[] combineBuffers(Queue<byte[]> bufs, int totalLen) {
if (bufs.isEmpty()) {
return new byte[0];
}
byte[] result = bufs.remove();
if (result.length == totalLen) {
return result;
}
int remaining = totalLen - result.length;
result = Arrays.copyOf(result, totalLen);
while (remaining > 0) {
byte[] buf = bufs.remove();
int bytesToCopy = min(remaining, buf.length);
int resultOffset = totalLen - remaining;
System.arraycopy(buf, 0, result, resultOffset, bytesToCopy);
remaining -= bytesToCopy;
}
return result;
}
/**
* Reads all bytes from an input stream into a byte array. Does not close the stream.
*
* <p><b>Java 9+ users:</b> use {@code in#readAllBytes()} instead.
*
* @param in the input stream to read from
* @return a byte array containing all the bytes from the stream
* @throws IOException if an I/O error occurs
*/
public static byte[] toByteArray(InputStream in) throws IOException {
checkNotNull(in);
return toByteArrayInternal(in, new ArrayDeque<byte[]>(TO_BYTE_ARRAY_DEQUE_SIZE), 0);
}
/**
* Reads all bytes from an input stream into a byte array. The given expected size is used to
* create an initial byte array, but if the actual number of bytes read from the stream differs,
* the correct result will be returned anyway.
*/
static byte[] toByteArray(InputStream in, long expectedSize) throws IOException {
checkArgument(expectedSize >= 0, "expectedSize (%s) must be non-negative", expectedSize);
if (expectedSize > MAX_ARRAY_LEN) {
throw new OutOfMemoryError(expectedSize + " bytes is too large to fit in a byte array");
}
byte[] bytes = new byte[(int) expectedSize];
int remaining = (int) expectedSize;
while (remaining > 0) {
int off = (int) expectedSize - remaining;
int read = in.read(bytes, off, remaining);
if (read == -1) {
// end of stream before reading expectedSize bytes
// just return the bytes read so far
return Arrays.copyOf(bytes, off);
}
remaining -= read;
}
// bytes is now full
int b = in.read();
if (b == -1) {
return bytes;
}
// the stream was longer, so read the rest normally
Queue<byte[]> bufs = new ArrayDeque<>(TO_BYTE_ARRAY_DEQUE_SIZE + 2);
bufs.add(bytes);
bufs.add(new byte[] {(byte) b});
return toByteArrayInternal(in, bufs, bytes.length + 1);
}
/**
* Reads and discards data from the given {@code InputStream} until the end of the stream is
* reached. Returns the total number of bytes read. Does not close the stream.
*
* @since 20.0
*/
@CanIgnoreReturnValue
public static long exhaust(InputStream in) throws IOException {
long total = 0;
long read;
byte[] buf = createBuffer();
while ((read = in.read(buf)) != -1) {
total += read;
}
return total;
}
/**
* Returns a new {@link ByteArrayDataInput} instance to read from the {@code bytes} array from the
* beginning.
*/
public static ByteArrayDataInput newDataInput(byte[] bytes) {
return newDataInput(new ByteArrayInputStream(bytes));
}
/**
* Returns a new {@link ByteArrayDataInput} instance to read from the {@code bytes} array,
* starting at the given position.
*
* @throws IndexOutOfBoundsException if {@code start} is negative or greater than the length of
* the array
*/
public static ByteArrayDataInput newDataInput(byte[] bytes, int start) {
checkPositionIndex(start, bytes.length);
return newDataInput(new ByteArrayInputStream(bytes, start, bytes.length - start));
}
/**
* Returns a new {@link ByteArrayDataInput} instance to read from the given {@code
* ByteArrayInputStream}. The given input stream is not reset before being read from by the
* returned {@code ByteArrayDataInput}.
*
* @since 17.0
*/
public static ByteArrayDataInput newDataInput(ByteArrayInputStream byteArrayInputStream) {
return new ByteArrayDataInputStream(checkNotNull(byteArrayInputStream));
}
private static class ByteArrayDataInputStream implements ByteArrayDataInput {
final DataInput input;
ByteArrayDataInputStream(ByteArrayInputStream byteArrayInputStream) {
this.input = new DataInputStream(byteArrayInputStream);
}
@Override
public void readFully(byte b[]) {
try {
input.readFully(b);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public void readFully(byte b[], int off, int len) {
try {
input.readFully(b, off, len);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public int skipBytes(int n) {
try {
return input.skipBytes(n);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public boolean readBoolean() {
try {
return input.readBoolean();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public byte readByte() {
try {
return input.readByte();
} catch (EOFException e) {
throw new IllegalStateException(e);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override
public int readUnsignedByte() {
try {
return input.readUnsignedByte();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public short readShort() {
try {
return input.readShort();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public int readUnsignedShort() {
try {
return input.readUnsignedShort();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public char readChar() {
try {
return input.readChar();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public int readInt() {
try {
return input.readInt();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public long readLong() {
try {
return input.readLong();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public float readFloat() {
try {
return input.readFloat();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public double readDouble() {
try {
return input.readDouble();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override
@CheckForNull
public String readLine() {
try {
return input.readLine();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public String readUTF() {
try {
return input.readUTF();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
/** Returns a new {@link ByteArrayDataOutput} instance with a default size. */
public static ByteArrayDataOutput newDataOutput() {
return newDataOutput(new ByteArrayOutputStream());
}
/**
* Returns a new {@link ByteArrayDataOutput} instance sized to hold {@code size} bytes before
* resizing.
*
* @throws IllegalArgumentException if {@code size} is negative
*/
public static ByteArrayDataOutput newDataOutput(int size) {
// When called at high frequency, boxing size generates too much garbage,
// so avoid doing that if we can.
if (size < 0) {
throw new IllegalArgumentException(String.format("Invalid size: %s", size));
}
return newDataOutput(new ByteArrayOutputStream(size));
}
/**
* Returns a new {@link ByteArrayDataOutput} instance which writes to the given {@code
* ByteArrayOutputStream}. The given output stream is not reset before being written to by the
* returned {@code ByteArrayDataOutput} and new data will be appended to any existing content.
*
* <p>Note that if the given output stream was not empty or is modified after the {@code
* ByteArrayDataOutput} is created, the contract for {@link ByteArrayDataOutput#toByteArray} will
* not be honored (the bytes returned in the byte array may not be exactly what was written via
* calls to {@code ByteArrayDataOutput}).
*
* @since 17.0
*/
public static ByteArrayDataOutput newDataOutput(ByteArrayOutputStream byteArrayOutputStream) {
return new ByteArrayDataOutputStream(checkNotNull(byteArrayOutputStream));
}
private static class ByteArrayDataOutputStream implements ByteArrayDataOutput {
final DataOutput output;
final ByteArrayOutputStream byteArrayOutputStream;
ByteArrayDataOutputStream(ByteArrayOutputStream byteArrayOutputStream) {
this.byteArrayOutputStream = byteArrayOutputStream;
output = new DataOutputStream(byteArrayOutputStream);
}
@Override
public void write(int b) {
try {
output.write(b);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override
public void write(byte[] b) {
try {
output.write(b);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override
public void write(byte[] b, int off, int len) {
try {
output.write(b, off, len);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override
public void writeBoolean(boolean v) {
try {
output.writeBoolean(v);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override
public void writeByte(int v) {
try {
output.writeByte(v);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override
public void writeBytes(String s) {
try {
output.writeBytes(s);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override
public void writeChar(int v) {
try {
output.writeChar(v);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override
public void writeChars(String s) {
try {
output.writeChars(s);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override
public void writeDouble(double v) {
try {
output.writeDouble(v);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override
public void writeFloat(float v) {
try {
output.writeFloat(v);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override
public void writeInt(int v) {
try {
output.writeInt(v);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override
public void writeLong(long v) {
try {
output.writeLong(v);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override
public void writeShort(int v) {
try {
output.writeShort(v);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override
public void writeUTF(String s) {
try {
output.writeUTF(s);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override
public byte[] toByteArray() {
return byteArrayOutputStream.toByteArray();
}
}
private static final OutputStream NULL_OUTPUT_STREAM =
new OutputStream() {
/** Discards the specified byte. */
@Override
public void write(int b) {}
/** Discards the specified byte array. */
@Override
public void write(byte[] b) {
checkNotNull(b);
}
/** Discards the specified byte array. */
@Override
public void write(byte[] b, int off, int len) {
checkNotNull(b);
checkPositionIndexes(off, off + len, b.length);
}
@Override
public String toString() {
return "ByteStreams.nullOutputStream()";
}
};
/**
* Returns an {@link OutputStream} that simply discards written bytes.
*
* @since 14.0 (since 1.0 as com.google.common.io.NullOutputStream)
*/
public static OutputStream nullOutputStream() {
return NULL_OUTPUT_STREAM;
}
/**
* Wraps a {@link InputStream}, limiting the number of bytes which can be read.
*
* @param in the input stream to be wrapped
* @param limit the maximum number of bytes to be read
* @return a length-limited {@link InputStream}
* @since 14.0 (since 1.0 as com.google.common.io.LimitInputStream)
*/
public static InputStream limit(InputStream in, long limit) {
return new LimitedInputStream(in, limit);
}
private static final class LimitedInputStream extends FilterInputStream {
private long left;
private long mark = -1;
LimitedInputStream(InputStream in, long limit) {
super(in);
checkNotNull(in);
checkArgument(limit >= 0, "limit must be non-negative");
left = limit;
}
@Override
public int available() throws IOException {
return (int) Math.min(in.available(), left);
}
// it's okay to mark even if mark isn't supported, as reset won't work
@Override
public synchronized void mark(int readLimit) {
in.mark(readLimit);
mark = left;
}
@Override
public int read() throws IOException {
if (left == 0) {
return -1;
}
int result = in.read();
if (result != -1) {
--left;
}
return result;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if (left == 0) {
return -1;
}
len = (int) Math.min(len, left);
int result = in.read(b, off, len);
if (result != -1) {
left -= result;
}
return result;
}
@Override
public synchronized void reset() throws IOException {
if (!in.markSupported()) {
throw new IOException("Mark not supported");
}
if (mark == -1) {
throw new IOException("Mark not set");
}
in.reset();
left = mark;
}
@Override
public long skip(long n) throws IOException {
n = Math.min(n, left);
long skipped = in.skip(n);
left -= skipped;
return skipped;
}
}
/**
* Attempts to read enough bytes from the stream to fill the given byte array, with the same
* behavior as {@link DataInput#readFully(byte[])}. Does not close the stream.
*
* @param in the input stream to read from.
* @param b the buffer into which the data is read.
* @throws EOFException if this stream reaches the end before reading all the bytes.
* @throws IOException if an I/O error occurs.
*/
public static void readFully(InputStream in, byte[] b) throws IOException {
readFully(in, b, 0, b.length);
}
/**
* Attempts to read {@code len} bytes from the stream into the given array starting at {@code
* off}, with the same behavior as {@link DataInput#readFully(byte[], int, int)}. Does not close
* the stream.
*
* @param in the input stream to read from.
* @param b the buffer into which the data is read.
* @param off an int specifying the offset into the data.
* @param len an int specifying the number of bytes to read.
* @throws EOFException if this stream reaches the end before reading all the bytes.
* @throws IOException if an I/O error occurs.
*/
public static void readFully(InputStream in, byte[] b, int off, int len) throws IOException {
int read = read(in, b, off, len);
if (read != len) {
throw new EOFException(
"reached end of stream after reading " + read + " bytes; " + len + " bytes expected");
}
}
/**
* Discards {@code n} bytes of data from the input stream. This method will block until the full
* amount has been skipped. Does not close the stream.
*
* @param in the input stream to read from
* @param n the number of bytes to skip
* @throws EOFException if this stream reaches the end before skipping all the bytes
* @throws IOException if an I/O error occurs, or the stream does not support skipping
*/
public static void skipFully(InputStream in, long n) throws IOException {
long skipped = skipUpTo(in, n);
if (skipped < n) {
throw new EOFException(
"reached end of stream after skipping " + skipped + " bytes; " + n + " bytes expected");
}
}
/**
* Discards up to {@code n} bytes of data from the input stream. This method will block until
* either the full amount has been skipped or until the end of the stream is reached, whichever
* happens first. Returns the total number of bytes skipped.
*/
static long skipUpTo(InputStream in, long n) throws IOException {
long totalSkipped = 0;
// A buffer is allocated if skipSafely does not skip any bytes.
byte[] buf = null;
while (totalSkipped < n) {
long remaining = n - totalSkipped;
long skipped = skipSafely(in, remaining);
if (skipped == 0) {
// Do a buffered read since skipSafely could return 0 repeatedly, for example if
// in.available() always returns 0 (the default).
int skip = (int) Math.min(remaining, BUFFER_SIZE);
if (buf == null) {
// Allocate a buffer bounded by the maximum size that can be requested, for
// example an array of BUFFER_SIZE is unnecessary when the value of remaining
// is smaller.
buf = new byte[skip];
}
if ((skipped = in.read(buf, 0, skip)) == -1) {
// Reached EOF
break;
}
}
totalSkipped += skipped;
}
return totalSkipped;
}
/**
* Attempts to skip up to {@code n} bytes from the given input stream, but not more than {@code
* in.available()} bytes. This prevents {@code FileInputStream} from skipping more bytes than
* actually remain in the file, something that it {@linkplain java.io.FileInputStream#skip(long)
* specifies} it can do in its Javadoc despite the fact that it is violating the contract of
* {@code InputStream.skip()}.
*/
private static long skipSafely(InputStream in, long n) throws IOException {
int available = in.available();
return available == 0 ? 0 : in.skip(Math.min(available, n));
}
/**
* Process the bytes of the given input stream using the given processor.
*
* @param input the input stream to process
* @param processor the object to which to pass the bytes of the stream
* @return the result of the byte processor
* @throws IOException if an I/O error occurs
* @since 14.0
*/
@CanIgnoreReturnValue // some processors won't return a useful result
@ParametricNullness
public static <T extends @Nullable Object> T readBytes(
InputStream input, ByteProcessor<T> processor) throws IOException {
checkNotNull(input);
checkNotNull(processor);
byte[] buf = createBuffer();
int read;
do {
read = input.read(buf);
} while (read != -1 && processor.processBytes(buf, 0, read));
return processor.getResult();
}
/**
* Reads some bytes from an input stream and stores them into the buffer array {@code b}. This
* method blocks until {@code len} bytes of input data have been read into the array, or end of
* file is detected. The number of bytes read is returned, possibly zero. Does not close the
* stream.
*
* <p>A caller can detect EOF if the number of bytes read is less than {@code len}. All subsequent
* calls on the same stream will return zero.
*
* <p>If {@code b} is null, a {@code NullPointerException} is thrown. If {@code off} is negative,
* or {@code len} is negative, or {@code off+len} is greater than the length of the array {@code
* b}, then an {@code IndexOutOfBoundsException} is thrown. If {@code len} is zero, then no bytes
* are read. Otherwise, the first byte read is stored into element {@code b[off]}, the next one
* into {@code b[off+1]}, and so on. The number of bytes read is, at most, equal to {@code len}.
*
* @param in the input stream to read from
* @param b the buffer into which the data is read
* @param off an int specifying the offset into the data
* @param len an int specifying the number of bytes to read
* @return the number of bytes read
* @throws IOException if an I/O error occurs
* @throws IndexOutOfBoundsException if {@code off} is negative, if {@code len} is negative, or if
* {@code off + len} is greater than {@code b.length}
*/
@CanIgnoreReturnValue
// Sometimes you don't care how many bytes you actually read, I guess.
// (You know that it's either going to read len bytes or stop at EOF.)
public static int read(InputStream in, byte[] b, int off, int len) throws IOException {
checkNotNull(in);
checkNotNull(b);
if (len < 0) {
throw new IndexOutOfBoundsException(String.format("len (%s) cannot be negative", len));
}
checkPositionIndexes(off, off + len, b.length);
int total = 0;
while (total < len) {
int result = in.read(b, off + total, len - total);
if (result == -1) {
break;
}
total += result;
}
return total;
}
}
| google/guava | android/guava/src/com/google/common/io/ByteStreams.java |
44,447 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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.iluwatar.bytecode;
import com.iluwatar.bytecode.util.InstructionConverterUtil;
import lombok.extern.slf4j.Slf4j;
/**
* The intention of Bytecode pattern is to give behavior the flexibility of data by encoding it as
* instructions for a virtual machine. An instruction set defines the low-level operations that can
* be performed. A series of instructions is encoded as a sequence of bytes. A virtual machine
* executes these instructions one at a time, using a stack for intermediate values. By combining
* instructions, complex high-level behavior can be defined.
*
* <p>This pattern should be used when there is a need to define high number of behaviours and
* implementation engine is not a good choice because It is too lowe level Iterating on it takes too
* long due to slow compile times or other tooling issues. It has too much trust. If you want to
* ensure the behavior being defined can’t break the game, you need to sandbox it from the rest of
* the codebase.
*/
@Slf4j
public class App {
private static final String LITERAL_0 = "LITERAL 0";
private static final String HEALTH_PATTERN = "%s_HEALTH";
private static final String GET_AGILITY = "GET_AGILITY";
private static final String GET_WISDOM = "GET_WISDOM";
private static final String ADD = "ADD";
private static final String LITERAL_2 = "LITERAL 2";
private static final String DIVIDE = "DIVIDE";
/**
* Main app method.
*
* @param args command line args
*/
public static void main(String[] args) {
var vm = new VirtualMachine(
new Wizard(45, 7, 11, 0, 0),
new Wizard(36, 18, 8, 0, 0));
vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_0));
vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_0));
vm.execute(InstructionConverterUtil.convertToByteCode(String.format(HEALTH_PATTERN, "GET")));
vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_0));
vm.execute(InstructionConverterUtil.convertToByteCode(GET_AGILITY));
vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_0));
vm.execute(InstructionConverterUtil.convertToByteCode(GET_WISDOM));
vm.execute(InstructionConverterUtil.convertToByteCode(ADD));
vm.execute(InstructionConverterUtil.convertToByteCode(LITERAL_2));
vm.execute(InstructionConverterUtil.convertToByteCode(DIVIDE));
vm.execute(InstructionConverterUtil.convertToByteCode(ADD));
vm.execute(InstructionConverterUtil.convertToByteCode(String.format(HEALTH_PATTERN, "SET")));
}
}
| smedals/java-design-patterns | bytecode/src/main/java/com/iluwatar/bytecode/App.java |
44,454 | /*
* Copyright (C) 2008 The Guava Authors
*
* 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.google.common.primitives;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.AbstractList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.RandomAccess;
import javax.annotation.CheckForNull;
/**
* Static utility methods pertaining to {@code byte} primitives, that are not already found in
* either {@link Byte} or {@link Arrays}, <i>and interpret bytes as neither signed nor unsigned</i>.
* The methods which specifically treat bytes as signed or unsigned are found in {@link SignedBytes}
* and {@link UnsignedBytes}.
*
* <p>See the Guava User Guide article on <a
* href="https://github.com/google/guava/wiki/PrimitivesExplained">primitive utilities</a>.
*
* @author Kevin Bourrillion
* @since 1.0
*/
// TODO(kevinb): how to prevent warning on UnsignedBytes when building GWT
// javadoc?
@GwtCompatible
@ElementTypesAreNonnullByDefault
public final class Bytes {
private Bytes() {}
/**
* Returns a hash code for {@code value}; equal to the result of invoking {@code ((Byte)
* value).hashCode()}.
*
* <p><b>Java 8+ users:</b> use {@link Byte#hashCode(byte)} instead.
*
* @param value a primitive {@code byte} value
* @return a hash code for the value
*/
public static int hashCode(byte value) {
return value;
}
/**
* Returns {@code true} if {@code target} is present as an element anywhere in {@code array}.
*
* @param array an array of {@code byte} values, possibly empty
* @param target a primitive {@code byte} value
* @return {@code true} if {@code array[i] == target} for some value of {@code i}
*/
public static boolean contains(byte[] array, byte target) {
for (byte value : array) {
if (value == target) {
return true;
}
}
return false;
}
/**
* Returns the index of the first appearance of the value {@code target} in {@code array}.
*
* @param array an array of {@code byte} values, possibly empty
* @param target a primitive {@code byte} value
* @return the least index {@code i} for which {@code array[i] == target}, or {@code -1} if no
* such index exists.
*/
public static int indexOf(byte[] array, byte target) {
return indexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int indexOf(byte[] array, byte target, int start, int end) {
for (int i = start; i < end; i++) {
if (array[i] == target) {
return i;
}
}
return -1;
}
/**
* Returns the start position of the first occurrence of the specified {@code target} within
* {@code array}, or {@code -1} if there is no such occurrence.
*
* <p>More formally, returns the lowest index {@code i} such that {@code Arrays.copyOfRange(array,
* i, i + target.length)} contains exactly the same elements as {@code target}.
*
* @param array the array to search for the sequence {@code target}
* @param target the array to search for as a sub-sequence of {@code array}
*/
public static int indexOf(byte[] array, byte[] target) {
checkNotNull(array, "array");
checkNotNull(target, "target");
if (target.length == 0) {
return 0;
}
outer:
for (int i = 0; i < array.length - target.length + 1; i++) {
for (int j = 0; j < target.length; j++) {
if (array[i + j] != target[j]) {
continue outer;
}
}
return i;
}
return -1;
}
/**
* Returns the index of the last appearance of the value {@code target} in {@code array}.
*
* @param array an array of {@code byte} values, possibly empty
* @param target a primitive {@code byte} value
* @return the greatest index {@code i} for which {@code array[i] == target}, or {@code -1} if no
* such index exists.
*/
public static int lastIndexOf(byte[] array, byte target) {
return lastIndexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int lastIndexOf(byte[] array, byte target, int start, int end) {
for (int i = end - 1; i >= start; i--) {
if (array[i] == target) {
return i;
}
}
return -1;
}
/**
* Returns the values from each provided array combined into a single array. For example, {@code
* concat(new byte[] {a, b}, new byte[] {}, new byte[] {c}} returns the array {@code {a, b, c}}.
*
* @param arrays zero or more {@code byte} arrays
* @return a single array containing all the values from the source arrays, in order
*/
public static byte[] concat(byte[]... arrays) {
int length = 0;
for (byte[] array : arrays) {
length += array.length;
}
byte[] result = new byte[length];
int pos = 0;
for (byte[] array : arrays) {
System.arraycopy(array, 0, result, pos, array.length);
pos += array.length;
}
return result;
}
/**
* Returns an array containing the same values as {@code array}, but guaranteed to be of a
* specified minimum length. If {@code array} already has a length of at least {@code minLength},
* it is returned directly. Otherwise, a new array of size {@code minLength + padding} is
* returned, containing the values of {@code array}, and zeroes in the remaining places.
*
* @param array the source array
* @param minLength the minimum length the returned array must guarantee
* @param padding an extra amount to "grow" the array by if growth is necessary
* @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative
* @return an array containing the values of {@code array}, with guaranteed minimum length {@code
* minLength}
*/
public static byte[] ensureCapacity(byte[] array, int minLength, int padding) {
checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
checkArgument(padding >= 0, "Invalid padding: %s", padding);
return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array;
}
/**
* Returns an array containing each value of {@code collection}, converted to a {@code byte} value
* in the manner of {@link Number#byteValue}.
*
* <p>Elements are copied from the argument collection as if by {@code collection.toArray()}.
* Calling this method is as thread-safe as calling that method.
*
* @param collection a collection of {@code Number} instances
* @return an array containing the same values as {@code collection}, in the same order, converted
* to primitives
* @throws NullPointerException if {@code collection} or any of its elements is null
* @since 1.0 (parameter was {@code Collection<Byte>} before 12.0)
*/
public static byte[] toArray(Collection<? extends Number> collection) {
if (collection instanceof ByteArrayAsList) {
return ((ByteArrayAsList) collection).toByteArray();
}
Object[] boxedArray = collection.toArray();
int len = boxedArray.length;
byte[] array = new byte[len];
for (int i = 0; i < len; i++) {
// checkNotNull for GWT (do not optimize)
array[i] = ((Number) checkNotNull(boxedArray[i])).byteValue();
}
return array;
}
/**
* Returns a fixed-size list backed by the specified array, similar to {@link
* Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to
* set a value to {@code null} will result in a {@link NullPointerException}.
*
* <p>The returned list maintains the values, but not the identities, of {@code Byte} objects
* written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for
* the returned list is unspecified.
*
* <p>The returned list is serializable.
*
* @param backingArray the array to back the list
* @return a list view of the array
*/
public static List<Byte> asList(byte... backingArray) {
if (backingArray.length == 0) {
return Collections.emptyList();
}
return new ByteArrayAsList(backingArray);
}
@GwtCompatible
private static class ByteArrayAsList extends AbstractList<Byte>
implements RandomAccess, Serializable {
final byte[] array;
final int start;
final int end;
ByteArrayAsList(byte[] array) {
this(array, 0, array.length);
}
ByteArrayAsList(byte[] array, int start, int end) {
this.array = array;
this.start = start;
this.end = end;
}
@Override
public int size() {
return end - start;
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public Byte get(int index) {
checkElementIndex(index, size());
return array[start + index];
}
@Override
public boolean contains(@CheckForNull Object target) {
// Overridden to prevent a ton of boxing
return (target instanceof Byte) && Bytes.indexOf(array, (Byte) target, start, end) != -1;
}
@Override
public int indexOf(@CheckForNull Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Byte) {
int i = Bytes.indexOf(array, (Byte) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override
public int lastIndexOf(@CheckForNull Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Byte) {
int i = Bytes.lastIndexOf(array, (Byte) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override
public Byte set(int index, Byte element) {
checkElementIndex(index, size());
byte oldValue = array[start + index];
// checkNotNull for GWT (do not optimize)
array[start + index] = checkNotNull(element);
return oldValue;
}
@Override
public List<Byte> subList(int fromIndex, int toIndex) {
int size = size();
checkPositionIndexes(fromIndex, toIndex, size);
if (fromIndex == toIndex) {
return Collections.emptyList();
}
return new ByteArrayAsList(array, start + fromIndex, start + toIndex);
}
@Override
public boolean equals(@CheckForNull Object object) {
if (object == this) {
return true;
}
if (object instanceof ByteArrayAsList) {
ByteArrayAsList that = (ByteArrayAsList) object;
int size = size();
if (that.size() != size) {
return false;
}
for (int i = 0; i < size; i++) {
if (array[start + i] != that.array[that.start + i]) {
return false;
}
}
return true;
}
return super.equals(object);
}
@Override
public int hashCode() {
int result = 1;
for (int i = start; i < end; i++) {
result = 31 * result + Bytes.hashCode(array[i]);
}
return result;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder(size() * 5);
builder.append('[').append(array[start]);
for (int i = start + 1; i < end; i++) {
builder.append(", ").append(array[i]);
}
return builder.append(']').toString();
}
byte[] toByteArray() {
return Arrays.copyOfRange(array, start, end);
}
private static final long serialVersionUID = 0;
}
/**
* Reverses the elements of {@code array}. This is equivalent to {@code
* Collections.reverse(Bytes.asList(array))}, but is likely to be more efficient.
*
* @since 23.1
*/
public static void reverse(byte[] array) {
checkNotNull(array);
reverse(array, 0, array.length);
}
/**
* Reverses the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex}
* exclusive. This is equivalent to {@code
* Collections.reverse(Bytes.asList(array).subList(fromIndex, toIndex))}, but is likely to be more
* efficient.
*
* @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
* {@code toIndex > fromIndex}
* @since 23.1
*/
public static void reverse(byte[] array, int fromIndex, int toIndex) {
checkNotNull(array);
checkPositionIndexes(fromIndex, toIndex, array.length);
for (int i = fromIndex, j = toIndex - 1; i < j; i++, j--) {
byte tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
}
/**
* Performs a right rotation of {@code array} of "distance" places, so that the first element is
* moved to index "distance", and the element at index {@code i} ends up at index {@code (distance
* + i) mod array.length}. This is equivalent to {@code Collections.rotate(Bytes.asList(array),
* distance)}, but is somewhat faster.
*
* <p>The provided "distance" may be negative, which will rotate left.
*
* @since 32.0.0
*/
public static void rotate(byte[] array, int distance) {
rotate(array, distance, 0, array.length);
}
/**
* Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code
* toIndex} exclusive. This is equivalent to {@code
* Collections.rotate(Bytes.asList(array).subList(fromIndex, toIndex), distance)}, but is somewhat
* faster.
*
* <p>The provided "distance" may be negative, which will rotate left.
*
* @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
* {@code toIndex > fromIndex}
* @since 32.0.0
*/
public static void rotate(byte[] array, int distance, int fromIndex, int toIndex) {
// See Ints.rotate for more details about possible algorithms here.
checkNotNull(array);
checkPositionIndexes(fromIndex, toIndex, array.length);
if (array.length <= 1) {
return;
}
int length = toIndex - fromIndex;
// Obtain m = (-distance mod length), a non-negative value less than "length". This is how many
// places left to rotate.
int m = -distance % length;
m = (m < 0) ? m + length : m;
// The current index of what will become the first element of the rotated section.
int newFirstIndex = m + fromIndex;
if (newFirstIndex == fromIndex) {
return;
}
reverse(array, fromIndex, newFirstIndex);
reverse(array, newFirstIndex, toIndex);
reverse(array, fromIndex, toIndex);
}
}
| google/guava | guava/src/com/google/common/primitives/Bytes.java |
44,455 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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.iluwatar.decorator;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/**
* Decorator that adds a club for the troll.
*/
@Slf4j
@RequiredArgsConstructor
public class ClubbedTroll implements Troll {
private final Troll decorated;
@Override
public void attack() {
decorated.attack();
LOGGER.info("The troll swings at you with a club!");
}
@Override
public int getAttackPower() {
return decorated.getAttackPower() + 10;
}
@Override
public void fleeBattle() {
decorated.fleeBattle();
}
}
| smedals/java-design-patterns | decorator/src/main/java/com/iluwatar/decorator/ClubbedTroll.java |
44,458 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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.iluwatar.iterator;
import static com.iluwatar.iterator.list.ItemType.ANY;
import static com.iluwatar.iterator.list.ItemType.POTION;
import static com.iluwatar.iterator.list.ItemType.RING;
import static com.iluwatar.iterator.list.ItemType.WEAPON;
import com.iluwatar.iterator.bst.BstIterator;
import com.iluwatar.iterator.bst.TreeNode;
import com.iluwatar.iterator.list.ItemType;
import com.iluwatar.iterator.list.TreasureChest;
import lombok.extern.slf4j.Slf4j;
/**
* The Iterator pattern is a design pattern in which an iterator is used to traverse a container and
* access the container's elements. The Iterator pattern decouples algorithms from containers.
*
* <p>In this example the Iterator ({@link Iterator}) adds abstraction layer on top of a collection
* ({@link TreasureChest}). This way the collection can change its internal implementation without
* affecting its clients.
*/
@Slf4j
public class App {
private static final TreasureChest TREASURE_CHEST = new TreasureChest();
private static void demonstrateTreasureChestIteratorForType(ItemType itemType) {
LOGGER.info("------------------------");
LOGGER.info("Item Iterator for ItemType " + itemType + ": ");
var itemIterator = TREASURE_CHEST.iterator(itemType);
while (itemIterator.hasNext()) {
LOGGER.info(itemIterator.next().toString());
}
}
private static void demonstrateBstIterator() {
LOGGER.info("------------------------");
LOGGER.info("BST Iterator: ");
var root = buildIntegerBst();
var bstIterator = new BstIterator<>(root);
while (bstIterator.hasNext()) {
LOGGER.info("Next node: " + bstIterator.next().getVal());
}
}
private static TreeNode<Integer> buildIntegerBst() {
var root = new TreeNode<>(8);
root.insert(3);
root.insert(10);
root.insert(1);
root.insert(6);
root.insert(14);
root.insert(4);
root.insert(7);
root.insert(13);
return root;
}
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
demonstrateTreasureChestIteratorForType(RING);
demonstrateTreasureChestIteratorForType(POTION);
demonstrateTreasureChestIteratorForType(WEAPON);
demonstrateTreasureChestIteratorForType(ANY);
demonstrateBstIterator();
}
}
| smedals/java-design-patterns | iterator/src/main/java/com/iluwatar/iterator/App.java |
44,461 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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.iluwatar.datamapper;
import java.io.Serial;
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* Class defining Student.
*/
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@ToString
@Getter
@Setter
@AllArgsConstructor
public final class Student implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
@EqualsAndHashCode.Include
private int studentId;
private String name;
private char grade;
}
| rajprins/java-design-patterns | data-mapper/src/main/java/com/iluwatar/datamapper/Student.java |
44,492 | package gr.aueb.cf.schoolapp;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import java.awt.Color;
import javax.swing.JTextField;
import javax.swing.border.BevelBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TeachersInsertForm extends JFrame {
private static final long serialVersionUID = 123456;
private JPanel contentPane;
private JTextField firstnameTxt;
private JTextField lastnameTxt;
public TeachersInsertForm() {
addWindowListener(new WindowAdapter() {
@Override
public void windowActivated(WindowEvent e) {
firstnameTxt.setText("");
lastnameTxt.setText("");
}
});
setTitle("Εισαγωγή Εκπαιδευτή");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 405, 280);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setLocationRelativeTo(null);
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel firstnameLbl = new JLabel("Όνομα");
firstnameLbl.setForeground(new Color(128, 0, 0));
firstnameLbl.setFont(new Font("Tahoma", Font.BOLD, 14));
firstnameLbl.setBounds(57, 57, 69, 25);
contentPane.add(firstnameLbl);
firstnameTxt = new JTextField();
firstnameTxt.setBounds(131, 61, 143, 20);
contentPane.add(firstnameTxt);
firstnameTxt.setColumns(10);
JLabel lastnameLbl = new JLabel("Επώνυμο");
lastnameLbl.setForeground(new Color(128, 0, 0));
lastnameLbl.setFont(new Font("Tahoma", Font.BOLD, 14));
lastnameLbl.setBounds(57, 90, 69, 25);
contentPane.add(lastnameLbl);
lastnameTxt = new JTextField();
lastnameTxt.setColumns(10);
lastnameTxt.setBounds(131, 94, 143, 20);
contentPane.add(lastnameTxt);
JPanel panel = new JPanel();
panel.setBackground(new Color(240, 240, 240));
panel.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
panel.setBounds(24, 11, 325, 156);
contentPane.add(panel);
JButton insertBtn = new JButton("Εισαγωγή");
insertBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String firstname = firstnameTxt.getText().trim();
String lastname = lastnameTxt.getText().trim();
if (firstname.equals("") || lastname.equals("")) {
JOptionPane.showMessageDialog(null, "Empty firstname / lastname", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
String sql = "INSERT INTO TEACHERS (FIRSTNAME, LASTNAME) VALUES (?, ?)";
Connection connection = Menu.getConnection();
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, firstname);
ps.setString(2, lastname);
int n = ps.executeUpdate();
JOptionPane.showMessageDialog(null, n + " row affected", "Insert", JOptionPane.INFORMATION_MESSAGE);
} catch (SQLException e1) {
e1.printStackTrace();
}
}
});
insertBtn.setForeground(new Color(0, 0, 255));
insertBtn.setFont(new Font("Tahoma", Font.BOLD, 14));
insertBtn.setBounds(99, 191, 129, 41);
contentPane.add(insertBtn);
JButton closeBtn = new JButton("Κλείσιμο");
closeBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Main.getTeachersSearchForm().setEnabled(true);
Main.getTeachersInsertForm().setVisible(false);
}
});
closeBtn.setForeground(Color.BLUE);
closeBtn.setFont(new Font("Tahoma", Font.BOLD, 14));
closeBtn.setBounds(226, 191, 129, 41);
contentPane.add(closeBtn);
}
}
| a8anassis/schoolapp-simple-swing | src/gr/aueb/cf/schoolapp/TeachersInsertForm.java |
44,516 | package gr.aueb.cf.schoolapp;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import java.awt.Color;
import javax.swing.JTextField;
import javax.swing.border.BevelBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TeachersInsertForm extends JFrame {
private static final long serialVersionUID = 123456;
private JPanel contentPane;
private JTextField firstnameTxt;
private JTextField lastnameTxt;
public TeachersInsertForm() {
addWindowListener(new WindowAdapter() {
@Override
public void windowActivated(WindowEvent e) {
firstnameTxt.setText("");
lastnameTxt.setText("");
}
});
setTitle("Εισαγωγή Εκπαιδευτή");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 405, 280);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setLocationRelativeTo(null);
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel firstnameLbl = new JLabel("Όνομα");
firstnameLbl.setForeground(new Color(128, 0, 0));
firstnameLbl.setFont(new Font("Tahoma", Font.BOLD, 14));
firstnameLbl.setBounds(57, 57, 69, 25);
contentPane.add(firstnameLbl);
firstnameTxt = new JTextField();
firstnameTxt.setBounds(131, 61, 143, 20);
contentPane.add(firstnameTxt);
firstnameTxt.setColumns(10);
JLabel lastnameLbl = new JLabel("Επώνυμο");
lastnameLbl.setForeground(new Color(128, 0, 0));
lastnameLbl.setFont(new Font("Tahoma", Font.BOLD, 14));
lastnameLbl.setBounds(57, 90, 69, 25);
contentPane.add(lastnameLbl);
lastnameTxt = new JTextField();
lastnameTxt.setColumns(10);
lastnameTxt.setBounds(131, 94, 143, 20);
contentPane.add(lastnameTxt);
JPanel panel = new JPanel();
panel.setBackground(new Color(240, 240, 240));
panel.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
panel.setBounds(24, 11, 325, 156);
contentPane.add(panel);
JButton insertBtn = new JButton("Εισαγωγή");
insertBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String firstname = firstnameTxt.getText().trim();
String lastname = lastnameTxt.getText().trim();
if (firstname.equals("") || lastname.equals("")) {
JOptionPane.showMessageDialog(null, "Empty firstname / lastname", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
String sql = "INSERT INTO TEACHERS (FIRSTNAME, LASTNAME) VALUES (?, ?)";
Connection connection = Menu.getConnection();
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, firstname);
ps.setString(2, lastname);
int n = ps.executeUpdate();
JOptionPane.showMessageDialog(null, n + " row affected", "Insert", JOptionPane.INFORMATION_MESSAGE);
} catch (SQLException e1) {
e1.printStackTrace();
}
}
});
insertBtn.setForeground(new Color(0, 0, 255));
insertBtn.setFont(new Font("Tahoma", Font.BOLD, 14));
insertBtn.setBounds(99, 191, 129, 41);
contentPane.add(insertBtn);
JButton closeBtn = new JButton("Κλείσιμο");
closeBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Main.getTeachersSearchForm().setEnabled(true);
Main.getTeachersInsertForm().setVisible(false);
}
});
closeBtn.setForeground(Color.BLUE);
closeBtn.setFont(new Font("Tahoma", Font.BOLD, 14));
closeBtn.setBounds(226, 191, 129, 41);
contentPane.add(closeBtn);
}
}
| LiontosDionisis/school-app | src/gr/aueb/cf/schoolapp/TeachersInsertForm.java |
44,517 | package gr.aueb.cf;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import java.awt.Color;
import javax.swing.JTextField;
import javax.swing.border.BevelBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TeachersInsertForm extends JFrame {
private static final long serialVersionUID = 123456;
private JPanel contentPane;
private JTextField firstnameTxt;
private JTextField lastnameTxt;
public TeachersInsertForm() {
addWindowListener(new WindowAdapter() {
@Override
public void windowActivated(WindowEvent e) {
firstnameTxt.setText("");
lastnameTxt.setText("");
}
});
setTitle("Εισαγωγή Εκπαιδευτή");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 405, 280);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setLocationRelativeTo(null);
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel firstnameLbl = new JLabel("Όνομα");
firstnameLbl.setForeground(new Color(128, 0, 0));
firstnameLbl.setFont(new Font("Tahoma", Font.BOLD, 14));
firstnameLbl.setBounds(57, 57, 69, 25);
contentPane.add(firstnameLbl);
firstnameTxt = new JTextField();
firstnameTxt.setBounds(131, 61, 143, 20);
contentPane.add(firstnameTxt);
firstnameTxt.setColumns(10);
JLabel lastnameLbl = new JLabel("Επώνυμο");
lastnameLbl.setForeground(new Color(128, 0, 0));
lastnameLbl.setFont(new Font("Tahoma", Font.BOLD, 14));
lastnameLbl.setBounds(57, 90, 69, 25);
contentPane.add(lastnameLbl);
lastnameTxt = new JTextField();
lastnameTxt.setColumns(10);
lastnameTxt.setBounds(131, 94, 143, 20);
contentPane.add(lastnameTxt);
JPanel panel = new JPanel();
panel.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
panel.setBounds(24, 11, 325, 156);
contentPane.add(panel);
JButton insertBtn = new JButton("Εισαγωγή");
insertBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String sql = "INSERT INTO TEACHERS (FIRSTNAME, LASTNAME) VALUES (?, ?)";
try {
String firstname = firstnameTxt.getText().trim();
String lastname = lastnameTxt.getText().trim();
if (firstname.equals("") || lastname.equals("")) {
JOptionPane.showMessageDialog(null, "Empty firstname / lastname", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
Connection connection = Menu.getConnection();
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, firstname);
ps.setString(2, lastname);
int n = ps.executeUpdate();
JOptionPane.showMessageDialog(null, n + " row affected", "Insert", JOptionPane.INFORMATION_MESSAGE);
} catch (SQLException e1) {
e1.printStackTrace();
}
}
});
insertBtn.setForeground(new Color(0, 0, 255));
insertBtn.setFont(new Font("Tahoma", Font.BOLD, 14));
insertBtn.setBounds(99, 191, 129, 41);
contentPane.add(insertBtn);
JButton closeBtn = new JButton("Κλείσιμο");
closeBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Main.getTeachersSearchForm().setEnabled(true);
Main.getTeachersInsertForm().setVisible(false);
}
});
closeBtn.setForeground(Color.BLUE);
closeBtn.setFont(new Font("Tahoma", Font.BOLD, 14));
closeBtn.setBounds(226, 191, 129, 41);
contentPane.add(closeBtn);
}
}
| KONSTANTINOS-EL/SchoolApp | gr/aueb/cf/TeachersInsertForm.java |
44,519 | package gr.aueb.cf.schoolapp.viewcontroller;
import gr.aueb.cf.schoolapp.Main;
import gr.aueb.cf.schoolapp.dao.ITeacherDAO;
import gr.aueb.cf.schoolapp.dao.TeacherDAOImpl;
import gr.aueb.cf.schoolapp.dao.exceptions.TeacherDAOException;
import gr.aueb.cf.schoolapp.dto.TeacherInsertDTO;
import gr.aueb.cf.schoolapp.model.Teacher;
import gr.aueb.cf.schoolapp.service.ITeacherService;
import gr.aueb.cf.schoolapp.service.TeacherServiceImpl;
import gr.aueb.cf.schoolapp.validator.TeacherValidator;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import java.awt.Color;
import javax.swing.JTextField;
import javax.swing.border.BevelBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Map;
public class TeachersInsertForm extends JFrame {
private static final long serialVersionUID = 123456;
private JPanel contentPane;
private JTextField firstnameTxt;
private JTextField lastnameTxt;
ITeacherDAO dao = new TeacherDAOImpl();
ITeacherService teacherService = new TeacherServiceImpl(dao);
public TeachersInsertForm() {
addWindowListener(new WindowAdapter() {
@Override
public void windowActivated(WindowEvent e) {
firstnameTxt.setText("");
lastnameTxt.setText("");
}
});
setTitle("Εισαγωγή Εκπαιδευτή");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 405, 280);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setLocationRelativeTo(null);
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel firstnameLbl = new JLabel("Όνομα");
firstnameLbl.setForeground(new Color(128, 0, 0));
firstnameLbl.setFont(new Font("Tahoma", Font.BOLD, 14));
firstnameLbl.setBounds(57, 57, 69, 25);
contentPane.add(firstnameLbl);
firstnameTxt = new JTextField();
firstnameTxt.setBounds(131, 61, 143, 20);
contentPane.add(firstnameTxt);
firstnameTxt.setColumns(10);
JLabel lastnameLbl = new JLabel("Επώνυμο");
lastnameLbl.setForeground(new Color(128, 0, 0));
lastnameLbl.setFont(new Font("Tahoma", Font.BOLD, 14));
lastnameLbl.setBounds(57, 90, 69, 25);
contentPane.add(lastnameLbl);
lastnameTxt = new JTextField();
lastnameTxt.setColumns(10);
lastnameTxt.setBounds(131, 94, 143, 20);
contentPane.add(lastnameTxt);
JPanel panel = new JPanel();
panel.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
panel.setBounds(24, 11, 325, 156);
contentPane.add(panel);
JButton insertBtn = new JButton("Εισαγωγή");
insertBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String firstname;
String lastname;
Map<String, String> teacherErrors;
TeacherInsertDTO dto;
try {
// Data binding
firstname = firstnameTxt.getText().trim();
lastname = lastnameTxt.getText().trim();
dto = new TeacherInsertDTO();
dto.setFirstname(firstname);
dto.setLastname(lastname);
// Validate
teacherErrors = TeacherValidator.validate(dto);
String firstnameMessage = (teacherErrors.get("firstname") != null) ? "Firstname: " + teacherErrors.get("firstname") : "";
String lastnameMessage = (teacherErrors.get("lastname") != null) ? "Lastname: " + teacherErrors.get("lastname") : "";
if (!teacherErrors.isEmpty()) {
JOptionPane.showMessageDialog(null,firstnameMessage + " " + lastnameMessage, "Validation Error",
JOptionPane.ERROR_MESSAGE);
return;
}
Teacher teacher = teacherService.insertTeacher(dto);
JOptionPane.showMessageDialog(null, "Teacher" + teacher.getLastname()
+ " was inserted", "INSERT", JOptionPane.PLAIN_MESSAGE);
} catch (TeacherDAOException e1) {
String message = e1.getMessage();
JOptionPane.showMessageDialog(null, message, "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
insertBtn.setForeground(new Color(0, 0, 255));
insertBtn.setFont(new Font("Tahoma", Font.BOLD, 14));
insertBtn.setBounds(99, 191, 129, 41);
contentPane.add(insertBtn);
JButton closeBtn = new JButton("Κλείσιμο");
closeBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Main.getTeachersSearchForm().setEnabled(true);
Main.getTeachersInsertForm().setVisible(false);
}
});
closeBtn.setForeground(Color.BLUE);
closeBtn.setFont(new Font("Tahoma", Font.BOLD, 14));
closeBtn.setBounds(226, 191, 129, 41);
contentPane.add(closeBtn);
}
}
| Polizo96/school-app | src/main/java/gr/aueb/cf/schoolapp/viewcontroller/TeachersInsertForm.java |
44,529 | package gr.cti.eslate.base.container;
import java.util.ListResourceBundle;
public class LogoOutputConsoleDialogBundle_el_GR extends ListResourceBundle {
public Object [][] getContents() {
return contents;
}
static final Object[][] contents={
{"DialogTitle", "Logo κονσόλα"},
{"Close", "Κλείσιμο"},
{"Clear", "Καθαρισμός"},
};
}
| vpapakir/myeslate | widgetESlate/src/gr/cti/eslate/base/container/LogoOutputConsoleDialogBundle_el_GR.java |
44,545 | package pt.tecnico.bubbledocs.integration.component;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import mockit.Expectations;
import mockit.Mocked;
import org.joda.time.DateTime;
import org.joda.time.Seconds;
import org.junit.Test;
import pt.tecnico.bubbledocs.domain.Session;
import pt.tecnico.bubbledocs.domain.SuperUser;
import pt.tecnico.bubbledocs.domain.User;
import pt.tecnico.bubbledocs.exceptions.LoginException;
import pt.tecnico.bubbledocs.exceptions.RemoteInvocationException;
import pt.tecnico.bubbledocs.exceptions.UnavailableServiceException;
import pt.tecnico.bubbledocs.service.BubbleDocsServiceTest;
import pt.tecnico.bubbledocs.service.remote.IDRemoteServices;
import pt.tecnico.bubbledocs.integration.LoginUserIntegrator;
// add needed import declarations
public class LoginUserIntegratorTest extends BubbleDocsServiceTest {
private String manel; // the token for user manel
private static final String ROOT = "root";
private static final String ROOT_PASS = "rute";
private static final String USERNAME = "danix";
private static final String NON_EXISTING = "spock";
private static final String LOGGED_IN = "manel";
private static final String PASSWORD = "hunter2";
private static final String DIFF_PASS = "toaster-repair";
private static final String ANY_PASS = "I-C-I-D";
private static final String JUBI_UNAME = "jubi";
private static final String JUBI_PASS = "password";
private static final String JUBI_NAME = "Jubileu Mandafacas";
private static final String NO_CACHE = "Nocache";
@Mocked IDRemoteServices remote;
@Override
public void populate4Test() {
createUser(USERNAME, "[email protected]",PASSWORD, "Marcos Pires");
createUser(LOGGED_IN, "[email protected]", PASSWORD, "Manuel da Silva");
createUser(JUBI_UNAME, "[email protected]", JUBI_PASS, JUBI_NAME);
createUser(NO_CACHE, "[email protected]", null, "No money");
manel = addUserToSession(LOGGED_IN);
}
// returns the time of the last access for the user with token userToken.
// It must get this data from the session object of the application
private DateTime getLastAccessTimeInSession(String userToken) {
Session s = getSessionFromToken(userToken);
return s.getAccess();
}
@Test
public void successNewToken() {
new Expectations() {{
remote.loginUser(USERNAME, PASSWORD); times = 1;
}};
assertNull("The user was not logged in", getUserFromUsername(USERNAME).getSession());
LoginUserIntegrator service = new LoginUserIntegrator(USERNAME, PASSWORD);
service.execute(); //it shouldn't explode here.
DateTime currentTime = new DateTime();
String token = service.getResult();
User user = getUserFromSession(token);
int difference = Seconds.secondsBetween(getLastAccessTimeInSession(token), currentTime).getSeconds();
assertTrue("Access time in session is not correctly set", difference >= 0);
assertTrue("Diference in seconds greater than expected", difference < 2);
assertNotEquals("Didn't generate a different token", token, manel); //P(failure) = The sun doesn't rise.
assertEquals("Usernames don't match", USERNAME, user.getUserName());
assertEquals("Password don't match", PASSWORD, user.getPassword());
assertEquals("Token doesn't match", token, user.getSession().getToken());
assertFalse("User shouldn't be SuperUser", user instanceof SuperUser);
}
@Test
public void successLoginTwiceSameToken() {
new Expectations() {{
remote.loginUser(LOGGED_IN, PASSWORD); times = 2;
}};
LoginUserIntegrator service = new LoginUserIntegrator(LOGGED_IN, PASSWORD);
service.execute();
String token1 = service.getResult();
DateTime access1 = getLastAccessTimeInSession(token1);
try {
//Wait at least one second.
Thread.sleep(1453); //Κωνσταντινούπολη έπεσε!
} catch (InterruptedException e) {/*good luck with that*/}
service.execute();
String token2 = service.getResult();
DateTime access2 = getLastAccessTimeInSession(token2);
int difference = Seconds.secondsBetween(access1, access2).getSeconds();
assertEquals("Tokens are not supposed to change", token1, token2);
assertEquals("Token is different from previous login", token1, manel);
assertTrue("Tokens were not touched", difference > 0);
}
@Test
public void rootIsSuperUser() {
new Expectations() {{
remote.loginUser(ROOT, ROOT_PASS); times = 1;
}};
LoginUserIntegrator service = new LoginUserIntegrator(ROOT, ROOT_PASS);
service.execute();
User supah = getUserFromSession(service.getResult());
assertTrue("Root should be an instance of SuperUser", supah instanceof SuperUser);
}
@Test(expected = LoginException.class)
public void loginUnknownUser() {
new Expectations() {{
remote.loginUser(NON_EXISTING, ANY_PASS);
result = new LoginException();
}};
LoginUserIntegrator service = new LoginUserIntegrator(NON_EXISTING, ANY_PASS);
service.execute();
}
@Test(expected = LoginException.class)
public void loginUserWithinWrongPassword() {
new Expectations(){{
remote.loginUser(USERNAME, DIFF_PASS);
times = 1;
result = new LoginException();
}};
LoginUserIntegrator service = new LoginUserIntegrator(USERNAME, DIFF_PASS);
service.execute();
}
//////////////////////////
// TESTS FOR 2ND SPRINT //
//////////////////////////
/** A successful login with remote authentication.
*/
@Test
public void loginRemote(){
//FIXME: assert login is remote and not cached
LoginUserIntegrator service = new LoginUserIntegrator(JUBI_UNAME, JUBI_PASS);
service.execute();
User u = this.getUserFromUsername(JUBI_UNAME);
String utoken = u.getSession().getToken();
String stoken = service.getResult();
assertNotNull(utoken);
assertNotNull(stoken);
assertEquals(stoken, utoken);
}
/** A successful login with local authentication.
*/
@Test
public void loginLocal(){
new Expectations(){{
remote.loginUser(JUBI_UNAME, JUBI_PASS);
result = new RemoteInvocationException();
}};
LoginUserIntegrator service = new LoginUserIntegrator(JUBI_UNAME, JUBI_PASS);
service.execute();
User u = this.getUserFromUsername(JUBI_UNAME);
String utoken = u.getSession().getToken();
String stoken = service.getResult();
assertNotNull(utoken);
assertNotNull(stoken);
assertEquals(stoken, utoken);
}
/** An unsuccessful login because remote authentication is down
* and there is no cached login.
* It should fail.
*/
@Test(expected = UnavailableServiceException.class)
public void noRemoteNoLocal(){
new Expectations(){{
remote.loginUser(NO_CACHE, "hunter2");
result = new RemoteInvocationException();
}};
LoginUserIntegrator service = new LoginUserIntegrator(NO_CACHE, "hunter2");
service.execute();
}
/** Try to login after "cache is cleaned".
* Since we got rid of the cache concept, we just set user's stored password to null.
* The test should fail.
*/
@Test (expected = UnavailableServiceException.class)
public void loginAfterCleanLocal(){
String temp_username = "abcd123";
String temp_password = "abd123";
String temp_name = "abcd123";
String temp_mail = "[email protected]";
// simulate an exception with a mock
new Expectations(){{
remote.loginUser(temp_username, temp_password);
result = new RemoteInvocationException();
}};
createUser(temp_username, temp_mail, temp_password, temp_name);
LoginUserIntegrator service = new LoginUserIntegrator(temp_username, temp_password);
service.execute();
User u = this.getUserFromUsername(temp_username);
u.setPassword(null);
service.execute();
}
/** A remote authentication attempt with a bad password.
* It should fail.
*/
@Test (expected = LoginException.class)
public void loginRemoteBadPass(){
String bad_pass = "Ah ah ah, you didn't say the magic word.";
new Expectations(){{
remote.loginUser(JUBI_UNAME, bad_pass);
result = new LoginException();
}};
LoginUserIntegrator service = new LoginUserIntegrator(JUBI_UNAME, bad_pass);
service.execute();
}
/** A local authentication attempt with a bad password when
* remote authentication is down.
* It should fail.
*/
@Test(expected = UnavailableServiceException.class)
public void loginLocalBadPass(){
String bad_pass = "Ah ah ah, you didn't say the magic word.";
new Expectations(){{
remote.loginUser(JUBI_UNAME, bad_pass);
result = new RemoteInvocationException();
}};
LoginUserIntegrator service = new LoginUserIntegrator(JUBI_UNAME, bad_pass);
service.execute();
}
/** A remote authentication attempt with a username that doesn't exist.
* It should fail.
*/
@Test(expected = LoginException.class)
public void loginRemoteBadUser(){
String bad_user = "I'm root, let me in.";
new Expectations() {{
remote.loginUser(bad_user, JUBI_PASS);
result = new LoginException();
}};
LoginUserIntegrator service = new LoginUserIntegrator(bad_user, JUBI_PASS);
service.execute();
}
}
| duarte-pompeu/projecto-es-sd | bubbledocs-appserver/src/test/java/pt/tecnico/bubbledocs/integration/component/LoginUserIntegratorTest.java |
44,553 | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package Asteras;
/**
*
* @author Ηλίας
*/
public class Author implements Comparable<Author>{
private String name;
private double score;
private String field;
public Author(String name, double score, String field) {
this.name = name;
this.score = score;
this.field = field;
}
public String getName() {
return name;
}
public double getScore() {
return score;
}
public String getField() {
return field;
}
@Override
public int compareTo(Author o) {
if( score - o.getScore() == 0){
return 0;
}
else if ( score - o.getScore() < 0){
return 1;
}
else{
return -1;
}
}
}
| IliasAlex/Asteras | src/java/Asteras/Author.java |
44,557 | /*
* 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 Asteras;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.stream.Collectors;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexableField;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.search.Explanation;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
/**
*
* @author Ηλίας
*/
public class LuceneTester {
String indexDir = "Index";
String dataDir = "Data";
Indexer indexer;
Searcher searcher;
long time;
int k;
HashMap<String, Author> matches = new HashMap<>();
public void run(String query, String k) throws IOException, ParseException {
this.k = Integer.parseInt(k);
createIndex(indexDir, dataDir);
search(query, this.k);
}
private boolean isEmpty(String dir) {
File directory = new File(dir);
if (directory.isDirectory()) {
String[] files = directory.list();
if (directory.length() > 0) {
return false;
} else {
return true;
}
}
return true;
}
private void createIndex(String iDir, String dDir) throws IOException {
indexer = new Indexer(iDir);
int numIndexed;
long startTime = System.currentTimeMillis();
numIndexed = indexer.createIndex(dDir, new TextFileFilter(".bib"));
long endTime = System.currentTimeMillis();
indexer.close();
// System.out.println(numIndexed + " File(s) indexed, time taken: " + (endTime - startTime) + " ms");
}
private void search(String searchQuery, int k) throws IOException, ParseException {
searcher = new Searcher(indexDir);
long startTime = System.currentTimeMillis();
TopDocs hits = searcher.search(searchQuery);
long endTime = System.currentTimeMillis();
time = endTime - startTime;
System.out.println(hits.totalHits + " documents found. Time :" + time);
int i = 1;
for (ScoreDoc scoreDoc : hits.scoreDocs) {
if (i > k) {
break;
} else {
i++;
}
Document doc = searcher.getDocument(scoreDoc);
System.out.println("File: " + doc.get(LuceneConstants.FILE_PATH));
System.out.println("SCORE: " + scoreDoc.score);
boolean flag = false;
for (IndexableField field : doc.getFields("fieldName")) {
String line = field.stringValue().toLowerCase();
File temp_file = new File("Temp_Data/temp.bib");
FileWriter myWriter = new FileWriter(temp_file);
myWriter.write(field.stringValue());
myWriter.close();
createIndex("Temp_Index", "Temp_Data");
Searcher srchr = new Searcher("Temp_Index");
TopDocs hits_2 = srchr.search(searchQuery);
for (ScoreDoc scorD : hits_2.scoreDocs) {
Explanation ex = srchr.indexSearcher.explain(srchr.query, scorD.doc);
if (ex.isMatch()) {
String author = doc.get(LuceneConstants.FILE_NAME).replace(".bib", "");
matches.put(author, new Author(author, scoreDoc.score, field.stringValue()));
flag = true;
break;
}
}
temp_file.delete();
if (flag) {
break;
}
}
}
searcher.close();
}
public double getCosineSimilarity(String a1, String a2) throws IOException {
CosineSimilarity cs = new CosineSimilarity();
String text1 = Files.readAllLines(Paths.get("Data/" + a1 + ".bib")).stream().collect(Collectors.joining(" "));
String text2 = Files.readAllLines(Paths.get("Data/" + a2 + ".bib")).stream().collect(Collectors.joining(" "));
return cs.score(text1, text2);
}
public ArrayList<Author> getCosineSimilarity(String a1) throws IOException {
ArrayList<Author> scores = new ArrayList<>();
CosineSimilarity cs = new CosineSimilarity();
String text1 = Files.readAllLines(Paths.get("Data/" + a1 + ".bib")).stream().collect(Collectors.joining(" "));
File folder = new File(dataDir);
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file.isFile() && !file.getName().contains(a1)) {
String text2 = Files.readAllLines(Paths.get(file.getPath())).stream().collect(Collectors.joining(" "));
Author a = new Author(file.getName().replace(".bib", ""), cs.score(text1, text2), "");
scores.add(a);
}
}
Collections.sort(scores);
return scores;
}
}
| IliasAlex/Asteras | src/java/Asteras/LuceneTester.java |
44,559 | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit this template
*/
package Asteras;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Ηλίας
*/
@WebServlet(name = "CosSim", urlPatterns = {"/CosSim"})
public class CosSim extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
String query = request.getParameter("query");
query = query.toLowerCase();
String k = request.getParameter("k");
if ( k.equals("")){
k = "5";
}
LuceneTester tester = new LuceneTester();
String[] parts = query.split(" ");
String result = "";
ArrayList<Author> scores = null;
if (parts.length > 1) {
result += tester.getCosineSimilarity(parts[0], parts[1]);
} else if (parts.length == 1) {
scores = tester.getCosineSimilarity(parts[0]);
}
out.println("<!DOCTYPE html>\n"
+ "<!--\n"
+ "Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license\n"
+ "Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Html.html to edit this template\n"
+ "-->\n"
+ "<html>\n"
+ " <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" integrity=\"sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T\" crossorigin=\"anonymous\">\n"
+ " <head>\n"
+ " <title>CosSim</title>\n"
+ " <meta charset=\"UTF-8\">\n"
+ " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n"
+ " </head>\n"
+ "\n"
+ "\n"
+ " <body>\n"
+ " <div class=\"container\">\n"
+ " <div class=\"ibox-content\">\n"
+ " <br>\n"
+ " <a href=\"http://localhost:8080/Asteras/\" class=\"btn btn-primary\">Home</a><br><br>\n"
+ " <label for=\"k_results\">Top k results: </label>\n"
+ " <input type=\"text\" id=\"k_results\" name=\"k_results\" required><br>\n"
+ " <input name =\"submit_btn\" id = \"submit_btn\" type=\"submit\" value=\"Submit\">\n"
+ " <br>\n"
+ " </div>\n"
+ " \n"
+ " </div>\n"
+ " \n"
+ " <table class=\"table\">\n"
+ " <thead>\n"
+ " <tr>\n"
+ " <th scope=\"col\">#</th>\n"
+ " <th scope=\"col\">Author 1</th>\n"
+ " <th scope=\"col\">Author 2</th>\n"
+ " <th scope=\"col\">Score(cos sim)</th>\n"
+ " </tr>\n"
+ " </thead>\n"
+ " <tbody>");
if (scores == null) {
out.println("<tr>\n"
+ " <th scope=\"row\">1</th>\n"
+ " <td>" + parts[0] + "</td>\n"
+ " <td>" + parts[1] + "</td>\n"
+ " <td>" + result + "</td>\n"
+ " </tr>");
} else {
int i = 1;
for (Author score : scores) {
out.println("<tr>\n"
+ " <th scope=\"row\">" + i + "</th>\n"
+ " <td>" + parts[0] + "</td>\n"
+ " <td>" + score.getName() + "</td>\n"
+ " <td>" + score.getScore() + "</td>\n"
+ " </tr>");
i++;
if (i > Integer.parseInt(k)) {
break;
}
}
}
out.println("</tbody>\n"
+ " </table>\n"
+ " </body>\n"
+ "</html>");
out.println("<script>\n"
+ " function refreshK() {\n"
+ " window.location.href = 'http://localhost:8080/Asteras/CosSim?query=" + query + "'" + " +' &k=' + document.getElementById(\"k_results\").value;\n"
+ " }\n"
+ "\n"
+ " document.getElementById(\"submit_btn\").addEventListener(\"click\", refreshK);\n"
+ "\n"
+ "</script> ");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| IliasAlex/Asteras | src/java/Asteras/CosSim.java |
44,560 | /*
* 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 Asteras;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Ηλίας
*/
public class DeleteAuthor extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
String author = request.getParameter("name");
File myObj = new File("Data/"+author+".bib");
myObj.delete();
response.sendRedirect("http://localhost:8080/Asteras/Insert_delete");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| IliasAlex/Asteras | src/java/Asteras/DeleteAuthor.java |
44,562 | package Asteras;
/*
* 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.
*/
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.lucene.queryparser.classic.ParseException;
/**
*
* @author Ηλίας
*/
public class Results extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
ArrayList<Author> results = new ArrayList<>();
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
String query = request.getParameter("query");
String k = request.getParameter("k");
System.out.println("K: " + k);
LuceneTester tester = new LuceneTester();
tester.run(query, k);
for (String i : tester.matches.keySet()) {
results.add(tester.matches.get(i));
}
Collections.sort(results);
out.println("<!DOCTYPE html>\n"
+ "<html lang=\"en\">\n"
+ " <head>\n"
+ " <meta charset=\"utf-8\">\n"
+ " <!-- This file has been downloaded from bootdey.com @bootdey on twitter -->\n"
+ " <!-- All snippets are MIT license http://bootdey.com/license -->\n"
+ " <title>Search Results</title>\n"
+ " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n"
+ " <script src=\"https://code.jquery.com/jquery-1.10.2.min.js\"></script>\n"
+ " <link href=\"https://netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css\" rel=\"stylesheet\">\n"
+ " <script src=\"https://netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js\"></script>\n"
+ " </head>\n"
+ " <body>\n"
+ " <div class=\"container bootstrap snippets bootdey\">\n"
+ " <div class=\"row\">\n"
+ " <div class=\"col-lg-12\">\n"
+ " <div class=\"ibox float-e-margins\">\n"
+ " <div class=\"ibox-content\">\n"
+ " <a href=\"http://localhost:8080/Asteras/\" class=\"btn btn-primary\">Home</a><br><br>\n"
+ " <label for=\"k_results\">Top k results: </label>\n"
+ " <input type=\"text\" id=\"k_results\" name=\"k_results\" required><br>\n"
+ " <input name =\"submit_btn\" id = \"submit_btn\" type=\"submit\" value=\"Submit\">\n");
out.println("<h2>\n"
+ results.size() + " results found for: <span class=\"text-navy\">" + query + "</span>\n"
+ " </h2>\n"
+ " <small>Request time ( " + tester.time / 10.0 + " Seconds)</small>");
for (Author i : results) {
out.println(" <div class=\"hr-line-dashed\"></div>\n"
+ " <div class=\"search-result\">\n"
+ " <h3><a href=\"#\">" + i.getName() + " score: " + i.getScore() + "</a></h3>\n"
+ " <a href=\"https://dblp.org/search?q=" + i.getName() + "\"" + "class=\"search-link\">https://dblp.org/search?q=" + i.getName() + "</a>\n"
+ " <p>\n"
+ i.getField() + "\n"
+ " </p>\n"
+ " </div>\n"
+ " <div class=\"hr-line-dashed\"></div>");
}
out.println("</div>\n"
+ " </div>\n"
+ " </div>\n"
+ " </div>\n"
+ " </div>\n"
+ "\n"
+ "\n"
+ " <style type=\"text/css\">\n"
+ " body{\n"
+ " background:#eee;\n"
+ " }\n"
+ " .ibox-content {\n"
+ " background-color: #FFFFFF;\n"
+ " color: inherit;\n"
+ " padding: 15px 20px 20px 20px;\n"
+ " border-color: #E7EAEC;\n"
+ " border-image: none;\n"
+ " border-style: solid solid none;\n"
+ " border-width: 1px 0px;\n"
+ " }\n"
+ "\n"
+ " .search-form {\n"
+ " margin-top: 10px;\n"
+ " }\n"
+ "\n"
+ " .search-result h3 {\n"
+ " margin-bottom: 0;\n"
+ " color: #1E0FBE;\n"
+ " }\n"
+ "\n"
+ " .search-result .search-link {\n"
+ " color: #006621;\n"
+ " }\n"
+ "\n"
+ " .search-result p {\n"
+ " font-size: 12px;\n"
+ " margin-top: 5px;\n"
+ " }\n"
+ "\n"
+ " .hr-line-dashed {\n"
+ " border-top: 1px dashed #E7EAEC;\n"
+ " color: #ffffff;\n"
+ " background-color: #ffffff;\n"
+ " height: 1px;\n"
+ " margin: 20px 0;\n"
+ " }\n"
+ "\n"
+ " h2 {\n"
+ " font-size: 24px;\n"
+ " font-weight: 100;\n"
+ " }\n"
+ "\n"
+ "\n"
+ " </style>\n"
+ "\n"
+ " <script type=\"text/javascript\">\n"
+ "\n"
+ "\n"
+ " </script>\n"
+ " </body>\n"
+ "</html>");
out.println("<script>\n"
+ " function refreshK() {\n"
+ " window.location.href = 'http://localhost:8080/Asteras/Results?query=" + query + "'"+ " +' &k=' + document.getElementById(\"k_results\").value;\n"
+ " }\n"
+ "\n"
+ " document.getElementById(\"submit_btn\").addEventListener(\"click\", refreshK);\n"
+ "\n"
+ "</script> ");
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException ex) {
Logger.getLogger(Results.class.getName()).log(Level.SEVERE, null, ex);
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| IliasAlex/Asteras | src/java/Asteras/Results.java |
44,563 | /*
* 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 Asteras;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Ηλίας
*/
public class Insert_delete extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>\n"
+ "<html lang=\"en\">\n"
+ " <head>\n"
+ " <meta charset=\"utf-8\">\n"
+ " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n"
+ " <title>Bootstrap Table with Add and Delete Row Feature</title>\n"
+ " <link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/css?family=Roboto|Varela+Round|Open+Sans\">\n"
+ " <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css\">\n"
+ " <link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/icon?family=Material+Icons\">\n"
+ " <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css\">\n"
+ " <script src=\"https://code.jquery.com/jquery-3.5.1.min.js\"></script>\n"
+ " <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\"></script>\n"
+ " <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js\"></script>\n"
+ " <style>\n"
+ " body {\n"
+ " color: #404E67;\n"
+ " background: #F5F7FA;\n"
+ " font-family: 'Open Sans', sans-serif;\n"
+ " }\n"
+ " .table-wrapper {\n"
+ " width: 700px;\n"
+ " margin: 30px auto;\n"
+ " background: #fff;\n"
+ " padding: 20px; \n"
+ " box-shadow: 0 1px 1px rgba(0,0,0,.05);\n"
+ " }\n"
+ " .table-title {\n"
+ " padding-bottom: 10px;\n"
+ " margin: 0 0 10px;\n"
+ " }\n"
+ " .table-title h2 {\n"
+ " margin: 6px 0 0;\n"
+ " font-size: 22px;\n"
+ " }\n"
+ " .table-title .add-new {\n"
+ " float: right;\n"
+ " height: 30px;\n"
+ " font-weight: bold;\n"
+ " font-size: 12px;\n"
+ " text-shadow: none;\n"
+ " min-width: 100px;\n"
+ " border-radius: 50px;\n"
+ " line-height: 13px;\n"
+ " }\n"
+ " .table-title .add-new i {\n"
+ " margin-right: 4px;\n"
+ " }\n"
+ " table.table {\n"
+ " table-layout: fixed;\n"
+ " }\n"
+ " table.table tr th, table.table tr td {\n"
+ " border-color: #e9e9e9;\n"
+ " }\n"
+ " table.table th i {\n"
+ " font-size: 13px;\n"
+ " margin: 0 5px;\n"
+ " cursor: pointer;\n"
+ " }\n"
+ " table.table th:last-child {\n"
+ " width: 100px;\n"
+ " }\n"
+ " table.table td a {\n"
+ " cursor: pointer;\n"
+ " display: inline-block;\n"
+ " margin: 0 5px;\n"
+ " min-width: 24px;\n"
+ " } \n"
+ " table.table td a.add {\n"
+ " color: #27C46B;\n"
+ " }\n"
+ " table.table td a.edit {\n"
+ " color: #FFC107;\n"
+ " }\n"
+ " table.table td a.delete {\n"
+ " color: #E34724;\n"
+ " }\n"
+ " table.table td i {\n"
+ " font-size: 19px;\n"
+ " }\n"
+ " table.table td a.add i {\n"
+ " font-size: 24px;\n"
+ " margin-right: -1px;\n"
+ " position: relative;\n"
+ " top: 3px;\n"
+ " } \n"
+ " table.table .form-control {\n"
+ " height: 32px;\n"
+ " line-height: 32px;\n"
+ " box-shadow: none;\n"
+ " border-radius: 2px;\n"
+ " }\n"
+ " table.table .form-control.error {\n"
+ " border-color: #f50000;\n"
+ " }\n"
+ " table.table td .add {\n"
+ " display: none;\n"
+ " }\n"
+ " </style>\n"
+ " <script>\n"
+ " $(document).ready(function () {\n"
+ " // Delete row on delete button click\n"
+ " $(document).on(\"click\", \".delete\", function () {\n"
+ " name = this.id;\n"
+ " $(this).parents(\"tr\").remove();\n"
+ " $(\".add-new\").removeAttr(\"disabled\");\n"
+ " window.location.href = 'http://localhost:8080/Asteras/DeleteAuthor?name=' + name;"
+ " });\n"
+ " });\n"
+ " </script>\n"
+ " </head>\n"
+ " <body>\n"
+ " <div class=\"container-lg\">\n"
+ " <div class=\"table-responsive\">\n"
+ " <div class=\"table-wrapper\">\n"
+ " <div class=\"table-title\">\n"
+ " <div class=\"row\">\n"
+ " <div class=\"col-sm-8\"><h2>Authors <b>Details</b></h2></div>\n"
+ "\n"
+ " </div>\n"
+ " </div>\n"
+ " <form action=\"http://localhost:8080/Asteras/DeleteAuthor\">\n"
+ " <br>\n"
+ " <label for=\"name\">Delete by Name:</label>\n"
+ " <input type=\"text\" id=\"name\" name=\"name\"><br>\n"
+ " <input type=\"submit\" value=\"Delete\"><br><br>\n"
+ " </form>"
+ " <table class=\"table table-bordered\">\n"
+ " <thead>\n"
+ " <tr>\n"
+ " <th>Name</th>\n"
+ " <th>Actions</th>\n"
+ " </tr>\n"
+ " </thead>\n"
+ " <tbody>\n"
);
File folder = new File(System.getProperty("user.dir")+"/Data");
if (folder.listFiles() != null) {
for (final File fileEntry : folder.listFiles()) {
if( fileEntry.length() == 0){
continue;
}
String name = fileEntry.getName().replace(".bib", "");
out.println("<tr>\n"
+ "<td>" + name + "</td>\n"
+ "<td>\n"
+ "<a class=\"delete\" title=\"Delete\" id = \""+name+"\"data-toggle=\"tooltip\"><i class=\"material-icons\"></i></a>\n"
+ "</td>\n"
+ "</tr> \n");
}
}
out.println(" </tbody>\n"
+ " </table>\n"
+ " <form method=\"post\" action=\"BibFileUpload\" enctype=\"multipart/form-data\">\n"
+ " <div class=\"col-sm-4\">\n"
+ " <input type=\"file\" id=\"file\" name=\"file\"required>\n"
+ " </div>\n"
+ " <div class=\"col-sm-4\">\n"
+" <br>"
+ " <button type=\"submit\" class=\"btn btn-info add-new\">Submit</button>\n"
+ " <a href=\"http://localhost:8080/Asteras/\" class=\"btn btn-primary\">Home</a>"
+ " </div>\n"
+ " </form>\n"
+ " </div>\n"
+ " </div>\n"
+ " </div> \n"
+ " </body>\n"
+ "</html>\n"
);
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| IliasAlex/Asteras | src/java/Asteras/Insert_delete.java |
44,565 | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package Asteras;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* @author Ηλίας
*/
public class CosineSimilarity {
private static class Values {
private int val1;
private int val2;
private Values(int v1, int v2) {
this.val1 = v1;
this.val2 = v2;
}
public void updateValues(int v1, int v2) {
this.val1 = v1;
this.val2 = v2;
}
}
public double score(String text1, String text2) {
//1. Identify distinct words from both documents
String[] text1Words = text1.split(" ");
String[] text2Words = text2.split(" ");
Map<String, Values> wordFreqVector = new HashMap<>();
List<String> distinctWords = new ArrayList<>();
//prepare word frequency vector by using Text1
for (String text : text1Words) {
String word = text.trim();
if (!word.isEmpty()) {
if (wordFreqVector.containsKey(word)) {
Values vals1 = wordFreqVector.get(word);
int freq1 = vals1.val1 + 1;
int freq2 = vals1.val2;
vals1.updateValues(freq1, freq2);
wordFreqVector.put(word, vals1);
} else {
Values vals1 = new Values(1, 0);
wordFreqVector.put(word, vals1);
distinctWords.add(word);
}
}
}
//prepare word frequency vector by using Text2
for (String text : text2Words) {
String word = text.trim();
if (!word.isEmpty()) {
if (wordFreqVector.containsKey(word)) {
Values vals1 = wordFreqVector.get(word);
int freq1 = vals1.val1;
int freq2 = vals1.val2 + 1;
vals1.updateValues(freq1, freq2);
wordFreqVector.put(word, vals1);
} else {
Values vals1 = new Values(0, 1);
wordFreqVector.put(word, vals1);
distinctWords.add(word);
}
}
}
//calculate the cosine similarity score.
double vectAB = 0.0000000;
double vectA = 0.0000000;
double vectB = 0.0000000;
for (int i = 0; i < distinctWords.size(); i++) {
Values vals12 = wordFreqVector.get(distinctWords.get(i));
double freq1 = vals12.val1;
double freq2 = vals12.val2;
vectAB = vectAB + freq1 * freq2;
vectA = vectA + freq1 * freq1;
vectB = vectB + freq2 * freq2;
}
return ((vectAB) / (Math.sqrt(vectA) * Math.sqrt(vectB)));
}
}
| IliasAlex/Asteras | src/java/Asteras/CosineSimilarity.java |