file_name
stringlengths 6
86
| file_path
stringlengths 45
249
| content
stringlengths 47
6.26M
| file_size
int64 47
6.26M
| language
stringclasses 1
value | extension
stringclasses 1
value | repo_name
stringclasses 767
values | repo_stars
int64 8
14.4k
| repo_forks
int64 0
1.17k
| repo_open_issues
int64 0
788
| repo_created_at
stringclasses 767
values | repo_pushed_at
stringclasses 767
values |
---|---|---|---|---|---|---|---|---|---|---|---|
EmailAddressGeneratorTest.java | /FileExtraction/Java_unseen/binarywang_java-testdata-generator/src/test/java/cn/binarywang/tools/generator/EmailAddressGeneratorTest.java | package cn.binarywang.tools.generator;
import static org.testng.Assert.assertNotNull;
import org.testng.annotations.Test;
public class EmailAddressGeneratorTest {
@Test
public void testGenerate() {
String generatedEmail = EmailAddressGenerator.getInstance().generate();
System.err.println(generatedEmail);
assertNotNull(generatedEmail);
}
}
| 382 | Java | .java | binarywang/java-testdata-generator | 584 | 276 | 0 | 2016-01-21T05:45:44Z | 2023-06-21T06:48:09Z |
ChineseNameGeneratorTest.java | /FileExtraction/Java_unseen/binarywang_java-testdata-generator/src/test/java/cn/binarywang/tools/generator/ChineseNameGeneratorTest.java | package cn.binarywang.tools.generator;
import static org.testng.Assert.assertNotNull;
import org.testng.annotations.Test;
public class ChineseNameGeneratorTest {
@Test
public void testGenerate() {
String generatedName = ChineseNameGenerator.getInstance().generate();
assertNotNull(generatedName);
System.err.println(generatedName);
}
@Test
public void testGenerateOdd() {
String generatedName = ChineseNameGenerator.getInstance().generateOdd();
assertNotNull(generatedName);
System.err.println(generatedName);
}
}
| 592 | Java | .java | binarywang/java-testdata-generator | 584 | 276 | 0 | 2016-01-21T05:45:44Z | 2023-06-21T06:48:09Z |
CSVFileGeneratorTest.java | /FileExtraction/Java_unseen/binarywang_java-testdata-generator/src/test/java/cn/binarywang/tools/generator/CSVFileGeneratorTest.java | package cn.binarywang.tools.generator;
import static org.testng.Assert.assertEquals;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
public class CSVFileGeneratorTest {
@Test
public void testGenerate() throws IOException {
String fileName = "tmp.csv";
List<HashMap<String, Object>> data = Lists.newArrayList(
new HashMap<>(ImmutableMap.<String, Object> of("1", "1a", "2", "2a",
"3", "3a")),
new HashMap<>(ImmutableMap.<String, Object> of("1", "1b", "2", "2b",
"3", "3b")),
new HashMap<>(ImmutableMap.<String, Object> of("1", "1c", "2", "2c",
"3", "3c")));
CSVFileGenerator.generate(data, new String[] { "1", "2", "3" },
fileName);
assertEquals(
Lists.newArrayList("1a,2a,3a", "1b,2b,3b", "1c,2c,3c"),
Files.readLines(new File(fileName), Charset.forName("utf-8")));
}
}
| 1,182 | Java | .java | binarywang/java-testdata-generator | 584 | 276 | 0 | 2016-01-21T05:45:44Z | 2023-06-21T06:48:09Z |
InsertSQLGeneratorTest.java | /FileExtraction/Java_unseen/binarywang_java-testdata-generator/src/test/java/cn/binarywang/tools/generator/InsertSQLGeneratorTest.java | package cn.binarywang.tools.generator;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import com.google.inject.Inject;
import com.google.inject.name.Named;
/**
* @author Binary Wang
*/
@Test
@Guice(modules = TestConfigModule.class)
public class InsertSQLGeneratorTest {
private InsertSQLGenerator generator;
@Inject
@Named("config.jdbc.driverClass")
private String className;
@Inject
@Named("config.jdbc.url")
private String url;
@Inject
@Named("config.jdbc.username")
private String username;
@Inject
@Named("config.jdbc.password")
private String password;
@BeforeTest
public void setup() {
try {
Class.forName(this.className);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
this.generator = new InsertSQLGenerator(this.url, this.username,
this.password, "data_order_ext");
}
@AfterTest
public void destroy() {
this.generator.close();
}
/**
* Test method for
* {@link cn.binarywang.tools.generator.InsertSQLGenerator#generateSQL()}.
*/
public void testGenerateSQL() {
System.err.println(this.generator.generateSQL());
}
/**
* Test method for
* {@link cn.binarywang.tools.generator.InsertSQLGenerator#generateParams()}
* .
*/
public void testGenerateParams() {
System.err.println(this.generator.generateParams());
}
}
| 1,582 | Java | .java | binarywang/java-testdata-generator | 584 | 276 | 0 | 2016-01-21T05:45:44Z | 2023-06-21T06:48:09Z |
ChineseAddressGeneratorTest.java | /FileExtraction/Java_unseen/binarywang_java-testdata-generator/src/test/java/cn/binarywang/tools/generator/ChineseAddressGeneratorTest.java | package cn.binarywang.tools.generator;
import static org.testng.Assert.assertNotNull;
import org.testng.annotations.Test;
public class ChineseAddressGeneratorTest {
@Test
public void testGenerate() {
String generatedAddress = ChineseAddressGenerator.getInstance()
.generate();
System.err.println(generatedAddress);
assertNotNull(generatedAddress);
}
}
| 405 | Java | .java | binarywang/java-testdata-generator | 584 | 276 | 0 | 2016-01-21T05:45:44Z | 2023-06-21T06:48:09Z |
ChineseIDCardNumberGeneratorTest.java | /FileExtraction/Java_unseen/binarywang_java-testdata-generator/src/test/java/cn/binarywang/tools/generator/ChineseIDCardNumberGeneratorTest.java | package cn.binarywang.tools.generator;
import static org.testng.Assert.assertNotNull;
import java.util.Date;
import org.testng.annotations.Test;
public class ChineseIDCardNumberGeneratorTest {
@Test
public void generateRandomDate() {
Date randomDate = ChineseIDCardNumberGenerator.randomDate();
System.err.println(randomDate);
assertNotNull(randomDate);
}
@Test
public void testGenerate() {
String idCard = ChineseIDCardNumberGenerator.getInstance().generate();
System.err.println(idCard);
assertNotNull(idCard);
if (idCard.charAt(idCard.length()-2)%2 == 0){
System.err.println("女");
} else {
System.err.println("男");
}
}
@Test
public void testGenerateIssueOrg() {
String issueOrg = ChineseIDCardNumberGenerator.generateIssueOrg();
System.err.println(issueOrg);
assertNotNull(issueOrg);
}
@Test
public void testGenerateValidPeriod() {
String result = ChineseIDCardNumberGenerator.generateValidPeriod();
System.err.println(result);
assertNotNull(result);
}
}
| 1,163 | Java | .java | binarywang/java-testdata-generator | 584 | 276 | 0 | 2016-01-21T05:45:44Z | 2023-06-21T06:48:09Z |
TestConfigModule.java | /FileExtraction/Java_unseen/binarywang_java-testdata-generator/src/test/java/cn/binarywang/tools/generator/TestConfigModule.java | package cn.binarywang.tools.generator;
import static com.google.inject.name.Names.named;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.Properties;
import com.google.inject.Binder;
import com.google.inject.Module;
/**
* @author Binary Wang
*/
public class TestConfigModule implements Module {
@Override
public void configure(Binder binder) {
Properties p = new Properties();
try {
p.load(new InputStreamReader(ClassLoader
.getSystemResourceAsStream("test-config.properties")));
} catch (IOException e) {
e.printStackTrace();
assert false;
}
Enumeration<Object> e = p.keys();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
String value = (String) p.get(key);
binder.bindConstant().annotatedWith(named("config." + key))
.to(value);
}
}
}
| 1,001 | Java | .java | binarywang/java-testdata-generator | 584 | 276 | 0 | 2016-01-21T05:45:44Z | 2023-06-21T06:48:09Z |
EnglishNameGeneratorTest.java | /FileExtraction/Java_unseen/binarywang_java-testdata-generator/src/test/java/cn/binarywang/tools/generator/EnglishNameGeneratorTest.java | package cn.binarywang.tools.generator;
import org.testng.annotations.Test;
import static org.testng.Assert.assertNotNull;
public class EnglishNameGeneratorTest {
@Test
public void testGenerate() {
String generatedName = EnglishNameGenerator.getInstance().generate();
assertNotNull(generatedName);
System.err.println(generatedName);
}
}
| 377 | Java | .java | binarywang/java-testdata-generator | 584 | 276 | 0 | 2016-01-21T05:45:44Z | 2023-06-21T06:48:09Z |
ChineseCharUtilsTest.java | /FileExtraction/Java_unseen/binarywang_java-testdata-generator/src/test/java/cn/binarywang/tools/generator/util/ChineseCharUtilsTest.java | package cn.binarywang.tools.generator.util;
import org.testng.annotations.Test;
import static cn.binarywang.tools.generator.util.ChineseCharUtils.*;
import static org.assertj.core.api.Assertions.assertThat;
/**
* 单元测试.
*
* @author <a href="https://github.com/binarywang">Binary Wang</a>
* @date 2020-10-03
*/
@Test
public class ChineseCharUtilsTest {
public void testGenOneChineseChars() {
final String result = genOneChineseChars();
System.out.println(result);
assertThat(result).hasSize(1);
}
public void testGenFixedLengthChineseChars() {
final String result = genFixedLengthChineseChars(20);
System.out.println(result);
assertThat(result).hasSize(20);
}
public void testGenRandomLengthChineseChars() {
final String result = genRandomLengthChineseChars(2, 10);
System.out.println(result);
assertThat(result).hasSizeBetween(2, 10);
}
public void testGetOneOddChar() {
final char result = getOneOddChar();
System.out.println(result);
assertThat(result).isNotNull();
}
}
| 1,118 | Java | .java | binarywang/java-testdata-generator | 584 | 276 | 0 | 2016-01-21T05:45:44Z | 2023-06-21T06:48:09Z |
BankCardNumberGeneratorTest.java | /FileExtraction/Java_unseen/binarywang_java-testdata-generator/src/test/java/cn/binarywang/tools/generator/bank/BankCardNumberGeneratorTest.java | package cn.binarywang.tools.generator.bank;
import org.testng.annotations.*;
import static org.testng.Assert.*;
public class BankCardNumberGeneratorTest {
@Test
public void testGenerate_by_bankName() {
String bankCardNo = BankCardNumberGenerator.generate(BankNameEnum.CR, null);
System.err.println(bankCardNo);
assertNotNull(bankCardNo);
bankCardNo = BankCardNumberGenerator.generate(BankNameEnum.ICBC, BankCardTypeEnum.CREDIT);
System.err.println(bankCardNo);
assertNotNull(bankCardNo);
bankCardNo = BankCardNumberGenerator.generate(BankNameEnum.ICBC, BankCardTypeEnum.DEBIT);
System.err.println(bankCardNo);
assertNotNull(bankCardNo);
}
@Test
public void testGenerateByPrefix() {
String bankCardNo = BankCardNumberGenerator.generateByPrefix(436742);
System.err.println(bankCardNo);
assertNotNull(bankCardNo);
}
@Test
public void testGenerate() {
String bankCardNo = BankCardNumberGenerator.getInstance().generate();
System.err.println(bankCardNo);
assertNotNull(bankCardNo);
}
}
| 1,145 | Java | .java | binarywang/java-testdata-generator | 584 | 276 | 0 | 2016-01-21T05:45:44Z | 2023-06-21T06:48:09Z |
BankCardNumberValidatorTest.java | /FileExtraction/Java_unseen/binarywang_java-testdata-generator/src/test/java/cn/binarywang/tools/generator/bank/BankCardNumberValidatorTest.java | package cn.binarywang.tools.generator.bank;
import org.testng.annotations.*;
import static org.assertj.core.api.Assertions.assertThat;
/**
* <pre>
*
* Created by Binary Wang on 2018/3/22.
* </pre>
*
* @author <a href="https://github.com/binarywang">Binary Wang</a>
*/
public class BankCardNumberValidatorTest {
@DataProvider
public Object[][] data() {
return new Object[][]{
{"220812000026626544"},
{"22480030862211715"},
{"2284039453077174"},
{"228480338189876372"},
{"230203199407281216"},
{"2304200060052505874"},
{"2848042531203871"},
{"2848395671637670"},
{"3217211210001022999"},
{"4295920020252229"},
{"436742109067408"},
{"441521198705193817"},
{"610628199207140822"},
{"6121260411007574030"},
{"6126611104001552735"},
{"6127004130000503693"},
{"617000150017089191"},
{"621003322005552162"},
{"62101135200035338861"},
{"621081103001115399914"},
{"621111110000540353"},
{"6211281082902084500"},
{"6211500100000513202"},
{"6211586100000512022"},
{"62116613100007617106"},
{"62117855000041067349"},
{"6211931562029258"},
{"6212202402018690921"},
{"62122536020229386"},
{"6212260200060118286"},
{"62122613030006322041"},
{"621226170202146127"},
{"6212261703005715922"},
{"62122617050113087625"},
{"621226190805639730"},
{"621226191300538209"},
{"6212262003010018007"},
{"621226201102782556"},
{"6212262314007531443"},
{"6212262502020825519"},
{"6212262602001076686"},
{"621226270300571592"},
{"62122630140024065183"},
{"6212263602066723007"},
{"621226400000313859"},
{"621226430100059399"},
{"62122644020659520"},
{"6212264402069510516"},
{"6213361726663133666"},
{"62136912100000479869"},
{"6214003240016970298"},
{"6214920200260744"},
{"6214923700051218"},
{"6215580405000660064"},
{"6215580804001004167"},
{"621558080900272864"},
{"6215581503797096"},
{"621558310005022166"},
{"621568310000107077"},
{"621568600000257443"},
{"62156975000105300355"},
{"6216616112000531669"},
{"6217000011045925156"},
{"62170000300007182833"},
{"62170002020066090309"},
{"62170006500002445588"},
{"621700069000138104"},
{"6217000944016450224"},
{"621700150018466778"},
{"621700203000646037"},
{"621700219006453253"},
{"621700243009386153"},
{"6217002433023834253"},
{"6217002850004855830"},
{"6217002870018709777"},
{"6217002870075668863"},
{"621700292013558792"},
{"62170029801064980053"},
{"62170032200019774499"},
{"62170033200638743228"},
{"621700364006123065"},
{"62170036500058141119"},
{"6217003810859126600"},
{"62170039500050012080"},
{"621700396000230939"},
{"6217004240009891"},
{"6217007200059610"},
{"62170096000230939"},
{"62170907000015087180"},
{"6217230912000742861"},
{"621723110201493188"},
{"62172326100008619"},
{"621723271200100589"},
{"621723401007064862"},
{"6217566000030513202"},
{"62176400019709352"},
{"6217730800111976"},
{"6217751768014206974"},
{"621785360023745002"},
{"621785700003456056"},
{"6217857600037659668"},
{"6217863100005832524"},
{"6217863600001059634"},
{"6217866000005105523"},
{"62179065000087299770"},
{"62179070000230171473"},
{"6217958500010529317"},
{"622003114460203036"},
{"6220081001032758769"},
{"6220580000016645996"},
{"6221131400015644"},
{"6221222000021697108"},
{"62212262405006074701"},
{"6221261410004280376"},
{"6221560539933028"},
{"6222004000107146212"},
{"622202020012055669"},
{"622202101059582285"},
{"62220214000485852"},
{"6222021602026082929"},
{"622202163015279473"},
{"62220227120052"},
{"6222023142879408"},
{"6222030905000202147"},
{"6222031208974192"},
{"6222032111000624285"},
{"6222081200002662654"},
{"622208120000666254"},
{"6222081616001266171"},
{"6222082806000878260"},
{"622208406001797972"},
{"62222032020000371017"},
{"62223100001708091"},
{"6222611210002887515"},
{"622262015008134641"},
{"622262021001711116"},
{"6222620210223002615"},
{"622262240001291709"},
{"6222625420000311212"},
{"622262953000740581"},
{"6222650580003695108"},
{"622277081229960575"},
{"6223221203014313711"},
{"6223263301023151250"},
{"62244030817172510"},
{"622480104067627151"},
{"622488012724040619"},
{"6225593202015827051"},
{"6226620804783028"},
{"622663260082645210"},
{"6226802968291436622"},
{"62268602438782309"},
{"622700001124019411"},
{"622700083290031701"},
{"62270018328301236440"},
{"6227002104010611916"},
{"6227002199166163831"},
{"62270033243100477377"},
{"622700339100107202"},
{"6227003413030048190"},
{"622700381401002666119"},
{"622700388140330044592"},
{"6228400469839976872"},
{"622840086485638471"},
{"622840328229782672"},
{"622840692112114774"},
{"622841206300734467"},
{"6228435979614813370"},
{"6228450316004325665"},
{"62284506888022090979"},
{"622845074801626237"},
{"622848001452213777"},
{"6228480031674226214"},
{"622848008396565117"},
{"622848024047721116"},
{"62284802467227164"},
{"622848029435148179"},
{"622848029443786878"},
{"622848029478832077"},
{"622848031637683779"},
{"6228480322045720212"},
{"622848033200674375"},
{"6228480368022884373"},
{"6228480405665999178"},
{"6228480405828157171"},
{"6228480409913258753"},
{"622848047841329679"},
{"6228480530662112715"},
{"622848059772296477"},
{"6228480609271414777"},
{"622848064814090897"},
{"6228480688118753271"},
{"6228480739442771277"},
{"622848076742861370"},
{"6228480838789325770"},
{"6228480838867786778"},
{"6228480846040840364"},
{"6228480898323076672"},
{"6228481262211422522"},
{"622848146968818877"},
{"6228481534204213188"},
{"6228481537828458074"},
{"62284818240638672"},
{"62284818490375573671"},
{"6228481908226681497"},
{"622848266105947960"},
{"622848269221492572"},
{"6228483056265990663"},
{"6228483066594264062"},
{"6228483078099931755"},
{"622848318547872"},
{"622848328430118771"},
{"622848397827586274"},
{"622848402840977697"},
{"62284842479594342275"},
{"622848626728571276"},
{"62284862673963857"},
{"6228486279206500273"},
{"622848858786859976"},
{"622848969411402577"},
{"6228623106581345"},
{"6228983368033970979"},
{"622908323038302348"},
{"622908576551033111"},
{"623052001002453507"},
{"623052010024535079"},
{"623052068014815374"},
{"623058000012878319"},
{"623058000013478998"},
{"6230944138002004761"},
{"623573600002111129"},
{"623575800000865733"},
{"6236680010001418775"},
{"6236680130006251077"},
{"623668214600064477899"},
{"62366825500023005266"},
{"623668292005651821"},
{"623668332000780058"},
{"623668332007800584"},
{"6256883100001070077"},
{"6270029201171628841"},
{"6270033200455921162"},
{"6280000008000000222"},
{"6280020998091229"},
{"628480333167998111"},
{"628481352283510018"},
{"6366112600016504488"},
{"6366832600009344533"},
{"6366833200203820322"},
{"66212261715002941831"},
{"66227000301430275516"},
{"6622848009480341313"},
{"6622848032317609617"},
{"8228480329458044271"},
{"8228480841076999918"},
{"82840128469874773"},
{"888459869038658733"},
{"9226621105618837"},
{"955882202000330378"},
{"?6228480378408245371?"},
{"?6228482478396320570?"},
};
}
@Test(dataProvider = "data")
public void testValidate(String cardNo) {
assertThat(BankCardNumberValidator.validate(cardNo)).isTrue();
}
}
| 10,087 | Java | .java | binarywang/java-testdata-generator | 584 | 276 | 0 | 2016-01-21T05:45:44Z | 2023-06-21T06:48:09Z |
ChineseAreaList.java | /FileExtraction/Java_unseen/binarywang_java-testdata-generator/src/main/java/cn/binarywang/tools/generator/ChineseAreaList.java | package cn.binarywang.tools.generator;
import java.util.ArrayList;
import java.util.List;
public class ChineseAreaList {
public static List<String> provinceCityList = new ArrayList<>();
public static List<String> cityNameList = new ArrayList<>();
static {
provinceCityList.add("黑龙江省齐齐哈尔市");
provinceCityList.add("黑龙江省黑河市");
provinceCityList.add("黑龙江省鹤岗市");
provinceCityList.add("黑龙江省鸡西市");
provinceCityList.add("黑龙江省绥化市");
provinceCityList.add("黑龙江省牡丹江市");
provinceCityList.add("黑龙江省大庆市");
provinceCityList.add("黑龙江省大兴安岭地区");
provinceCityList.add("黑龙江省哈尔滨市");
provinceCityList.add("黑龙江省双鸭山市");
provinceCityList.add("黑龙江省佳木斯市");
provinceCityList.add("黑龙江省伊春市");
provinceCityList.add("黑龙江省七台河市");
provinceCityList.add("香港特别行政区香港特别行政区");
provinceCityList.add("青海省黄南藏族自治州");
provinceCityList.add("青海省西宁市");
provinceCityList.add("青海省玉树藏族自治州");
provinceCityList.add("青海省海西蒙古族藏族自治州");
provinceCityList.add("青海省海南藏族自治州");
provinceCityList.add("青海省海北藏族自治州");
provinceCityList.add("青海省海东地区");
provinceCityList.add("青海省果洛藏族自治州");
provinceCityList.add("陕西省铜川市");
provinceCityList.add("陕西省西安市");
provinceCityList.add("陕西省渭南市");
provinceCityList.add("陕西省汉中市");
provinceCityList.add("陕西省榆林市");
provinceCityList.add("陕西省延安市");
provinceCityList.add("陕西省宝鸡市");
provinceCityList.add("陕西省安康市");
provinceCityList.add("陕西省商洛市");
provinceCityList.add("陕西省咸阳市");
provinceCityList.add("重庆市重庆市");
provinceCityList.add("辽宁省鞍山市");
provinceCityList.add("辽宁省阜新市");
provinceCityList.add("辽宁省锦州市");
provinceCityList.add("辽宁省铁岭市");
provinceCityList.add("辽宁省辽阳市");
provinceCityList.add("辽宁省葫芦岛市");
provinceCityList.add("辽宁省营口市");
provinceCityList.add("辽宁省盘锦市");
provinceCityList.add("辽宁省沈阳市");
provinceCityList.add("辽宁省本溪市");
provinceCityList.add("辽宁省朝阳市");
provinceCityList.add("辽宁省抚顺市");
provinceCityList.add("辽宁省大连市");
provinceCityList.add("辽宁省丹东市");
provinceCityList.add("贵州省黔西南布依族苗族自治州");
provinceCityList.add("贵州省黔南布依族苗族自治州");
provinceCityList.add("贵州省黔东南苗族侗族自治州");
provinceCityList.add("贵州省铜仁地区");
provinceCityList.add("贵州省遵义市");
provinceCityList.add("贵州省贵阳市");
provinceCityList.add("贵州省毕节地区");
provinceCityList.add("贵州省安顺市");
provinceCityList.add("贵州省六盘水市");
provinceCityList.add("西藏自治区阿里地区");
provinceCityList.add("西藏自治区那曲地区");
provinceCityList.add("西藏自治区林芝地区");
provinceCityList.add("西藏自治区昌都地区");
provinceCityList.add("西藏自治区日喀则地区");
provinceCityList.add("西藏自治区拉萨市");
provinceCityList.add("西藏自治区山南地区");
provinceCityList.add("福建省龙岩市");
provinceCityList.add("福建省莆田市");
provinceCityList.add("福建省福州市");
provinceCityList.add("福建省漳州市");
provinceCityList.add("福建省泉州市");
provinceCityList.add("福建省宁德市");
provinceCityList.add("福建省厦门市");
provinceCityList.add("福建省南平市");
provinceCityList.add("福建省三明市");
provinceCityList.add("甘肃省陇南市");
provinceCityList.add("甘肃省金昌市");
provinceCityList.add("甘肃省酒泉市");
provinceCityList.add("甘肃省白银市");
provinceCityList.add("甘肃省甘南藏族自治州");
provinceCityList.add("甘肃省武威市");
provinceCityList.add("甘肃省张掖市");
provinceCityList.add("甘肃省庆阳市");
provinceCityList.add("甘肃省平凉市");
provinceCityList.add("甘肃省定西市");
provinceCityList.add("甘肃省天水市");
provinceCityList.add("甘肃省嘉峪关市");
provinceCityList.add("甘肃省兰州市");
provinceCityList.add("甘肃省临夏回族自治州");
provinceCityList.add("澳门特别行政区澳门特别行政区");
provinceCityList.add("湖南省长沙市");
provinceCityList.add("湖南省郴州市");
provinceCityList.add("湖南省邵阳市");
provinceCityList.add("湖南省衡阳市");
provinceCityList.add("湖南省益阳市");
provinceCityList.add("湖南省湘西土家族苗族自治州");
provinceCityList.add("湖南省湘潭市");
provinceCityList.add("湖南省永州市");
provinceCityList.add("湖南省株洲市");
provinceCityList.add("湖南省怀化市");
provinceCityList.add("湖南省张家界市");
provinceCityList.add("湖南省常德市");
provinceCityList.add("湖南省岳阳市");
provinceCityList.add("湖南省娄底市");
provinceCityList.add("湖北省黄石市");
provinceCityList.add("湖北省黄冈市");
provinceCityList.add("湖北省随州市");
provinceCityList.add("湖北省鄂州市");
provinceCityList.add("湖北省襄樊市");
provinceCityList.add("湖北省荆门市");
provinceCityList.add("湖北省荆州市");
provinceCityList.add("湖北省神农架");
provinceCityList.add("湖北省武汉市");
provinceCityList.add("湖北省恩施土家族苗族自治州");
provinceCityList.add("湖北省宜昌市");
provinceCityList.add("湖北省孝感市");
provinceCityList.add("湖北省咸宁市");
provinceCityList.add("湖北省十堰市");
provinceCityList.add("海南省海口市");
provinceCityList.add("海南省三亚市");
provinceCityList.add("浙江省金华市");
provinceCityList.add("浙江省衢州市");
provinceCityList.add("浙江省舟山市");
provinceCityList.add("浙江省绍兴市");
provinceCityList.add("浙江省湖州市");
provinceCityList.add("浙江省温州市");
provinceCityList.add("浙江省杭州市");
provinceCityList.add("浙江省宁波市");
provinceCityList.add("浙江省嘉兴市");
provinceCityList.add("浙江省台州市");
provinceCityList.add("浙江省丽水市");
provinceCityList.add("河南省鹤壁市");
provinceCityList.add("河南省驻马店市");
provinceCityList.add("河南省郑州市");
provinceCityList.add("河南省许昌市");
provinceCityList.add("河南省焦作市");
provinceCityList.add("河南省濮阳市");
provinceCityList.add("河南省漯河市");
provinceCityList.add("河南省洛阳市");
provinceCityList.add("河南省新乡市");
provinceCityList.add("河南省开封市");
provinceCityList.add("河南省平顶山市");
provinceCityList.add("河南省安阳市");
provinceCityList.add("河南省商丘市");
provinceCityList.add("河南省周口市");
provinceCityList.add("河南省南阳市");
provinceCityList.add("河南省信阳市");
provinceCityList.add("河南省三门峡市");
provinceCityList.add("河北省邯郸市");
provinceCityList.add("河北省邢台市");
provinceCityList.add("河北省衡水市");
provinceCityList.add("河北省秦皇岛市");
provinceCityList.add("河北省石家庄市");
provinceCityList.add("河北省沧州市");
provinceCityList.add("河北省承德市");
provinceCityList.add("河北省张家口市");
provinceCityList.add("河北省廊坊市");
provinceCityList.add("河北省唐山市");
provinceCityList.add("河北省保定市");
provinceCityList.add("江西省鹰潭市");
provinceCityList.add("江西省赣州市");
provinceCityList.add("江西省萍乡市");
provinceCityList.add("江西省景德镇市");
provinceCityList.add("江西省新余市");
provinceCityList.add("江西省抚州市");
provinceCityList.add("江西省宜春市");
provinceCityList.add("江西省吉安市");
provinceCityList.add("江西省南昌市");
provinceCityList.add("江西省九江市");
provinceCityList.add("江西省上饶市");
provinceCityList.add("江苏省镇江市");
provinceCityList.add("江苏省连云港市");
provinceCityList.add("江苏省苏州市");
provinceCityList.add("江苏省盐城市");
provinceCityList.add("江苏省淮安市");
provinceCityList.add("江苏省泰州市");
provinceCityList.add("江苏省无锡市");
provinceCityList.add("江苏省扬州市");
provinceCityList.add("江苏省徐州市");
provinceCityList.add("江苏省常州市");
provinceCityList.add("江苏省宿迁市");
provinceCityList.add("江苏省南通市");
provinceCityList.add("江苏省南京市");
provinceCityList.add("新疆维吾尔自治区阿拉尔市");
provinceCityList.add("新疆维吾尔自治区阿勒泰地区");
provinceCityList.add("新疆维吾尔自治区阿克苏地区");
provinceCityList.add("新疆维吾尔自治区石河子市");
provinceCityList.add("新疆维吾尔自治区昌吉回族自治州");
provinceCityList.add("新疆维吾尔自治区巴音郭楞蒙古自治州");
provinceCityList.add("新疆维吾尔自治区塔城地区");
provinceCityList.add("新疆维吾尔自治区图木舒克市");
provinceCityList.add("新疆维吾尔自治区喀什地区");
provinceCityList.add("新疆维吾尔自治区哈密地区");
provinceCityList.add("新疆维吾尔自治区和田地区");
provinceCityList.add("新疆维吾尔自治区吐鲁番地区");
provinceCityList.add("新疆维吾尔自治区博尔塔拉蒙古自治州");
provinceCityList.add("新疆维吾尔自治区克拉玛依市");
provinceCityList.add("新疆维吾尔自治区克孜勒苏柯尔克孜自治州");
provinceCityList.add("新疆维吾尔自治区伊犁哈萨克自治州");
provinceCityList.add("新疆维吾尔自治区五家渠市");
provinceCityList.add("新疆维吾尔自治区乌鲁木齐市");
provinceCityList.add("广西壮族自治区防城港市");
provinceCityList.add("广西壮族自治区钦州市");
provinceCityList.add("广西壮族自治区贺州市");
provinceCityList.add("广西壮族自治区贵港市");
provinceCityList.add("广西壮族自治区百色市");
provinceCityList.add("广西壮族自治区玉林市");
provinceCityList.add("广西壮族自治区河池市");
provinceCityList.add("广西壮族自治区梧州市");
provinceCityList.add("广西壮族自治区桂林市");
provinceCityList.add("广西壮族自治区柳州市");
provinceCityList.add("广西壮族自治区来宾市");
provinceCityList.add("广西壮族自治区崇左市");
provinceCityList.add("广西壮族自治区南宁市");
provinceCityList.add("广西壮族自治区北海市");
provinceCityList.add("广东省韶关市");
provinceCityList.add("广东省阳江市");
provinceCityList.add("广东省茂名市");
provinceCityList.add("广东省肇庆市");
provinceCityList.add("广东省珠海市");
provinceCityList.add("广东省潮州市");
provinceCityList.add("广东省湛江市");
provinceCityList.add("广东省清远市");
provinceCityList.add("广东省深圳市");
provinceCityList.add("广东省河源市");
provinceCityList.add("广东省江门市");
provinceCityList.add("广东省汕尾市");
provinceCityList.add("广东省汕头市");
provinceCityList.add("广东省梅州市");
provinceCityList.add("广东省揭阳市");
provinceCityList.add("广东省惠州市");
provinceCityList.add("广东省广州市");
provinceCityList.add("广东省佛山市");
provinceCityList.add("广东省云浮市");
provinceCityList.add("广东省中山市");
provinceCityList.add("广东省东莞市");
provinceCityList.add("山西省阳泉市");
provinceCityList.add("山西省长治市");
provinceCityList.add("山西省运城市");
provinceCityList.add("山西省朔州市");
provinceCityList.add("山西省晋城市");
provinceCityList.add("山西省晋中市");
provinceCityList.add("山西省忻州市");
provinceCityList.add("山西省太原市");
provinceCityList.add("山西省大同市");
provinceCityList.add("山西省吕梁市");
provinceCityList.add("山西省临汾市");
provinceCityList.add("山东省青岛市");
provinceCityList.add("山东省菏泽市");
provinceCityList.add("山东省莱芜市");
provinceCityList.add("山东省聊城市");
provinceCityList.add("山东省烟台市");
provinceCityList.add("山东省潍坊市");
provinceCityList.add("山东省滨州市");
provinceCityList.add("山东省淄博市");
provinceCityList.add("山东省济宁市");
provinceCityList.add("山东省济南市");
provinceCityList.add("山东省泰安市");
provinceCityList.add("山东省枣庄市");
provinceCityList.add("山东省日照市");
provinceCityList.add("山东省德州市");
provinceCityList.add("山东省威海市");
provinceCityList.add("山东省临沂市");
provinceCityList.add("山东省东营市");
provinceCityList.add("安徽省黄山市");
provinceCityList.add("安徽省马鞍山市");
provinceCityList.add("安徽省阜阳市");
provinceCityList.add("安徽省铜陵市");
provinceCityList.add("安徽省蚌埠市");
provinceCityList.add("安徽省芜湖市");
provinceCityList.add("安徽省滁州市");
provinceCityList.add("安徽省淮南市");
provinceCityList.add("安徽省淮北市");
provinceCityList.add("安徽省池州市");
provinceCityList.add("安徽省巢湖市");
provinceCityList.add("安徽省宿州市");
provinceCityList.add("安徽省宣城市");
provinceCityList.add("安徽省安庆市");
provinceCityList.add("安徽省合肥市");
provinceCityList.add("安徽省六安市");
provinceCityList.add("安徽省亳州市");
provinceCityList.add("宁夏回族自治区银川市");
provinceCityList.add("宁夏回族自治区石嘴山市");
provinceCityList.add("宁夏回族自治区固原市");
provinceCityList.add("宁夏回族自治区吴忠市");
provinceCityList.add("宁夏回族自治区中卫市");
provinceCityList.add("天津市天津市");
provinceCityList.add("四川省雅安市");
provinceCityList.add("四川省阿坝藏族羌族自治州");
provinceCityList.add("四川省遂宁市");
provinceCityList.add("四川省达州市");
provinceCityList.add("四川省资阳市");
provinceCityList.add("四川省自贡市");
provinceCityList.add("四川省绵阳市");
provinceCityList.add("四川省眉山市");
provinceCityList.add("四川省甘孜藏族自治州");
provinceCityList.add("四川省泸州市");
provinceCityList.add("四川省攀枝花市");
provinceCityList.add("四川省成都市");
provinceCityList.add("四川省德阳市");
provinceCityList.add("四川省广安市");
provinceCityList.add("四川省广元市");
provinceCityList.add("四川省巴中市");
provinceCityList.add("四川省宜宾市");
provinceCityList.add("四川省南充市");
provinceCityList.add("四川省凉山彝族自治州");
provinceCityList.add("四川省内江市");
provinceCityList.add("四川省乐山市");
provinceCityList.add("吉林省长春市");
provinceCityList.add("吉林省通化市");
provinceCityList.add("吉林省辽源市");
provinceCityList.add("吉林省白山市");
provinceCityList.add("吉林省白城市");
provinceCityList.add("吉林省松原市");
provinceCityList.add("吉林省延边朝鲜族自治州");
provinceCityList.add("吉林省四平市");
provinceCityList.add("吉林省吉林市");
provinceCityList.add("台湾省台湾省");
provinceCityList.add("北京市北京市");
provinceCityList.add("内蒙古自治区阿拉善盟");
provinceCityList.add("内蒙古自治区锡林郭勒盟");
provinceCityList.add("内蒙古自治区鄂尔多斯市");
provinceCityList.add("内蒙古自治区通辽市");
provinceCityList.add("内蒙古自治区赤峰市");
provinceCityList.add("内蒙古自治区巴彦淖尔市");
provinceCityList.add("内蒙古自治区呼和浩特市");
provinceCityList.add("内蒙古自治区呼伦贝尔市");
provinceCityList.add("内蒙古自治区包头市");
provinceCityList.add("内蒙古自治区兴安盟");
provinceCityList.add("内蒙古自治区乌海市");
provinceCityList.add("内蒙古自治区乌兰察布市");
provinceCityList.add("云南省迪庆藏族自治州");
provinceCityList.add("云南省西双版纳傣族自治州");
provinceCityList.add("云南省红河哈尼族彝族自治州");
provinceCityList.add("云南省玉溪市");
provinceCityList.add("云南省楚雄彝族自治州");
provinceCityList.add("云南省曲靖市");
provinceCityList.add("云南省普洱市");
provinceCityList.add("云南省昭通市");
provinceCityList.add("云南省昆明市");
provinceCityList.add("云南省文山壮族苗族自治州");
provinceCityList.add("云南省怒江傈僳族自治州");
provinceCityList.add("云南省德宏傣族景颇族自治州");
provinceCityList.add("云南省大理白族自治州");
provinceCityList.add("云南省保山市");
provinceCityList.add("云南省丽江市");
provinceCityList.add("云南省临沧市");
provinceCityList.add("上海市上海市");
}
static {
cityNameList.add("北京市");
cityNameList.add("上海市");
cityNameList.add("天津市");
cityNameList.add("重庆市");
cityNameList.add("石家庄市");
cityNameList.add("唐山市");
cityNameList.add("秦皇岛市");
cityNameList.add("邯郸市");
cityNameList.add("邢台市");
cityNameList.add("保定市");
cityNameList.add("张家口市");
cityNameList.add("承德市");
cityNameList.add("沧州市");
cityNameList.add("廊坊市");
cityNameList.add("衡水市");
cityNameList.add("太原市");
cityNameList.add("大同市");
cityNameList.add("阳泉市");
cityNameList.add("长治市");
cityNameList.add("晋城市");
cityNameList.add("朔州市");
cityNameList.add("晋中市");
cityNameList.add("运城市");
cityNameList.add("忻州市");
cityNameList.add("临汾市");
cityNameList.add("吕梁市");
cityNameList.add("呼和浩特市");
cityNameList.add("包头市");
cityNameList.add("乌海市");
cityNameList.add("赤峰市");
cityNameList.add("通辽市");
cityNameList.add("鄂尔多斯市");
cityNameList.add("呼伦贝尔市");
cityNameList.add("巴彦淖尔市");
cityNameList.add("乌兰察布市");
cityNameList.add("兴安盟");
cityNameList.add("锡林郭勒盟");
cityNameList.add("阿拉善盟");
cityNameList.add("沈阳市");
cityNameList.add("大连市");
cityNameList.add("鞍山市");
cityNameList.add("抚顺市");
cityNameList.add("本溪市");
cityNameList.add("丹东市");
cityNameList.add("锦州市");
cityNameList.add("营口市");
cityNameList.add("阜新市");
cityNameList.add("辽阳市");
cityNameList.add("盘锦市");
cityNameList.add("铁岭市");
cityNameList.add("朝阳市");
cityNameList.add("葫芦岛市");
cityNameList.add("长春市");
cityNameList.add("吉林市");
cityNameList.add("四平市");
cityNameList.add("辽源市");
cityNameList.add("通化市");
cityNameList.add("白山市");
cityNameList.add("松原市");
cityNameList.add("白城市");
cityNameList.add("延边朝鲜族自治州");
cityNameList.add("哈尔滨市");
cityNameList.add("齐齐哈尔市");
cityNameList.add("鸡西市");
cityNameList.add("鹤岗市");
cityNameList.add("双鸭山市");
cityNameList.add("大庆市");
cityNameList.add("伊春市");
cityNameList.add("佳木斯市");
cityNameList.add("七台河市");
cityNameList.add("牡丹江市");
cityNameList.add("黑河市");
cityNameList.add("绥化市");
cityNameList.add("大兴安岭地区");
cityNameList.add("南京市");
cityNameList.add("无锡市");
cityNameList.add("徐州市");
cityNameList.add("常州市");
cityNameList.add("苏州市");
cityNameList.add("南通市");
cityNameList.add("连云港市");
cityNameList.add("淮安市");
cityNameList.add("盐城市");
cityNameList.add("扬州市");
cityNameList.add("镇江市");
cityNameList.add("泰州市");
cityNameList.add("宿迁市");
cityNameList.add("杭州市");
cityNameList.add("宁波市");
cityNameList.add("温州市");
cityNameList.add("嘉兴市");
cityNameList.add("湖州市");
cityNameList.add("绍兴市");
cityNameList.add("金华市");
cityNameList.add("衢州市");
cityNameList.add("舟山市");
cityNameList.add("台州市");
cityNameList.add("丽水市");
cityNameList.add("合肥市");
cityNameList.add("芜湖市");
cityNameList.add("蚌埠市");
cityNameList.add("淮南市");
cityNameList.add("马鞍山市");
cityNameList.add("淮北市");
cityNameList.add("铜陵市");
cityNameList.add("安庆市");
cityNameList.add("黄山市");
cityNameList.add("滁州市");
cityNameList.add("阜阳市");
cityNameList.add("宿州市");
cityNameList.add("六安市");
cityNameList.add("亳州市");
cityNameList.add("池州市");
cityNameList.add("宣城市");
cityNameList.add("福州市");
cityNameList.add("厦门市");
cityNameList.add("莆田市");
cityNameList.add("三明市");
cityNameList.add("泉州市");
cityNameList.add("漳州市");
cityNameList.add("南平市");
cityNameList.add("龙岩市");
cityNameList.add("宁德市");
cityNameList.add("南昌市");
cityNameList.add("景德镇市");
cityNameList.add("萍乡市");
cityNameList.add("九江市");
cityNameList.add("新余市");
cityNameList.add("鹰潭市");
cityNameList.add("赣州市");
cityNameList.add("吉安市");
cityNameList.add("宜春市");
cityNameList.add("抚州市");
cityNameList.add("上饶市");
cityNameList.add("济南市");
cityNameList.add("青岛市");
cityNameList.add("淄博市");
cityNameList.add("枣庄市");
cityNameList.add("东营市");
cityNameList.add("烟台市");
cityNameList.add("潍坊市");
cityNameList.add("济宁市");
cityNameList.add("泰安市");
cityNameList.add("威海市");
cityNameList.add("日照市");
cityNameList.add("莱芜市");
cityNameList.add("临沂市");
cityNameList.add("德州市");
cityNameList.add("聊城市");
cityNameList.add("滨州市");
cityNameList.add("菏泽市");
cityNameList.add("郑州市");
cityNameList.add("开封市");
cityNameList.add("洛阳市");
cityNameList.add("平顶山市");
cityNameList.add("安阳市");
cityNameList.add("鹤壁市");
cityNameList.add("新乡市");
cityNameList.add("焦作市");
cityNameList.add("濮阳市");
cityNameList.add("许昌市");
cityNameList.add("漯河市");
cityNameList.add("三门峡市");
cityNameList.add("南阳市");
cityNameList.add("商丘市");
cityNameList.add("信阳市");
cityNameList.add("周口市");
cityNameList.add("驻马店市");
cityNameList.add("省直辖县级行政区划");
cityNameList.add("武汉市");
cityNameList.add("黄石市");
cityNameList.add("十堰市");
cityNameList.add("宜昌市");
cityNameList.add("襄阳市");
cityNameList.add("鄂州市");
cityNameList.add("荆门市");
cityNameList.add("孝感市");
cityNameList.add("荆州市");
cityNameList.add("黄冈市");
cityNameList.add("咸宁市");
cityNameList.add("随州市");
cityNameList.add("恩施土家族苗族自治州");
cityNameList.add("省直辖县级行政区划");
cityNameList.add("长沙市");
cityNameList.add("株洲市");
cityNameList.add("湘潭市");
cityNameList.add("衡阳市");
cityNameList.add("邵阳市");
cityNameList.add("岳阳市");
cityNameList.add("常德市");
cityNameList.add("张家界市");
cityNameList.add("益阳市");
cityNameList.add("郴州市");
cityNameList.add("永州市");
cityNameList.add("怀化市");
cityNameList.add("娄底市");
cityNameList.add("湘西土家族苗族自治州");
cityNameList.add("广州市");
cityNameList.add("韶关市");
cityNameList.add("深圳市");
cityNameList.add("珠海市");
cityNameList.add("汕头市");
cityNameList.add("佛山市");
cityNameList.add("江门市");
cityNameList.add("湛江市");
cityNameList.add("茂名市");
cityNameList.add("肇庆市");
cityNameList.add("惠州市");
cityNameList.add("梅州市");
cityNameList.add("汕尾市");
cityNameList.add("河源市");
cityNameList.add("阳江市");
cityNameList.add("清远市");
cityNameList.add("东莞市");
cityNameList.add("中山市");
cityNameList.add("潮州市");
cityNameList.add("揭阳市");
cityNameList.add("云浮市");
cityNameList.add("南宁市");
cityNameList.add("柳州市");
cityNameList.add("桂林市");
cityNameList.add("梧州市");
cityNameList.add("北海市");
cityNameList.add("防城港市");
cityNameList.add("钦州市");
cityNameList.add("贵港市");
cityNameList.add("玉林市");
cityNameList.add("百色市");
cityNameList.add("贺州市");
cityNameList.add("河池市");
cityNameList.add("来宾市");
cityNameList.add("崇左市");
cityNameList.add("海口市");
cityNameList.add("三亚市");
cityNameList.add("三沙市");
cityNameList.add("成都市");
cityNameList.add("自贡市");
cityNameList.add("攀枝花市");
cityNameList.add("泸州市");
cityNameList.add("德阳市");
cityNameList.add("绵阳市");
cityNameList.add("广元市");
cityNameList.add("遂宁市");
cityNameList.add("内江市");
cityNameList.add("乐山市");
cityNameList.add("南充市");
cityNameList.add("眉山市");
cityNameList.add("宜宾市");
cityNameList.add("广安市");
cityNameList.add("达州市");
cityNameList.add("雅安市");
cityNameList.add("巴中市");
cityNameList.add("资阳市");
cityNameList.add("阿坝藏族羌族自治州");
cityNameList.add("甘孜藏族自治州");
cityNameList.add("凉山彝族自治州");
cityNameList.add("贵阳市");
cityNameList.add("六盘水市");
cityNameList.add("遵义市");
cityNameList.add("安顺市");
cityNameList.add("毕节市");
cityNameList.add("铜仁市");
cityNameList.add("黔西南布依族苗族自治州");
cityNameList.add("黔东南苗族侗族自治州");
cityNameList.add("黔南布依族苗族自治州");
cityNameList.add("昆明市");
cityNameList.add("曲靖市");
cityNameList.add("玉溪市");
cityNameList.add("保山市");
cityNameList.add("昭通市");
cityNameList.add("丽江市");
cityNameList.add("普洱市");
cityNameList.add("临沧市");
cityNameList.add("楚雄彝族自治州");
cityNameList.add("红河哈尼族彝族自治州");
cityNameList.add("文山壮族苗族自治州");
cityNameList.add("西双版纳傣族自治州");
cityNameList.add("大理白族自治州");
cityNameList.add("德宏傣族景颇族自治州");
cityNameList.add("怒江傈僳族自治州");
cityNameList.add("迪庆藏族自治州");
cityNameList.add("拉萨市");
cityNameList.add("日喀则市");
cityNameList.add("昌都地区");
cityNameList.add("山南地区");
cityNameList.add("那曲地区");
cityNameList.add("阿里地区");
cityNameList.add("林芝地区");
cityNameList.add("西安市");
cityNameList.add("铜川市");
cityNameList.add("宝鸡市");
cityNameList.add("咸阳市");
cityNameList.add("渭南市");
cityNameList.add("延安市");
cityNameList.add("汉中市");
cityNameList.add("榆林市");
cityNameList.add("安康市");
cityNameList.add("商洛市");
cityNameList.add("兰州市");
cityNameList.add("嘉峪关市");
cityNameList.add("金昌市");
cityNameList.add("白银市");
cityNameList.add("天水市");
cityNameList.add("武威市");
cityNameList.add("张掖市");
cityNameList.add("平凉市");
cityNameList.add("酒泉市");
cityNameList.add("庆阳市");
cityNameList.add("定西市");
cityNameList.add("陇南市");
cityNameList.add("临夏回族自治州");
cityNameList.add("甘南藏族自治州");
cityNameList.add("西宁市");
cityNameList.add("海东市");
cityNameList.add("海北藏族自治州");
cityNameList.add("黄南藏族自治州");
cityNameList.add("海南藏族自治州");
cityNameList.add("果洛藏族自治州");
cityNameList.add("玉树藏族自治州");
cityNameList.add("海西蒙古族藏族自治州");
cityNameList.add("银川市");
cityNameList.add("石嘴山市");
cityNameList.add("吴忠市");
cityNameList.add("固原市");
cityNameList.add("中卫市");
cityNameList.add("乌鲁木齐市");
cityNameList.add("克拉玛依市");
cityNameList.add("吐鲁番地区");
cityNameList.add("哈密地区");
cityNameList.add("昌吉回族自治州");
cityNameList.add("博尔塔拉蒙古自治州");
cityNameList.add("巴音郭楞蒙古自治州");
cityNameList.add("阿克苏地区");
cityNameList.add("克孜勒苏柯尔克孜自治州");
cityNameList.add("喀什地区");
cityNameList.add("和田地区");
cityNameList.add("伊犁哈萨克自治州");
cityNameList.add("塔城地区");
cityNameList.add("阿勒泰地区");
}
}
| 33,585 | Java | .java | binarywang/java-testdata-generator | 584 | 276 | 0 | 2016-01-21T05:45:44Z | 2023-06-21T06:48:09Z |
ChineseMobileNumberGenerator.java | /FileExtraction/Java_unseen/binarywang_java-testdata-generator/src/main/java/cn/binarywang/tools/generator/ChineseMobileNumberGenerator.java | package cn.binarywang.tools.generator;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import cn.binarywang.tools.generator.base.GenericGenerator;
public class ChineseMobileNumberGenerator extends GenericGenerator {
private static final int[] MOBILE_PREFIX = new int[] { 133, 153, 177, 180,
181, 189, 134, 135, 136, 137, 138, 139, 150, 151, 152, 157, 158, 159,
178, 182, 183, 184, 187, 188, 130, 131, 132, 155, 156, 176, 185, 186,
145, 147, 170 };
private static ChineseMobileNumberGenerator instance = new ChineseMobileNumberGenerator();
private ChineseMobileNumberGenerator() {
}
public static ChineseMobileNumberGenerator getInstance() {
return instance;
}
@Override
public String generate() {
return genMobilePre() + StringUtils
.leftPad("" + RandomUtils.nextInt(0, 99999999 + 1), 8, "0");
}
/**
* 生成假的手机号,以19开头
*/
public String generateFake() {
return "19" + StringUtils
.leftPad("" + RandomUtils.nextInt(0, 999999999 + 1), 9, "0");
}
private static String genMobilePre() {
return "" + MOBILE_PREFIX[RandomUtils.nextInt(0, MOBILE_PREFIX.length)];
}
}
| 1,274 | Java | .java | binarywang/java-testdata-generator | 584 | 276 | 0 | 2016-01-21T05:45:44Z | 2023-06-21T06:48:09Z |
ChineseIDCardNumberGenerator.java | /FileExtraction/Java_unseen/binarywang_java-testdata-generator/src/main/java/cn/binarywang/tools/generator/ChineseIDCardNumberGenerator.java | package cn.binarywang.tools.generator;
import cn.binarywang.tools.generator.base.GenericGenerator;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
/**
* 身份证号码
* 1、号码的结构
* 公民身份号码是特征组合码,由十七位数字本体码和一位校验码组成。排列顺序从左至右依次为:六位数字地址码,
* 八位数字出生日期码,三位数字顺序码和一位数字校验码。
* 2、地址码(前六位数)
* 表示编码对象常住户口所在县(市、旗、区)的行政区划代码,按GB/T2260的规定执行。
* 3、出生日期码(第七位至十四位)
* 表示编码对象出生的年、月、日,按GB/T7408的规定执行,年、月、日代码之间不用分隔符。
* 4、顺序码(第十五位至十七位)
* 表示在同一地址码所标识的区域范围内,对同年、同月、同日出生的人编定的顺序号,
* 顺序码的奇数分配给男性,偶数分配给女性。
* 5、校验码(第十八位数)
* (1)十七位数字本体码加权求和公式 S = Sum(Ai * Wi), i = 0, ... , 16 ,先对前17位数字的权求和
* Ai:表示第i位置上的身份证号码数字值 Wi:表示第i位置上的加权因子 Wi: 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4
* 2 (2)计算模 Y = mod(S, 11) (3)通过模得到对应的校验码 Y: 0 1 2 3 4 5 6 7 8 9 10 校验码: 1 0
* X 9 8 7 6 5 4 3 2
*/
public class ChineseIDCardNumberGenerator extends GenericGenerator {
private static GenericGenerator instance = new ChineseIDCardNumberGenerator();
private ChineseIDCardNumberGenerator() {
}
public static GenericGenerator getInstance() {
return instance;
}
/**
* 生成签发机关:XXX公安局/XX区分局
* Authority
*/
public static String generateIssueOrg() {
return ChineseAreaList.cityNameList
.get(RandomUtils.nextInt(0, ChineseAreaList.cityNameList.size()))
+ "公安局某某分局";
}
/**
* 生成有效期限:20150906-20350906
* Valid Through
*/
public static String generateValidPeriod() {
DateTime beginDate =new DateTime(randomDate()) ;
String formater = "yyyyMMdd";
DateTime endDate = beginDate.withYear(beginDate.getYear() + 20);
return beginDate.toString(formater) + "-" + endDate.toString(formater);
}
@Override
public String generate() {
Map<String, String> code = getAreaCode();
String areaCode = code.keySet().toArray(new String[0])[RandomUtils
.nextInt(0, code.size())]
+ StringUtils.leftPad((RandomUtils.nextInt(0, 9998) + 1) + "", 4,
"0");
String birthday = new SimpleDateFormat("yyyyMMdd").format(randomDate());
String randomCode = String.valueOf(1000 + RandomUtils.nextInt(0, 999))
.substring(1);
String pre = areaCode + birthday + randomCode;
String verifyCode = getVerifyCode(pre);
String result = pre + verifyCode;
return result;
}
static Date randomDate() {
Calendar calendar = Calendar.getInstance();
calendar.set(1970, 1, 1);
long earlierDate = calendar.getTime().getTime();
calendar.set(2000, 1, 1);
long laterDate = calendar.getTime().getTime();
long chosenDate = RandomUtils.nextLong(earlierDate, laterDate);
return new Date(chosenDate);
}
private static String getVerifyCode(String cardId) {
String[] ValCodeArr = { "1", "0", "X", "9", "8", "7", "6", "5", "4",
"3", "2" };
String[] Wi = { "7", "9", "10", "5", "8", "4", "2", "1", "6", "3", "7",
"9", "10", "5", "8", "4", "2" };
int tmp = 0;
for (int i = 0; i < Wi.length; i++) {
tmp += Integer.parseInt(String.valueOf(cardId.charAt(i)))
* Integer.parseInt(Wi[i]);
}
int modValue = tmp % 11;
String strVerifyCode = ValCodeArr[modValue];
return strVerifyCode;
}
private static Map<String, String> getAreaCode() {
final Map<String, String> map = Maps.newHashMap();
map.put("11", "北京");
map.put("12", "天津");
map.put("13", "河北");
map.put("14", "山西");
map.put("15", "内蒙古");
map.put("21", "辽宁");
map.put("22", "吉林");
map.put("23", "黑龙江");
map.put("31", "上海");
map.put("32", "江苏");
map.put("33", "浙江");
map.put("34", "安徽");
map.put("35", "福建");
map.put("36", "江西");
map.put("37", "山东");
map.put("41", "河南");
map.put("42", "湖北");
map.put("43", "湖南");
map.put("44", "广东");
map.put("45", "广西");
map.put("46", "海南");
map.put("50", "重庆");
map.put("51", "四川");
map.put("52", "贵州");
map.put("53", "云南");
map.put("54", "西藏");
map.put("61", "陕西");
map.put("62", "甘肃");
map.put("63", "青海");
map.put("64", "宁夏");
map.put("65", "新疆");
map.put("71", "台湾");
map.put("81", "香港");
map.put("82", "澳门");
map.put("91", "国外");
return map;
}
}
| 5,566 | Java | .java | binarywang/java-testdata-generator | 584 | 276 | 0 | 2016-01-21T05:45:44Z | 2023-06-21T06:48:09Z |
EnglishNameGenerator.java | /FileExtraction/Java_unseen/binarywang_java-testdata-generator/src/main/java/cn/binarywang/tools/generator/EnglishNameGenerator.java | package cn.binarywang.tools.generator;
import cn.binarywang.tools.generator.base.GenericGenerator;
public class EnglishNameGenerator extends GenericGenerator {
static String[] FIRST_NAMES = {
"Aaron",
"Abel",
"Abraham",
"Adam",
"Adrian",
"Aidan",
"Alva",
"Alex",
"Alexander",
"Alan",
"Albert",
"Alfred",
"Andrew",
"Andy",
"Angus",
"Anthony",
"Apollo",
"Arnold",
"Arthur",
"August",
"Austin",
"Ben",
"Benjamin",
"Bert",
"Benson",
"Bill",
"Billy",
"Blake",
"Bob",
"Bobby",
"Brad",
"Brandon",
"Brant",
"Brent",
"Brian",
"Brown",
"Bruce",
"Caleb",
"Cameron",
"Carl",
"Carlos",
"Cary",
"Caspar",
"Cecil",
"Charles",
"Cheney",
"Chris",
"Christian",
"Christopher",
"Clark",
"Cliff",
"Cody",
"Cole",
"Colin",
"Cosmo",
"Daniel",
"Denny",
"Darwin",
"David",
"Dennis",
"Derek",
"Dick",
"Donald",
"Douglas",
"Duke",
"Dylan",
"Eddie",
"Edgar",
"Edison",
"Edmund",
"Edward",
"Edwin",
"Elijah",
"Elliott",
"Elvis",
"Eric",
"Ethan",
"Eugene",
"Evan",
"Enterprise",
"Ford",
"Francis",
"Frank",
"Franklin",
"Fred",
"Gabriel",
"Gaby",
"Garfield",
"Gary",
"Gavin",
"Geoffrey",
"George",
"Gino",
"Glen",
"Glendon",
"Hank",
"Hardy",
"Harrison",
"Harry",
"Hayden",
"Henry",
"Hilton",
"Hugo",
"Hunk",
"Howard",
"Henry",
"Ian",
"Ignativs",
"Ivan",
"Isaac",
"Isaiah",
"Jack",
"Jackson",
"Jacob",
"James",
"Jason",
"Jay",
"Jeffery",
"Jerome",
"Jerry",
"Jesse",
"Jim",
"Jimmy",
"Joe",
"John",
"Johnny",
"Jonathan",
"Jordan",
"Jose",
"Joshua",
"Justin",
"Keith",
"Ken",
"Kennedy",
"Kenneth",
"Kenny",
"Kevin",
"Kyle",
"Lance",
"Larry",
"Laurent",
"Lawrence",
"Leander",
"Lee",
"Leo",
"Leonard",
"Leopold",
"Leslie",
"Loren",
"Lori",
"Lorin",
"Louis",
"Luke",
"Marcus",
"Marcy",
"Mark",
"Marks",
"Mars",
"Marshal",
"Martin",
"Marvin",
"Mason",
"Matthew",
"Max",
"Michael",
"Mickey",
"Mike",
"Nathan",
"Nathaniel",
"Neil",
"Nelson",
"Nicholas",
"Nick",
"Noah",
"Norman",
"Oliver",
"Oscar",
"Owen",
"Patrick",
"Paul",
"Peter",
"Philip",
"Phoebe",
"Quentin",
"Randall",
"Randolph",
"Randy",
"Ray",
"Raymond",
"Reed",
"Rex",
"Richard",
"Richie",
"Riley",
"Robert",
"Robin",
"Robinson",
"Rock",
"Roger",
"Ronald",
"Rowan",
"Roy",
"Ryan",
"Sam",
"Sammy",
"Samuel",
"Scott",
"Sean",
"Shawn",
"Sidney",
"Simon",
"Solomon",
"Spark",
"Spencer",
"Spike",
"Stanley",
"Steve",
"Steven",
"Stewart",
"Stuart",
"Terence",
"Terry",
"Ted",
"Thomas",
"Tim",
"Timothy",
"Todd",
"Tommy",
"Tom",
"Thomas",
"Tony",
"Tyler",
"Ultraman",
"Ulysses",
"Van",
"Vern",
"Vernon",
"Victor",
"Vincent",
"Warner",
"Warren",
"Wayne",
"Wesley",
"William",
"Willy",
"Zack",
"Zachary",
"Abigail",
"Abby",
"Ada",
"Adelaide",
"Adeline",
"Alexandra",
"Ailsa",
"Aimee",
"Alexis",
"Alice",
"Alicia",
"Alina",
"Allison",
"Alyssa",
"Amanda",
"Amy",
"Amber",
"Anastasia",
"Andrea",
"Angel",
"Angela",
"Angelia",
"Angelina",
"Ann",
"Anna",
"Anne",
"Annie",
"Anita",
"Ariel",
"April",
"Ashley",
"Audrey",
"Aviva",
"Barbara",
"Barbie",
"Beata",
"Beatrice",
"Becky",
"Bella",
"Bess",
"Bette",
"Betty",
"Blanche",
"Bonnie",
"Brenda",
"Brianna",
"Britney",
"Brittany",
"Camille",
"Candice",
"Candy",
"Carina",
"Carmen",
"Carol",
"Caroline",
"Carry",
"Carrie",
"Cassandra",
"Cassie",
"Catherine",
"Cathy",
"Chelsea",
"Charlene",
"Charlotte",
"Cherry",
"Cheryl",
"Chloe",
"Chris",
"Christina",
"Christine",
"Christy",
"Cindy",
"Claire",
"Claudia",
"Clement",
"Cloris",
"Connie",
"Constance",
"Cora",
"Corrine",
"Crystal",
"Daisy",
"Daphne",
"Darcy",
"Dave",
"Debbie",
"Deborah",
"Debra",
"Demi",
"Diana",
"Dolores",
"Donna",
"Dora",
"Doris",
"Edith",
"Editha",
"Elaine",
"Eleanor",
"Elizabeth",
"Ella",
"Ellen",
"Ellie",
"Emerald",
"Emily",
"Emma",
"Enid",
"Elsa",
"Erica",
"Estelle",
"Esther",
"Eudora",
"Eva",
"Eve",
"Evelyn",
"Fannie",
"Fay",
"Fiona",
"Flora",
"Florence",
"Frances",
"Frederica",
"Frieda",
"Flta",
"Gina",
"Gillian",
"Gladys",
"Gloria",
"Grace",
"Grace",
"Greta",
"Gwendolyn",
"Hannah",
"Haley",
"Hebe",
"Helena",
"Hellen",
"Henna",
"Heidi",
"Hillary",
"Ingrid",
"Isabella",
"Ishara",
"Irene",
"Iris",
"Ivy",
"Jacqueline",
"Jade",
"Jamie",
"Jane",
"Janet",
"Jasmine",
"Jean",
"Jenna",
"Jennifer",
"Jenny",
"Jessica",
"Jessie",
"Jill",
"Joan",
"Joanna",
"Jocelyn",
"Joliet",
"Josephine",
"Josie",
"Joy",
"Joyce",
"Judith",
"Judy",
"Julia",
"Juliana",
"Julie",
"June",
"Karen",
"Karida",
"Katherine",
"Kate",
"Kathy",
"Katie",
"Katrina",
"Kay",
"Kayla",
"Kelly",
"Kelsey",
"Kimberly",
"Kitty",
"Lareina",
"Lassie",
"Laura",
"Lauren",
"Lena",
"Lydia",
"Lillian",
"Lily",
"Linda",
"lindsay",
"Lisa",
"Liz",
"Lora",
"Lorraine",
"Louisa",
"Louise",
"Lucia",
"Lucy",
"Lucine",
"Lulu",
"Lydia",
"Lynn",
"Mabel",
"Madeline",
"Maggie",
"Mamie",
"Manda",
"Mandy",
"Margaret",
"Mariah",
"Marilyn",
"Martha",
"Mavis",
"Mary",
"Matilda",
"Maureen",
"Mavis",
"Maxine",
"May",
"Mayme",
"Megan",
"Melinda",
"Melissa",
"Melody",
"Mercedes",
"Meredith",
"Mia",
"Michelle",
"Milly",
"Miranda",
"Miriam",
"Miya",
"Molly",
"Monica",
"Morgan",
"Nancy",
"Natalie",
"Natasha",
"Nicole",
"Nikita",
"Nina",
"Nora",
"Norma",
"Nydia",
"Octavia",
"Olina",
"Olivia",
"Ophelia",
"Oprah",
"Pamela",
"Patricia",
"Patty",
"Paula",
"Pauline",
"Pearl",
"Peggy",
"Philomena",
"Phoebe",
"Phyllis",
"Polly",
"Priscilla",
"Quentina",
"Rachel",
"Rebecca",
"Regina",
"Rita",
"Rose",
"Roxanne",
"Ruth",
"Sabrina",
"Sally",
"Sandra",
"Samantha",
"Sami",
"Sandra",
"Sandy",
"Sarah",
"Savannah",
"Scarlett",
"Selma",
"Selina",
"Serena",
"Sharon",
"Sheila",
"Shelley",
"Sherry",
"Shirley",
"Sierra",
"Silvia",
"Sonia",
"Sophia",
"Stacy",
"Stella",
"Stephanie",
"Sue",
"Sunny",
"Susan",
"Tamara",
"Tammy",
"Tanya",
"Tasha",
"Teresa",
"Tess",
"Tiffany",
"Tina",
"Tonya",
"Tracy",
"Ursula",
"Vanessa",
"Venus",
"Vera",
"Vicky",
"Victoria",
"Violet",
"Virginia",
"Vita",
"Vivian"
};
private static EnglishNameGenerator instance = new EnglishNameGenerator();
private EnglishNameGenerator() {
}
public static EnglishNameGenerator getInstance() {
return instance;
}
@Override
public String generate() {
//英文名
return genFirstName();
}
private String genFirstName() {
return FIRST_NAMES[getRandomInstance().nextInt(FIRST_NAMES.length)];
}
}
| 10,665 | Java | .java | binarywang/java-testdata-generator | 584 | 276 | 0 | 2016-01-21T05:45:44Z | 2023-06-21T06:48:09Z |
ChineseNameGenerator.java | /FileExtraction/Java_unseen/binarywang_java-testdata-generator/src/main/java/cn/binarywang/tools/generator/ChineseNameGenerator.java | package cn.binarywang.tools.generator;
import cn.binarywang.tools.generator.util.ChineseCharUtils;
import cn.binarywang.tools.generator.base.GenericGenerator;
public class ChineseNameGenerator extends GenericGenerator {
private static final String[] FIRST_NAMES = new String[] { "李", "王", "张",
"刘", "陈", "杨", "黄", "赵", "周", "吴", "徐", "孙", "朱", "马", "胡", "郭", "林",
"何", "高", "梁", "郑", "罗", "宋", "谢", "唐", "韩", "曹", "许", "邓", "萧", "冯",
"曾", "程", "蔡", "彭", "潘", "袁", "於", "董", "余", "苏", "叶", "吕", "魏", "蒋",
"田", "杜", "丁", "沈", "姜", "范", "江", "傅", "钟", "卢", "汪", "戴", "崔", "任",
"陆", "廖", "姚", "方", "金", "邱", "夏", "谭", "韦", "贾", "邹", "石", "熊", "孟",
"秦", "阎", "薛", "侯", "雷", "白", "龙", "段", "郝", "孔", "邵", "史", "毛", "常",
"万", "顾", "赖", "武", "康", "贺", "严", "尹", "钱", "施", "牛", "洪", "龚", "东方",
"夏侯", "诸葛", "尉迟", "皇甫", "宇文", "鲜于", "西门", "司马", "独孤", "公孙", "慕容", "轩辕",
"左丘", "欧阳", "皇甫", "上官", "闾丘", "令狐" };
/*
* "欧阳",
* "太史", "端木", "上官", "司马", "东方", "独孤", "南宫", "万俟", "闻人", "夏侯", "诸葛", "尉迟",
* "公羊", "赫连", "澹台", "皇甫", "宗政", "濮阳", "公冶", "太叔", "申屠", "公孙", "慕容", "仲孙",
* "钟离", "长孙", "宇文", "司徒", "鲜于", "司空", "闾丘", "子车", "亓官", "司寇", "巫马", "公西",
* "颛孙", "壤驷", "公良", "漆雕", "乐正", "宰父", "谷梁", "拓跋", "夹谷", "轩辕", "令狐", "段干",
* "百里", "呼延", "东郭", "南门", "羊舌", "微生", "公户", "公玉", "公仪", "梁丘", "公仲", "公上",
* "公门", "公山", "公坚", "左丘", "公伯", "西门", "公祖", "第五", "公乘", "贯丘", "公皙", "南荣",
* "东里", "东宫", "仲长", "子书", "子桑", "即墨", "达奚", "褚师", "吴铭"
*/
private static ChineseNameGenerator instance = new ChineseNameGenerator();
private ChineseNameGenerator() {
}
public static ChineseNameGenerator getInstance() {
return instance;
}
@Override
public String generate() {
//姓名暂时还是两到三字,比较常见些
return genFirstName()
+ ChineseCharUtils.genRandomLengthChineseChars(1, 2);
}
private String genFirstName() {
return FIRST_NAMES[getRandomInstance().nextInt(FIRST_NAMES.length)];
}
/**
* 生成带有生僻名字部分的姓名
*/
public String generateOdd() {
return genFirstName() + ChineseCharUtils.getOneOddChar();
}
}
| 2,848 | Java | .java | binarywang/java-testdata-generator | 584 | 276 | 0 | 2016-01-21T05:45:44Z | 2023-06-21T06:48:09Z |
InsertSQLGenerator.java | /FileExtraction/Java_unseen/binarywang_java-testdata-generator/src/main/java/cn/binarywang/tools/generator/InsertSQLGenerator.java | package cn.binarywang.tools.generator;
import static com.google.common.collect.Collections2.transform;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;
import com.google.common.base.CaseFormat;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
/**
* @author Binary Wang
*/
public class InsertSQLGenerator {
private static final Joiner COMMA_JOINER = Joiner.on(", ");
private Connection con;
private String tableName;
public InsertSQLGenerator(String url, String username, String password,
String tableName) {
try {
this.con = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
}
this.tableName = tableName;
}
public String generateSQL() {
List<String> columns = getColumns();
return String.format("insert into %s(%s) values(%s)", this.tableName,
COMMA_JOINER.join(columns),
COMMA_JOINER.join(Collections.nCopies(columns.size(), "?")));
}
public String generateParams() {
return COMMA_JOINER
.join(transform(getColumns(), new Function<String, String>() {
@Override
public String apply(String input) {
return "abc.get" + CaseFormat.LOWER_UNDERSCORE
.to(CaseFormat.UPPER_CAMEL, input) + "()";
}
}));
}
private List<String> getColumns() {
List<String> columns = Lists.newArrayList();
try (PreparedStatement ps = this.con
.prepareStatement("select * from " + this.tableName);
ResultSet rs = ps.executeQuery();) {
ResultSetMetaData rsm = rs.getMetaData();
for (int i = 1; i <= rsm.getColumnCount(); i++) {
String columnName = rsm.getColumnName(i);
System.out.print("Name: " + columnName);
System.out.println(", Type : " + rsm.getColumnClassName(i));
columns.add(columnName);
}
} catch (SQLException e) {
e.printStackTrace();
return null;
}
return columns;
}
public void close() {
try {
this.con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
| 2,603 | Java | .java | binarywang/java-testdata-generator | 584 | 276 | 0 | 2016-01-21T05:45:44Z | 2023-06-21T06:48:09Z |
EmailAddressGenerator.java | /FileExtraction/Java_unseen/binarywang_java-testdata-generator/src/main/java/cn/binarywang/tools/generator/EmailAddressGenerator.java | package cn.binarywang.tools.generator;
import org.apache.commons.lang3.RandomStringUtils;
import cn.binarywang.tools.generator.base.GenericGenerator;
public class EmailAddressGenerator extends GenericGenerator {
private static GenericGenerator instance = new EmailAddressGenerator();
private EmailAddressGenerator() {
}
public static GenericGenerator getInstance() {
return instance;
}
@Override
public String generate() {
StringBuilder result = new StringBuilder();
result.append(RandomStringUtils.randomAlphanumeric(10));
result.append("@");
result.append(RandomStringUtils.randomAlphanumeric(5));
result.append(".");
result.append(RandomStringUtils.randomAlphanumeric(3));
return result.toString().toLowerCase();
}
}
| 823 | Java | .java | binarywang/java-testdata-generator | 584 | 276 | 0 | 2016-01-21T05:45:44Z | 2023-06-21T06:48:09Z |
ChineseAddressGenerator.java | /FileExtraction/Java_unseen/binarywang_java-testdata-generator/src/main/java/cn/binarywang/tools/generator/ChineseAddressGenerator.java | package cn.binarywang.tools.generator;
import org.apache.commons.lang3.RandomUtils;
import cn.binarywang.tools.generator.util.ChineseCharUtils;
import cn.binarywang.tools.generator.base.GenericGenerator;
public class ChineseAddressGenerator extends GenericGenerator {
private static GenericGenerator instance = new ChineseAddressGenerator();
private ChineseAddressGenerator() {
}
public static GenericGenerator getInstance() {
return instance;
}
@Override
public String generate() {
StringBuilder result = new StringBuilder(genProvinceAndCity());
result.append(ChineseCharUtils.genRandomLengthChineseChars(2, 3) + "路");
result.append(RandomUtils.nextInt(1, 8000) + "号");
result
.append(ChineseCharUtils.genRandomLengthChineseChars(2, 3) + "小区");
result.append(RandomUtils.nextInt(1, 20) + "单元");
result.append(RandomUtils.nextInt(101, 2500) + "室");
return result.toString();
}
private static String genProvinceAndCity() {
return ChineseAreaList.provinceCityList.get(
RandomUtils.nextInt(0, ChineseAreaList.provinceCityList.size()));
}
}
| 1,195 | Java | .java | binarywang/java-testdata-generator | 584 | 276 | 0 | 2016-01-21T05:45:44Z | 2023-06-21T06:48:09Z |
CSVFileGenerator.java | /FileExtraction/Java_unseen/binarywang_java-testdata-generator/src/main/java/cn/binarywang/tools/generator/CSVFileGenerator.java | package cn.binarywang.tools.generator;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
public class CSVFileGenerator {
private static final String LINE_SEPERATOR = System
.getProperty("line.separator");
private final static Charset charset = Charset.forName("utf-8");
public static void generate(List<HashMap<String, Object>> data,
String[] columns,
String fileName) {
File file = new File(fileName);
if (file.exists()) {
file.delete();
}
for (Map<String, Object> objects : data) {
List<String> result = Lists.newArrayList();
for (String column : columns) {
if (objects.get(column) != null) {
result.add(objects.get(column).toString());
} else {
result.add("");
}
}
String lineData = Joiner.on(",").skipNulls().join(result);
try {
Files.append(lineData + LINE_SEPERATOR, file, charset);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
| 1,372 | Java | .java | binarywang/java-testdata-generator | 584 | 276 | 0 | 2016-01-21T05:45:44Z | 2023-06-21T06:48:09Z |
GenericGenerator.java | /FileExtraction/Java_unseen/binarywang_java-testdata-generator/src/main/java/cn/binarywang/tools/generator/base/GenericGenerator.java | package cn.binarywang.tools.generator.base;
import java.util.Date;
import java.util.Random;
public abstract class GenericGenerator {
public abstract String generate();
private static Random random = null;
protected Random getRandomInstance() {
if (random == null) {
random = new Random(new Date().getTime());
}
return random;
}
}
| 387 | Java | .java | binarywang/java-testdata-generator | 584 | 276 | 0 | 2016-01-21T05:45:44Z | 2023-06-21T06:48:09Z |
ChineseCharUtils.java | /FileExtraction/Java_unseen/binarywang_java-testdata-generator/src/main/java/cn/binarywang/tools/generator/util/ChineseCharUtils.java | package cn.binarywang.tools.generator.util;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Random;
public class ChineseCharUtils {
public static String ODD_CHINESE_CHARS = "厷厸厹厺厼厽厾叀叁参叄叅叆叇亝収叏叐叒叓叕叚叜叝叞"
+ "叠叧叨叭叱叴叵叺叻叼叽叾卟叿吀吁吂吅吆吇吋吒吔吖吘吙吚吜吡吢吣吤吥吧吩吪吭吮吰吱吲呐吷吺吽呁呃呄呅呇呉"
+ "呋呋呌呍呎呏呐呒呓呔呕呗呙呚呛呜呝呞呟呠呡呢呣呤呥呦呧周呩呪呫呬呭呮呯呰呱呲呴呶呵呷呸呹呺呻呾呿咀咁咂"
+ "咃咄咅咇咈咉咊咋咍咎咐咑咓咔咕咖咗咘咙咚咛咜咝咞咟咠咡咢咣咤咥咦咧咨咩咪咫咬咭咮咯咰咲咳咴咵咶啕咹咺咻"
+ "呙咽咾咿哂哃哅哆哇哈哊哋哌哎哏哐哑哒哓哔哕哖哗哘哙哚哛哜哝哞哟哠咔哣哤哦哧哩哪哫哬哯哰唝哵哶哷哸哹哻哼"
+ "哽哾哿唀唁唂唃呗唅唆唈唉唊唋唌唍唎唏唑唒唓唔唣唖唗唘唙吣唛唜唝唞唟唠唡唢唣唤唥唦唧唨唩唪唫唬唭唯唰唲唳"
+ "唴唵唶唷念唹唺唻唼唽唾唿啀啁啃啄啅啇啈啉啋啌啍啎问啐啑啒启啔啕啖啖啘啙啚啛啜啝哑启啠啡唡衔啥啦啧啨啩啪"
+ "啫啬啭啮啯啰啱啲啳啴啵啶啷啹啺啻啼啽啾啿喀喁喂喃善喅喆喇喈喉喊喋喌喍喎喏喐喑喒喓喔喕喖喗喙喛喞喟喠喡喢"
+ "喣喤喥喦喨喩喯喭喯喰喱哟喳喴喵営喷喸喹喺喼喽喾喿嗀嗁嗂嗃嗄嗅呛啬嗈嗉唝嗋嗌嗍吗嗏嗐嗑嗒嗓嗕嗖嗗嗘嗙呜嗛"
+ "嗜嗝嗞嗟嗠嗡嗢嗧嗨唢嗪嗫嗬嗭嗮嗰嗱嗲嗳嗴嗵哔嗷嗸嗹嗺嗻嗼嗽嗾嗿嘀嘁嘂嘃嘄嘅嘅嘇嘈嘉嘊嘋嘌喽嘎嘏嘐嘑嘒嘓"
+ "呕嘕啧嘘嘙嘚嘛唛嘝嘞嘞嘟嘠嘡嘢嘣嘤嘥嘦嘧嘨哗嘪嘫嘬嘭唠啸囍嘴哓嘶嘷呒嘹嘺嘻嘼啴嘾嘿噀噂噃噄咴噆噇噈噉噊"
+ "噋噌噍噎噏噐噑噒嘘噔噕噖噗噘噙噚噛噜咝噞噟哒噡噢噣噤哝哕噧噩噪噫噬噭噮嗳噰噱哙噳喷噵噶噷吨噺噻噼噽噾噿"
+ "咛嚁嚂嚃嚄嚅嚆吓嚈嚉嚊嚋哜嚍嚎嚏尝嚑嚒嚓嚔噜嚖嚗嚘啮嚚嚛嚜嚝嚞嚟嚠嚡嚢嚣嚤呖嚧咙嚩咙嚧嚪嚫嚬嚭嚯嚰嚱亸"
+ "喾嚵嘤嚷嚸嚹嚺嚻嚼嚽嚾嚿啭嗫嚣囃囄冁囆囇呓囊囋囍囎囏囐嘱囒啮囔囕囖囘囙囜囝回囟囡団囤囥囦囧囨囩囱囫囬囮"
+ "囯困囱囲図囵囶囷囸囹囻囼图囿圀圁圂圂圃圄圅圆囵圈圉圊国圌圎圏圎圐圑园圆圔圕图圗团圙圚圛圜圝圞凹凸圠圡圢"
+ "圤圥圦圧圩圪圫圬圮圯地圱圲圳圴圵圶圷圸圹圻圼埢鴪址坁坂坃坄坅坆坈坉坊坋坌坍坒坓坔坕坖坘坙坜坞坢坣坥坧坨"
+ "坩坪坫坬坭坮坯垧坱坲坳坴坶坸坹坺坻坼坽坾坿垀垁垃垅垆垇垈垉垊垌垍垎垏垐垑垓垔垕垖垗垘垙垚垛垜垝垞垟垠垡"
+ "垤垥垧垨垩垪垫垬垭垮垯垰垱垲垲垳垴埯垶垷垸垹垺垺垻垼垽垾垽垿埀埁埂埃埄埅埆埇埈埉埊埋埌埍城埏埐埑埒埓埔"
+ "埕埖埗埘埙埚埛野埝埞域埠垭埢埣埤埥埦埧埨埩埪埫埬埭埮埯埰埱埲埳埴埵埶执埸培基埻崎埽埾埿堀堁堃堄坚堆堇堈"
+ "堉垩堋堌堍堎堏堐堑堒堓堔堕垴堗堘堙堚堛堜埚堞堟堠堢堣堥堦堧堨堩堫堬堭堮尧堰报堲堳场堶堷堸堹堺堻堼堽堾堼"
+ "堾碱塀塁塂塃塄塅塇塆塈塉块茔塌塍塎垲塐塑埘塓塕塖涂塘塙冢塛塜塝塟塠墘塣墘塥塦塧塨塩塪填塬塭塮塯塰塱塲塳"
+ "塴尘塶塷塸堑塺塻塼塽塾塿墀墁墂墄墅墆墇墈墉垫墋墌墍墎墏墐墒墒墓墔墕墖墘墖墚墛坠墝增墠墡墢墣墤墥墦墧墨墩"
+ "墪樽墬墭堕墯墰墱墲坟墴墵垯墷墸墹墺墙墼墽垦墿壀壁壂壃壄壅壆坛壈壉壊垱壌壍埙壏壐壑壒压壔壕壖壗垒圹垆壛壜"
+ "壝垄壠壡坜壣壤壥壦壧壨坝塆圭壭壱売壳壴壵壶壷壸壶壻壸壾壿夀夁夃夅夆夈変夊夌夎夐夑夒夓夔夗夘夛夝夞夡夣夤"
+ "夥夦夨夨夬夯夰夲夳夵夶夹夻夼夽夹夿奀奁奃奂奄奃奅奆奊奌奍奏奂奒奓奘奙奚奛奜奝奞奟奡奣奤奦奨奁奫妸奯奰奱"
+ "奲奵奺奻奼奾奿妀妁妅妉妊妋妌妍妎妏妐妑妔妕妗妘妚妛妜妟妠妡妢妤妦妧妩妫妭妮妯妰妱妲妴妵妶妷妸妺妼妽妿姀"
+ "姁姂姃姄姅姆姇姈姉姊姌姗姎姏姒姕姖姘姙姛姝姞姟姠姡姢姣姤姥奸姧姨姩姫姬姭姮姯姰姱姲姳姴姵姶姷姸姹姺姻姼"
+ "姽姾娀威娂娅娆娈娉娊娋娌娍娎娏娐娑娒娓娔娕娖娗娙娚娱娜娝娞娟娠娡娢娣娤娥娦娧娨娩娪娫娬娭娮娯娰娱娲娳娴"
+ "娵娷娸娹娺娻娽娾娿婀娄婂婃婄婅婇婈婋婌婍婎婏婐婑婒婓婔婕婖婗婘婙婛婜婝婞婟婠婡婢婣婤婥妇婧婨婩婪婫娅婮"
+ "婯婰婱婲婳婵婷婸婹婺婻婼婽婾婿媀媁媂媄媃媅媪媈媉媊媋媌媍媎媏媐媑媒媓媔媕媖媗媘媙媚媛媜媝媜媞媟媠媡媢媣"
+ "媤媥媦媨媩媪媫媬媭妫媰媱媲媳媴媵媶媷媸媹媺媻媪媾嫀嫃嫄嫅嫆嫇嫈嫉嫊袅嫌嫍嫎嫏嫐嫑嫒嫓嫔嫕嫖妪嫘嫙嫚嫛嫜"
+ "嫝嫞嫟嫠嫡嫢嫣嫤嫥嫦嫧嫨嫧嫩嫪嫫嫬嫭嫮嫯嫰嫱嫲嫳嫴嫳妩嫶嫷嫸嫹嫺娴嫼嫽嫾婳妫嬁嬂嬃嬄嬅嬆嬇娆嬉嬊娇嬍嬎"
+ "嬏嬐嬑嬒嬓嬔嬕嬖嬗嬘嫱嬚嬛嬜嬞嬟嬠嫒嬢嬣嬥嬦嬧嬨嬩嫔嬫嬬奶嬬嬮嬯婴嬱嬲嬳嬴嬵嬶嬷婶嬹嬺嬻嬼嬽嬾嬿孀孁孂"
+ "娘孄孅孆孇孆孈孉孊娈孋孊孍孎孏嫫婿媚孑孒孓孖孚孛孜孞孠孡孢孥学孧孨孪孙孬孭孮孯孰孱孲孳孴孵孶孷孹孻孼孽"
+ "孾宄宆宊宍宎宐宑宒宓宔宖実宥宧宨宩宬宭宯宱宲宷宸宺宻宼寀寁寃寈寉寊寋寍寎寏寔寕寖寗寘寙寚寜寝寠寡寣寥寪"
+ "寭寮寯寰寱寲寳寴寷寽対尀専尃尅尌尐尒尕尗尛尜尞尟尠尣尢尥尦尨尩尪尫尬尭尮尯尰尲尳尴尵尶尾屃届屇屈屎屐屑"
+ "屒屓屔屖屗屘屙屚屛屉扉屟屡屣履屦屧屦屩屪屫属敳屮屰屲屳屴屵屶屷屸屹屺屻屼屽屾屿岃岄岅岆岇岈岉岊岋岌岍岎"
+ "岏岐岑岒岓岔岕岖岘岙岚岜岝岞岟岠岗岢岣岤岥岦岧岨岪岫岬岮岯岰岲岴岵岶岷岹岺岻岼岽岾岿峀峁峂峃峄峅峆峇峈"
+ "峉峊峋峌峍峎峏峐峑峒峓崓峖峗峘峚峙峛峜峝峞峟峠峢峣峤峥峦峧峨峩峪峬峫峭峮峯峱峲峳岘峵峷峸峹峺峼峾峿崀崁"
+ "崂崃崄崅崆崇崈崉崊崋崌崃崎崏崐崒崓崔崕崖崘崚崛崜崝崞崟岽崡峥崣崤崥崦崧崨崩崪崫崬崭崮崯崰崱崲嵛崴崵崶崷"
+ "崸崹崺崻崼崽崾崿嵀嵁嵂嵃嵄嵅嵆嵇嵈嵉嵊嵋嵌嵍嵎嵏岚嵑岩嵓嵔嵕嵖嵗嵘嵙嵚嵛嵜嵝嵞嵟嵠嵡嵢嵣嵤嵥嵦嵧嵨嵩嵪"
+ "嵫嵬嵭嵮嵯嵰嵱嵲嵳嵴嵵嵶嵷嵸嵹嵺嵻嵼嵽嵾嵿嶀嵝嶂嶃崭嶅嶆岖嶈嶉嶊嶋嶌嶍嶎嶏嶐嶑嶒嶓嵚嶕嶖嶘嶙嶚嶛嶜嶝嶞"
+ "嶟峤嶡峣嶣嶤嶥嶦峄峃嶩嶪嶫嶬嶭崄嶯嶰嶱嶲嶳岙嶵嶶嶷嵘嶹岭嶻屿岳帋巀巁巂巃巄巅巆巇巈巉巊岿巌巍巎巏巐巑峦"
+ "巓巅巕岩巗巘巙巚巛巜巠巡巢巣巤匘巪巬巭巯巵巶巸卺巺巼巽巿帀币帄帇帉帊帋帍帎帏帑帒帓帔帗帙帚帞帟帠帡帢帣"
+ "帤帨帩帪帬帯帰帱帲帴帵帷帹帺帻帼帽帾帿帧幁幂帏幄幅幆幇幈幉幊幋幌幍幎幏幐幑幒幓幖幙幚幛幜幝幞帜幠幡幢幤"
+ "幥幦幧幨幩幪幭幮幯幰幱幷幺吆玄幼兹滋庀庁仄広庅庇庈庉庋庌庍庎庑庖庘庛庝庞庠庡庢庣庤庥庨庩庪库庬庮庯庰庱"
+ "庲庳庴庵庹庺庻庼庽庿廀厕廃厩廅廆廇廋廌廍庼廏廐廑廒廔廕廖廗廘廙廛廜廞庑廤廥廦廧廨廭廮廯廰痈廲廵廸廹廻廼"
+ "廽廿弁弅弆弇弉弋弌弍弎弐弑弖弙弚弜弝弞弡弢弣弤弨弩弪弫弬弭弮弰弲弪弴弶弸弻弼弽弿彀彁彂彃彄彅彇彉彋弥彍"
+ "彏彑彔彖彗彘彚彛彜彝彞彟彡彣彧彨彭彮彯彲澎彳彴彵彶彷彸役彺彻彽彾佛徂徃徆徇徉后徍徎徏径徒従徔徕徖徙徚徛"
+ "徜徝从徟徕御徢徣徤徥徦徧徨复循徫旁徭微徯徰徱徲徳徴徵徶德徸彻徺徻徼徽徾徿忀忁忂忄惔愔忇忈忉忊忋忎忏忐忑"
+ "忒忓忔忕忖忚忛応忝忞忟忡忢忣忥忦忨忩忪忬忭忮忯忰忱忲忳忴念忶汹忸忹忺忻忼忾忿怂怃怄怅怆怇怈怉怊怋怌怍怏"
+ "怐怑怓怔怗怘怙怚怛怞怟怡怢怣怤怦怩怫怬怭怮怯怰怲怳怴怵怶怷怸怹怺怼悙怿恀恁恂恃恄恅恒恇恈恉恊恌恍恎恏恑"
+ "恒恓恔恖恗恘恙恚恛恜恝恞恠恡恦恧恫恬恮恰恱恲恴恷恹恺恻恽恾恿悀悁悂悃悆悇悈悊悋悌悍悎悏悐悑悒悓悕悖悗悘"
+ "悙悚悛悜悝悞悟悡悢悤悥悧悩悪悫悭悮悰悱悳悴悷悹悺悻悼悾悿惀惁惂惃惄惆惈惉惊惋惌惍惎惏惐惑惒惓惔惕惖惗惘"
+ "惙惚惛惜惝惞惠恶惢惣惤惥惦惧惨惩惪惫惬惮恼恽惴惵惶惸惺惼惽惾惿愀愂愃愄愅愆愇愉愊愋愌愍愎愐愑愒愓愕愖愗"
+ "愘愙愝愞愠愡愢愣愥愦愧愩愪愫愬愭愮愯愰愱愲愳怆愵愶恺愸愹愺愻愼愽忾愿慀慁慂慃栗慅慆慈慉慊态慏慐慑慒慓慔"
+ "慖慗惨慙惭慛慜慝慞恸慠慡慢慥慦慧慨慩怄怂慬悯慯慰慲悭慴慵慷慸慹慺慻慽慿憀憁忧憃憄憅憆憇憈憉惫憋憌憍憎憏"
+ "怜憓憔憕憖憗憘憙憛憜憝憞憟憠憡憢憣愤憥憦憧憨憩憪憬憭怃憯憰憱憳憴憵忆憷憸憹憺憻憼憽憾憿懀懁懂懄懅懆恳懈"
+ "懊懋怿懔懎懏懐懑懓懔懕懖懗懘懙懚懛懜懝怼懠懡懢懑懤懥懦懧恹懩懪懫懬懭懮懯懰懱惩懳懴懵懒怀悬懹忏懻惧懽慑"
+ "懿恋戁戂戃戄戅戆懯戉戊戋戌戍戎戓戋戕彧或戗戙戛戜戝戞戟戠戡戢戣戤戥戦戗戨戬截戫戭戮戱戳戴戵戈戚残牋戸戹"
+ "戺戻戼戽戾扂扃扄扅扆扈扊扏扐払扖扗扙扚扜扝扞扟扠扦扢扣扤扥扦扨扪扭扮扰扲扴扵扷扸抵扻扽抁挸抆抇抈抉抋抌"
+ "抍抎抏抐抔抖抙抝択抟抠抡抣护抦抧抨抩抪抬抮抰抲抳抵抶抷抸抹抺押抻抽抾抿拀拁拃拄拇拈拊拌拎拏拑拓拕拗拘拙"
+ "拚拝拞拠拡拢拣拤拧择拪拫括拭拮拯拰拱拲拳拴拵拶拷拸拹拺拻拼拽拾拿挀挂挃挄挅挆挈挊挋挌挍挎挏挐挒挓挔挕挗"
+ "挘挙挚挛挜挝挞挟挠挡挢挣挦挧挨挩挪挫挬挭挮挰挱挲挳挴挵挷挸挹挺挻挼挽挿捀捁捂捃捄捅捆捇捈捊捋捌捍捎捏捐"
+ "捑捒捓捔捕捖捗捘捙捚捛捜捝捞损捠捡换捣捤捥捦捧舍捩捪扪捬捭据捯捰捱捳捴捵捶捷捸捹捺捻捼捽捾捿掀掁掂扫抡"
+ "掅掆掇授掉掊掋掍掎掐掑排掓掔掕挜掖掘挣掚挂掜掝掞掟掠采探掣掤掦措掫掬掭掮掯掰掱掲掳掴掵掶掸掹掺掻掼掽掾"
+ "掿拣揁揂揃揅揄揆揇揈揉揊揋揌揍揎揑揓揔揕揖揗揘揙揜揝揞揟揠揢揤揥揦揧揨揫捂揰揱揲揳援揵揶揷揸揻揼揾揿搀"
+ "搁搂搃搄搅搇搈搉搊搋搌搎搏搐搑搒搓搔搕搘搙搚搛搝擀搠搡搢搣搤捶搦搧搨搩搪搫搬搮搰搱搲搳搴搵搷搸搹搻搼搽"
+ "榨搿摂摅摈摉摋摌摍摎摏摐掴摒摓摔摕摖摗摙摚摛掼摝摞摠摡摢揸摤摥摦摧摨摪摫摬摭摮挚摰摱摲抠摴摵抟摷摹摺掺"
+ "摼摽摾摿撀撁撂撃撄撅撉撊撋撌撍撎挦挠撒挠撔撖撗撘撙捻撛撜撝挢撠撡掸掸撧撨撩撪撬撮撯撱揿撴撵撶撷撸撹撺挞"
+ "撼撽挝擀擃掳擅擆擈擉擌擎擏擐擑擓擕擖擗擘擙擛擜擝擞擟擡擢擤擥擧擨擩擪擫擭擮摈擳擵擶撷擸擹擽擿攁攂攃摅攅"
+ "撵攇攈攉攊攋攌攍攎拢攐攑攒攓攕撄攗攘搀攚撺攞攟攠攡攒挛攥攦攧攨攩搅攫攭攮攰攱攲攳攴攵攸攺攼攽敀敁敂敃敄"
+ "敆敇敉敊敋敍敐敒敓敔敕敖敚敜敟敠敡敤敥敧敨敩敪敫敭敮敯敱敳敶敹敺敻敼敽敾敿斀斁敛斄斅斆敦斈斉斊斍斎斏斒"
+ "斓斔斓斖斑斘斚斛斝斞斟斠斡斢斣斦斨斪斫斩斮斱斲斳斴斵斶斸斺斻於斾斿旀旃旄旆旇旈旊旍旎旐旑旒旓旔旕旖旘旙"
+ "旚旜旝旞旟旡旣旤兂旪旫旮旯旰旱旲旳旴旵旸旹旻旼旽旾旿昀昁昃昄昅昈昉昊昋昍昐昑昒昕昖昗昘昙昚昛昜昝晻昢昣"
+ "昤春昦昧昩昪昫昬昮昰昱昲昳昴昵昶昷昸昹昺昻昼昽昿晀晁时晃晄晅晆晇晈晋晊晌晍晎晏晐晑晒晓晔晕晖晗晘晙晛晜"
+ "晞晟晠晡晰晣晤晥晦晧晪晫晬晭晰晱晲晳晴晵晷晸晹晻晼晽晾晿暀暁暂暃暄暅暆暇晕晖暊暋暌暍暎暏暐暑暒暓暔暕暖"
+ "暗旸暙暚暛暜暝暞暟暠暡暣暤暥暦暧暨暩暪暬暭暮暯暰昵暲暳暴暵暶暷暸暹暺暻暼暽暾暿曀曁曂曃晔曅曈曊曋曌曍曎"
+ "曏曐曑曒曓曔曕曗曘曙曚曛曜曝曞曟旷曡曢曣曤曥曦曧昽曩曪曫晒曭曮曯曰曱曵曶曷曹曺曻曽朁朂朄朅朆朇最羯肜朊"
+ "朌朎朏朐朑朒朓朕朖朘朙朚朜朞朠朡朣朤朥朦胧朩术朰朲朳枛朸朹朻朼朾朿杁杄杅杆圬杈杉杊杋杍杒杓杔杕杗杘杙杚"
+ "杛杝杞杢杣杤杦杧杩杪杫杬杮柿杰东杲杳杴杵杶杷杸杹杺杻杼杽枀枂枃枅枆枇枈枊枋枌枍枎枏析枑枒枓枔枖枘枙枛枞"
+ "枟枠枡枤枥枦枧枨枩枬枭枮枰枱枲枳枵枷枸枹枺枻枼枽枾枿柀柁柂柃柄柅柆柇柈柉柊柋柌柍柎柒柕柖柗柘柙查楂呆柙"
+ "柚柛柜柝柞柟柠柡柢柣柤柦柧柨柩柪柬柭柮柯柰柲柳栅柶柷柸柹拐査柼柽柾栀栁栂栃栄栆栈栉栊栋栌栍栎栐旬栔栕栗"
+ "栘栙栚栛栜栝栞栟栠栢栣栤栥栦栧栨栩株栫栬栭栮栯栰栱栲栳栴栵栶核栺栻栽栾栿桀桁桂桄桅桇桉桊桋桍桎桏桒桕桖"
+ "桗桘桙桚桛桜桝桞桟桠桡桢档桤桦桧桨桩桪桫桬桭杯桯桰桱桲桳桴桵桶桷桸桹桺桻桼桽桾杆梀梁梂梃梄梅梆梇梈梉枣"
+ "梌梍梎梏梐梑梒梓梕梖梗枧梙梚梛梜梞梠梡梢梣梤梥梧梩梪梫梬梭梮梯械梲梴梵梶梷梸梹梺梻梼梽梾梿检棁棂棃棅棆"
+ "棇棈棉棊棋棌棍棎棏棐棒棓棔棕枨枣棘棙棚棛棜棝棞栋棠棡棢棣棤棥棦棨棩棪棫桊棭棯棰棱栖棳棴棵梾棷棸棹棺棻棼"
+ "棽棾棿椀椁椂椃椄椆椇椈椉椊椋椌椎桠椐椒椓椔椕椖椗椘椙椚椛検椝椞椟椠椡椢椣椤椥椦椧椨椩椪椫椬椭椮椯椰椱椲"
+ "椳椴椵椶椷椸椹椺椻椼椽椾椿楀楁楂楃楅楆楇楈楉杨楋楌楍楎楏楐楑楒楔楕楖楗楘楛楜楝楞楟楠楡楢楣楤楥楦楧桢楩"
+ "楪楫楬楮椑楯楰楱楲楳楴极楶榉榊榋榌楷楸楹楺楻楽楾楿榀榁榃榄榅榆榇榈榉榊榋榌榍槝搌榑榒榓榔榕榖榗榘榙榚榛"
+ "榜榝榞榟榠榡榢榣榤榥榧榨榩杩榫榬榭榯榰榱榲榳榴榵榶榷榸榹榺榻榼榽榾桤槀槁槂盘槄槅槆槇槈槉槊构槌枪槎槏槐"
+ "槑槒杠槔槕槖槗様槙槚槛槜槝槞槟槠槡槢槣槥槦椠椁槩槪槫槬槭槮槯槰槱槲桨槴槵槶槷槸槹槺槻槼槽槾槿樀桩樃樄枞"
+ "樆樇樈樉樊樋樌樍樎樏樐樒樔樕樖樗樘樚樛樜樝樟樠樢样樤樥樦樧樨権横樫樬樭樮樯樰樱樲樳樴樵樶樷朴树桦樻樼樽"
+ "樾樿橀橁橂橃橄橅橆橇桡橉橊桥橌橍橎橏橐橑橒橓橔橕橖橗橘橙橚橛橜橝橞橠橡椭橣橤橥橧橨橩橪橬橭橮橯橰橱橲橳"
+ "橴橵橶橷橸橹橺橻橼柜橿檀檩檂檃檄檅檆檇檈柽檊檋檌檍檎檏檐檑檒檓档檕檖檗檘檙檚檛桧檝檞槚檠檡检樯檤檥檦檧"
+ "檨檩檪檫檬檭梼檰檱檲槟檴檵檶栎柠檹檺槛檼檽桐檿櫀櫁棹柜櫄櫅櫆櫇櫈櫉櫊櫋櫌櫍櫎櫏累櫑櫒櫔櫕櫖櫗櫘櫙榈栉櫜"
+ "椟橼櫠櫡櫢櫣櫤橱櫦槠栌櫩枥橥榇櫭櫮櫯櫰櫱櫲栊櫴櫵櫶櫷榉櫹櫼櫽櫾櫿欀欁欂欃栏欅欆欇欈欉权欋欌欍欎椤欐欑栾"
+ "欓欔欕榄欗欘欙欚欛欜欝棂欟欤欥欦欨欩欪欫欬欭欮欯欰欱欳欴欵欶欷唉欹欻欼钦款欿歀歁歂歃歄歅歆歇歈歉歊歋歍"
+ "欧歑歒歓歔殓歗歘歙歚歛歜歝歞欤歠欢钦歧歨歩歫歬歭歮歯歰歱歳歴歵歶歾殁殁殂殃殄殅殆殇殈殉殌殍殎殏殐殑殒殓"
+ "殔殕殖殗残殙殚殛殜殝殒殟殠殡殢殣殇殥殦殧殨殩殪殚殬殰殱歼殶殸殹殾殿毂毃毄毅殴毇毈毉毊母毋毎毐毑毓坶拇毖"
+ "毗毘坒陛屁芘楷砒玭昆吡纰妣锴鈚秕庇沘毜毝毞毟毠毡毢毣毤毥毦毧毨毩毪毫毬毭毮毯毰毱毲毳毴毵毶毷毸毹毺毻毼"
+ "毽毾毵氀氁氂氃氋氄氅氆氇毡氉氊氍氎氒氐抵坻坁胝阍痻泜汦茋芪柢砥奃睧眡蚳蚔呧軧軝崏弤婚怟惛忯岻貾氕氖気氘"
+ "氙氚氜氝氞氟氠氡氢氤氥氦氧氨氩氪氭氮氯氰氱氲氶氷凼氺氻氼氽氾氿汀汃汄汅氽汈汊汋汌泛汏汐汑汒汓汔汕汖汘污"
+ "汚汛汜汞汢汣汥汦汧汨汩汫汬汭汮汯汰汱汲汳汴汵汶汷汸汹汻汼汾汿沀沂沃沄沅沆沇沊沋沌冱沎沏洓沓沔沕沗沘沚沛"
+ "沜沝沞沠沢沣沤沥沦沨沩沪沫沬沭沮沯沰沱沲沴沵沶沷沸沺沽泀泂泃泅泆泇泈泋泌泍泎泏泐泑泒泓泔泖泗泘泙泚泜溯"
+ "泞泟泠泤泦泧泩泫泬泭泮泯泱泲泴泵泶泷泸泹泺泾泿洀洂洃洄洅洆洇洈洉洊洌洍洎洏洐洑洒洓洔洕洖洘洙洚洜洝洠洡"
+ "洢洣洤洦洧洨洫洬洭洮洯洰洱洳洴洵洷洸洹洺洼洽洿浀浂浃浄浈浉浊浌浍浏浐浒浔浕浖浗浘浚浛浜浝浞浟浠浡浢浣浤"
+ "浥浦浧浨浫浭浯浰浱浲浳浵浶浃浺浻浼浽浾浿涀涁涂涃涄涅涆泾涊涋涍涎涐涑涒涓涔涖涗涘涙涚涜涝涞涟涠涡涢涣涤"
+ "涥涧涪涫涬涭涰涱涳涴涶涷涸涹涺涻凉涽涾涿淁淂淃淄淅淆淇淈淉淊淌淍淎淏淐淓淔淕淖淗淙淛淜淞淟淠淢淣淤渌淦"
+ "淧沦淬淭淯淰淲淳淴涞滍淾淿渀渁渂渃渄渆渇済渋渌渍渎渏渑渒渓渕渖渘渚渜渝渞渟沨渥渧渨渪渫渮渰渱渲渳渵渶渷"
+ "渹渻渼渽渿湀湁湂湄湅湆湇湈湉湋湌湍湎湏湐湑湒湓湔湕湗湙湚湜湝浈湟湠湡湢湤湥湦湨湩湪湫湬湭湮湰湱湲湳湴湵"
+ "湶湷湸湹湺湻湼湽満溁溂溄溆溇沩溉溊溋溌溍溎溏溑溒溓溔溕溗溘溙溚溛溞溟溠溡溣溤溥溦溧溨溩溬溭溯溰溱溲涢溴"
+ "溵溶溷溸溹溻溽溾溿滀滁滂滃沧滆滇滈滉滊涤滍荥滏滐滒滓滖滗滘滙滛滜滝滞滟滠滢滣滦滧滪滫沪滭滮滰滱渗滳滵滶"
+ "滹滺浐滼滽漀漃漄漅漈漉溇漋漌漍漎漐漑澙熹漗漘漙沤漛漜漝漞漟漡漤漥漦漧漨漪渍漭漮漯漰漱漳漴溆漶漷漹漺漻漼"
+ "漽漾浆潀颍潂潃潄潅潆潇潈潉潊潋潌潍潎潏潐潒潓洁潕潖潗潘沩潚潜潝潞潟潠潡潢潣润潥潦潧潨潩潪潫潬潭浔溃潱潲"
+ "潳潴潵潶滗潸潹潺潻潼潽潾涠澁澄澃澅浇涝澈澉澊澋澌澍澎澏湃澐澑澒澓澔澕澖涧澘澙澚澛澜澝澞澟渑澢澣泽澥滪澧"
+ "澨澪澫澬澭浍澯澰淀澲澳澴澵澶澷澸澹澺澻澼澽澾澿濂濄濅濆濇濈濉濊濋濌濍濎濏濐濑濒濓沵濖濗泞濙濚濛浕濝濞济"
+ "濠濡濢濣涛濥濦濧濨濩濪滥浚濭濮濯潍滨濲濳濴濵濶濷濸濹溅濻泺濽滤濿瀀漾瀂瀃灋渎瀇瀈泻瀊沈瀌瀍瀎浏瀐瀒瀓瀔"
+ "濒瀖瀗泸瀙瀚瀛瀜瀞潇潆瀡瀢瀣瀤瀥潴泷濑瀩瀪瀫瀬瀭瀮瀯弥瀱潋瀳瀴瀵瀶瀷瀸瀹瀺瀻瀼瀽澜瀿灀灁瀺灂沣滠灅灆灇"
+ "灈灉灊灋灌灍灎灏灐洒灒灓漓灖灗滩灙灚灛灜灏灞灟灠灡灢湾滦灥灦灧灨灪灮灱灲灳灴灷灸灹灺灻灼炀炁炂炃炄炅炆"
+ "炇炈炋炌炍炏炐炑炓炔炕炖炗炘炙炚炛炜炝炞炟炠炡炢炣炤炥炦炧炨炩炪炫炯炰炱炲炳炴炵炶炷炻炽炾炿烀烁烃烄烅"
+ "烆烇烉烊烋烌烍烎烐烑烒烓烔烕烖烗烙烚烜烝烞烠烡烢烣烥烩烪烯烰烱烲烳烃烵烶烷烸烹烺烻烼烾烿焀焁焂焃焄焇焈"
+ "焉焋焌焍焎焏焐焑焒焓焔焕焖焗焘焙焛焜焝焞焟焠焢焣焤焥焧焨焩焪焫焬焭焮焯焱焲焳焴焵焷焸焹焺焻焼焽焾焿煀煁"
+ "煂煃煄煅煇煈炼煊煋煌煍煎煏煐煑炜煓煔暖煗煘煚煛煜煝煞煟煠煡茕煣焕煦煨煪煫炀煭煯煰煱煲煳煴煵煶煷煸煹煺煻"
+ "煼煽煾煿熀熁熂熃熄熅熆熇熈熉熋熌熍熎熏熐熑荧熓熔熕熖炝熘熚熛熜熝熞熠熡熢熣熤熥熦熧熨熩熪熫熬熭熮熯熰颎"
+ "熳熴熵熶熷熸熹熺熻熼熽炽熿燀烨燂燅燆燇炖燊燋燌燍燎燏燐燑燓燔燖燗燘燚燛燝燞燠燡燢燣燤燥灿燧燨燩燪燫燮燯"
+ "燰燱燲燳烩燵燵燸燹燺薰燽焘燿爀爁爂爃爄爅爇爈爉爊爋爌烁爎爏爑爒爓爔爕爖爗爘爙爚烂爜爝爞爟爠爡爢爣爤爥爦"
+ "爧爨爩爮爯爰爳爴舀爷爻爼爽牀牁牂牃牄牅牊牉牋牍牎牏牐牑牒牓牔牕牖牗牚芽牜牝牞牟牣牤牥牦牨牪牫牬牭牮牯牰"
+ "牱牳牴牶牷牸牻牼牾牿犂犃犄犅犆犇犈犉犊犋犌犍犎犏犐犑犒犓犔犕荦犗犘犙犚牦犜犝犞犟犠犡犣犤犥犦牺犨犩犪犫"
+ "犭犰犱犲犳犴犵犷犸犹犺犻犼犽犾犿狘狁狃狄狅狆狇狉狊狋狌狍狎狏狑狒狓狔狕狖狙狚狛狜狝狞狟狡猯狢狣狤狥狦狧"
+ "狨狩狪狫狭狮狯狰狱狲狳狴狵狶狷狭狺狻狾狿猀猁猂猃猄猅猆猇猈猉猊猋猌猍猑猒猓猔猕猗猘狰猚猝猞猟猠猡猢猣猤"
+ "猥猦猧猨猬猭猰猱猲猳猵犹猷猸猹猺狲猼猽猾獀犸獂獆獇獈獉獊獋獌獍獏獐獑獒獓獔獕獖獗獘獙獚獛獜獝獞獟獠獡獢"
+ "獣獤獥獦獧獩狯猃獬獭狝獯狞獱獳獴獶獹獽獾獿猡玁玂玃";
private static Random random = new Random(new Date().getTime());
public static String genOneChineseChars() {
String str = null;
int highPos = (176 + Math.abs(random.nextInt(39)));
int lowPos = 161 + Math.abs(random.nextInt(93));
byte[] b = new byte[] { (new Integer(highPos)).byteValue(),
(new Integer(lowPos)).byteValue() };
try {
str = new String(b, "GB2312");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return str;
}
public static String genFixedLengthChineseChars(int length) {
String str = "";
for (int i = length; i > 0; i--) {
str = str + genOneChineseChars();
}
return str;
}
public static String genRandomLengthChineseChars(int start, int end) {
String str = "";
int length = random.nextInt(end + 1);
if (length < start) {
str = genRandomLengthChineseChars(start, end);
} else {
for (int i = 0; i < length; i++) {
str = str + genOneChineseChars();
}
}
return str;
}
public static char getOneOddChar() {
return ODD_CHINESE_CHARS
.charAt(random.nextInt(ODD_CHINESE_CHARS.length()));
}
}
| 23,456 | Java | .java | binarywang/java-testdata-generator | 584 | 276 | 0 | 2016-01-21T05:45:44Z | 2023-06-21T06:48:09Z |
LuhnUtils.java | /FileExtraction/Java_unseen/binarywang_java-testdata-generator/src/main/java/cn/binarywang/tools/generator/util/LuhnUtils.java | package cn.binarywang.tools.generator.util;
/**
* <pre>
* Luhn算法工具类
* Created by Binary Wang on 2018/3/22.
* </pre>
*
* @author <a href="https://github.com/binarywang">Binary Wang</a>
*/
public class LuhnUtils {
/**
* 从不含校验位的银行卡卡号采用 Luhn 校验算法获得校验位
* 该校验的过程:
* 1、从卡号最后一位数字开始,逆向将奇数位(1、3、5等等)相加。
* 2、从卡号最后一位数字开始,逆向将偶数位数字,先乘以2(如果乘积为两位数,则将其减去9),再求和。
* 3、将奇数位总和加上偶数位总和,结果应该可以被10整除。
*/
public static int getLuhnSum(char[] chs) {
int luhnSum = 0;
for (int i = chs.length - 1, j = 0; i >= 0; i--, j++) {
int k = chs[i] - '0';
if (j % 2 == 0) {
k *= 2;
k = k / 10 + k % 10;
}
luhnSum += k;
}
return luhnSum;
}
}
| 1,028 | Java | .java | binarywang/java-testdata-generator | 584 | 276 | 0 | 2016-01-21T05:45:44Z | 2023-06-21T06:48:09Z |
BankCardTypeEnum.java | /FileExtraction/Java_unseen/binarywang_java-testdata-generator/src/main/java/cn/binarywang/tools/generator/bank/BankCardTypeEnum.java | package cn.binarywang.tools.generator.bank;
/**
* <pre>
* 银行卡类型枚举类
* Created by Binary Wang on 2017-3-31.
* @author <a href="https://github.com/binarywang">binarywang(Binary Wang)</a>
* </pre>
*/
public enum BankCardTypeEnum {
/**
* 借记卡/储蓄卡
*/
DEBIT("借记卡/储蓄卡"),
/**
* 信用卡/贷记卡
*/
CREDIT("信用卡/贷记卡");
private final String name;
BankCardTypeEnum(String name) {
this.name = name;
}
}
| 508 | Java | .java | binarywang/java-testdata-generator | 584 | 276 | 0 | 2016-01-21T05:45:44Z | 2023-06-21T06:48:09Z |
BankCardNumberValidator.java | /FileExtraction/Java_unseen/binarywang_java-testdata-generator/src/main/java/cn/binarywang/tools/generator/bank/BankCardNumberValidator.java | package cn.binarywang.tools.generator.bank;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import cn.binarywang.tools.generator.util.LuhnUtils;
/**
* <pre>
* 银行卡号校验类
* Created by Binary Wang on 2018/3/22.
* </pre>
*
* @author <a href="https://github.com/binarywang">Binary Wang</a>
*/
public class BankCardNumberValidator {
/**
* 校验银行卡号是否合法
*
* @param cardNo 银行卡号
* @return 是否合法
*/
public static boolean validate(String cardNo) {
if (StringUtils.isEmpty(cardNo)) {
return false;
}
if (!NumberUtils.isDigits(cardNo)) {
return false;
}
if (cardNo.length() > 19 || cardNo.length() < 16) {
return false;
}
int luhnSum = LuhnUtils.getLuhnSum(cardNo.substring(0, cardNo.length() - 1).trim().toCharArray());
char checkCode = (luhnSum % 10 == 0) ? '0' : (char) ((10 - luhnSum % 10) + '0');
return cardNo.substring(cardNo.length() - 1).charAt(0) == checkCode;
}
}
| 1,114 | Java | .java | binarywang/java-testdata-generator | 584 | 276 | 0 | 2016-01-21T05:45:44Z | 2023-06-21T06:48:09Z |
BankNameEnum.java | /FileExtraction/Java_unseen/binarywang_java-testdata-generator/src/main/java/cn/binarywang/tools/generator/bank/BankNameEnum.java | package cn.binarywang.tools.generator.bank;
import org.apache.commons.lang3.ArrayUtils;
/**
* <pre>
* 常见银行名称枚举类
* Created by Binary Wang on 2017-3-31.
*
* @author <a href="https://github.com/binarywang">binarywang(Binary Wang)</a>
* </pre>
*/
public enum BankNameEnum {
/**
* <pre>
* 中国工商银行
* 中国工商银行VISA学生国际信用卡:427020
* 中国工商银行VISA国际信用卡金卡:427030
* 中国工商银行MC国际信用卡普通卡:530990
* 中国工商银行新版人民币贷记卡普卡:622230
* 中国工商银行新版人民币贷记卡金卡:622235
* 中国工商银行新版信用卡(准贷)普卡:622210
* 中国工商银行新版信用卡(准贷)金卡:622215
* 中国工商银行牡丹灵通卡借记卡:622200
* 中国工商银行原牡丹灵通卡借记卡:955880
* </pre>
*/
ICBC("102", "中国工商银行", "工行", new Integer[]{622200, 955880},
new Integer[]{427020, 427030, 530990, 622230, 622235, 622210, 622215}),
/**
* <pre>
* 中国农业银行
* 中国农业银行人民币贷记卡 香港旅游卡贷记卡金卡:622836
* 中国农业银行人民币贷记卡 香港旅游卡贷记卡普卡:622837
* 中国农业银行世纪通宝借记卡:622848
* 农业银行:552599、404119、404121、519412、403361、558730、520083、520082、519413、49102、404120、404118、53591、404117
* </pre>
*/
ABC("103", "中国农业银行", "农行"),
/**
* <pre>
* 中国银行
* 中国银行中银都市卡:622760
* 中国银行BOC系列VISA标准卡普通卡/VISA高校认同卡:409666
* 中国银行国航知音信用卡:438088
* 中国银行上海市分行长城人民币贷记卡普通卡:622752
* </pre>
*/
BOC("104", "中国银行", "中行"),
/**
* <pre>
* 中国建设银行
* 中国建设银行VISA龙卡借记卡:436742
* 中国建设银行VISA龙卡贷记卡:436745
* 中国建设银行支付宝龙卡借记卡:622280
* </pre>
*/
CCB("105", "中国建设银行", "建行"),
/**
* <pre>
* 交通银行
* 交通银行VISA普通卡:458123
* 交通银行MC信用卡普通卡:521899
* 交通银行太平洋卡借记卡:622260
* </pre>
*/
BCOM("301", "交通银行", "交行"),
/**
* <pre>
* 中信银行
* 中信银行国航知音信用卡/万事达卡普通卡:518212
* 中信银行理财宝卡借记卡:622690
* 中信银行万事达卡金卡:520108
* 中信银行蓝卡/I卡信用卡:622680
* 中信银行:376968、376966、622918、622916、376969、622919、556617、403391、558916、514906、400360、433669、433667、433666、404173、404172、404159、404158、403393、403392、622689、622688、433668、404157、404171、404174、628209、628208、628206
* </pre>
*/
CITIC("302", "中信银行"),
/**
* <pre>
* 中国光大银行
* 光大银行卡号开头:406254、622655、622650、622658、356839、486497、481699、543159、425862、406252、356837、356838、356840、622161、628201、628202
* </pre>
*/
CEB("303", "中国光大银行"),
/**
* <pre>
* 华夏银行
* 华夏银行:539867,528709
* 华夏银行MC钛金卡:523959
* 华夏银行人民币卡金卡:622637
* 华夏银行人民币卡普卡:622636
* 华夏银行MC金卡:528708
* 华夏银行MC普卡:539868
* </pre>
*/
HXB("304", "华夏银行"),
/**
* <pre>
* 中国民生银行
* 民生银行:407405,517636
* 中国民生银行MC金卡:512466
* 中国民生银行星座卡借记卡:415599
* 中国民生银行VISA信用卡金卡:421870
* 中国民生银行蝶卡银卡借记卡:622622
* 民生银行:528948,552288,556610,622600,622601,622602,622603,421869,421871,628258
* </pre>
*/
CMBC("305", "中国民生银行"),
/**
* <pre>
* 广东发展银行
* 广东发展银行新理财通借记卡:622568
* 广东发展银行南航明珠卡MC金卡:520152
* 广东发展银行南航明珠卡MC普卡:520382
* 广东发展银行理财通借记卡:911121
* 广发真情卡:548844
* </pre>
*/
CGB("306", "广东发展银行"),
/**
* <pre>
* 平安银行
* 深圳平安银行:622155,622156
* 深圳平安银行万事达卡普卡:528020
* 深圳平安银行万事达卡金卡:526855
* 深发展联名普卡:435744
* 深发展卡普通卡:622526
* 深发展联名金卡:435745
* 深圳发展银行:998801,998802
* 深发展卡金卡:622525
* 深圳发展银行发展卡借记卡:622538
* </pre>
*/
PAB("307", "平安银行"),
/**
* <pre>
* 招商银行
* 招商银行哆啦A梦粉丝信用卡:518710
* 招商银行哆啦A梦粉丝信用卡珍藏版卡面/MC贝塔斯曼金卡/MC车主卡:518718
* 招商银行QQ一卡通借记卡:622588
* 招商银行HELLO KITTY单币卡:622575
* 招商银行:545947、521302、439229、552534、622577、622579、439227、479229、356890、356885、545948、545623、552580、552581、552582、552583、552584、552585、552586、552588、552589、645621、545619、356886、622578、622576、622581、439228、628262、628362、628362、628262
* 招商银行JCB信用卡普通卡:356889
* 招商银行VISA白金卡:439188
* 招商银行VISA信用卡普通卡:439225招商银行VISA信用卡金卡:439226
* </pre>
*/
CMB("308", "招商银行", "招行"),
/**
* <pre>
* 兴业银行
* 兴业银行:451289、622902、622901、527414、524070、486493、486494、451290、523036、486861、622922
* </pre>
*/
CIB("309", "兴业银行"),
/**
* <pre>
* 上海浦东发展银行
* 上海浦东发展银行奥运WOW卡美元单币:418152
* 上海浦东发展银行WOW卡/奥运WOW卡:456418
* 上海浦东发展银行东方卡借记卡:622521
* 上海浦东发展银行VISA普通卡:404738
* 上海浦东发展银行VISA金卡:404739
* 浦东发展银行:498451,622517,622518,515672,517650,525998,356850,356851,356852
* </pre>
*/
SPDB("310", "上海浦东发展银行"),
/**
* <pre>
* 华润银行
* </pre>
*/
CR("999999", "华润银行", new Integer[]{622363}),
/**
* <pre>
* 渤海银行
* </pre>
*/
BHB("318", "渤海银行"),
/**
* <pre>
* 徽商银行
* </pre>
*/
HSB("319", "徽商银行"),
/**
* <pre>
* 江苏银行
* </pre>
*/
JSB_1("03133010", "江苏银行"),
/**
* <pre>
* 江苏银行
* </pre>
*/
JSB("03133120", "江苏银行"),
/**
* <pre>
* 上海银行
* 上海银行VISA金卡:402674
* 上海银行借记卡:622892
* </pre>
*/
SHB("04012900", "上海银行"),
/**
* <pre>
* 中国邮政储蓄银行
* 中国邮政储蓄绿卡借记卡:622188
* </pre>
*/
POST("403", "中国邮政储蓄银行"),
/**
* <pre>
* 北京银行
* 北京银行京卡借记卡:602969
* </pre>
*/
BOB("", "北京银行"),
/**
* <pre>
* 宁波银行
* 宁波银行:512431,520194,622318,622778
* 宁波银行汇通卡人民币金卡/钻石联名卡:622282
* </pre>
*/
BON("", "宁波银行");
/**
* 银行代码
*/
private final String code;
/**
* 银行名称
*/
private final String name;
/**
* 银行简称
*/
private String abbrName;
/**
* 信用卡卡号前缀数组
*/
private Integer[] creditCardPrefixes;
/**
* 借记卡卡号前缀数组
*/
private Integer[] debitCardPrefixes;
/**
* 所有卡号前缀数组
*/
private Integer[] allCardPrefixes;
BankNameEnum(String code, String name) {
this.code = code;
this.name = name;
}
BankNameEnum(String code, String name, String abbrName) {
this.code = code;
this.name = name;
this.abbrName = abbrName;
}
BankNameEnum(String code, String name, String abbrName, Integer[] debitCardPrefixes, Integer[] creditCardPrefixes) {
this.code = code;
this.name = name;
this.abbrName = abbrName;
this.creditCardPrefixes = creditCardPrefixes;
this.debitCardPrefixes = debitCardPrefixes;
this.allCardPrefixes = ArrayUtils.addAll(this.creditCardPrefixes, this.debitCardPrefixes);
}
BankNameEnum(String code, String name, Integer[] debitCardPrefixes) {
this.code = code;
this.name = name;
this.debitCardPrefixes = debitCardPrefixes;
this.allCardPrefixes = debitCardPrefixes;
}
BankNameEnum(String code, String name, Integer[] debitCardPrefixes, Integer[] creditCardPrefixes) {
this.code = code;
this.name = name;
this.creditCardPrefixes = creditCardPrefixes;
this.debitCardPrefixes = debitCardPrefixes;
this.allCardPrefixes = ArrayUtils.addAll(this.creditCardPrefixes, this.debitCardPrefixes);
}
public String getName() {
return this.name;
}
public String getAbbrName() {
return this.abbrName;
}
public Integer[] getCreditCardPrefixes() {
return this.creditCardPrefixes;
}
public Integer[] getDebitCardPrefixes() {
return this.debitCardPrefixes;
}
public Integer[] getAllCardPrefixes() {
return this.allCardPrefixes;
}
public String getCode() {
return this.code;
}
}
| 9,971 | Java | .java | binarywang/java-testdata-generator | 584 | 276 | 0 | 2016-01-21T05:45:44Z | 2023-06-21T06:48:09Z |
BankCardNumberGenerator.java | /FileExtraction/Java_unseen/binarywang_java-testdata-generator/src/main/java/cn/binarywang/tools/generator/bank/BankCardNumberGenerator.java | package cn.binarywang.tools.generator.bank;
import java.util.Random;
import org.apache.commons.lang3.StringUtils;
import cn.binarywang.tools.generator.base.GenericGenerator;
import cn.binarywang.tools.generator.util.LuhnUtils;
/**
* <pre>
* 生成随机银行卡号:
*
* 参考:效验是否为银行卡,用于验证:
* 现行 16 位银联卡现行卡号开头 6 位是 622126~622925 之间的,7 到 15 位是银行自定义的,
* 可能是发卡分行,发卡网点,发卡序号,第 16 位是校验码。
* 16 位卡号校验位采用 Luhm 校验方法计算:
* 1,将未带校验位的 15 位卡号从右依次编号 1 到 15,位于奇数位号上的数字乘以 2
* 2,将奇位乘积的个十位全部相加,再加上所有偶数位上的数字
* 3,将加法和加上校验位能被 10 整除。
* </pre>
*/
public class BankCardNumberGenerator extends GenericGenerator {
private static GenericGenerator instance = new BankCardNumberGenerator();
private BankCardNumberGenerator() {
}
public static GenericGenerator getInstance() {
return instance;
}
@Override
public String generate() {
Random random = getRandomInstance();
// ContiguousSet<Integer> sets = ContiguousSet
// .create(Range.closed(622126, 622925), DiscreteDomain.integers());
// ImmutableList<Integer> list = sets.asList();
Integer prev = 622126 + random.nextInt(925 + 1 - 126);
return generateByPrefix(prev);
}
/**
* <pre>
* 根据给定前六位生成卡号
* </pre>
*/
public static String generateByPrefix(Integer prefix) {
Random random = new Random(System.currentTimeMillis());
String bardNo = prefix
+ StringUtils.leftPad(random.nextInt(999999999) + "", 9, "0");
char[] chs = bardNo.trim().toCharArray();
int luhnSum = LuhnUtils.getLuhnSum(chs);
char checkCode = luhnSum % 10 == 0 ? '0' : (char) (10 - luhnSum % 10 + '0');
return bardNo + checkCode;
}
/**
* 根据银行名称 及银行卡类型生成对应卡号
*
* @param bankName 银行名称
* @param cardType 银行卡类型
* @return 银行卡号
*/
public static String generate(BankNameEnum bankName, BankCardTypeEnum cardType) {
Integer[] candidatePrefixes = null;
if (cardType == null) {
candidatePrefixes = bankName.getAllCardPrefixes();
} else {
switch (cardType) {
case DEBIT:
candidatePrefixes = bankName.getDebitCardPrefixes();
break;
case CREDIT:
candidatePrefixes = bankName.getCreditCardPrefixes();
break;
default:
}
}
if (candidatePrefixes == null || candidatePrefixes.length == 0) {
throw new RuntimeException("没有该银行的相关卡号信息");
}
Integer prefix = candidatePrefixes[new Random().nextInt(candidatePrefixes.length)];
return generateByPrefix(prefix);
}
}
| 3,141 | Java | .java | binarywang/java-testdata-generator | 584 | 276 | 0 | 2016-01-21T05:45:44Z | 2023-06-21T06:48:09Z |
MurmurHash3Test.java | /FileExtraction/Java_unseen/EdwardRaff_jLZJD/src/test/java/com/edwardraff/jlzjd/MurmurHash3Test.java | /*
* 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 com.edwardraff.jlzjd;
import java.util.Random;
import jsat.utils.random.XORWOW;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Edward Raff
*/
public class MurmurHash3Test
{
public MurmurHash3Test()
{
}
@BeforeClass
public static void setUpClass()
{
}
@AfterClass
public static void tearDownClass()
{
}
@Before
public void setUp()
{
}
@After
public void tearDown()
{
}
/**
* Test of pushByte method, of class MurmurHash3.
*/
@org.junit.Test
public void testPushByte()
{
System.out.println("pushByte");
Random rand = new XORWOW();
int seed = rand.nextInt();
MurmurHash3 instance = new MurmurHash3(seed);
byte[] bytes = new byte[4096];
rand.nextBytes(bytes);
for(int i = 0; i < bytes.length; i++)
assertEquals("Failed on " + i, MurmurHash3.murmurhash3_x86_32(bytes, 0, i+1, seed), instance.pushByte(bytes[i]));
}
}
| 1,367 | Java | .java | EdwardRaff/jLZJD | 17 | 6 | 1 | 2017-05-24T03:31:07Z | 2017-09-17T23:32:30Z |
MurmurHash3.java | /FileExtraction/Java_unseen/EdwardRaff_jLZJD/src/main/java/com/edwardraff/jlzjd/MurmurHash3.java | package com.edwardraff.jlzjd;
/**
* The MurmurHash3 algorithm was created by Austin Appleby and placed in the public domain.
* This java port was authored by Yonik Seeley and also placed into the public domain.
* The author hereby disclaims copyright to this source code.
* <p>
* This produces exactly the same hash values as the final C++
* version of MurmurHash3 and is thus suitable for producing the same hash values across
* platforms.
* <p>
* The 32 bit x86 version of this hash should be the fastest variant for relatively short keys like ids.
* murmurhash3_x64_128 is a good choice for longer strings or if you need more than 32 bits of hash.
* <p>
* Note - The x86 and x64 versions do _not_ produce the same results, as the
* algorithms are optimized for their respective platforms.
* <p>
* See http://github.com/yonik/java_util for future updates to this file.
*/
public final class MurmurHash3
{
/**
* the length of the current running byte sequence
*/
private int _len;
/**
* the byte history for the last 4 bytes seen
*/
private final byte[] data = new byte[4];
private int _h1;
private int _seed = 0;
public MurmurHash3()
{
this(0);
}
public MurmurHash3(int seed)
{
this._seed = seed;
reset();
}
public void reset()
{
_len = 0;
_h1 = _seed;
}
public int pushByte(byte b)
{
//store the current byte of input
data[_len % 4] = b;
_len++;
final int c1 = 0xcc9e2d51;
final int c2 = 0x1b873593;
// int h1 = seed;
// int roundedEnd = offset + (len & 0xfffffffc); // round down to 4 byte block
/**
* We will use this as the value of _h1 to dirty for returning to the caller
*/
int h1_as_if_done;
if(_len > 0 && _len % 4 == 0)//we have a valid history of 4 items!
{
// little endian load order
int k1 = (data[0] & 0xff) | ((data[1] & 0xff) << 8) | ((data[2] & 0xff) << 16) | (data[3] << 24);
k1 *= c1;
k1 = (k1 << 15) | (k1 >>> 17); // ROTL32(k1,15);
k1 *= c2;
_h1 ^= k1;
_h1 = (_h1 << 13) | (_h1 >>> 19); // ROTL32(h1,13);
_h1 = _h1*5+0xe6546b64;
h1_as_if_done = _h1;
}
else//tail case
{
// tail
int k1 = 0;
h1_as_if_done = _h1;
switch(_len & 0x03) {
case 3:
k1 = (data[2] & 0xff) << 16;
// fallthrough
case 2:
k1 |= (data[1] & 0xff) << 8;
// fallthrough
case 1:
k1 |= (data[0] & 0xff);
k1 *= c1;
k1 = (k1 << 15) | (k1 >>> 17); // ROTL32(k1,15);
k1 *= c2;
h1_as_if_done ^= k1;
}
}
// finalization
h1_as_if_done ^= _len;
// fmix(h1);
h1_as_if_done ^= h1_as_if_done >>> 16;
h1_as_if_done *= 0x85ebca6b;
h1_as_if_done ^= h1_as_if_done >>> 13;
h1_as_if_done *= 0xc2b2ae35;
h1_as_if_done ^= h1_as_if_done >>> 16;
return h1_as_if_done;
}
/** 128 bits of state */
public static final class LongPair {
public long val1;
public long val2;
}
public static final int fmix32(int h) {
h ^= h >>> 16;
h *= 0x85ebca6b;
h ^= h >>> 13;
h *= 0xc2b2ae35;
h ^= h >>> 16;
return h;
}
public static final long fmix64(long k) {
k ^= k >>> 33;
k *= 0xff51afd7ed558ccdL;
k ^= k >>> 33;
k *= 0xc4ceb9fe1a85ec53L;
k ^= k >>> 33;
return k;
}
/** Gets a long from a byte buffer in little endian byte order. */
public static final long getLongLittleEndian(byte[] buf, int offset) {
return ((long)buf[offset+7] << 56) // no mask needed
| ((buf[offset+6] & 0xffL) << 48)
| ((buf[offset+5] & 0xffL) << 40)
| ((buf[offset+4] & 0xffL) << 32)
| ((buf[offset+3] & 0xffL) << 24)
| ((buf[offset+2] & 0xffL) << 16)
| ((buf[offset+1] & 0xffL) << 8)
| ((buf[offset ] & 0xffL)); // no shift needed
}
/**
* Returns the MurmurHash3_x86_32 hash. Uses a seed of 0.
*
* @param data the data to hash
* @param offset the starting index to begin hashing from
* @param len the length in bytes of the sequence to hash
* @return the final hash output value
*/
public static int murmurhash3_x86_32(byte[] data, int offset, int len)
{
return murmurhash3_x86_32(data, offset, len, 0);
}
/**
* Returns the MurmurHash3_x86_32 hash.
*
* @param data the data to hash
* @param offset the starting index to begin hashing from
* @param len the length in bytes of the sequence to hash
* @param seed the seed to use for hashing
* @return the final hash output value
*/
public static int murmurhash3_x86_32(byte[] data, int offset, int len, int seed)
{
final int c1 = 0xcc9e2d51;
final int c2 = 0x1b873593;
int h1 = seed;
int roundedEnd = offset + (len & 0xfffffffc); // round down to 4 byte block
for (int i=offset; i<roundedEnd; i+=4) {
// little endian load order
int k1 = (data[i] & 0xff) | ((data[i+1] & 0xff) << 8) | ((data[i+2] & 0xff) << 16) | (data[i+3] << 24);
k1 *= c1;
k1 = (k1 << 15) | (k1 >>> 17); // ROTL32(k1,15);
k1 *= c2;
h1 ^= k1;
h1 = (h1 << 13) | (h1 >>> 19); // ROTL32(h1,13);
h1 = h1*5+0xe6546b64;
}
// tail
int k1 = 0;
switch(len & 0x03) {
case 3:
k1 = (data[roundedEnd + 2] & 0xff) << 16;
// fallthrough
case 2:
k1 |= (data[roundedEnd + 1] & 0xff) << 8;
// fallthrough
case 1:
k1 |= (data[roundedEnd] & 0xff);
k1 *= c1;
k1 = (k1 << 15) | (k1 >>> 17); // ROTL32(k1,15);
k1 *= c2;
h1 ^= k1;
}
// finalization
h1 ^= len;
// fmix(h1);
h1 ^= h1 >>> 16;
h1 *= 0x85ebca6b;
h1 ^= h1 >>> 13;
h1 *= 0xc2b2ae35;
h1 ^= h1 >>> 16;
return h1;
}
/** Returns the MurmurHash3_x86_32 hash of the UTF-8 bytes of the String without actually encoding
* the string to a temporary buffer. This is more than 2x faster than hashing the result
* of String.getBytes().
*/
public static int murmurhash3_x86_32(CharSequence data, int offset, int len, int seed) {
final int c1 = 0xcc9e2d51;
final int c2 = 0x1b873593;
int h1 = seed;
int pos = offset;
int end = offset + len;
int k1 = 0;
int k2 = 0;
int shift = 0;
int bits = 0;
int nBytes = 0; // length in UTF8 bytes
while (pos < end) {
int code = data.charAt(pos++);
if (code < 0x80) {
k2 = code;
bits = 8;
/***
// optimized ascii implementation (currently slower!!! code size?)
if (shift == 24) {
k1 = k1 | (code << 24);
k1 *= c1;
k1 = (k1 << 15) | (k1 >>> 17); // ROTL32(k1,15);
k1 *= c2;
h1 ^= k1;
h1 = (h1 << 13) | (h1 >>> 19); // ROTL32(h1,13);
h1 = h1*5+0xe6546b64;
shift = 0;
nBytes += 4;
k1 = 0;
} else {
k1 |= code << shift;
shift += 8;
}
continue;
***/
}
else if (code < 0x800) {
k2 = (0xC0 | (code >> 6))
| ((0x80 | (code & 0x3F)) << 8);
bits = 16;
}
else if (code < 0xD800 || code > 0xDFFF || pos>=end) {
// we check for pos>=end to encode an unpaired surrogate as 3 bytes.
k2 = (0xE0 | (code >> 12))
| ((0x80 | ((code >> 6) & 0x3F)) << 8)
| ((0x80 | (code & 0x3F)) << 16);
bits = 24;
} else {
// surrogate pair
// int utf32 = pos < end ? (int) data.charAt(pos++) : 0;
int utf32 = (int) data.charAt(pos++);
utf32 = ((code - 0xD7C0) << 10) + (utf32 & 0x3FF);
k2 = (0xff & (0xF0 | (utf32 >> 18)))
| ((0x80 | ((utf32 >> 12) & 0x3F))) << 8
| ((0x80 | ((utf32 >> 6) & 0x3F))) << 16
| (0x80 | (utf32 & 0x3F)) << 24;
bits = 32;
}
k1 |= k2 << shift;
// int used_bits = 32 - shift; // how many bits of k2 were used in k1.
// int unused_bits = bits - used_bits; // (bits-(32-shift)) == bits+shift-32 == bits-newshift
shift += bits;
if (shift >= 32) {
// mix after we have a complete word
k1 *= c1;
k1 = (k1 << 15) | (k1 >>> 17); // ROTL32(k1,15);
k1 *= c2;
h1 ^= k1;
h1 = (h1 << 13) | (h1 >>> 19); // ROTL32(h1,13);
h1 = h1*5+0xe6546b64;
shift -= 32;
// unfortunately, java won't let you shift 32 bits off, so we need to check for 0
if (shift != 0) {
k1 = k2 >>> (bits-shift); // bits used == bits - newshift
} else {
k1 = 0;
}
nBytes += 4;
}
} // inner
// handle tail
if (shift > 0) {
nBytes += shift >> 3;
k1 *= c1;
k1 = (k1 << 15) | (k1 >>> 17); // ROTL32(k1,15);
k1 *= c2;
h1 ^= k1;
}
// finalization
h1 ^= nBytes;
// fmix(h1);
h1 ^= h1 >>> 16;
h1 *= 0x85ebca6b;
h1 ^= h1 >>> 13;
h1 *= 0xc2b2ae35;
h1 ^= h1 >>> 16;
return h1;
}
/** Returns the MurmurHash3_x64_128 hash, placing the result in "out". */
public static void murmurhash3_x64_128(byte[] key, int offset, int len, int seed, LongPair out) {
// The original algorithm does have a 32 bit unsigned seed.
// We have to mask to match the behavior of the unsigned types and prevent sign extension.
long h1 = seed & 0x00000000FFFFFFFFL;
long h2 = seed & 0x00000000FFFFFFFFL;
final long c1 = 0x87c37b91114253d5L;
final long c2 = 0x4cf5ad432745937fL;
int roundedEnd = offset + (len & 0xFFFFFFF0); // round down to 16 byte block
for (int i=offset; i<roundedEnd; i+=16) {
long k1 = getLongLittleEndian(key, i);
long k2 = getLongLittleEndian(key, i+8);
k1 *= c1; k1 = Long.rotateLeft(k1,31); k1 *= c2; h1 ^= k1;
h1 = Long.rotateLeft(h1,27); h1 += h2; h1 = h1*5+0x52dce729;
k2 *= c2; k2 = Long.rotateLeft(k2,33); k2 *= c1; h2 ^= k2;
h2 = Long.rotateLeft(h2,31); h2 += h1; h2 = h2*5+0x38495ab5;
}
long k1 = 0;
long k2 = 0;
switch (len & 15) {
case 15: k2 = (key[roundedEnd+14] & 0xffL) << 48;
case 14: k2 |= (key[roundedEnd+13] & 0xffL) << 40;
case 13: k2 |= (key[roundedEnd+12] & 0xffL) << 32;
case 12: k2 |= (key[roundedEnd+11] & 0xffL) << 24;
case 11: k2 |= (key[roundedEnd+10] & 0xffL) << 16;
case 10: k2 |= (key[roundedEnd+ 9] & 0xffL) << 8;
case 9: k2 |= (key[roundedEnd+ 8] & 0xffL);
k2 *= c2; k2 = Long.rotateLeft(k2, 33); k2 *= c1; h2 ^= k2;
case 8: k1 = ((long)key[roundedEnd+7]) << 56;
case 7: k1 |= (key[roundedEnd+6] & 0xffL) << 48;
case 6: k1 |= (key[roundedEnd+5] & 0xffL) << 40;
case 5: k1 |= (key[roundedEnd+4] & 0xffL) << 32;
case 4: k1 |= (key[roundedEnd+3] & 0xffL) << 24;
case 3: k1 |= (key[roundedEnd+2] & 0xffL) << 16;
case 2: k1 |= (key[roundedEnd+1] & 0xffL) << 8;
case 1: k1 |= (key[roundedEnd ] & 0xffL);
k1 *= c1; k1 = Long.rotateLeft(k1,31); k1 *= c2; h1 ^= k1;
}
//----------
// finalization
h1 ^= len; h2 ^= len;
h1 += h2;
h2 += h1;
h1 = fmix64(h1);
h2 = fmix64(h2);
h1 += h2;
h2 += h1;
out.val1 = h1;
out.val2 = h2;
}
}
| 11,957 | Java | .java | EdwardRaff/jLZJD | 17 | 6 | 1 | 2017-05-24T03:31:07Z | 2017-09-17T23:32:30Z |
Main.java | /FileExtraction/Java_unseen/EdwardRaff_jLZJD/src/main/java/com/edwardraff/jlzjd/Main.java | package com.edwardraff.jlzjd;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.converters.FileConverter;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.file.Files;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.IntStream;
import jsat.utils.SystemInfo;
/**
*
* @author Edward Raff <[email protected]>
*/
public class Main
{
@Parameter(names = { "-t", "--threshold" }, description = "only show results >=threshold")
public Integer threshold = 20;
@Parameter(names = { "-r", "--deep" }, description = "generate SDBFs from directories and files")
private boolean goDeep = false;
@Parameter(names = { "-g", "--gen-compare" }, description = "generate SDBFs and compare all pairs")
private boolean genCompare = false;
@Parameter(names = { "-p", "--threads" }, description = "compute threads to use")
public Integer threads = SystemInfo.LogicalCores;
public Integer minhashSize = 1024;
/**
* This will hold the indexes we are supposed to compare
*/
@Parameter(names = { "-c", "--compare" }, description = "compare all pairs in SDBF file, or compare two SDBF files to each other")
private boolean toCompare = false;
@Parameter(names = { "-o", "--output" }, description = "send output to files", converter = FileConverter.class)
public File alt_output = new File("");
/**
* This will hold default inputs we should parse
*/
@Parameter(converter = FileConverter.class)
private List<File> parameters = new ArrayList<>();
//Tools used for parallel execution
private static ExecutorService ex;
/**
* Multiplier applied to the number of problem sub-components created. Done
* so that work-stealing pool can do load balancing for us
*/
private static final int P_MUL = 500;
private static final ReentrantLock stdOutLock = new ReentrantLock();
/**
* This list provides a place for ALL StringBuilders used by any and all
* threads.
*/
private static final ConcurrentLinkedQueue<StringBuilder> localOutPuts = new ConcurrentLinkedQueue<>();
/**
* Access to thread local string builder to place text you want to put to
* STD out, but can't because its under contention
*/
private static final ThreadLocal<StringBuilder> localToStdOut = ThreadLocal.withInitial(() ->
{
StringBuilder sb = new StringBuilder();
localOutPuts.add(sb);
return sb;
});
public static void main(String... args) throws IOException, InterruptedException
{
new Main().run(args);
}
public void run(String... args) throws IOException, InterruptedException
{
JCommander jc = new JCommander(this);
jc.parse(args);
ex = Executors.newWorkStealingPool(Math.max(1, threads));
if(!alt_output.getPath().equals(""))
System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(alt_output)), true));
//collect all the files we will be hashing
List<File> toHash = new ArrayList<>();
for(File candidate : parameters)
if(candidate.isFile())
toHash.add(candidate);
else if(candidate.isDirectory() && goDeep)
Files.walk(candidate.toPath()).filter(Files::isRegularFile).forEach(c -> toHash.add(c.toFile()));
if(toCompare)
{
if(parameters.size() > 2 || parameters.isEmpty())
throw new IllegalArgumentException("Can only compare at most two indexes at a time!");
List<int[]> hashesA = new ArrayList<>();
List<String> filesA = new ArrayList<>();
List<int[]> hashesB = new ArrayList<>();
List<String> filesB = new ArrayList<>();
readHashesFromFile(parameters.get(0), hashesA, filesA);
if(parameters.size() == 2)
readHashesFromFile(parameters.get(1), hashesB, filesB);
else
{
hashesB = hashesA;
filesB = filesA;
}
compare(hashesA, filesA, hashesB, filesB);
}
else if(genCompare)
genComp(toHash);
else
hashFiles(toHash);
ex.shutdownNow();
}
/**
* Perform comparisons of the given digests lists. If each list points to
* the same object, only the above-diagonal elements of the comparison
* matrix will be performed
*
* @param hashesA the list of min-hashes for the first set, ordered
* @param filesA the list of file names for the first set, ordered
* @param hashesB the list of min-hashes for the second set, ordered
* @param filesB the list of file names for the first set, ordered
* @throws InterruptedException
*/
public void compare(List<int[]> hashesA, List<String> filesA, List<int[]> hashesB, List<String> filesB) throws InterruptedException
{
CountDownLatch latch = new CountDownLatch(hashesA.size());
for(int i = 0; i < hashesA.size(); i++)
{
int[] hAiH = hashesA.get(i);
String hAiN = filesA.get(i);
int j_start;
if(hashesA == hashesB)
j_start = i+1;//don't self compare / repeat comparisons
else
j_start = 0;
ex.submit(() ->
{
for(int j = j_start; j < hashesB.size(); j++)
{
int sim = (int) Math.round(100*LZJDf.similarity(hAiH, hashesB.get(j)));
if(sim >= threshold)
{
StringBuilder toPrint = localToStdOut.get();
toPrint.append(String.format(hAiN + "|" + filesB.get(j) + "|%03d\n", sim));
tryPrint(toPrint);
}
}
latch.countDown();
});
}
latch.await();
printAllLocalBuffers();
}
private void readHashesFromFile(File f, List<int[]> hashesA, List<String> files) throws IOException
{
try(BufferedReader br = new BufferedReader(new FileReader(f)))
{
String line;
while((line = br.readLine()) != null)
{
line = line.trim();
if(line.isEmpty())
continue;
int colonIndx = line.lastIndexOf(":");
String name = line.substring("lzjd:".length(), colonIndx);
String b64 = line.substring(colonIndx+1);
byte[] cmp = Base64.getDecoder().decode(b64);
int hashLen = cmp.length/Integer.SIZE;
int[] hash = new int[hashLen];
IntBuffer readBack = ByteBuffer.wrap(cmp).asIntBuffer();
for(int i = 0; i < hash.length; i++)
hash[i] = readBack.get(i);
hashesA.add(hash);
files.add(name);
}
}
}
/**
* Digest and print out the hashes for the given list of files
* @param toHash the list of files to digest
* @throws IOException
* @throws InterruptedException
*/
private void hashFiles(List<File> toHash) throws IOException, InterruptedException
{
ThreadLocal<byte[]> localTmpSpace = ThreadLocal.withInitial(()->new byte[minhashSize*Integer.BYTES]);
CountDownLatch latch = new CountDownLatch(SystemInfo.LogicalCores*P_MUL);
IntStream.range(0, SystemInfo.LogicalCores * P_MUL).forEach(id->
{
ex.submit(() ->
{
for (int i = id; i < toHash.size(); i += SystemInfo.LogicalCores * P_MUL)
{
try
{
File f = toHash.get(i);
LZJDf.min_hashes.clear();//hacky, but I don't really care
int[] hash = LZJDf.getMinHash(-1, f, (int) Math.min(minhashSize, f.length()/2));
byte[] byte_tmp_space = localTmpSpace.get();
ByteBuffer byteBuffer = ByteBuffer.wrap(byte_tmp_space);
IntBuffer intBuffer = byteBuffer.asIntBuffer();
intBuffer.put(hash);
String b64 = Base64.getEncoder().encodeToString(byte_tmp_space);
StringBuilder toPrint = localToStdOut.get();
toPrint.append("lzjd:").append(f.toString()).append(":").append(b64).append("\n");
tryPrint(toPrint);
}
catch (IOException ex1)
{
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex1);
}
}
latch.countDown();
});
});
latch.await();
printAllLocalBuffers();
}
/**
* Go through every local string buffer and pring them all to std out.
*/
public void printAllLocalBuffers()
{
for(StringBuilder sb: localOutPuts)//make sure we print off everything!
{
System.out.print(sb.toString());
sb.setLength(0);
}
}
/**
* This will attempt to print out the locally built buffer of lines to send
* to STD out. Will update toPrint as appropriate if the attempt was
* successful
*
* @param toPrint the string buffer to print out
*/
public void tryPrint(StringBuilder toPrint)
{
if(stdOutLock.tryLock())
{
System.out.print(toPrint.toString());
toPrint.setLength(0);
stdOutLock.unlock();
}
else if(toPrint.length() > 1024*1024*10)//you have 10MB worth of ASCII? Just print already!
{
stdOutLock.lock();
try
{
System.out.print(toPrint.toString());
toPrint.setLength(0);
}
finally
{
stdOutLock.unlock();
}
}
}
/**
* Generate the set of digests and do the all pairs comparison at the same
* time.
*
* @param toHash the list of files to digest and compare
* @throws IOException
* @throws InterruptedException
*/
private void genComp(List<File> toHash) throws IOException, InterruptedException
{
int[][] hashes = new int[toHash.size()][minhashSize];
String[] names = new String[toHash.size()];
CountDownLatch latch = new CountDownLatch(SystemInfo.LogicalCores * P_MUL);
IntStream.range(0, SystemInfo.LogicalCores * P_MUL).forEach(id->
{
ex.submit(() ->
{
for (int i = id; i < toHash.size(); i += SystemInfo.LogicalCores * P_MUL)
{
try
{
File f = toHash.get(i);
LZJDf.min_hashes.clear();
int[] hash = LZJDf.getMinHash(-1, f, minhashSize);
hashes[i] = hash;
names[i] = f.toString();
}
catch (IOException ex1)
{
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex1);
}
}
latch.countDown();
});
});
latch.await();
List<int[]> hashList = Arrays.asList(hashes);
List<String> nameList = Arrays.asList(names);
compare(hashList, nameList, hashList, nameList);
}
}
| 12,277 | Java | .java | EdwardRaff/jLZJD | 17 | 6 | 1 | 2017-05-24T03:31:07Z | 2017-09-17T23:32:30Z |
IntSetNoRemove.java | /FileExtraction/Java_unseen/EdwardRaff_jLZJD/src/main/java/com/edwardraff/jlzjd/IntSetNoRemove.java |
package com.edwardraff.jlzjd;
import java.io.Serializable;
import java.util.*;
import static jsat.utils.ClosedHashingUtil.*;
/**
* A utility class for efficiently storing a set of integers. The implementation
* is based on Algorithm D (Open addressing with double hashing) from Knuth's
* TAOCP page 528.
*
* @author Edward Raff
*/
public class IntSetNoRemove extends AbstractSet<Integer> implements Serializable
{
private static final long serialVersionUID = -2175363824037596497L;
private static final int DEFAULT_CAPACITY = 8;
private float loadFactor;
private int used = 0;
/**
* true if occupied, false otherwise (i.e., free)
*/
private boolean[] status;
private int[] keys;
private final static boolean FREE = false;
private final static boolean OCCUPIED = true;
/**
* Creates a new empty integer set
*/
public IntSetNoRemove()
{
this(DEFAULT_CAPACITY);
}
/**
* Creates an empty integer set pre-allocated to store a specific number of
* items
*
* @param capacity the number of items to store
*/
public IntSetNoRemove(int capacity)
{
this(capacity, 0.75f);
}
/**
* Creates an empty integer set pre-allocated to store a specific number of
* items
*
* @param capacity the number of items to store
* @param loadFactor the maximum ratio of used to un-used storage
*/
public IntSetNoRemove(int capacity, float loadFactor)
{
this.loadFactor = loadFactor;
int size = getNextPow2TwinPrime((int) Math.max(capacity / loadFactor, 4));
status = new boolean[size];
keys = new int[size];
used = 0;
}
/**
* Creates a new set of integers from the given set
* @param set the set of integers to create a copy of
*/
public IntSetNoRemove(Set<Integer> set)
{
this(set.size());
for(Integer integer : set)
this.add(integer);
}
/**
* Creates a set of integers from the given collection
* @param collection a collection of integers to create a set from
*/
public IntSetNoRemove(Collection<Integer> collection)
{
this();
for(Integer integer : collection)
this.add(integer);
}
/**
* Gets the index of the given key. Based on that {@link #status} variable,
* the index is either the location to insert OR the location of the key.
*
* This method returns 2 integer table in the long. The lower 32 bits are
* the index that either contains the key, or is the first empty index.
*
* The upper 32 bits is the index of the first position marked as
* {@link #DELETED} either {@link Integer#MIN_VALUE} if no position was
* marked as DELETED while searching.
*
* @param key they key to search for
* @return the mixed long containing the index of the first DELETED position
* and the position that the key is in or the first EMPTY position found
*/
private int getIndex(int key)
{
//D1
final int hash = key & 0x7fffffff;
int i = hash % keys.length;
//D2
if(status[i] == FREE || keys[i] == key)
return i;
//D3
final int c = 1 + (hash % (keys.length -2));
while(true)//this loop will terminate
{
//D4
i -= c;
if(i < 0)
i += keys.length;
//D5
if( status[i] == FREE || keys[i] == key)
return i;
}
}
private void enlargeIfNeeded()
{
if(used < keys.length*loadFactor)
return;
//enlarge
final boolean[] oldSatus = status;
final int[] oldKeys = keys;
int newSize = getNextPow2TwinPrime(status.length*3/2);//it will actually end up doubling in size since we have twin primes spaced that was
status = new boolean[newSize];
keys = new int[newSize];
used = 0;
for(int oldIndex = 0; oldIndex < oldSatus.length; oldIndex++)
if(oldSatus[oldIndex] == OCCUPIED)
add(oldKeys[oldIndex]);
}
@Override
public void clear()
{
used = 0;
Arrays.fill(status, FREE);
}
@Override
public boolean add(Integer e)
{
if(e == null)
return false;
return add(e.intValue());
}
/**
*
* @param e element to be added to this set
* @return true if this set did not already contain the specified element
*/
public boolean add(int e)
{
final int key = e;
int pair_index = getIndex(key);
// int deletedIndex = (int) (pair_index >>> 32);
// int valOrFreeIndex = (int) (pair_index & INT_MASK);
int valOrFreeIndex = pair_index;
if(status[valOrFreeIndex] == OCCUPIED)//easy case
{
return false;//we already had this item in the set!
}
//else, not present
int i = valOrFreeIndex;
// if(deletedIndex >= 0)//use occupied spot instead
// i = deletedIndex;
status[i] = OCCUPIED;
keys[i] = key;
used++;
enlargeIfNeeded();
return true;//item was not in the set previously
}
public boolean contains(int o)
{
int index = getIndex(o);
return status[index] == OCCUPIED;//would be FREE if we didn't have the key
}
@Override
public boolean contains(Object o)
{
if(o != null && o instanceof Integer)
return contains(((Integer)o).intValue());
else
return false;
}
@Override
public Iterator<Integer> iterator()
{
//find the first starting inded
int START = 0;
while (START < status.length && status[START] != OCCUPIED)
START++;
if (START == status.length)
return Collections.emptyIterator();
final int startPos = START;
return new Iterator<Integer>()
{
int pos = startPos;
int prevPos = -1;
@Override
public boolean hasNext()
{
return pos < status.length;
}
@Override
public Integer next()
{
//final int make so that object remains good after we call next again
final int oldPos = prevPos = pos++;
//find next
while (pos < status.length && status[pos] != OCCUPIED)
pos++;
//and return new object
return keys[oldPos];
}
@Override
public void remove()
{
throw new UnsupportedOperationException();
}
};
}
@Override
public int size()
{
return used;
}
}
| 7,040 | Java | .java | EdwardRaff/jLZJD | 17 | 6 | 1 | 2017-05-24T03:31:07Z | 2017-09-17T23:32:30Z |
LZJDf.java | /FileExtraction/Java_unseen/EdwardRaff_jLZJD/src/main/java/com/edwardraff/jlzjd/LZJDf.java | package com.edwardraff.jlzjd;
import com.google.common.collect.Ordering;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import jsat.classifiers.DataPoint;
import jsat.distributions.kernels.KernelTrick;
import jsat.linear.DenseVector;
import jsat.linear.Vec;
import jsat.linear.distancemetrics.DistanceMetric;
import jsat.parameters.Parameter;
import jsat.utils.IntList;
/**
*
* @author Edward Raff
*/
public class LZJDf implements DistanceMetric, KernelTrick
{
static final ConcurrentMap<File, Integer> files = new ConcurrentHashMap<>();
static final AtomicInteger file_counter = new AtomicInteger();
static final ConcurrentMap<Integer, int[]> min_hashes = new ConcurrentHashMap<>();
static ThreadLocal<HashSet<ByteBuffer>> localSets = ThreadLocal.withInitial(() -> new HashSet<>());
static ThreadLocal<byte[]> localByteBuffer = ThreadLocal.withInitial(() -> new byte[4*1024]);
public static int min_hash_size = 1024;
static final ThreadLocal<IntList> LOCAL_INT_LIST = ThreadLocal.withInitial(()->new IntList());
static final ThreadLocal<IntSetNoRemove> LOCAL_X_SET = ThreadLocal.withInitial(()->new IntSetNoRemove(1024, 0.65f));
/**
* Fills a set of ByteBuffers according the the LZ algorithm. Returns the
* set as a list of unique integer hashes found.
*
* @param ints the location t store all of the integer hashes of the sub-sequences
* @param is the byte source to hash
*/
private static void getAllHashes(IntList ints, InputStream is) throws IOException
{
IntSetNoRemove x_set = LOCAL_X_SET.get();
x_set.clear();
MurmurHash3 running_hash = new MurmurHash3();
int pos = 0;
int end = 0;
byte[] buffer = localByteBuffer.get();
while(true)
{
if(end == pos)//we need more bytes!
{
end = is.read(buffer);
if(end < 0)
break;//EOF, we are done
pos = 0;
}
//else, procceed
int hash = running_hash.pushByte(buffer[pos++]);
if(x_set.add(hash))
{//never seen it before, put it in!
ints.add(hash);
running_hash.reset();
}
}
}
/**
* Obtains a min-hash set for the given input file
* @param indx the unique index assigned for this file
* @param x_file the file to get the LZJDf min-hash of
* @param min_hash_size the max size for the min-hash
* @return an int array of the min-hash values in sorted order
* @throws IOException
*/
protected static int[] getMinHash(int indx, File x_file, int min_hash_size) throws IOException
{
int[] x_minset = min_hashes.get(indx);
if(x_minset == null)
{
try(FileInputStream fis = new FileInputStream(x_file))
{
IntList hashes = LOCAL_INT_LIST.get();
hashes.clear();
getAllHashes(hashes, fis);
List<Integer> sub_hashes = Ordering.natural().leastOf(hashes, Math.min(min_hash_size, hashes.size()));
x_minset = new int[sub_hashes.size()];
for(int i = 0; i < x_minset.length; i++)
x_minset[i] = sub_hashes.get(i);
Arrays.sort(x_minset);
min_hashes.putIfAbsent(indx, x_minset);
}
}
return x_minset;
}
/**
* Obtains a DataPoint object for the given file, which stores a representation that can be used with this distance metric
* @param f the file to get a min-hash for
* @return a DataPoint that will correspond to the given file
*/
public static DataPoint getDPforFile(File f)
{
int id;
id = file_counter.getAndIncrement();
files.put(f, id);
DenseVector dv = new DenseVector(1);
dv.set(0, id);
try
{
getMinHash(id, f, min_hash_size);
}
catch (IOException ex)
{
Logger.getLogger(LZJDf.class.getName()).log(Level.SEVERE, null, ex);
}
return new DataPoint(dv);
}
/**
* Obtains a DataPoint object for the given file, which stores a representation that can be used with this distance metric
* @param f the file to get a min-hash for
* @return a DataPoint that will correspond to the given file
*/
public static int[] getMHforFile(File f)
{
int id;
id = file_counter.getAndIncrement();
files.put(f, id);
DenseVector dv = new DenseVector(1);
dv.set(0, id);
try
{
return getMinHash(id, f, min_hash_size);
}
catch (IOException ex)
{
Logger.getLogger(LZJDf.class.getName()).log(Level.SEVERE, null, ex);
}
return new int[0];
}
@Override
public boolean isSymmetric()
{
return true;
}
@Override
public boolean isSubadditive()
{
return true;
}
@Override
public boolean isIndiscemible()
{
return true;
}
@Override
public double metricBound()
{
return 1;
}
@Override
public boolean supportsAcceleration()
{
return false;
}
@Override
public List<Double> getAccelerationCache(List<? extends Vec> vecs)
{
return null;
}
@Override
public List<Double> getAccelerationCache(List<? extends Vec> vecs, ExecutorService threadpool)
{
return null;
}
@Override
public double dist(Vec a, Vec b)
{
int x = (int) a.get(0);
int y = (int) b.get(0);
try
{
int[] x_minset = getMinHash(x, null, min_hash_size);
int[] y_minset = getMinHash(y, null, min_hash_size);
return dist(x_minset, y_minset);
}
catch (IOException ex)
{
Logger.getLogger(LZJDf.class.getName()).log(Level.SEVERE, null, ex);
}
return 1;
}
public static double dist(int[] x_minset, int[] y_minset)
{
double sim = similarity(x_minset, y_minset);
return 1.0 - sim;
}
public static double similarity(int[] x_minset, int[] y_minset)
{
int same = 0;
int x_pos = 0, y_pos = 0;
while(x_pos < x_minset.length && y_pos < y_minset.length)
{
int x_v = x_minset[x_pos];
int y_v = y_minset[y_pos];
if(x_v == y_v)
{
same++;
x_pos++;
y_pos++;
}
else if(x_v < y_v)
x_pos++;
else
y_pos++;
}
double sim = same / (double) (x_minset.length + y_minset.length - same);
return sim;
}
@Override
public double dist(int a, int b, List<? extends Vec> vecs, List<Double> cache)
{
return dist(vecs.get(a), vecs.get(b));
}
@Override
public double dist(int a, Vec b, List<? extends Vec> vecs, List<Double> cache)
{
return dist(vecs.get(a), b);
}
@Override
public List<Double> getQueryInfo(Vec q)
{
return null;
}
@Override
public double dist(int a, Vec b, List<Double> qi, List<? extends Vec> vecs, List<Double> cache)
{
return dist(vecs.get(a), b);
}
@Override
public LZJDf clone()
{
return this;
}
@Override
public double eval(Vec a, Vec b) {
return 1-dist(a, b);
}
@Override
public void addToCache(Vec newVec, List<Double> cache) {
}
@Override
public double eval(int a, Vec b, List<Double> qi, List<? extends Vec> vecs, List<Double> cache) {
return 1-dist(a, b, qi, vecs, cache);
}
@Override
public double eval(int a, int b, List<? extends Vec> trainingSet, List<Double> cache) {
return 1-dist(a, b, trainingSet, cache);
}
@Override
public double evalSum(List<? extends Vec> finalSet, List<Double> cache, double[] alpha, Vec y, int start, int end) {
double dot = 0;
for(int i = 0; i < alpha.length; i++)
if(alpha[i] != 0)
dot += alpha[i] * eval(i, y, null, finalSet, cache);
return dot;
}
@Override
public double evalSum(List<? extends Vec> finalSet, List<Double> cache, double[] alpha, Vec y, List<Double> qi, int start, int end) {
double dot = 0;
for(int i = 0; i < alpha.length; i++)
if(alpha[i] != 0)
dot += alpha[i] * eval(i, y, qi, finalSet, cache);
return dot;
}
@Override
public boolean normalized() {
return true;
}
@Override
public List<Parameter> getParameters() {
return Collections.EMPTY_LIST;
}
@Override
public Parameter getParameter(String paramName) {
return null;
}
}
| 9,488 | Java | .java | EdwardRaff/jLZJD | 17 | 6 | 1 | 2017-05-24T03:31:07Z | 2017-09-17T23:32:30Z |
AESUtilsTest.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/test/java/com/hyd/pass/utils/AESUtilsTest.java | package com.hyd.pass.utils;
import org.junit.jupiter.api.Test;
/**
* (description)
* created at 2018/2/6
*
* @author yidin
*/
public class AESUtilsTest {
@Test
public void testEncodeDecode() throws Exception {
String content = "1932年1月28日,日軍向閘北進攻,國軍堅決抵抗,第一次淞滬戰爭爆發," +
"正當蔣介石準備大量調集國軍與日作戰時,2月4日彭德懷率紅三和紅四軍攻打江西贛州," +
"歷時33天,拖住蔣五萬大軍無法增援上海,3月3日中日停戰。 3月7日在國軍守城部隊" +
"的抵抗和援軍的反擊下,紅軍攻城失敗。";
System.out.println(content);
String key = "12345678";
String encoded = AESUtils.encode128(content, key);
System.out.println(encoded);
String decoded = AESUtils.decode128(encoded, key);
System.out.println(decoded);
}
} | 991 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
TableViewSortTest.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/test/java/com/hyd/pass/fxtests/TableViewSortTest.java | package com.hyd.pass.fxtests;
import com.hyd.fx.builders.TableViewBuilder;
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import java.util.function.Function;
/**
* @author yiding_he
*/
public class TableViewSortTest extends Application {
private TableView<String> tableView = new TableView<>();
{
TableViewBuilder.of(tableView)
.addStrColumn("value", Function.identity());
}
@Override
public void start(Stage primaryStage) throws Exception {
tableView.getItems().addAll("111", "222", "333", "555", "444");
tableView.setOnSort(event -> {
ObservableList<TableColumn<String, ?>> sortOrder = event.getSource().getSortOrder();
sortOrder.forEach(c -> {
System.out.println(c.getText() + " - " + c.getSortType());
});
System.out.println(tableView.getItems());
});
primaryStage.setScene(new Scene(new BorderPane(tableView), 400, 300));
primaryStage.show();
}
}
| 1,262 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
UserConfigTest.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/test/java/com/hyd/pass/conf/UserConfigTest.java | package com.hyd.pass.conf;
/**
* (description)
* created at 2017/7/6
*
* @author yidin
*/
public class UserConfigTest {
public static void main(String[] args) {
System.out.println(System.getProperty("user.home"));
UserConfig.setString("name", "heyiding");
System.out.println(UserConfig.getString("name", ""));
}
}
| 369 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
Logger.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/main/java/com/hyd/pass/Logger.java | package com.hyd.pass;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
/**
* 支持 logback, log4j 和 log4j2 的日志框架
* 使用方法:
* <pre>
* Logger LOG = Logger.getLogger(this.getClass());
* LOG.debug("Hello!");
* </pre>
* 本类会自动检测是否存在三个日志框架之一,如果检测到则使用该框架来记录日志。
* 如果有多个框架同时存在,可以指定使用哪一个。以 logback 为例,方法是:
* <pre>
* Logger.setLoggerFactory(Logger.LOGBACK_FACTORY);
* </pre>
* 如果没有指定使用哪个框架,则按照 logback, log4j, log4j2 的顺序检测。
* 如果没有外部框架,则使用 java.util.logging。
*
* @author Yiding
*/
public class Logger {
public interface LoggerFactory {
Object getLogger(String loggerName);
LoggerType getLoggerType();
}
public static final LoggerFactory LOGBACK_FACTORY = new LoggerFactory() {
public Object getLogger(String loggerName) {
return executeMethod(null, "org.slf4j.LoggerFactory", "getLogger",
new Object[]{loggerName}, new Class[]{String.class});
}
public LoggerType getLoggerType() {
return LoggerType.LOGBACK;
}
};
public static final LoggerFactory LOG4J_FACTORY = new LoggerFactory() {
public Object getLogger(String loggerName) {
return executeMethod(null, "org.apache.log4j.Logger", "getLogger",
new Object[]{loggerName}, new Class[]{String.class});
}
public LoggerType getLoggerType() {
return LoggerType.LOG4J;
}
};
public static final LoggerFactory LOG4J2_FACTORY = new LoggerFactory() {
public Object getLogger(String loggerName) {
return executeMethod(null, "org.apache.logging.log4j.LogManager", "getLogger",
new Object[]{loggerName}, new Class[]{String.class});
}
public LoggerType getLoggerType() {
return LoggerType.LOG4J2;
}
};
public static final LoggerFactory JDK_FACTORY = new LoggerFactory() {
public Object getLogger(String loggerName) {
return java.util.logging.Logger.getLogger(loggerName);
}
public LoggerType getLoggerType() {
return LoggerType.JDK;
}
};
//////////////////////////////////////////////////////////////// reflection methods
private static Class<?> cls(String className) {
try {
return Class.forName(className);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
public static Object executeMethod(
Object obj, String className, String methodName, Object[] args, Class[] types) {
try {
Class<?> type = Class.forName(className);
Method method = type.getMethod(methodName, types);
return method.invoke(obj, args);
} catch (Exception e) {
System.err.println(obj + ", " + className + ", " + methodName + ", "
+ Arrays.toString(args) + ", " + Arrays.toString(types));
throw new RuntimeException(e);
}
}
private static Object member(Object obj, String className, String memberName) {
try {
Class<?> type = Class.forName(className);
Field field = type.getField(memberName);
return field.get(obj);
} catch (Exception e) {
return null;
}
}
private static Object create(String className, Object[] args, Class[] types) {
try {
Class<?> type = Class.forName(className);
return type.getConstructor(types).newInstance(args);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
////////////////////////////////////////////////////////////////
public enum Level {
Trace, Debug, Info, Warn, Error,;
}
public enum LoggerType {
LOGBACK("ch.qos.logback.classic.Logger", new Object[]{0, 10, 20, 30, 40}),
LOG4J(
"org.apache.log4j.Logger", new Object[]{
member(null, "org.apache.log4j.Level", "TRACE"),
member(null, "org.apache.log4j.Level", "DEBUG"),
member(null, "org.apache.log4j.Level", "INFO"),
member(null, "org.apache.log4j.Level", "WARN"),
member(null, "org.apache.log4j.Level", "ERROR")
}),
LOG4J2("org.apache.logging.log4j.core.Logger", new Object[]{
member(null, "org.apache.logging.log4j.Level", "TRACE"),
member(null, "org.apache.logging.log4j.Level", "DEBUG"),
member(null, "org.apache.logging.log4j.Level", "INFO"),
member(null, "org.apache.logging.log4j.Level", "WARN"),
member(null, "org.apache.logging.log4j.Level", "ERROR")
}),
JDK("java.util.logging.Logger", new Object[]{
java.util.logging.Level.FINER,
java.util.logging.Level.FINE,
java.util.logging.Level.INFO,
java.util.logging.Level.WARNING,
java.util.logging.Level.SEVERE
}),;
public final String checkClass;
public final Object trace;
public final Object debug;
public final Object info;
public final Object warn;
public final Object error;
private boolean enabled;
LoggerType(String checkClass, Object[] levelObjects) {
this.checkClass = checkClass;
this.trace = levelObjects[0];
this.debug = levelObjects[1];
this.info = levelObjects[2];
this.warn = levelObjects[3];
this.error = levelObjects[4];
try {
Class.forName(checkClass);
this.enabled = true;
} catch (ClassNotFoundException e) {
this.enabled = false;
}
}
public boolean enabled() {
return enabled;
}
public Object levelObj(Level level) {
if (level == Level.Trace) {
return trace;
} else if (level == Level.Debug) {
return debug;
} else if (level == Level.Info) {
return info;
} else if (level == Level.Warn) {
return warn;
} else if (level == Level.Error) {
return error;
}
return null;
}
}
////////////////////////////////////////////////////////////////
private static LoggerFactory loggerFactory;
// 设置自定义的 LoggerFactory
public static void setLoggerFactory(LoggerFactory loggerFactory) {
Logger.loggerFactory = loggerFactory;
}
public static LoggerType getLoggerType() {
return loggerFactory == null ? null : loggerFactory.getLoggerType();
}
public static Logger getLogger(String loggerName) {
if (loggerFactory == null) {
autoDetect();
}
if (loggerFactory == null) {
throw new RuntimeException("没有找到支持的日志框架(logback/log4j/log4j2)");
}
Logger l = new Logger();
l.logger = loggerFactory.getLogger(loggerName);
l.type = loggerFactory.getLoggerType();
return l;
}
private synchronized static void autoDetect() {
for (LoggerType loggerType : LoggerType.values()) {
if (loggerType.enabled()) {
if (loggerType == LoggerType.LOGBACK) {
loggerFactory = LOGBACK_FACTORY;
} else if (loggerType == LoggerType.LOG4J) {
loggerFactory = LOG4J_FACTORY;
} else if (loggerType == LoggerType.LOG4J2) {
loggerFactory = LOG4J2_FACTORY;
} else if (loggerType == LoggerType.JDK) {
loggerFactory = JDK_FACTORY;
}
return;
}
}
}
public static Logger getLogger(Class<?> type) {
return getLogger(type.getName());
}
private static final Object[] EMPTY_ARR = new Object[]{};
////////////////////////////////////////////////////////////////
private Object logger;
private LoggerType type;
public Object getLogger() {
return logger;
}
private void logLogback(Object message, Object level, Throwable throwable) {
if (logger == null) {
return;
}
executeMethod(logger, "org.slf4j.spi.LocationAwareLogger", "log",
new Object[]{null, Logger.class.getName(), level, message, EMPTY_ARR, throwable},
new Class[]{cls("org.slf4j.Marker"), String.class, Integer.TYPE, String.class,
EMPTY_ARR.getClass(), Throwable.class});
}
private void logLog4j(Object message, Object level, Throwable throwable) {
if (logger == null) {
return;
}
executeMethod(logger, "org.apache.log4j.Category", "log",
new Object[]{Logger.class.getName(), level, message, throwable},
new Class[]{String.class, cls("org.apache.log4j.Priority"), Object.class, Throwable.class});
}
private void logLog4j2(Object message, Object level, Throwable throwable) {
if (logger == null) {
return;
}
Class<?> levelClass = cls("org.apache.logging.log4j.Level");
Class<?> messageClass = cls("org.apache.logging.log4j.message.Message");
Class<?> markerClass = cls("org.apache.logging.log4j.Marker");
Object msg = create("org.apache.logging.log4j.message.SimpleMessage",
new Object[]{message}, new Class[]{String.class});
executeMethod(logger, "org.apache.logging.log4j.core.Logger", "logMessage",
new Object[]{Logger.class.getName(), level, null, msg, throwable},
new Class[]{String.class, levelClass, markerClass, messageClass, Throwable.class});
}
private void logJdk(Object message, Object level, Throwable throwable) {
if (logger == null) {
return;
}
java.util.logging.Logger l = (java.util.logging.Logger) logger;
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
// 在堆栈中向下找,找到退出本 Logger 类的地方
int pointer = 0;
while (pointer < stackTrace.length && !stackTrace[pointer].getClassName().equals(this.getClass().getName())) {
pointer++;
}
while (pointer < stackTrace.length && stackTrace[pointer].getClassName().equals(this.getClass().getName())) {
pointer++;
}
String sourceClassName = this.getClass().getName();
String sourceMethodName = "logJDK";
if (pointer < stackTrace.length) {
sourceClassName = stackTrace[pointer].getClassName();
sourceMethodName = stackTrace[pointer].getMethodName();
}
if (throwable != null) {
l.logp((java.util.logging.Level) level,
sourceClassName, sourceMethodName, String.valueOf(message), throwable);
} else {
l.logp((java.util.logging.Level) level,
sourceClassName, sourceMethodName, String.valueOf(message));
}
}
private void log(Object level, Object message, Throwable t) {
if (type == LoggerType.LOGBACK) {
logLogback(message, level, t);
} else if (type == LoggerType.LOG4J) {
logLog4j(message, level, t);
} else if (type == LoggerType.LOG4J2) {
logLog4j2(message, level, t);
} else if (type == LoggerType.JDK) {
logJdk(message, level, t);
}
}
public void trace(Object message) {
log(type.trace, message, null);
}
public void trace(Object message, Throwable t) {
log(type.trace, message, t);
}
public void debug(Object message) {
log(type.debug, message, null);
}
public void debug(Object message, Throwable t) {
log(type.debug, message, t);
}
public void info(Object message) {
log(type.info, message, null);
}
public void info(Object message, Throwable t) {
log(type.info, message, t);
}
public void warn(Object message) {
log(type.warn, message, null);
}
public void warn(Object message, Throwable t) {
log(type.warn, message, t);
}
public void error(Object message) {
log(type.error, message, null);
}
public void error(Object message, Throwable t) {
log(type.error, message, t);
}
public boolean isEnabled(Level level) {
String methodName = "is" + level + "Enabled";
if (type == LoggerType.LOGBACK) {
return (Boolean) executeMethod(logger, "org.slf4j.Logger", methodName, null, null);
} else if (type == LoggerType.LOG4J) {
return (Boolean) executeMethod(logger, "org.apache.log4j.Logger", methodName, null, null);
} else if (type == LoggerType.LOG4J2) {
return (Boolean) executeMethod(logger, "org.apache.logging.log4j.Logger", methodName, null, null);
} else if (type == LoggerType.JDK) {
return ((java.util.logging.Logger) logger).isLoggable((java.util.logging.Level) type.levelObj(level));
}
throw new IllegalStateException("Unsupported logger type '" + type + "'");
}
}
| 14,059 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
App.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/main/java/com/hyd/pass/App.java | package com.hyd.pass;
import com.hyd.fx.app.AppPrimaryStage;
import com.hyd.fx.dialog.FileDialog;
import com.hyd.pass.fx.Icons;
import com.hyd.pass.model.Category;
import com.hyd.pass.model.Entry;
import com.hyd.pass.model.PasswordLib;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.io.File;
import java.util.Timer;
/**
* JVM parameters need to be added at runtime:
* <pre>
* --module-path [local path javafx-sdk-20.0.1\lib]
* --add-modules javafx.controls
* --add-exports javafx.base/com.sun.javafx.binding=ALL-UNNAMED
* --add-exports javafx.base/com.sun.javafx.reflect=ALL-UNNAMED
* --add-exports javafx.base/com.sun.javafx.beans=ALL-UNNAMED
* --add-exports javafx.controls/com.sun.javafx.scene.control.behavior=ALL-UNNAMED
* --add-exports javafx.controls/com.sun.javafx.scene.control=ALL-UNNAMED
* --add-exports javafx.graphics/com.sun.javafx.stage=ALL-UNNAMED
* --add-exports javafx.graphics/com.sun.javafx.util=ALL-UNNAMED
* </pre>
*/
@SpringBootApplication
public class App extends Application {
public static final String APP_NAME = "Hydrogen Pass 密码管理";
public static final String FILE_EXT = "*.hpass";
public static final String FILE_EXT_NAME = "HPass 密码库";
public static final boolean IS_DEV = Boolean.parseBoolean(System.getProperty("dev", "false"));
public static final Timer TIMER = new Timer(true);
private static PasswordLib passwordLib;
public static void setPasswordLib(PasswordLib passwordLib) {
App.passwordLib = passwordLib;
}
public static PasswordLib getPasswordLib() {
return passwordLib;
}
public static void setPasswordLibChanged() {
if (passwordLib != null) {
passwordLib.setChanged(true);
}
}
public static void main(String[] args) {
SpringApplication.run(App.class, args);
Application.launch(App.class, args);
}
@Override
public void start(Stage primaryStage) throws Exception {
AppPrimaryStage.setPrimaryStage(primaryStage);
FileDialog.setInitDirectory(new File("."));
Parent parent = FXMLLoader.load(getClass().getResource("/fxml/main.fxml"));
primaryStage.getIcons().add(Icons.Logo.getImage());
primaryStage.setTitle(APP_NAME);
primaryStage.setScene(new Scene(parent));
primaryStage.show();
}
////////////////////////////////////////////////////////////////////////////////
private static Category currentCategory;
private static Entry currentEntry;
public static Category getCurrentCategory() {
return currentCategory;
}
public static void setCurrentCategory(Category currentCategory) {
App.currentCategory = currentCategory;
}
public static Entry getCurrentEntry() {
return currentEntry;
}
public static void setCurrentEntry(Entry currentEntry) {
App.currentEntry = currentEntry;
}
}
| 3,300 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
EntryTableRow.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/main/java/com/hyd/pass/fx/EntryTableRow.java | package com.hyd.pass.fx;
import com.hyd.fx.app.AppPrimaryStage;
import com.hyd.fx.dialog.AlertDialog;
import com.hyd.fx.system.ClipboardHelper;
import com.hyd.pass.App;
import com.hyd.pass.dialogs.EntryInfoDialog;
import com.hyd.pass.model.Category;
import com.hyd.pass.model.Entry;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import java.util.List;
import static com.hyd.fx.builders.ImageBuilder.imageView;
import static com.hyd.fx.builders.MenuBuilder.*;
import static com.hyd.fx.system.ClipboardHelper.putApplicationClipboard;
import static com.hyd.pass.fx.AuthenticationTableRow.ENTRY_CLIP_KEY;
/**
* @author yidin
*/
public class EntryTableRow extends AbstractTableRow<Entry> {
private ContextMenu currentContextMenu;
@Override
ContextMenu createContextMenu() {
currentContextMenu = contextMenu(
menuItem("编辑入口...", imageView("/icons/edit.png", 16), this::editEntryClicked),
menuItem("复制入口", imageView("/icons/copy.png", 16), this::copyEntryClicked),
menuItem("删除入口", imageView("/icons/delete.png", 16), this::deleteEntryClicked)
);
List<String> locationList = this.getItem().locationAsList();
if (!locationList.isEmpty()) {
currentContextMenu.getItems().add(menu(
"复制地址",
imageView("/icons/copy.png", 16),
locationList.stream()
.map(l -> menuItem(l, () -> ClipboardHelper.putString(l)))
.toArray(MenuItem[]::new)
));
}
return currentContextMenu;
}
public EntryTableRow() {
}
@Override
void onDoubleClick() {
editEntryClicked();
}
private void copyEntryClicked() {
putApplicationClipboard(ENTRY_CLIP_KEY, this.getItem().clone());
}
private void deleteEntryClicked() {
if (AlertDialog.confirmYesNo("删除项", "确定要删除“" + getItem().getName() + "”吗?")) {
Category currentCategory = App.getCurrentCategory();
if (currentCategory != null) {
currentCategory.removeEntry(getItem());
getTableView().getItems().remove(getItem());
App.setPasswordLibChanged();
}
}
}
private void editEntryClicked() {
EntryInfoDialog dialog = new EntryInfoDialog(getItem());
dialog.setOwner(AppPrimaryStage.getPrimaryStage());
if (dialog.showAndWait().orElse(ButtonType.CANCEL) == ButtonType.OK) {
App.setPasswordLibChanged();
getTableView().refresh();
getTableView().sort();
}
}
}
| 2,743 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
AbstractTableRow.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/main/java/com/hyd/pass/fx/AbstractTableRow.java | package com.hyd.pass.fx;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.TableRow;
import javafx.scene.input.MouseButton;
public abstract class AbstractTableRow<T> extends TableRow<T> {
protected ContextMenu contextMenu;
public AbstractTableRow() {
setOnContextMenuRequested(event -> {
if (!isEmpty()) {
this.contextMenu = createContextMenu();
this.contextMenu.show(this, event.getScreenX(), event.getScreenY());
event.consume();
}
});
setOnMouseClicked(event -> {
if (event.getClickCount() == 2 && event.getButton() == MouseButton.PRIMARY) {
onDoubleClick();
} else if (event.getClickCount() == 1 && event.getButton() == MouseButton.PRIMARY && contextMenu != null) {
contextMenu.hide();
}
});
focusedProperty().addListener((ob, old, focused) -> {
if (!focused && contextMenu != null) {
contextMenu.hide();
}
});
}
abstract ContextMenu createContextMenu();
abstract void onDoubleClick();
}
| 1,165 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
CategoryTreeView.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/main/java/com/hyd/pass/fx/CategoryTreeView.java | package com.hyd.pass.fx;
import com.hyd.fx.helpers.TreeViewHelper;
import com.hyd.pass.model.Category;
import com.hyd.pass.model.Entry;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
/**
* (description)
* created at 2018/2/6
*
* @author yidin
*/
public class CategoryTreeView extends TreeView<Category> {
public CategoryTreeView() {
init();
}
public CategoryTreeView(TreeItem<Category> root) {
super(root);
init();
}
private void init() {
this.setCellFactory(tv -> new CategoryTreeCell());
}
public void deleteTreeItem(TreeItem<Category> treeItem) {
TreeViewHelper.iterate(this, item -> {
if (item.getChildren().contains(treeItem)) {
item.getChildren().remove(treeItem);
return false;
} else {
return true;
}
});
}
public void selectCellByEntry(Entry entry) {
TreeViewHelper.iterate(getRoot(), treeItem -> {
if (treeItem.getValue().containsEntry(entry)) {
getSelectionModel().select(treeItem);
return false;
}
return true;
});
}
}
| 1,278 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
CategoryTreeCell.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/main/java/com/hyd/pass/fx/CategoryTreeCell.java | package com.hyd.pass.fx;
import com.hyd.fx.app.AppPrimaryStage;
import com.hyd.fx.dialog.AlertDialog;
import com.hyd.pass.App;
import com.hyd.pass.dialogs.EditCategoryDialog;
import com.hyd.pass.dialogs.SortCategoryChildDialog;
import com.hyd.pass.model.Category;
import javafx.scene.control.*;
import static com.hyd.fx.builders.ImageBuilder.imageView;
import static com.hyd.fx.builders.MenuBuilder.contextMenu;
import static com.hyd.fx.builders.MenuBuilder.menuItem;
/**
* (description)
* created at 2018/2/6
*
* @author yidin
*/
public class CategoryTreeCell extends TreeCell<Category> {
private final ContextMenu contextMenu = contextMenu(
menuItem("编辑", imageView("/icons/edit.png", 16), this::editItem),
menuItem("新建分类... ", imageView("/icons/new.png", 16), this::createChild),
menuItem("子类排序... ", imageView("/icons/sort.png", 16), this::sortChild),
new SeparatorMenuItem(),
menuItem("删除", imageView("/icons/delete.png", 16), this::deleteItem)
);
private final ContextMenu rootContextMenu = contextMenu(
menuItem("编辑", imageView("/icons/edit.png", 16), this::editItem),
menuItem("新建分类... ", imageView("/icons/new.png", 16), this::createChild),
menuItem("子类排序... ", imageView("/icons/sort.png", 16), this::sortChild)
);
private void deleteItem() {
if (!AlertDialog.confirmYesNo("删除分类",
"确定要删除“" + getItem().getName() + "”及其下面的所有分类和内容吗?")) {
return;
}
App.getPasswordLib().deleteCategory(getItem());
((CategoryTreeView) getTreeView()).deleteTreeItem(getTreeItem());
}
private void sortChild() {
SortCategoryChildDialog dialog = new SortCategoryChildDialog(this.getTreeItem());
dialog.show();
}
private void createChild() {
EditCategoryDialog dialog = new EditCategoryDialog("编辑分类", "");
dialog.setOwner(AppPrimaryStage.getPrimaryStage());
ButtonType buttonType = dialog.showAndWait().orElse(ButtonType.CANCEL);
if (buttonType == ButtonType.OK) {
Category category = getItem().createChild(dialog.getCategoryName());
getTreeItem().getChildren().add(new TreeItem<>(category));
getTreeItem().setExpanded(true);
App.setPasswordLibChanged();
}
}
private void editItem() {
EditCategoryDialog dialog = new EditCategoryDialog("编辑分类", getItem().getName());
dialog.setOwner(AppPrimaryStage.getPrimaryStage());
ButtonType buttonType = dialog.showAndWait().orElse(ButtonType.CANCEL);
if (buttonType == ButtonType.OK) {
getItem().setName(dialog.getCategoryName());
getTreeView().refresh();
App.setPasswordLibChanged();
}
}
private ContextMenu getCurrentContextMenu() {
return isRoot() ? rootContextMenu : contextMenu;
}
private boolean isRoot() {
return getTreeItem() == getTreeView().getRoot();
}
public CategoryTreeCell() {
setOnContextMenuRequested(event -> {
if (!isEmpty()) {
getCurrentContextMenu()
.show(this, event.getScreenX(), event.getScreenY());
}
});
}
@Override
public void updateItem(Category item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
setGraphic(Icons.Folder.getIconImageView());
setText(item.getName());
}
}
}
| 3,823 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
TreeItemBuilder.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/main/java/com/hyd/pass/fx/TreeItemBuilder.java | package com.hyd.pass.fx;
import com.hyd.pass.model.Category;
import com.hyd.pass.model.Entry;
import com.hyd.pass.model.SearchItem;
import javafx.scene.control.CheckBoxTreeItem;
import javafx.scene.control.TreeItem;
public class TreeItemBuilder {
public static TreeItem<SearchItem> buildSearchItemTree(Category rootCategory) {
SearchItem.CategorySearchItem searchItem = new SearchItem.CategorySearchItem(rootCategory);
CheckBoxTreeItem<SearchItem> rootTreeItem = new CheckBoxTreeItem<>(searchItem);
rootTreeItem.setGraphic(Icons.Folder.getIconImageView());
rootTreeItem.setExpanded(true);
rootTreeItem.selectedProperty().addListener(
(ob, oldValue, newValue) -> searchItem.setSelected(newValue));
rootCategory.getChildren().forEach(
childCategory -> {
TreeItem<SearchItem> childTreeItem = buildSearchItemTree(childCategory);
rootTreeItem.getChildren().add(childTreeItem);
});
rootCategory.getEntries().forEach(childEntry -> {
TreeItem<SearchItem> childTreeItem = buildSearchItem(childEntry);
rootTreeItem.getChildren().add(childTreeItem);
});
return rootTreeItem;
}
private static TreeItem<SearchItem> buildSearchItem(Entry entry) {
SearchItem.EntrySearchItem searchItem = new SearchItem.EntrySearchItem(entry);
CheckBoxTreeItem<SearchItem> treeItem = new CheckBoxTreeItem<>(searchItem);
treeItem.setGraphic(Icons.Pc.getIconImageView());
treeItem.setExpanded(true);
treeItem.selectedProperty().addListener(
(ob, oldValue, newValue) -> searchItem.setSelected(newValue));
return treeItem;
}
}
| 1,814 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
Icons.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/main/java/com/hyd/pass/fx/Icons.java | package com.hyd.pass.fx;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
/**
* (description)
* created at 2017/7/6
*
* @author yidin
*/
public enum Icons {
Logo("/logo.png"),
Folder("/icons/folder.png"),
Pc("/icons/pc.png"),
//////////////////////////////////////////////////////////////
;
private Image image;
Icons(String imagePath) {
this.image = new Image(getClass().getResourceAsStream(imagePath));
}
public Image getImage() {
return image;
}
public ImageView getIconImageView() {
ImageView imageView = new ImageView(getImage());
imageView.setFitWidth(16);
imageView.setFitHeight(16);
return imageView;
}
}
| 782 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
AuthenticationTableRow.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/main/java/com/hyd/pass/fx/AuthenticationTableRow.java | package com.hyd.pass.fx;
import com.hyd.fx.app.AppPrimaryStage;
import com.hyd.fx.dialog.AlertDialog;
import com.hyd.fx.system.ClipboardHelper;
import com.hyd.pass.App;
import com.hyd.pass.dialogs.AuthenticationInfoDialog;
import com.hyd.pass.model.Authentication;
import com.hyd.pass.model.Entry;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.SeparatorMenuItem;
import static com.hyd.fx.builders.ImageBuilder.imageView;
import static com.hyd.fx.builders.MenuBuilder.contextMenu;
import static com.hyd.fx.builders.MenuBuilder.menuItem;
import static com.hyd.fx.system.ClipboardHelper.putApplicationClipboard;
/**
* @author yiding.he
*/
public class AuthenticationTableRow extends AbstractTableRow<Authentication> {
public static final String AUTH_CLIP_KEY = "copy_authentication";
public static final String ENTRY_CLIP_KEY = "copy_entry";
private final ContextMenu contextMenu = contextMenu(
menuItem("复制用户名", imageView("/icons/copy.png", 16), "Shortcut+X", this::copyUsernameClicked),
menuItem("复制密码", imageView("/icons/copy.png", 16), "Shortcut+C", this::copyPasswordClicked),
new SeparatorMenuItem(),
menuItem("复制账号", imageView("/icons/copy.png", 16), this::copyEntryClicked),
menuItem("编辑账号...", imageView("/icons/edit.png", 16), this::editEntryClicked),
menuItem("删除账号", imageView("/icons/delete.png", 16), this::deleteEntryClicked)
);
private void copyEntryClicked() {
putApplicationClipboard(AUTH_CLIP_KEY, this.getItem().clone());
}
public AuthenticationTableRow() {
}
@Override
ContextMenu createContextMenu() {
return contextMenu;
}
@Override
void onDoubleClick() {
editEntryClicked();
}
private void deleteEntryClicked() {
if (AlertDialog.confirmYesNo("删除登录", "确定要删除“" + getItem().getUsername() + "”吗?")) {
Entry currentEntry = App.getCurrentEntry();
if (currentEntry != null) {
currentEntry.getAuthentications().remove(getItem());
getTableView().getItems().remove(getItem());
App.setPasswordLibChanged();
}
}
}
private void editEntryClicked() {
AuthenticationInfoDialog dialog = new AuthenticationInfoDialog(getItem());
dialog.setOwner(AppPrimaryStage.getPrimaryStage());
if (dialog.showAndWait().orElse(ButtonType.CANCEL) == ButtonType.OK) {
App.setPasswordLibChanged();
getTableView().refresh();
getTableView().sort();
}
}
private void copyUsernameClicked() {
ClipboardHelper.putString(getItem().getUsername());
}
private void copyPasswordClicked() {
ClipboardHelper.putString(getItem().getPassword());
}
}
| 3,020 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
BaseController.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/main/java/com/hyd/pass/controllers/BaseController.java | package com.hyd.pass.controllers;
import com.hyd.fx.dialog.AlertDialog;
import com.hyd.pass.Logger;
/**
* (description)
* created at 2018/2/6
*
* @author yidin
*/
public abstract class BaseController {
private static final Logger logger = Logger.getLogger(BaseController.class);
protected interface Task {
void run() throws Exception;
}
protected void runSafe(Task task) {
try {
task.run();
} catch (Exception e) {
logger.error("", e);
AlertDialog.error("错误", e.toString());
}
}
}
| 611 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
MainController.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/main/java/com/hyd/pass/controllers/MainController.java | package com.hyd.pass.controllers;
import com.hyd.fx.NodeUtils;
import com.hyd.fx.app.AppPrimaryStage;
import com.hyd.fx.dialog.AlertDialog;
import com.hyd.fx.dialog.FileDialog;
import com.hyd.fx.system.ClipboardHelper;
import com.hyd.pass.App;
import com.hyd.pass.Logger;
import com.hyd.pass.conf.UserConfig;
import com.hyd.pass.dialogs.*;
import com.hyd.pass.fx.AuthenticationTableRow;
import com.hyd.pass.fx.CategoryTreeView;
import com.hyd.pass.fx.EntryTableRow;
import com.hyd.pass.model.*;
import com.hyd.pass.utils.OrElse;
import com.hyd.pass.utils.Str;
import javafx.application.Platform;
import javafx.beans.property.ReadOnlyObjectProperty;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.*;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.stage.WindowEvent;
import java.io.File;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.TimerTask;
import java.util.function.Consumer;
import static com.hyd.fx.helpers.TableViewHelper.setColumnValueFactory;
import static com.hyd.fx.system.ClipboardHelper.getApplicationClipboard;
import static com.hyd.pass.fx.AuthenticationTableRow.AUTH_CLIP_KEY;
import static com.hyd.pass.fx.AuthenticationTableRow.ENTRY_CLIP_KEY;
import static javafx.scene.control.TableColumn.SortType.ASCENDING;
import static javafx.scene.control.TableColumn.SortType.DESCENDING;
/**
* @author yiding.he
*/
public class MainController extends BaseController {
private static final Logger logger = Logger.getLogger(MainController.class);
public SplitPane split1;
public SplitPane split2;
public CategoryTreeView tvCategories;
public TableView<Entry> tblEntries;
public TableView<Authentication> tblAuthentications;
public Button btnNewEntry;
public Button btnNewLogin;
public TextArea txtNote;
public TabPane tpEntryInfo;
public TableColumn<Entry, String> colEntryName;
public TableColumn<Entry, String> colEntryLocation;
public TableColumn<Entry, String> colEntryCreateTime;
public TableColumn<Entry, String> colEntryComment;
public TableColumn<Authentication, String> colAuthUsername;
public TableColumn<Authentication, String> colAuthPassword;
public CheckMenuItem mnuAutoSave;
public CheckMenuItem mnuAutoOpen;
public CheckMenuItem mnuNoteWrap;
public MenuItem mnuPasteAuthentication;
public MenuItem mnuPasteEntry;
public MenuItem mnuExport;
public Label lblStatus;
public void initialize() {
this.split1.setDividerPositions(0.2);
this.split2.setDividerPositions(0.4);
////////////////////////////////////////////////////////////////////////////////
ObservableValue<TreeItem<Category>> selectedCategoryItem =
this.tvCategories.getSelectionModel().selectedItemProperty();
selectedCategoryItem.addListener(this::selectedCategoryChanged);
////////////////////////////////////////////////////////////////////////////////
setColumnValueFactory(colEntryName, Entry::getName);
setColumnValueFactory(colEntryLocation, Entry::getLocation);
setColumnValueFactory(colEntryCreateTime, Entry::getCreateTime);
setColumnValueFactory(colEntryComment, Entry::getComment);
this.tblEntries.setRowFactory(tv -> new EntryTableRow());
this.tblEntries.getSortOrder().add(colEntryName);
this.tblEntries.setOnSort(this::onEntryTableSort);
////////////////////////////////////////////////////////////////////////////////
ReadOnlyObjectProperty<Entry> selectedEntry =
this.tblEntries.getSelectionModel().selectedItemProperty();
selectedEntry.addListener(this::selectedEntryChanged);
this.txtNote.textProperty().addListener(this::noteTextChanged);
////////////////////////////////////////////////////////////////////////////////
setColumnValueFactory(colAuthUsername, Authentication::getUsername);
setColumnValueFactory(colAuthPassword, Authentication::getPassword);
this.tblAuthentications.setRowFactory(tv -> new AuthenticationTableRow());
this.tblAuthentications.getSortOrder().add(colAuthUsername);
////////////////////////////////////////////////////////////////////////////////
AppPrimaryStage.getPrimaryStage().setOnCloseRequest(this::beforeClose);
AppPrimaryStage.getPrimaryStage().addEventFilter(KeyEvent.KEY_PRESSED, this::keyEventHandler);
mnuAutoSave.setSelected(UserConfig.getBoolean("auto_save_on_exit", false));
mnuAutoOpen.setSelected(UserConfig.getBoolean("auto_open_on_start", false));
mnuNoteWrap.setSelected(UserConfig.getBoolean("note_wrap_text", false));
///////////////////////////////////////////////
tryAutoOpenRecentFile();
}
private void onEntryTableSort(SortEvent<TableView<Entry>> event) {
List<TableColumn<Entry, ?>> sortColumns = event.getSource().getSortOrder();
if (!sortColumns.isEmpty()) {
TableColumn<Entry, ?> column = sortColumns.get(0);
Category currentCategory = App.getCurrentCategory();
currentCategory.setSortBy(getSortByName(column));
currentCategory.setSortAscending(column.getSortType() != DESCENDING);
}
}
private void tryAutoOpenRecentFile() {
if (App.IS_DEV) {
return;
}
if (UserConfig.getBoolean("auto_open_on_start", false)) {
String filePath = Str.decodeUrl(UserConfig.getString("latest_file", ""));
if (Str.isNotBlank(filePath)) {
File file = new File(filePath);
if (file.exists() && file.canRead()) {
openPasswordLibFile(file);
}
}
}
}
private void keyEventHandler(KeyEvent event) {
if (this.tblAuthentications.isFocused()) {
if (event.isControlDown() && event.getCode() == KeyCode.X) {
withCurrentAuthentication(auth -> ClipboardHelper.putString(auth.getUsername()));
event.consume();
} else if (event.isControlDown() && event.getCode() == KeyCode.C) {
withCurrentAuthentication(auth -> ClipboardHelper.putString(auth.getPassword()));
event.consume();
}
}
}
public void openSearch() {
SearchDialog searchDialog = new SearchDialog();
searchDialog.setOwner(AppPrimaryStage.getPrimaryStage());
searchDialog.showAndWait();
Entry entry = searchDialog.getSelectedEntry();
if (entry != null) {
selectEntry(entry);
}
}
private void selectEntry(Entry entry) {
tvCategories.selectCellByEntry(entry);
tblEntries.getSelectionModel().select(entry);
tblEntries.scrollTo(entry);
tblEntries.requestFocus();
}
private void withCurrentAuthentication(Consumer<Authentication> consumer) {
Authentication item = this.tblAuthentications.getSelectionModel().getSelectedItem();
if (item != null) {
consumer.accept(item);
}
}
@SuppressWarnings("unused")
private void noteTextChanged(ObservableValue<? extends String> ob, String _old, String text) {
if (NodeUtils.getUserData(this.txtNote, "muteChange") != null) {
return;
}
Entry currentEntry = App.getCurrentEntry();
if (currentEntry != null) {
currentEntry.setNote(text);
App.setPasswordLibChanged();
}
}
@SuppressWarnings("unused")
private void selectedCategoryChanged(
ObservableValue<? extends TreeItem<Category>> ob,
TreeItem<Category> _old,
TreeItem<Category> selected) {
App.setCurrentCategory(selected == null ? null : selected.getValue());
this.btnNewEntry.setDisable(selected == null);
this.tblEntries.setDisable(selected == null);
if (selected != null) {
String sortBy = selected.getValue().getSortBy();
boolean ascending = selected.getValue().isSortAscending();
Collection<? extends TableColumn<Entry, ?>> col = getEntryTableColumn(sortBy, ascending);
this.tblEntries.getSortOrder().setAll(col);
}
refreshEntryList();
}
private Collection<? extends TableColumn<Entry, ?>> getEntryTableColumn(String property, boolean ascending) {
TableColumn<Entry, ?> result;
if (property == null) {
result = colEntryName;
} else {
result = this.tblEntries.getColumns().stream()
.filter(column -> column.getUserData().equals(property))
.findFirst().orElse(colEntryName);
}
result.setSortType(ascending? ASCENDING : DESCENDING);
return Collections.singleton(result);
}
private String getSortByName(TableColumn<Entry, ?> column) {
return String.valueOf(column.getUserData());
}
@SuppressWarnings("unused")
private void selectedEntryChanged(
ObservableValue<? extends Entry> ob,
Entry _old,
Entry selected
) {
App.setCurrentEntry(selected);
this.btnNewLogin.setDisable(selected == null);
this.tblAuthentications.setDisable(selected == null);
this.tpEntryInfo.setDisable(selected == null);
this.txtNote.setEditable(selected != null);
NodeUtils.setUserData(this.txtNote, "muteChange", true);
this.txtNote.setText(selected == null ? "" : selected.getNote());
NodeUtils.setUserData(this.txtNote, "muteChange", null);
refreshAuthenticationList();
}
private void beforeClose(WindowEvent event) {
if (App.getPasswordLib() == null) {
return;
}
if (App.getPasswordLib().isChanged()) {
if (mnuAutoSave.isSelected()) {
trySaveOnExit(event);
return;
}
ButtonType buttonType = AlertDialog.confirmYesNoCancel("保存文件",
"""
文件尚未保存。是否保存然后退出?
点击“是”则保存文件然后退出,点击“否”则直接退出,点击“取消”不退出。""");
if (buttonType == ButtonType.CANCEL) {
event.consume();
return;
}
if (buttonType == ButtonType.YES) {
trySaveOnExit(event);
}
}
}
private void trySaveOnExit(WindowEvent event) {
try {
App.getPasswordLib().save();
} catch (Exception e) {
logger.error("保存文件失败", e);
AlertDialog.error("保存文件失败: ", e);
event.consume();
}
}
public void openFileClicked() {
File file = FileDialog.showOpenFile(
AppPrimaryStage.getPrimaryStage(), "打开密码库文件", App.FILE_EXT, App.FILE_EXT_NAME);
if (file != null) {
openPasswordLibFile(file);
}
}
private void openPasswordLibFile(File file) {
EnterPasswordDialog dialog = new EnterPasswordDialog(file.getName());
ButtonType buttonType = dialog.showAndWait().orElse(ButtonType.CANCEL);
if (buttonType == ButtonType.OK) {
try {
String masterPassword = dialog.getPassword();
PasswordLib passwordLib = new PasswordLib(file, masterPassword, false);
loadPasswordLib(passwordLib);
App.setPasswordLib(passwordLib);
AppPrimaryStage.getPrimaryStage().setTitle(App.APP_NAME + " - " + file.getName());
} catch (PasswordLibException e) {
logger.error("打开文件失败", e);
AlertDialog.error("密码不正确", e);
}
} else if (buttonType == EnterPasswordDialog.EXIT_BUTTON_TYPE) {
Platform.exit();
}
}
public void newFileClicked() {
runSafe(this::newFileClicked0);
}
private void newFileClicked0() {
CreatePasswordLibDialog createPasswordLibDialog = new CreatePasswordLibDialog();
createPasswordLibDialog.setOwner(AppPrimaryStage.getPrimaryStage());
ButtonType buttonType = createPasswordLibDialog.showAndWait().orElse(ButtonType.CANCEL);
if (buttonType == ButtonType.OK) {
// 先保存现有密码库
if (App.getPasswordLib() != null) {
App.getPasswordLib().save();
}
try {
createPasswordLib(createPasswordLibDialog);
} catch (Exception e) {
logger.error("创建密码库失败", e);
AlertDialog.error("创建密码库失败", e);
}
}
}
private void createPasswordLib(CreatePasswordLibDialog createPasswordLibDialog) {
PasswordLib passwordLib = new PasswordLib(
createPasswordLibDialog.getSaveFile(),
createPasswordLibDialog.getMasterPassword(),
true
);
passwordLib.save();
loadPasswordLib(passwordLib);
App.setPasswordLib(passwordLib);
}
private void loadPasswordLib(PasswordLib passwordLib) {
loadCategories(passwordLib);
this.mnuExport.setDisable(false);
this.tvCategories.getRoot().setExpanded(true);
this.tvCategories.getSelectionModel().select(this.tvCategories.getRoot());
if (!App.IS_DEV) {
UserConfig.setString("latest_file", Str.encodeUrl(passwordLib.filePath()));
}
}
private void loadCategories(PasswordLib passwordLib) {
Category rootCategory = passwordLib.getRootCategory();
TreeItem<Category> root = loadCategory(rootCategory);
this.tvCategories.setRoot(root);
}
private TreeItem<Category> loadCategory(Category category) {
TreeItem<Category> treeItem = new TreeItem<>(category);
for (Category child : category.getChildren()) {
treeItem.getChildren().add(loadCategory(child));
}
treeItem.setExpanded(true);
return treeItem;
}
@SuppressWarnings("UnusedReturnValue")
private OrElse ifCategorySelectedThen(Consumer<Category> consumer) {
TreeItem<Category> item = this.tvCategories.getSelectionModel().getSelectedItem();
if (item == null || item.getValue() == null) {
return OrElse.negative();
}
return OrElse.positive(() -> consumer.accept(item.getValue()));
}
private void refreshEntryList() {
Category currentCategory = App.getCurrentCategory();
if (currentCategory != null) {
tblEntries.getItems().setAll(currentCategory.getEntries());
tblEntries.sort();
} else {
tblEntries.getItems().clear();
}
}
private void refreshAuthenticationList() {
Entry currentEntry = App.getCurrentEntry();
if (currentEntry != null) {
this.tblAuthentications.getItems().setAll(currentEntry.getAuthentications());
this.tblAuthentications.sort();
} else {
this.tblAuthentications.getItems().clear();
}
}
public void saveClicked() {
if (App.getPasswordLib() != null) {
App.getPasswordLib().save();
String now = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss"));
lblStatus.setText("密码库已成功保存 [" + now + "]");
setupClearStatus();
}
}
private void setupClearStatus() {
App.TIMER.schedule(new TimerTask() {
@Override
public void run() {
Platform.runLater(() -> lblStatus.setText(""));
}
}, 3000);
}
public void newEntryClicked() {
EntryInfoDialog dialog = new EntryInfoDialog(null);
dialog.setOwner(AppPrimaryStage.getPrimaryStage());
ButtonType buttonType = dialog.showAndWait().orElse(ButtonType.CANCEL);
if (buttonType == ButtonType.OK) {
Entry entry = dialog.getEntry();
ifCategorySelectedThen(category -> category.addEntry(entry));
refreshEntryList();
App.setPasswordLibChanged();
}
}
public void newLoginClicked() {
AuthenticationInfoDialog dialog = new AuthenticationInfoDialog(null);
dialog.setOwner(AppPrimaryStage.getPrimaryStage());
if (dialog.showAndWait().orElse(ButtonType.CANCEL) == ButtonType.OK) {
App.getCurrentEntry().getAuthentications().add(dialog.getAuthentication());
refreshAuthenticationList();
}
}
public void autoOpenToggleClicked() {
UserConfig.setString("auto_open_on_start", String.valueOf(mnuAutoOpen.isSelected()));
}
public void autoSaveToggleClicked() {
UserConfig.setString("auto_save_on_exit", String.valueOf(mnuAutoSave.isSelected()));
}
public void noteWrapToggleClicked() {
txtNote.setWrapText(mnuNoteWrap.isSelected());
UserConfig.setString("note_wrap_text", String.valueOf(mnuNoteWrap.isSelected()));
}
public void exitClicked() {
AppPrimaryStage.getPrimaryStage().close();
}
public void changeMasterPasswordClicked() {
PasswordLib passwordLib = App.getPasswordLib();
if (passwordLib == null) {
return;
}
ChangeMasterPasswordDialog dialog = new ChangeMasterPasswordDialog();
dialog.setOwner(AppPrimaryStage.getPrimaryStage());
if (dialog.showAndWait().orElse(ButtonType.CANCEL) == ButtonType.OK) {
passwordLib.setMasterPassword(dialog.getNewPassword());
passwordLib.save();
AlertDialog.info("密码已修改", "密码库已经按照新的主密码重新加密保存。");
}
}
public void onAuthTablePaste() {
Authentication a = getApplicationClipboard(AUTH_CLIP_KEY);
if (a != null) {
Entry currentEntry = App.getCurrentEntry();
if (currentEntry != null) {
currentEntry.getAuthentications().add(a.clone());
refreshAuthenticationList();
}
}
}
public void onEntryTablePaste() {
Entry entry = getApplicationClipboard(ENTRY_CLIP_KEY);
if (entry != null) {
Category c = App.getCurrentCategory();
if (c != null) {
c.addEntry(entry.clone());
refreshEntryList();
}
}
}
public void onAuthTableContextMenuShown() {
mnuPasteAuthentication.setDisable(getApplicationClipboard(AUTH_CLIP_KEY) == null);
}
public void onEntryTableContextMenuShown() {
mnuPasteEntry.setDisable(getApplicationClipboard(ENTRY_CLIP_KEY) == null);
}
public void exportFileClicked() {
new ExportDialog().showAndWait();
}
}
| 19,145 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
EncryptException.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/main/java/com/hyd/pass/utils/EncryptException.java | package com.hyd.pass.utils;
/**
* (description)
* created at 2018/2/6
*
* @author yidin
*/
public class EncryptException extends RuntimeException {
public EncryptException() {
}
public EncryptException(String message) {
super(message);
}
public EncryptException(String message, Throwable cause) {
super(message, cause);
}
public EncryptException(Throwable cause) {
super(cause);
}
}
| 474 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
Str.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/main/java/com/hyd/pass/utils/Str.java | package com.hyd.pass.utils;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.stream.Stream;
public final class Str {
private Str() {
}
public static boolean isBlank(String s) {
return s == null || s.trim().length() == 0;
}
public static boolean isNotBlank(String s) {
return !isBlank(s);
}
public static String trim(String s) {
return s == null ? "" : s.trim();
}
public static boolean isAnyBlank(String... strs) {
return Stream.of(strs).anyMatch(Str::isBlank);
}
public static boolean isAllBlank(String... strs) {
return Stream.of(strs).allMatch(Str::isBlank);
}
public static boolean containsIgnoreCase(String str, String find) {
if (str == null || find == null) {
return false;
}
return str.toLowerCase().contains(find.toLowerCase());
}
public static String formatDate(Date date, String pattern) {
return new SimpleDateFormat(pattern).format(date);
}
public static String encodeUrl(String s) {
try {
return URLEncoder.encode(s, "UTF-8");
} catch (UnsupportedEncodingException e) {
return s;
}
}
public static String decodeUrl(String s) {
try {
return URLDecoder.decode(s, "UTF-8");
} catch (UnsupportedEncodingException e) {
return s;
}
}
}
| 1,545 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
OrElse.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/main/java/com/hyd/pass/utils/OrElse.java | package com.hyd.pass.utils;
/**
*
*
* @author yidin
*/
public class OrElse {
private boolean predicate;
public static OrElse negative() {
return new OrElse(false);
}
public static OrElse positive(Runnable positiveAction) {
return new OrElse(true, positiveAction);
}
private OrElse(boolean predicate) {
this.predicate = predicate;
}
private OrElse(boolean predicate, Runnable positiveAction) {
this.predicate = predicate;
if (predicate) {
if (positiveAction != null) {
positiveAction.run();
}
}
}
public void orElse(Runnable negativeAction) {
if (!predicate) {
if (negativeAction != null) {
negativeAction.run();
}
}
}
}
| 861 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
Bytes.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/main/java/com/hyd/pass/utils/Bytes.java | package com.hyd.pass.utils;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Bytes {
private static final String[] HEX_ARRAY = {
"00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F",
"10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1A", "1B", "1C", "1D", "1E", "1F",
"20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2A", "2B", "2C", "2D", "2E", "2F",
"30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3A", "3B", "3C", "3D", "3E", "3F",
"40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4A", "4B", "4C", "4D", "4E", "4F",
"50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5A", "5B", "5C", "5D", "5E", "5F",
"60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6A", "6B", "6C", "6D", "6E", "6F",
"70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7A", "7B", "7C", "7D", "7E", "7F",
"80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8A", "8B", "8C", "8D", "8E", "8F",
"90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9A", "9B", "9C", "9D", "9E", "9F",
"A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "AA", "AB", "AC", "AD", "AE", "AF",
"B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "BA", "BB", "BC", "BD", "BE", "BF",
"C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CA", "CB", "CC", "CD", "CE", "CF",
"D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "DA", "DB", "DC", "DD", "DE", "DF",
"E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "EA", "EB", "EC", "ED", "EE", "EF",
"F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "FA", "FB", "FC", "FD", "FE", "FF"};
private Bytes() {
}
/**
* 组合多个 byte[] 数组
*
* @param byteArrays 要组合的数组
*
* @return 组合的结果
*/
public static byte[] concat(byte[]... byteArrays) {
int totalLength = 0;
for (byte[] byteArray : byteArrays) {
totalLength += byteArray.length;
}
byte[] result = new byte[totalLength];
int counter = 0;
for (byte[] byteArray : byteArrays) {
System.arraycopy(byteArray, 0, result, counter, byteArray.length);
counter += byteArray.length;
}
return result;
}
/**
* 字节串生成16进制字符串(最笨但最快的办法)
*
* @param bytes 要转换的字节串
*
* @return 转换后的字符串
*/
public static String toString(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
sb.append(HEX_ARRAY[0xFF & b]);
}
return sb.toString();
}
public static String md5(String source) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(source.getBytes());
byte[] digest = md.digest();
return toString(digest);
} catch (NoSuchAlgorithmException e) {
// nothing to do
return null;
}
}
} | 3,402 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
AESUtils.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/main/java/com/hyd/pass/utils/AESUtils.java | package com.hyd.pass.utils;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Base64;
/**
* AES 加密解密
*
* @author yiding.he
*/
public class AESUtils {
public static final byte SPACE = " ".getBytes()[0];
private static final String DEFAULT_MODE = "AES";
private static byte[] toBytes(String content) {
try {
return content.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
return content.getBytes();
}
}
private static String toString(byte[] bytes) {
try {
return new String(bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
return new String(bytes);
}
}
public static String encode128(String content, String key) {
return Base64.getEncoder().encodeToString(encode128(toBytes(content), toBytes(key)));
}
public static String decode128(String encoded, String key) {
return toString(decode128(Base64.getDecoder().decode(encoded), toBytes(key)));
}
/**
* 128位加密
*
* @param content 要加密的内容
* @param key 密钥
*
* @return 加密后的内容
*
* @throws EncryptException 如果加密失败
*/
public static byte[] encode128(byte[] content, byte[] key) throws EncryptException {
return encode(content, key, 128, DEFAULT_MODE);
}
/**
* 128位加密
*
* @param content 要加密的内容
* @param key 密钥
* @param mode 加密模式
*
* @return 加密后的内容
*
* @throws EncryptException 如果加密失败
*/
public static byte[] encode128(byte[] content, byte[] key, String mode) throws EncryptException {
return encode(content, key, 128, mode);
}
/**
* 128位解密
*
* @param encoded 被加密的内容
* @param key 密钥
*
* @return 原始内容
*
* @throws EncryptException 如果解密失败
*/
public static byte[] decode128(byte[] encoded, byte[] key) throws EncryptException {
return decode(encoded, key, 128, DEFAULT_MODE);
}
/**
* 128位解密
*
* @param encoded 被加密的内容
* @param key 密钥
* @param mode 模式
*
* @return 原始内容
*
* @throws EncryptException 如果解密失败
*/
public static byte[] decode128(byte[] encoded, byte[] key, String mode) throws EncryptException {
return decode(encoded, key, 128, mode);
}
public static byte[] encode(byte[] content, byte[] key, int length, String mode) throws EncryptException {
if (length != 128 && length != 192 && length != 256) {
throw new IllegalArgumentException("不正确的长度");
}
key = expand(key, length);
try {
// AES/CBC/NoPadding (128)
// AES/CBC/PKCS5Padding (128)
// AES/ECB/NoPadding (128)
// AES/ECB/PKCS5Padding (128) [AES默认]
Cipher cipher = Cipher.getInstance(mode);
SecretKeySpec keyspec = new SecretKeySpec(key, "AES");
cipher.init(Cipher.ENCRYPT_MODE, keyspec);
return cipher.doFinal(content);
} catch (Exception e) {
throw new EncryptException(e);
}
}
public static byte[] decode(byte[] encoded, byte[] key, int length, String mode) throws EncryptException {
if (length != 128 && length != 192 && length != 256) {
throw new IllegalArgumentException("不正确的长度");
}
key = expand(key, length);
try {
Cipher cipher = Cipher.getInstance(mode);
SecretKeySpec keyspec = new SecretKeySpec(key, "AES");
cipher.init(Cipher.DECRYPT_MODE, keyspec);
return cipher.doFinal(encoded);
} catch (Exception e) {
throw new EncryptException(e);
}
}
public static byte[] expand(byte[] key, int length) {
byte[] result = new byte[length / 8];
int end = Math.min(key.length, result.length);
System.arraycopy(key, 0, result, 0, end);
Arrays.fill(result, end, result.length, SPACE);
return result;
}
} | 4,521 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
FileUtils.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/main/java/com/hyd/pass/utils/FileUtils.java | package com.hyd.pass.utils;
import com.hyd.pass.Logger;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
/**
* (description)
* created at 2018/2/6
*
* @author yidin
*/
public class FileUtils {
private static final Logger logger = Logger.getLogger(FileUtils.class);
public static boolean ensureFile(String filePath) {
if (Str.isBlank(filePath)) {
return false;
}
File file = new File(filePath);
if (file.exists()) {
return true;
}
try {
return file.createNewFile();
} catch (IOException e) {
logger.error("创建文件失败", e);
return false;
} finally {
if (file.exists()) {
file.delete();
}
}
}
public static String read(File file) throws IOException {
return IoStream.toString(file, StandardCharsets.UTF_8);
}
public static void write(File file, String content, String charset) throws IOException {
IoStream.write(file, content, charset);
}
}
| 1,165 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
IoStream.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/main/java/com/hyd/pass/utils/IoStream.java | package com.hyd.pass.utils;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
public class IoStream {
public static String toString(InputStream inputStream, Charset charset) throws IOException {
try (
InputStreamReader reader = new InputStreamReader(inputStream, charset);
BufferedReader bufferedReader = new BufferedReader(reader)
) {
String line;
StringBuilder sb = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
sb.append(line).append("\n");
}
return sb.toString();
}
}
public static String toString(File file, Charset charset) throws IOException {
try (FileInputStream fileInputStream = new FileInputStream(file)) {
return toString(fileInputStream, charset);
}
}
public static void write(File file, String content, String charset) throws IOException {
Files.write(file.toPath(), content.getBytes(charset));
}
}
| 1,061 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
ChangeMasterPasswordDialog.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/main/java/com/hyd/pass/dialogs/ChangeMasterPasswordDialog.java | package com.hyd.pass.dialogs;
import com.hyd.fx.app.AppLogo;
import com.hyd.fx.dialog.AlertDialog;
import com.hyd.fx.dialog.BasicDialog;
import com.hyd.fx.dialog.DialogBuilder;
import com.hyd.pass.App;
import com.hyd.pass.model.PasswordLib;
import com.hyd.pass.utils.Str;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.ButtonType;
import javafx.scene.control.PasswordField;
import java.util.Objects;
/**
* @author yidin
*/
public class ChangeMasterPasswordDialog extends BasicDialog {
@FXML
private PasswordField txtOldPassword;
@FXML
private PasswordField txtNewPassword;
@FXML
private PasswordField txtNewPassword2;
private String newPassword;
public ChangeMasterPasswordDialog() {
new DialogBuilder()
.title("修改主密码")
.logo(AppLogo.getLogo())
.body(getClass().getResource("/fxml/change-master-password.fxml"), this)
.buttons(ButtonType.OK, ButtonType.CANCEL)
.onOkButtonClicked(this::onOkButtonClicked)
.onStageShown(event -> txtOldPassword.requestFocus())
.applyTo(this);
}
public String getNewPassword() {
return newPassword;
}
private void onOkButtonClicked(ActionEvent actionEvent) {
PasswordLib passwordLib = App.getPasswordLib();
String oldPassword = txtOldPassword.getText();
String newPassword = txtNewPassword.getText();
String newPassword2 = txtNewPassword2.getText();
if (!passwordLib.validatePassword(oldPassword)) {
AlertDialog.error("修改主密码失败", "旧密码不正确");
actionEvent.consume();
return;
}
if (Str.isAnyBlank(newPassword, newPassword2)) {
AlertDialog.error("修改主密码失败", "新密码不能为空");
actionEvent.consume();
return;
}
if (!Objects.equals(newPassword, newPassword2)) {
AlertDialog.error("修改主密码失败", "两次输入的新密码不一致");
actionEvent.consume();
return;
}
this.newPassword = newPassword;
}
}
| 2,300 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
EntryInfoDialog.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/main/java/com/hyd/pass/dialogs/EntryInfoDialog.java | package com.hyd.pass.dialogs;
import com.hyd.fx.app.AppLogo;
import com.hyd.fx.dialog.BasicDialog;
import com.hyd.fx.dialog.DialogBuilder;
import com.hyd.pass.model.Entry;
import com.hyd.pass.utils.Str;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.ButtonType;
import javafx.scene.control.TextField;
/**
* @author yidin
*/
public class EntryInfoDialog extends BasicDialog {
private Entry entry;
@FXML
public TextField txtEntryName;
@FXML
public TextField txtEntryLocation;
@FXML
public TextField txtEntryComment;
public EntryInfoDialog(Entry entry) {
this.entry = entry;
new DialogBuilder()
.title("入口信息")
.logo(AppLogo.getLogo())
.body(getClass().getResource("/fxml/entry-info-dialog.fxml"), this)
.buttons(ButtonType.OK, ButtonType.CANCEL)
.onOkButtonClicked(this::onOkButtonClicked)
.onStageShown(event -> txtEntryName.requestFocus())
.applyTo(this);
}
public void initialize() {
if (this.entry != null) {
this.txtEntryName.setText(this.entry.getName());
this.txtEntryLocation.setText(this.entry.getLocation());
this.txtEntryComment.setText(this.entry.getComment());
}
}
public Entry getEntry() {
return entry;
}
private void onOkButtonClicked(ActionEvent event) {
if (Str.isBlank(txtEntryName.getText())) {
event.consume();
return;
}
String name = Str.trim(txtEntryName.getText());
String location = Str.trim(txtEntryLocation.getText());
String comment = Str.trim(txtEntryComment.getText());
if (this.entry == null) {
this.entry = new Entry(name, location, comment);
} else {
this.entry.setName(name);
this.entry.setLocation(location);
this.entry.setComment(comment);
}
}
}
| 2,099 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
CreatePasswordLibDialog.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/main/java/com/hyd/pass/dialogs/CreatePasswordLibDialog.java | package com.hyd.pass.dialogs;
import com.hyd.fx.app.AppLogo;
import com.hyd.fx.app.AppPrimaryStage;
import com.hyd.fx.dialog.AlertDialog;
import com.hyd.fx.dialog.BasicDialog;
import com.hyd.fx.dialog.DialogBuilder;
import com.hyd.fx.dialog.FileDialog;
import com.hyd.pass.App;
import com.hyd.pass.utils.FileUtils;
import com.hyd.pass.utils.Str;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.ButtonType;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import java.io.File;
import java.util.Objects;
/**
* (description)
* created at 2018/2/6
*
* @author yidin
*/
public class CreatePasswordLibDialog extends BasicDialog {
@FXML
private TextField txtSavePath;
@FXML
private PasswordField password1;
@FXML
private PasswordField password2;
public CreatePasswordLibDialog() {
new DialogBuilder()
.title("创建密码库")
.logo(AppLogo.getLogo())
.body(getClass().getResource("/fxml/create-password-lib.fxml"), this)
.buttons(ButtonType.OK, ButtonType.CANCEL)
.onOkButtonClicked(this::onOkButtonClicked)
.applyTo(this);
}
private void onOkButtonClicked(ActionEvent event) {
if (Str.isBlank(txtSavePath.getText())) {
AlertDialog.error("存储文件不能为空");
event.consume();
return;
}
if (!FileUtils.ensureFile(txtSavePath.getText())) {
AlertDialog.error("无法在目标位置创建文件,请选择其他位置");
event.consume();
return;
}
if (Str.isAllBlank(password1.getText(), password2.getText())) {
AlertDialog.error("主密码不能为空");
event.consume();
return;
}
if (!Objects.equals(password1.getText(), password2.getText())) {
AlertDialog.error("主密码不一致");
event.consume();
return;
}
this.saveFile = new File(this.txtSavePath.getText());
this.masterPassword = this.password1.getText();
}
private File saveFile;
private String masterPassword;
@FXML
public void onSelectFileClicked() {
File f = FileDialog.showSaveFile(
AppPrimaryStage.getPrimaryStage(), "选择保存位置", App.FILE_EXT, App.FILE_EXT_NAME, "");
if (f != null) {
this.txtSavePath.setText(f.getAbsolutePath());
}
}
public File getSaveFile() {
return saveFile;
}
public String getMasterPassword() {
return masterPassword;
}
}
| 2,788 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
SearchDialog.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/main/java/com/hyd/pass/dialogs/SearchDialog.java | package com.hyd.pass.dialogs;
import com.hyd.fx.app.AppPrimaryStage;
import com.hyd.fx.cells.TreeCellFactory;
import com.hyd.fx.components.FilterableTreeView;
import com.hyd.fx.dialog.BasicDialog;
import com.hyd.fx.dialog.DialogBuilder;
import com.hyd.pass.App;
import com.hyd.pass.model.Category;
import com.hyd.pass.model.Entry;
import com.hyd.pass.model.SearchItem;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import static com.hyd.fx.builders.ImageBuilder.image;
import static com.hyd.pass.utils.Str.containsIgnoreCase;
/**
* @author yidin
*/
public class SearchDialog extends BasicDialog {
@FXML
private TextField txtKeyword;
@FXML
private FilterableTreeView<SearchItem> tvSearchResult;
@FXML
private Button btnClear;
private Entry selectedEntry;
public SearchDialog() {
new DialogBuilder()
.body(getClass().getResource("/fxml/search.fxml"), this)
.owner(AppPrimaryStage.getPrimaryStage())
.title("关键字搜索")
.buttons(ButtonType.CLOSE)
.onButtonClicked(ButtonType.CLOSE, this::closeButtonClicked)
.onStageShown(this::onStageShown)
.applyTo(this);
}
public Entry getSelectedEntry() {
return selectedEntry;
}
private void onStageShown(DialogEvent dialogEvent) {
this.txtKeyword.requestFocus();
}
public void initialize() {
this.btnClear.setOnAction(event -> this.clear());
this.txtKeyword.textProperty().addListener((ob, oldValue, newValue) -> this.keywordChanged(newValue));
this.tvSearchResult.setOriginalRoot(buildOriginalRoot());
this.tvSearchResult.setCellFactory(new TreeCellFactory<SearchItem>()
.setToString(SearchItem::toString)
.setOnDoubleClick(this::searchItemSelected)
.setIconSupplier(this::getTreeNodeIcon)
);
}
private Image getTreeNodeIcon(TreeItem<SearchItem> treeItem) {
if (treeItem.getValue() instanceof SearchItem.CategorySearchItem) {
return image("/icons/folder.png");
} else if (treeItem.getValue() instanceof SearchItem.EntrySearchItem) {
return image("/icons/pc.png");
} else {
return null;
}
}
private TreeItem<SearchItem> buildOriginalRoot() {
Category rootCategory = App.getPasswordLib().getRootCategory();
TreeItem<SearchItem> rootTreeItem = new TreeItem<>(new SearchItem.CategorySearchItem(rootCategory));
buildOriginalRoot(rootCategory, rootTreeItem);
return rootTreeItem;
}
private void buildOriginalRoot(Category parentCategory, TreeItem<SearchItem> parentTreeItem) {
parentTreeItem.setExpanded(true);
for (Category child : parentCategory.getChildren()) {
TreeItem<SearchItem> childTreeItem = new TreeItem<>(new SearchItem.CategorySearchItem(child));
parentTreeItem.getChildren().add(childTreeItem);
buildOriginalRoot(child, childTreeItem);
}
for (Entry entry : parentCategory.getEntries()) {
TreeItem<SearchItem> childTreeItem = new TreeItem<>(new SearchItem.EntrySearchItem(entry));
parentTreeItem.getChildren().add(childTreeItem);
}
}
private void searchItemSelected(SearchItem item) {
if (item instanceof SearchItem.EntrySearchItem) {
entrySelected(((SearchItem.EntrySearchItem) item).entry);
}
}
private void entrySelected(Entry entry) {
this.selectedEntry = entry;
this.close();
}
private void keywordChanged(String keyword) {
this.tvSearchResult.filter(searchItem -> {
if (searchItem instanceof SearchItem.CategorySearchItem) {
return ((SearchItem.CategorySearchItem) searchItem).category.getName().contains(keyword);
} else if (searchItem instanceof SearchItem.EntrySearchItem) {
Entry entry = ((SearchItem.EntrySearchItem) searchItem).entry;
return containsIgnoreCase(entry.getName(), keyword) ||
containsIgnoreCase(entry.getNote(), keyword) ||
containsIgnoreCase(entry.getComment(), keyword) ||
containsIgnoreCase(entry.getLocation(), keyword);
}
return false;
});
}
private void closeButtonClicked(ActionEvent actionEvent) {
this.close();
}
public void clear() {
this.txtKeyword.setText("");
this.txtKeyword.requestFocus();
}
///////////////////////////////////////////////
}
| 4,886 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
EnterPasswordDialog.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/main/java/com/hyd/pass/dialogs/EnterPasswordDialog.java | package com.hyd.pass.dialogs;
import com.hyd.fx.app.AppLogo;
import com.hyd.fx.dialog.AlertDialog;
import com.hyd.fx.dialog.BasicDialog;
import com.hyd.fx.dialog.DialogBuilder;
import com.hyd.pass.utils.Str;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.control.ButtonType;
import javafx.scene.control.PasswordField;
/**
* (description)
* created at 2018/2/6
*
* @author yidin
*/
public class EnterPasswordDialog extends BasicDialog {
@FXML
private PasswordField mainPassword;
private String fileName;
private String password;
public static final ButtonType EXIT_BUTTON_TYPE = new ButtonType("退出", ButtonData.RIGHT);
public EnterPasswordDialog(String fileName) {
new DialogBuilder()
.title("输入“" + fileName + "”的主密码")
.logo(AppLogo.getLogo())
.body(getClass().getResource("/fxml/enter-password.fxml"), this)
.buttons(ButtonType.OK, ButtonType.CANCEL, EXIT_BUTTON_TYPE)
.onOkButtonClicked(this::onOkButtonClicked)
.onStageShown(event -> mainPassword.requestFocus())
.applyTo(this);
}
private void onOkButtonClicked(ActionEvent event) {
if (Str.isBlank(mainPassword.getText())) {
AlertDialog.error("密码不能为空");
event.consume();
return;
}
this.password = mainPassword.getText();
}
public String getPassword() {
return password;
}
}
| 1,617 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
EditCategoryDialog.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/main/java/com/hyd/pass/dialogs/EditCategoryDialog.java | package com.hyd.pass.dialogs;
import com.hyd.fx.app.AppLogo;
import com.hyd.fx.dialog.AlertDialog;
import com.hyd.fx.dialog.BasicDialog;
import com.hyd.fx.dialog.DialogBuilder;
import com.hyd.pass.utils.Str;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.TextField;
/**
* (description)
* created at 2018/2/6
*
* @author yidin
*/
public class EditCategoryDialog extends BasicDialog {
@FXML
public TextField txtCategoryName;
private String categoryName;
public EditCategoryDialog(String title, String defaultName) {
new DialogBuilder()
.logo(AppLogo.getLogo())
.body(getClass().getResource("/fxml/edit-category.fxml"), this)
.title(title)
.onOkButtonClicked(this::okClicked)
.onStageShown(event -> {
txtCategoryName.requestFocus();
})
.applyTo(this);
this.categoryName = defaultName;
this.txtCategoryName.setText(this.categoryName);
}
private void okClicked(ActionEvent event) {
if (Str.isBlank(this.txtCategoryName.getText())) {
AlertDialog.error("分类名称不能为空");
event.consume();
return;
}
this.categoryName = txtCategoryName.getText();
}
public String getCategoryName() {
return categoryName;
}
}
| 1,476 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
ExportDialog.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/main/java/com/hyd/pass/dialogs/ExportDialog.java | package com.hyd.pass.dialogs;
import com.hyd.fx.app.AppPrimaryStage;
import com.hyd.fx.dialog.AlertDialog;
import com.hyd.fx.dialog.BasicDialog;
import com.hyd.fx.dialog.DialogBuilder;
import com.hyd.fx.dialog.FileDialog;
import com.hyd.fx.helpers.TreeViewHelper;
import com.hyd.pass.App;
import com.hyd.pass.fx.TreeItemBuilder;
import com.hyd.pass.model.Category;
import com.hyd.pass.model.PasswordLib;
import com.hyd.pass.model.SearchItem;
import com.hyd.pass.utils.Str;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.control.cell.CheckBoxTreeCell;
import java.io.File;
public class ExportDialog extends BasicDialog {
@FXML
private TreeView<SearchItem> tvEntries;
@FXML
private PasswordField pwdMasterPassword;
@FXML
private TextField txtSavePath;
public static final ButtonType BUTTON_TYPE_EXPORT =
new ButtonType("导出...", ButtonBar.ButtonData.YES);
public ExportDialog() {
new DialogBuilder()
.body(getClass().getResource("/fxml/export.fxml"), this)
.owner(AppPrimaryStage.getPrimaryStage())
.title("导出密码库")
.buttons(BUTTON_TYPE_EXPORT, ButtonType.CLOSE)
.onButtonClicked(ButtonType.CLOSE, this::closeButtonClicked)
.onButtonClicked(BUTTON_TYPE_EXPORT, this::exportButtonClicked)
.onStageShown(this::onStageShown)
.applyTo(this);
}
private void exportButtonClicked(ActionEvent actionEvent) {
TreeItem<SearchItem> rootEntry =
TreeViewHelper.buildSubTree(tvEntries.getRoot(), SearchItem::isSelected);
String password = pwdMasterPassword.getText();
String savePath = txtSavePath.getText();
if (rootEntry == null) {
AlertDialog.error("导出", "请选择要导出的节点。");
actionEvent.consume();
return;
}
if (Str.isBlank(password)) {
AlertDialog.error("导出", "请填写主密码。");
actionEvent.consume();
return;
}
if (Str.isBlank(savePath)) {
AlertDialog.error("导出", "请选择要导出的文件位置。");
actionEvent.consume();
return;
}
try {
exportPasswordLib(rootEntry, password, savePath);
AlertDialog.info("导出完毕", "导出完毕。");
} catch (Exception e) {
AlertDialog.error("导出失败", e);
actionEvent.consume();
}
}
private void exportPasswordLib(TreeItem<SearchItem> rootEntry, String password, String savePath) {
Category rootCategory = assembleCategory(rootEntry);
PasswordLib passwordLib = new PasswordLib(new File(savePath), password, true);
passwordLib.setRootCategory(rootCategory);
passwordLib.save();
}
private Category assembleCategory(TreeItem<SearchItem> rootEntry) {
Category origin = ((SearchItem.CategorySearchItem) rootEntry.getValue()).category;
Category category = copyCategory(origin);
copyChildren(rootEntry, category);
return category;
}
private Category copyCategory(Category origin) {
Category category = new Category();
copyProperties(origin, category);
return category;
}
private void copyChildren(TreeItem<SearchItem> treeItem, Category category) {
treeItem.getChildren().forEach(childTreeItem -> {
SearchItem searchItem = childTreeItem.getValue();
if (searchItem instanceof SearchItem.CategorySearchItem) {
Category origin = ((SearchItem.CategorySearchItem) searchItem).category;
Category child = copyCategory(origin);
category.addChild(child);
copyChildren(childTreeItem, child);
} else if (searchItem instanceof SearchItem.EntrySearchItem) {
category.addEntry(((SearchItem.EntrySearchItem) searchItem).entry);
}
});
}
// 将基本属性从 origin 拷贝到 category
private void copyProperties(Category origin, Category category) {
category.setId(origin.getId());
category.setName(origin.getName());
category.setOrder(origin.getOrder());
category.setSortBy(origin.getSortBy());
category.setParentId(origin.getParentId());
}
private void onStageShown(DialogEvent dialogEvent) {
Category rootCategory = App.getPasswordLib().getRootCategory();
tvEntries.setRoot(TreeItemBuilder.buildSearchItemTree(rootCategory));
tvEntries.setCellFactory(CheckBoxTreeCell.forTreeView());
}
private void closeButtonClicked(ActionEvent actionEvent) {
this.close();
}
@FXML
public void onSelectFileClicked() {
File f = FileDialog.showSaveFile(
AppPrimaryStage.getPrimaryStage(), "选择保存位置", App.FILE_EXT, App.FILE_EXT_NAME, "");
if (f != null) {
this.txtSavePath.setText(f.getAbsolutePath());
}
}
}
| 5,302 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
SortCategoryChildDialog.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/main/java/com/hyd/pass/dialogs/SortCategoryChildDialog.java | package com.hyd.pass.dialogs;
import com.hyd.fx.app.AppLogo;
import com.hyd.fx.cells.ListCellFactory;
import com.hyd.fx.dialog.BasicDialog;
import com.hyd.fx.dialog.DialogBuilder;
import com.hyd.pass.App;
import com.hyd.pass.model.Category;
import javafx.fxml.FXML;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ListView;
import javafx.scene.control.TreeItem;
import java.util.List;
import java.util.function.BiFunction;
/**
* (description)
* created at 2018/2/11
*
* @author yidin
*/
public class SortCategoryChildDialog extends BasicDialog {
private TreeItem<Category> treeItem;
private Category parent;
@FXML
public ListView<Category> lvCategories;
public SortCategoryChildDialog(TreeItem<Category> treeItem) {
this.treeItem = treeItem;
this.parent = treeItem.getValue();
new DialogBuilder()
.title("子类排序")
.logo(AppLogo.getLogo())
.body(getClass().getResource("/fxml/sort-category-child.fxml"), this)
.buttons(ButtonType.CLOSE)
.applyTo(this);
lvCategories.setCellFactory(
new ListCellFactory<Category>().withTextFunction(Category::getName));
}
public void initialize() {
this.lvCategories.getItems().addAll(this.parent.getChildren());
}
public void move(
BiFunction<List<Category>, Integer, Boolean> canMove,
BiFunction<List<Category>, Integer, Integer> insertPosition
) {
int selectedIndex = this.lvCategories.getSelectionModel().getSelectedIndex();
if (selectedIndex == -1) {
return;
}
List<Category> items = this.lvCategories.getItems();
if (canMove.apply(items, selectedIndex)) {
Category selectedItem = items.remove(selectedIndex);
items.add(insertPosition.apply(items, selectedIndex), selectedItem);
this.parent.updateChildrenOrder(items);
this.parent.applyChildrenOrder(treeItem);
this.lvCategories.getSelectionModel().select(selectedItem);
App.setPasswordLibChanged();
}
}
public void moveUp() {
move(
(list, selectedIndex) -> selectedIndex > 0,
(list, selectedIndex) -> selectedIndex - 1
);
}
public void moveDown() {
move(
(list, selectedIndex) -> selectedIndex < list.size() - 1,
(list, selectedIndex) -> selectedIndex + 1
);
}
public void moveTop() {
move(
(list, selectedIndex) -> selectedIndex > 0,
(list, selectedIndex) -> 0
);
}
public void moveBottom() {
move(
(list, selectedIndex) -> selectedIndex < list.size() - 1,
(list, selectedIndex) -> list.size()
);
}
}
| 2,932 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
AuthenticationInfoDialog.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/main/java/com/hyd/pass/dialogs/AuthenticationInfoDialog.java | package com.hyd.pass.dialogs;
import com.hyd.fx.app.AppLogo;
import com.hyd.fx.dialog.BasicDialog;
import com.hyd.fx.dialog.DialogBuilder;
import com.hyd.pass.model.Authentication;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import java.security.SecureRandom;
import java.util.Random;
import static com.hyd.pass.utils.Str.isBlank;
import static com.hyd.pass.utils.Str.trim;
/**
* @author yiding.he
*/
@SuppressWarnings("unused")
public class AuthenticationInfoDialog extends BasicDialog {
private Authentication authentication;
@FXML
private TextField txtUsername;
@FXML
private TextArea txtPassword;
@FXML
private CheckBox chkNum;
@FXML
private CheckBox chkSml;
@FXML
private CheckBox chkBig;
@FXML
private CheckBox chkSpc;
@FXML
private CheckBox chkCfs;
@FXML
private Spinner<Integer> spnLength;
private final Random random = new SecureRandom();
public void onGenerateClick() {
String chars = "";
if (chkNum.isSelected()) {
chars += "0123456789";
}
if (chkSml.isSelected()) {
chars += "abcdefghijklmnopqrstuvwxyz";
}
if (chkBig.isSelected()) {
chars += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
}
if (chkSpc.isSelected()) {
chars += "~!#$%^&*()_+`-=[]{}\\|;':\",./<>?";
}
if (chkCfs.isSelected()) {
chars = chars.replaceAll("[0oO1Ilq9QB85sSuvUVZ2]", "");
}
int length = spnLength.getValue();
char[] selection = chars.toCharArray();
char[] result = new char[length];
for (int i = 0; i < length; i++) {
result[i] = selection[random.nextInt(selection.length)];
}
txtPassword.setText(new String(result));
}
public AuthenticationInfoDialog(Authentication authentication) {
this.authentication = authentication;
new DialogBuilder()
.title("登录信息")
.logo(AppLogo.getLogo())
.body(getClass().getResource("/fxml/authentication-info-dialog.fxml"), this)
.buttons(ButtonType.OK, ButtonType.CANCEL)
.onOkButtonClicked(this::onOkButtonClicked)
.onStageShown(event -> txtUsername.requestFocus())
.resizable(true)
.applyTo(this);
// make textarea grows vertically
this.txtPassword.prefHeightProperty().bind(((HBox)this.txtPassword.getParent()).heightProperty());
}
public void initialize() {
if (this.authentication != null) {
this.txtUsername.setText(this.authentication.getUsername());
this.txtPassword.setText(this.authentication.getPassword());
}
}
public Authentication getAuthentication() {
return authentication;
}
private void onOkButtonClicked(ActionEvent actionEvent) {
if (isBlank(txtUsername.getText())) {
actionEvent.consume();
return;
}
String username = trim(txtUsername.getText());
String password = trim(txtPassword.getText());
if (this.authentication == null) {
this.authentication = new Authentication(username, password);
} else {
this.authentication.setUsername(username);
this.authentication.setPassword(password);
}
}
}
| 3,443 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
ConfigException.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/main/java/com/hyd/pass/conf/ConfigException.java | package com.hyd.pass.conf;
/**
* (description)
* created at 2017/7/6
*
* @author yidin
*/
public class ConfigException extends RuntimeException {
public ConfigException() {
}
public ConfigException(String message) {
super(message);
}
public ConfigException(String message, Throwable cause) {
super(message, cause);
}
public ConfigException(Throwable cause) {
super(cause);
}
}
| 468 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
UserConfig.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/main/java/com/hyd/pass/conf/UserConfig.java | package com.hyd.pass.conf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.Properties;
/**
* User Configuration
*
* @author yidin
*/
public class UserConfig {
private static final Logger LOG = LoggerFactory.getLogger(UserConfig.class);
private static final String userConfigPath =
System.getProperty("user.home") + "/.hydrogen-pass/user-config.properties";
private static boolean readOnly = false;
private static final Properties properties = new Properties();
static {
loadConfig();
}
private static void loadConfig() {
try {
File file = new File(userConfigPath);
if (!file.exists()) {
File parentFile = file.getParentFile();
if (!parentFile.exists() && !parentFile.mkdirs()) {
LOG.error("Unable to create configuration file");
return;
}
if (!file.createNewFile()) {
LOG.error("Unable to create configuration file");
return;
}
} else if (!file.canWrite()) {
readOnly = true;
}
try (Reader reader = new FileReader(file)) {
properties.load(reader);
}
} catch (IOException e) {
throw new ConfigException(e);
}
}
public static String getString(String key, String def) {
return properties.getProperty(key, def);
}
public static boolean getBoolean(String key, boolean def) {
return Boolean.parseBoolean(getString(key, String.valueOf(def)));
}
public static void setString(String key, String value) {
properties.put(key, value);
if (!readOnly) {
try {
try (Writer writer = new FileWriter(new File(userConfigPath))) {
properties.store(writer, "");
}
} catch (IOException e) {
throw new ConfigException(e);
}
}
}
}
| 2,168 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
PasswordLib.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/main/java/com/hyd/pass/model/PasswordLib.java | package com.hyd.pass.model;
import static com.hyd.pass.utils.AESUtils.encode128;
import static com.hyd.pass.utils.Bytes.md5;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.annotation.JSONField;
import com.hyd.pass.utils.FileUtils;
import com.hyd.pass.utils.IoStream;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.zip.*;
/**
* (description)
* created at 2018/2/6
*
* @author yidin
*/
public class PasswordLib {
private static final String ENC_TEST_STRING = "abcdefghijklmnopqrstuvwxyz";
private Charset charset = StandardCharsets.UTF_8;
private File saveFile;
private String masterPasswordValidator;
private Category rootCategory;
@JSONField(serialize = false)
private boolean changed;
@JSONField(serialize = false)
private String masterPassword;
/**
* 创建或打开密码库
*
* @param saveFile 文件路径
* @param masterPassword 主密码
* @param create true 表示是创建新的密码库,false 表示是打开现有的密码库
*
* @throws PasswordLibException 如果创建或打开密码库失败
*/
public PasswordLib(File saveFile, String masterPassword, boolean create) throws PasswordLibException {
if (create) {
this.saveFile = saveFile;
this.rootCategory = new Category("我的密码库");
this.masterPasswordValidator = generateValidator(masterPassword, rootCategory.getId());
this.masterPassword = masterPassword;
} else {
String masterPasswordValidator;
JSONObject jsonObject;
try {
String content = readContent(saveFile);
jsonObject = JSON.parseObject(content);
masterPasswordValidator = jsonObject.getString("masterPasswordValidator");
} catch (IOException e) {
throw new PasswordLibException("无法打开文件", e);
}
try {
long rootId = jsonObject.getJSONObject("rootCategory").getLong("id");
String userValue = generateValidator(masterPassword, rootId);
if (!userValue.equals(masterPasswordValidator)) {
throw new PasswordLibException("密码不正确");
}
} catch (PasswordLibException e) {
throw e;
} catch (Exception e) {
throw new PasswordLibException("密码不正确", e);
}
this.saveFile = saveFile;
this.rootCategory = jsonObject.getObject("rootCategory", Category.class);
this.masterPasswordValidator = masterPasswordValidator;
this.masterPassword = masterPassword;
try {
if (this.rootCategory == null) {
this.rootCategory = new Category("我的密码库");
} else {
this.rootCategory.iterateChildren(category -> {
category.readEntries(masterPassword);
}); // 解密内容
}
} catch (Exception e) {
throw new PasswordLibException(e);
}
}
}
private String generateValidator(String masterPassword, long rootId) {
// 转为 MD5 是为了防止同样的 masterPassword 产生外观相似的校验字符串
return md5(encode128(ENC_TEST_STRING + rootId, masterPassword));
}
public boolean isChanged() {
return changed;
}
public void setChanged(boolean changed) {
this.changed = changed;
}
public void setMasterPassword(String masterPassword) {
this.masterPassword = masterPassword;
}
public String filePath() {
return this.saveFile.getAbsolutePath();
}
public Category getRootCategory() {
return rootCategory;
}
public void setRootCategory(Category rootCategory) {
this.rootCategory = rootCategory;
}
public String getMasterPasswordValidator() {
return masterPasswordValidator;
}
public void setMasterPasswordValidator(String masterPasswordValidator) {
this.masterPasswordValidator = masterPasswordValidator;
}
public void save() {
// 保证校验字符串与最新的主密码一致
masterPasswordValidator = generateValidator(this.masterPassword, rootCategory.getId());
// 加密所有 entry
rootCategory.iterateChildren(category -> {
category.saveEntries(this.masterPassword);
});
Map<String, Object> data = new HashMap<>();
data.put("masterPasswordValidator", masterPasswordValidator);
data.put("rootCategory", rootCategory);
try {
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(saveFile))) {
saveContent(data, zos);
}
setChanged(false);
} catch (IOException e) {
throw new PasswordLibException(e);
}
}
private void saveContent(Map<String, Object> data, ZipOutputStream zos) throws IOException {
String content = JSON.toJSONString(data, JSONWriter.Feature.PrettyFormat);
zos.putNextEntry(new ZipEntry("content.json"));
zos.write(content.getBytes(charset));
zos.closeEntry();
}
private String readContent(File saveFile) throws IOException {
try {
try (ZipFile f = new ZipFile(saveFile)) {
ZipEntry entry = f.getEntry("content.json");
if (entry != null) {
try (InputStream is = f.getInputStream(entry)) {
return IoStream.toString(is, charset);
}
} else {
throw new IOException("文件内容不存在");
}
}
} catch (ZipException e) {
// 读取时兼容最初的纯文本格式,但保存时以 zip 格式保存
return FileUtils.read(saveFile);
}
}
public void deleteCategory(Category c) {
boolean[] removed = {false};
this.rootCategory.iterateChildren(category -> {
if (category.getChildren().contains(c)) {
category.getChildren().remove(c);
removed[0] = true;
return false;
} else {
return true;
}
});
if (removed[0]) {
setChanged(true);
}
}
public boolean validatePassword(String password) {
return Objects.equals(this.masterPassword, password);
}
}
| 7,004 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
PasswordLibException.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/main/java/com/hyd/pass/model/PasswordLibException.java | package com.hyd.pass.model;
/**
* (description)
* created at 2018/2/6
*
* @author yidin
*/
public class PasswordLibException extends RuntimeException {
public PasswordLibException() {
}
public PasswordLibException(String message) {
super(message);
}
public PasswordLibException(String message, Throwable cause) {
super(message, cause);
}
public PasswordLibException(Throwable cause) {
super(cause);
}
}
| 494 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
SearchItem.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/main/java/com/hyd/pass/model/SearchItem.java | package com.hyd.pass.model;
public abstract class SearchItem {
private boolean selected;
public abstract String toString();
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
///////////////////////////////////////////////
public static class EntrySearchItem extends SearchItem {
public Entry entry;
public EntrySearchItem(Entry entry) {
this.entry = entry;
}
@Override
public String toString() {
return entry.getName() + " (" + entry.getLocation() + ")";
}
}
public static class CategorySearchItem extends SearchItem {
public Category category;
public CategorySearchItem(Category category) {
this.category = category;
}
@Override
public String toString() {
return category.getName();
}
}
}
| 1,025 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
Entry.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/main/java/com/hyd/pass/model/Entry.java | package com.hyd.pass.model;
import com.hyd.pass.utils.Str;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.hyd.pass.utils.Str.containsIgnoreCase;
/**
* @author yiding.he
*/
public class Entry extends OrderedItem implements Cloneable {
public static final String DATE_PATTERN = "yyyy-MM-dd HH:mm";
private String location;
private String comment;
private String note;
private String createTime = now();
private List<Authentication> authentications = new ArrayList<>();
public Entry() {
}
public Entry(String name, String location, String comment) {
this.setName(name);
this.location = location;
this.comment = comment;
}
private static String now() {
return Str.formatDate(new Date(), DATE_PATTERN);
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public List<Authentication> getAuthentications() {
return authentications;
}
public void setAuthentications(List<Authentication> authentications) {
this.authentications = authentications;
}
///////////////////////////////////////////////
public boolean matchKeyword(String keyword) {
return containsIgnoreCase(getName(), keyword) ||
containsIgnoreCase(location, keyword) ||
containsIgnoreCase(comment, keyword) ||
containsIgnoreCase(note, keyword);
}
public List<String> locationAsList() {
if (Str.isBlank(location)) {
return Collections.emptyList();
}
return Stream.of(location.split(","))
.filter(Str::isNotBlank)
.map(String::trim)
.collect(Collectors.toList());
}
@Override
public final Entry clone() {
try {
return (Entry) super.clone();
} catch (CloneNotSupportedException e) {
// ignore this
return null;
}
}
}
| 2,624 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
OrderedItem.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/main/java/com/hyd/pass/model/OrderedItem.java | package com.hyd.pass.model;
/**
* (description)
* created at 2018/2/6
*
* @author yidin
*/
public abstract class OrderedItem {
private long id = System.currentTimeMillis();
private String name;
private int order;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getOrder() {
return order;
}
public void setOrder(int order) {
this.order = order;
}
}
| 650 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
Category.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/main/java/com/hyd/pass/model/Category.java | package com.hyd.pass.model;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.annotation.JSONField;
import com.hyd.pass.utils.AESUtils;
import javafx.scene.control.TreeItem;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
/**
* (description)
* created at 2018/2/6
*
* @author yidin
*/
public class Category extends OrderedItem {
private long parentId;
private List<Category> children = new ArrayList<>();
@JSONField(serialize = false)
private List<Entry> entries = new ArrayList<>();
private List<String> entryStrings = new ArrayList<>();
/**
* 当前按照哪个属性排序
*/
private String sortBy;
/**
* 当前排序的方向,仅当 {@link #sortBy} 不为空时有效
*/
private boolean sortAscending = true;
public Category() {
}
public Category(String name) {
setName(name);
}
public boolean isSortAscending() {
return sortAscending;
}
public void setSortAscending(boolean sortAscending) {
this.sortAscending = sortAscending;
}
public String getSortBy() {
return sortBy;
}
public void setSortBy(String sortBy) {
this.sortBy = sortBy;
}
public List<Entry> getEntries() {
return entries;
}
public void setEntries(List<Entry> entries) {
this.entries = entries;
}
public List<Category> getChildren() {
return children;
}
public void setChildren(List<Category> children) {
this.children = children;
}
public long getParentId() {
return parentId;
}
public void setParentId(long parentId) {
this.parentId = parentId;
}
public List<String> getEntryStrings() {
return entryStrings;
}
public void setEntryStrings(List<String> entryStrings) {
this.entryStrings = entryStrings;
}
public Category createChild(String categoryName) {
Category category = new Category(categoryName);
addChild(category);
return category;
}
public void addChild(Category category) {
category.setParentId(getId());
category.setOrder(children.size());
children.add(category);
}
public void updateChildrenOrder(List<Category> orderedChildren) {
for (int i = 0; i < orderedChildren.size(); i++) {
Category child = orderedChildren.get(i);
child.setOrder(i);
}
this.children.sort(Comparator.comparing(Category::getOrder));
}
public void applyChildrenOrder(TreeItem<Category> thisTreeItem) {
thisTreeItem.getChildren().sort(
Comparator.comparing(treeItem -> treeItem.getValue().getOrder()));
}
public void addEntry(Entry entry) {
this.entries.add(entry);
}
public void removeEntry(Entry entry) {
this.entries.remove(entry);
}
public void readEntries(String password) {
if (this.entryStrings == null) {
return;
}
this.entries.clear();
this.entryStrings.forEach(entryString -> {
String json = AESUtils.decode128(entryString, password);
Entry entry = JSON.parseObject(json, Entry.class);
this.entries.add(entry);
});
}
public void saveEntries(String password) {
if (this.entries == null) {
return;
}
this.entryStrings.clear();
this.entries.forEach(entry -> {
String json = JSON.toJSONString(entry);
String enc = AESUtils.encode128(json, password);
this.entryStrings.add(enc);
});
}
public void iterateChildren(Consumer<Category> consumer) {
iterateChildren(category -> {
consumer.accept(category);
return true;
});
}
public void iterateChildren(Function<Category, Boolean> processor) {
if (processor.apply(this)) {
iterateChildren(this, processor);
}
}
private void iterateChildren(Category parent, Function<Category, Boolean> processor) {
for (Category child : parent.getChildren()) {
if (processor.apply(child)) {
iterateChildren(child, processor);
}
}
}
public boolean containsEntry(Entry entry) {
return entries != null && entries.contains(entry);
}
}
| 4,672 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
Authentication.java | /FileExtraction/Java_unseen/yiding-he_hydrogen-pass/src/main/java/com/hyd/pass/model/Authentication.java | package com.hyd.pass.model;
/**
* @author yiding.he
*/
public class Authentication implements Cloneable {
private String username;
private String password;
public Authentication() {
}
public Authentication(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public final Authentication clone() {
try {
return (Authentication) super.clone();
} catch (CloneNotSupportedException e) {
// ignore this
return null;
}
}
}
| 937 | Java | .java | yiding-he/hydrogen-pass | 8 | 1 | 8 | 2017-06-20T14:56:15Z | 2023-09-01T02:50:56Z |
JavaTokenizer.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/JavaParser/src/jtree/parser/JavaTokenizer.java | package jtree.parser;
import static java.lang.Character.*;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.stream.Collectors;
import org.apache.commons.text.StringEscapeUtils;
import jtree.nodes.Name;
import lombok.NonNull;
public class JavaTokenizer<TokenType> implements Iterator<Token<TokenType>> {
protected CharSequence str;
protected int pos, line, column;
protected char ch;
protected boolean returnedEndmarker = false;
protected CharSequence currentLine;
protected TokenType defaultType, stringType, numberType, charType, wordType, errorType, commentType;
protected Map<String, TokenType> tokens;
protected List<String> sortedTokens, wordTokens;
protected String filename;
public JavaTokenizer(@NonNull CharSequence str, TokenType defaultType, TokenType errorType, TokenType stringType,
TokenType charType, TokenType numberType, TokenType wordType, TokenType commentType,
@NonNull Map<String,TokenType> tokens) {
this(str, "<unknown source>", defaultType, errorType, stringType, charType, numberType, wordType, commentType, tokens);
}
public JavaTokenizer(@NonNull CharSequence str, @NonNull String filename, TokenType defaultType,
TokenType errorType, TokenType stringType,
TokenType charType, TokenType numberType, TokenType wordType, TokenType commentType,
@NonNull Map<String,TokenType> tokens) {
this.str = str;
this.pos = 0;
this.line = this.column = 1;
if(str.length() > 0) {
this.ch = str.charAt(0);
}
this.filename = filename;
this.defaultType = defaultType;
this.errorType = errorType;
this.stringType = stringType;
this.numberType = numberType;
this.charType = charType;
this.wordType = wordType;
this.commentType = commentType;
int i = 0;
while(i+1 < str.length() && str.charAt(i) != '\n') {
i++;
}
this.currentLine = i+1 > str.length()? "" : str.subSequence(0, i+1);
this.tokens = tokens;
/*this.sortedTokens = new TreeSet<>((token1, token2) -> Integer.compare(token2.length(), token1.length()));
this.wordTokens = new TreeSet<>((token1, token2) -> Integer.compare(token2.length(), token1.length()));
for(var key : tokens.keySet()) {
if(isJavaIdentifierPart(key.charAt(key.length()-1))) {
boolean added = wordTokens.add(key);
assert added;
} else {
boolean added = sortedTokens.add(key);
assert added;
}
}*/
this.sortedTokens = tokens.keySet().stream()
.filter(token -> !isJavaIdentifierPart(token.charAt(token.length()-1)))
.sorted((token1, token2) -> Integer.compare(token2.length(), token1.length()))
.collect(Collectors.toList());
this.wordTokens = tokens.keySet().stream()
.filter(token -> isJavaIdentifierPart(token.charAt(token.length()-1)))
.sorted((token1, token2) -> Integer.compare(token2.length(), token1.length()))
.collect(Collectors.toList());
eatWhite();
}
protected void nextChar() {
if(pos+1 >= str.length()) {
ch = 0;
pos = str.length();
} else {
if(ch == '\n') {
line++;
column = 1;
int i = pos+1;
while(i+1 < str.length() && str.charAt(i+1) != '\n') {
i++;
}
currentLine = str.subSequence(pos+1, i+1);
} else {
column += 1;
}
//do {
ch = str.charAt(++pos);
//} while(ch == '\r' && pos+1 < str.length());
}
}
protected void setPos(int newpos) {
if(pos < newpos) {
for(int i = 0, end = newpos - pos; i < end && pos < str.length(); i++) {
nextChar();
}
} else if(pos > newpos) {
for(int i = 0, end = pos - newpos; i < end && pos > 0; i++) {
ch = str.charAt(--pos);
if(ch == '\n') {
int j = pos-1;
while(j > 0 && str.charAt(j) != '\n') {
j--;
}
if(str.charAt(j) == '\n') {
j++;
}
currentLine = str.subSequence(j, pos+1);
line--;
column = currentLine.length();
} else {
column--;
}
}
}
}
protected boolean eat(char c) {
if(ch == c) {
nextChar();
return true;
} else {
return false;
}
}
protected boolean eat(String sub) {
if(pos + sub.length() > str.length()) {
return false;
} else if(sub.contentEquals(str.subSequence(pos, pos + sub.length()))) {
setPos(pos + sub.length());
return true;
} else {
return false;
}
}
protected boolean eatWord(String sub) {
if(pos + sub.length() > str.length()) {
return false;
} else if(sub.contentEquals(str.subSequence(pos, pos + sub.length())) && (pos + sub.length() == str.length() || !isJavaIdentifierPart(str.charAt(pos + sub.length())))) {
setPos(pos + sub.length());
return true;
} else {
return false;
}
}
@Override
public boolean hasNext() {
return pos < str.length() || !returnedEndmarker;
}
@Override
public Token<TokenType> next() {
if(pos >= str.length()) {
if(returnedEndmarker) {
throw new NoSuchElementException();
} else {
returnedEndmarker = true;
var start = new Position(line, column);
var end = new Position(line, column);
return new Token<>(defaultType, "", start, end, currentLine);
}
}
Token<TokenType> result = switch(ch) {
case '"' -> eatString();
case '\'' -> eatChar();
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' -> eatNumber();
case '/' -> eatCommentOrDefault();
default -> defaultNext();
};
eatWhite();
return result;
}
protected Token<TokenType> defaultNext() {
if(ch == '.' && pos + 1 < str.length() && isDigit(str.charAt(pos+1))) {
return eatNumber();
}
var start = new Position(line, column);
for(String word : wordTokens) {
if(eatWord(word)) {
var end = new Position(line, column);
return new Token<>(tokens.get(word), word, start, end, currentLine);
}
}
for(String symbol : sortedTokens) {
if(eat(symbol)) {
var end = new Position(line, column);
return new Token<>(tokens.get(symbol), symbol, start, end, currentLine);
}
}
int startPos = pos;
if(isJavaIdentifierStart(ch)) {
int endPos = pos+1;
nextChar();
while(pos < str.length() && isJavaIdentifierPart(ch)) {
endPos = pos+1;
nextChar();
}
var end = new Position(line, column);
var content = str.subSequence(startPos, endPos).toString();
if(!Name.isValidName(content)) {
throw new AssertionError(StringEscapeUtils.escapeJava(content));
}
return new Token<>(wordType, content, start, end, currentLine);
}
nextChar();
var end = new Position(line, column);
return new Token<>(errorType, str.subSequence(startPos, pos).toString(), start, end, currentLine);
}
protected void eatWhite() {
while(pos < str.length() && isWhitespace(ch)) {
nextChar();
}
}
protected Token<TokenType> eatCommentOrDefault() {
var start = new Position(line, column);
var startPos = pos;
var startPos2 = pos - column + 1;
if(eat("//")) { // single-line comment
while(pos < str.length() && !eat('\n')) {
nextChar();
}
} else if(eat("/*")) { // multi-line comment
while(pos < str.length() && !eat("*/")) {
nextChar();
}
} else { // not a comment
return defaultNext();
}
var end = new Position(line, column);
int i = pos;
while(i+1 < str.length() && str.charAt(i) != '\n') {
i++;
}
if(i+1 > str.length()) {
i = str.length()-1;
}
return new Token<>(commentType, str.subSequence(startPos, pos).toString().indent(-100), start, end, str.subSequence(startPos2, i+1));
}
protected Token<TokenType> eatString() {
return eatString('"', stringType);
}
protected Token<TokenType> eatChar() {
return eatString('\'', charType);
}
protected Token<TokenType> eatString(char ends, TokenType type) {
assert ch == ends;
var start = new Position(line, column);
int startPos = pos - column + 1;
nextChar();
var sb = new StringBuilder();
sb.append(ends);
boolean escape = false;
while(pos < str.length() && (ch != ends && ch != '\n' || escape)) {
if(escape) {
escape = false;
if(ch == '\n') {
nextChar();
while(ch != '\n' && isWhitespace(ch)) {
nextChar();
}
continue;
} else {
sb.append('\\').append(ch);
}
} else if(ch == '\\') {
escape = true;
} else {
sb.append(ch);
}
nextChar();
}
if(!eat(ends)) {
throw new SyntaxError("unterminated string", filename, line, column, currentLine);
}
sb.append(ends);
var end = new Position(line, column);
int i = pos;
while(i+1 < str.length() && str.charAt(i) != '\n') {
i++;
}
if(i+1 > str.length()) {
i = str.length()-1;
}
return new Token<>(type, sb.toString(), start, end, str.subSequence(startPos, i+1));
}
protected Token<TokenType> eatNumber() {
assert ch == '.' || isDigit(ch);
int startPos = pos;
var start = new Position(line, column);
if(eat("0x") || eat("0X")) {
if(!isHexDigit(ch)) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
boolean first = false;
while(isHexDigit(ch)) {
first = true;
nextChar();
if(ch == '_') {
while(eat('_')) {
nextChar();
}
if(!isHexDigit(ch)) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
}
}
if(ch == '.' && (!first || pos+1 < str.length() && isHexDigit(str.charAt(pos+1)))) {
nextChar();
if(!first && !isHexDigit(ch)) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
while(isHexDigit(ch)) {
nextChar();
if(ch == '_') {
while(eat('_')) {
nextChar();
}
if(!isHexDigit(ch)) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
}
}
if(eat('p') || eat('P')) {
if(!eat('+')) {
eat('-');
}
if(!isDigit(ch)) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
while(isDigit(ch)) {
nextChar();
if(ch == '_') {
while(eat('_')) {
nextChar();
}
if(!isDigit(ch)) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
}
}
} else {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
} else {
if(!first) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
if(eat('p') || eat('P')) {
if(!eat('+')) {
eat('-');
}
if(!isDigit(ch)) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
while(isDigit(ch)) {
nextChar();
if(ch == '_') {
while(eat('_')) {
nextChar();
}
if(!isDigit(ch)) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
}
}
if(!(eat('f') || eat('F') || eat('d'))) {
eat('D');
}
} else if(!eat('l')) {
eat('L');
}
}
} else if(eat("0b") || eat("0B")) {
do {
if(ch != '1' && ch != '0') {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
nextChar();
if(ch == '_') {
while(eat('_')) {
nextChar();
}
if(!isDigit(ch)) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
}
} while(isDigit(ch));
} else {
boolean first = false;
while(isDigit(ch)) {
first = true;
nextChar();
if(ch == '_') {
while(eat('_')) {
nextChar();
}
if(!isDigit(ch)) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
}
}
if(ch == '.' && (!first || pos+1 < str.length() && isDigit(str.charAt(pos+1)))) {
nextChar();
if(!first && !isDigit(ch)) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
while(isDigit(ch)) {
nextChar();
if(ch == '_') {
while(eat('_')) {
nextChar();
}
if(!isDigit(ch)) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
}
}
if(eat('e') || eat('E')) {
if(!eat('+')) {
eat('-');
}
if(!isDigit(ch)) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
while(isDigit(ch)) {
nextChar();
if(ch == '_') {
while(eat('_')) {
nextChar();
}
if(!isDigit(ch)) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
}
}
} else if(!eat('f') || eat('F') || eat('d')) {
eat('D');
}
} else {
if(!first) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
if(eat('e') || eat('E')) {
if(!eat('+')) {
eat('-');
}
if(!isDigit(ch)) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
while(isDigit(ch)) {
nextChar();
if(ch == '_') {
while(eat('_')) {
nextChar();
}
if(!isDigit(ch)) {
throw new SyntaxError("invalid number literal", filename, line, column, currentLine);
}
}
}
if(!(eat('f') || eat('F') || eat('d'))) {
eat('D');
}
} else if(!(eat('F') || eat('d') || eat('D') || eat('l'))) {
eat('L');
}
}
}
var end = new Position(line, column);
return new Token<>(numberType, str.subSequence(startPos, pos).toString(), start, end, currentLine);
}
public static boolean isOctalDigit(char c) {
return switch(c) {
case '0', '1', '2', '3', '4', '5', '6', '7' -> true;
default -> false;
};
}
public static boolean isHexDigit(char c) {
return isDigit(c) || switch(c) {
case 'A', 'a', 'B', 'b', 'C', 'c', 'D', 'd', 'E', 'e', 'F', 'f' -> true;
default -> false;
};
}
}
| 14,937 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
Position.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/JavaParser/src/jtree/parser/Position.java | package jtree.parser;
import lombok.ToString;
import lombok.Value;
@ToString(includeFieldNames = false)
public @Value class Position {
int line, column;
}
| 158 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
JavaTokenType.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/JavaParser/src/jtree/parser/JavaTokenType.java | package jtree.parser;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import lombok.Getter;
import lombok.NonNull;
import lombok.experimental.Accessors;
public enum JavaTokenType implements CharSequence, TokenPredicate<JavaTokenType> {
ENDMARKER,
ERRORTOKEN,
STRING,
CHARACTER,
NUMBER,
COMMENT,
NAME(Tag.NAMED),
// Keywords
IF("if", Tag.STATEMENT_KW),
WHILE("while", Tag.STATEMENT_KW),
FOR("for", Tag.STATEMENT_KW),
DO("do", Tag.STATEMENT_KW),
ELSE("else", Tag.STATEMENT_KW),
SYNCHRONIZED("synchronized", Tag.METHOD_MODIFIER, Tag.STATEMENT_KW),
VOID("void"),
BOOLEAN("boolean", Tag.PRIMITIVE_TYPE),
BYTE("byte", Tag.PRIMITIVE_TYPE),
SHORT("short", Tag.PRIMITIVE_TYPE),
CHAR("char", Tag.PRIMITIVE_TYPE),
INT("int", Tag.PRIMITIVE_TYPE),
LONG("long", Tag.PRIMITIVE_TYPE),
FLOAT("float", Tag.PRIMITIVE_TYPE),
DOUBLE("double", Tag.PRIMITIVE_TYPE),
NULL("null"),
TRUE("true"),
FALSE("false"),
CLASS("class"),
INTERFACE("interface"),
ENUM("enum"),
ASSERT("assert", Tag.STATEMENT_KW),
RETURN("return", Tag.STATEMENT_KW),
TRY("try", Tag.STATEMENT_KW),
CATCH("catch", Tag.STATEMENT_KW),
FINALLY("finally", Tag.STATEMENT_KW),
THROW("throw", Tag.STATEMENT_KW),
THROWS("throws"),
SUPER("super"),
THIS("this"),
NEW("new"),
PUBLIC("public", Tag.CLASS_MODIFIER, Tag.FIELD_MODIFIER, Tag.METHOD_MODIFIER, Tag.CONSTRUCTOR_MODIFIER, Tag.VISIBILITY_MODIFIER),
PRIVATE("private", Tag.CLASS_MODIFIER, Tag.FIELD_MODIFIER, Tag.METHOD_MODIFIER, Tag.CONSTRUCTOR_MODIFIER, Tag.VISIBILITY_MODIFIER),
PROTECTED("protected", Tag.CLASS_MODIFIER, Tag.FIELD_MODIFIER, Tag.METHOD_MODIFIER, Tag.CONSTRUCTOR_MODIFIER, Tag.VISIBILITY_MODIFIER),
PACKAGE("package", Tag.CLASS_MODIFIER, Tag.FIELD_MODIFIER, Tag.METHOD_MODIFIER, Tag.CONSTRUCTOR_MODIFIER, Tag.VISIBILITY_MODIFIER),
STATIC("static", Tag.CLASS_MODIFIER, Tag.FIELD_MODIFIER, Tag.METHOD_MODIFIER, Tag.REQUIRES_MODIFIER),
NATIVE("native", Tag.METHOD_MODIFIER),
STRICTFP("strictfp", Tag.CLASS_MODIFIER, Tag.METHOD_MODIFIER),
ABSTRACT("abstract", Tag.CLASS_MODIFIER, Tag.METHOD_MODIFIER),
TRANSIENT("transient", Tag.FIELD_MODIFIER),
VOLATILE("volatile", Tag.FIELD_MODIFIER),
FINAL("final", Tag.CLASS_MODIFIER, Tag.METHOD_MODIFIER, Tag.FIELD_MODIFIER, Tag.LOCAL_VAR_MODIFIER),
EXTENDS("extends"),
IMPLEMENTS("implements"),
INSTANCEOF("instanceof"),
BREAK("break", Tag.STATEMENT_KW),
CONTINUE("continue", Tag.STATEMENT_KW),
SWITCH("switch", Tag.STATEMENT_KW),
CASE("case", Tag.STATEMENT_KW),
DEFAULT("default", Tag.METHOD_MODIFIER, Tag.STATEMENT_KW),
IMPORT("import", Tag.STATEMENT_KW),
VAR("var", Tag.NAMED),
MODULE("module", Tag.NAMED),
REQUIRES("requires", Tag.NAMED),
EXPORTS("exports", Tag.NAMED),
OPENS("opens", Tag.NAMED),
USES("uses", Tag.NAMED),
PROVIDES("provides", Tag.NAMED),
OPEN("open", Tag.NAMED, Tag.MODULE_MODIFIER),
TO("to", Tag.NAMED),
WITH("with", Tag.NAMED, Tag.STATEMENT_KW),
TRANSITIVE("transitive", Tag.NAMED, Tag.REQUIRES_MODIFIER),
YIELD("yield", Tag.NAMED),
// unused by vanilla Java
FROM("from", Tag.NAMED, Tag.STATEMENT_KW),
IN("in", Tag.NAMED),
IS("is", Tag.NAMED),
AS("as", Tag.NAMED),
UNIMPORT("unimport", Tag.NAMED, Tag.STATEMENT_KW),
PRINT("print", Tag.NAMED),
PRINTLN("println", Tag.NAMED),
PRINTF("printf", Tag.NAMED),
PRINTFLN("printfln", Tag.NAMED),
ANNOTATION("annotation", Tag.NAMED),
OVERRIDE("override", Tag.NAMED),
ENABLE("enable", Tag.NAMED),
DISABLE("disable", Tag.NAMED),
EXIT("exit", Tag.NAMED),
GET("get", Tag.NAMED),
SET("set", Tag.NAMED),
SELECT("select", Tag.NAMED),
UNDERSCORE("_"),
// Other
/** {@code +} */
PLUS("+"),
/** {@code -} */
SUB("-"),
/** {@code *} */
STAR("*"),
/** {@code /} */
SLASH("/"),
/** {@code %} */
PERCENT("%"),
/** {@code ^} */
CARET("^"),
/** {@code |} */
BAR("|"),
/** {@code &} */
AMP("&"),
/** {@code !} */
BANG("!"),
/** {@code ~} */
TILDE("~"),
/** {@code =} */
EQ("="),
/** {@code :} */
COLON(":"),
/** {@code .} */
DOT("."),
/** {@code <} */
LT("<"),
/** {@code >} */
GT(">"),
/** {@code ;} */
SEMI(";"),
/** {@code ,} */
COMMA(","),
/** {@code ?} */
QUES("?"),
/** {@code @} */
AT("@"),
/** {@code #} */
HASHTAG("#"),
/** {@code (} */
LPAREN("("),
/** {@code )} */
RPAREN(")"),
/** {@code [} */
LBRACKET("["),
/** {@code ]} */
RBRACKET("]"),
/** <code>{</code> */
LBRACE("{"),
/** <code>}</code> */
RBRACE("}"),
/** {@code ++} */
PLUSPLUS("++"),
/** {@code --} */
SUBSUB("--"),
/** {@code <<} */
LTLT("<<"),
/** {@code &&} */
AMPAMP("&&"),
/** {@code ||} */
BARBAR("||"),
/** {@code ::} */
COLCOL("::"),
/** {@code ==} */
EQEQ("=="),
/** {@code !=} */
BANGEQ("!="),
/** {@code +=} */
PLUSEQ("+="),
/** {@code -=} */
SUBEQ("-="),
/** {@code *=} */
STAREQ("*="),
/** {@code /=} */
SLASHEQ("/="),
/** {@code %=} */
PERCENTEQ("%="),
/** {@code <=} */
LTEQ("<="),
/** {@code >=} */
GTEQ(">="),
/** {@code ^=} */
CARETEQ("^="),
/** {@code |=} */
BAREQ("|="),
/** {@code &=} */
AMPEQ("&="),
/** {@code ->} */
ARROW("->"),
/** {@code <<=} */
LTLTEQ("<<="),
/** {@code >>=} */
GTGTEQ(">>="),
/** {@code ...} */
ELLIPSIS("..."),
/** {@code >>>=} */
GTGTGTEQ(">>>="),
;
private static final Set<JavaTokenType> mutableValues = new HashSet<>(EnumSet.allOf(JavaTokenType.class));
private static final Set<JavaTokenType> mutableNormalTokens = new HashSet<>(EnumSet.allOf(JavaTokenType.class));
static {
mutableNormalTokens.removeIf(type -> type.symbol.isEmpty());
}
public static final Set<JavaTokenType> VALUES = Collections.unmodifiableSet(mutableValues);
public static final Set<JavaTokenType> NORMAL_TOKENS = Collections.unmodifiableSet(mutableNormalTokens);
/*/// JavaTokenType()
private static final Constructor<JavaTokenType> constructor1;
/// JavaTokenType(Tag...)
private static final Constructor<JavaTokenType> constructor2;
/// JavaTokenType(String)
private static final Constructor<JavaTokenType> constructor3;
/// JavaTokenType(String, Tag...)
private static final Constructor<JavaTokenType> constructor4;
static {
try {
constructor1 = JavaTokenType.class.getDeclaredConstructor(String.class, int.class);
constructor1.setAccessible(true);
constructor2 = JavaTokenType.class.getDeclaredConstructor(String.class, int.class, Tag[].class);
constructor2.setAccessible(true);
constructor3 = JavaTokenType.class.getDeclaredConstructor(String.class, int.class, String.class);
constructor3.setAccessible(true);
constructor4 = JavaTokenType.class.getDeclaredConstructor(String.class, int.class, String.class, Tag[].class);
constructor4.setAccessible(true);
} catch(NoSuchMethodException | SecurityException e) {
throw new RuntimeException(e);
}
}
@SneakyThrows
public static JavaTokenType add(@NonNull String name) {
JavaTokenType type = constructor1.newInstance(name, VALUES.size());
mutableValues.add(type);
return type;
}
@SneakyThrows
public static JavaTokenType add(@NonNull String name, Tag... tags) {
for(var tag : tags) {
Objects.requireNonNull(tag);
}
JavaTokenType type = constructor2.newInstance(name, VALUES.size(), tags);
mutableValues.add(type);
return type;
}
@SneakyThrows
public static JavaTokenType add(@NonNull String name, @NonNull String symbol) {
JavaTokenType type = constructor3.newInstance(name, VALUES.size(), symbol);
mutableValues.add(type);
mutableNormalTokens.add(type);
return type;
}
@SneakyThrows
public static JavaTokenType add(@NonNull String name, @NonNull String symbol, Tag... tags) {
for(var tag : tags) {
Objects.requireNonNull(tag);
}
JavaTokenType type = constructor4.newInstance(name, VALUES.size(), symbol, tags);
mutableValues.add(type);
mutableNormalTokens.add(type);
return type;
}*/
@Getter
private final Optional<String> symbol;
@Getter @Accessors(fluent = true)
private final String toString;
@Getter
private final Set<JavaTokenType.Tag> tags;
@Getter
private final boolean isKeyword;
JavaTokenType() {
symbol = Optional.empty();
toString = name();
tags = Collections.unmodifiableSet(EnumSet.noneOf(Tag.class));
isKeyword = false;
}
JavaTokenType(String str) {
symbol = Optional.of(str);
toString = "'" + str + "'";
tags = Collections.unmodifiableSet(EnumSet.noneOf(Tag.class));
isKeyword = isKeyword(str);
}
JavaTokenType(Tag tag) {
symbol = Optional.empty();
toString = name();
tags = Collections.unmodifiableSet(EnumSet.of(tag));
isKeyword = false;
}
JavaTokenType(String str, Tag tag) {
symbol = Optional.of(str);
toString = "'" + str + "'";
tags = Collections.unmodifiableSet(EnumSet.of(tag));
isKeyword = isKeyword(str) && !hasTag(Tag.NAMED);
}
JavaTokenType(Tag... tagsIn) {
symbol = Optional.empty();
toString = name();
tags = Collections.unmodifiableSet(tagsIn.length == 0? EnumSet.noneOf(Tag.class) : EnumSet.of(tagsIn[0], tagsIn));
isKeyword = false;
}
JavaTokenType(String str, Tag... tagsIn) {
symbol = Optional.of(str);
toString = "'" + str + "'";
tags = Collections.unmodifiableSet(tagsIn.length == 0? EnumSet.noneOf(Tag.class) : EnumSet.of(tagsIn[0], tagsIn));
isKeyword = isKeyword(str) && !hasTag(Tag.NAMED);
}
private static boolean isKeyword(String str) {
return Character.isJavaIdentifierPart(str.charAt(str.length()-1));
}
@Override
public int length() {
return symbol.map(String::length).orElse(0);
}
@Override
public char charAt(int index) {
return symbol.orElse("").charAt(index);
}
@Override
public CharSequence subSequence(int start, int end) {
return symbol.orElse("").subSequence(start, end);
}
@Override
public boolean test(Token<JavaTokenType> t) {
return this == t.getType();
}
public boolean hasTag(@NonNull Tag tag) {
return tags.contains(tag);
}
public static enum Tag implements TokenPredicate<JavaTokenType> {
NAMED,
PRIMITIVE_TYPE,
STATEMENT_KW,
CLASS_MODIFIER,
LOCAL_VAR_MODIFIER,
FIELD_MODIFIER,
METHOD_MODIFIER,
CONSTRUCTOR_MODIFIER,
VISIBILITY_MODIFIER,
MODULE_MODIFIER,
REQUIRES_MODIFIER,
;
@Override
public boolean test(Token<JavaTokenType> token) {
return token.getType().hasTag(this);
}
}
}
| 10,251 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
Token.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/JavaParser/src/jtree/parser/Token.java | package jtree.parser;
import org.apache.commons.text.StringEscapeUtils;
import lombok.NonNull;
import lombok.Value;
public @Value class Token<TokenType> {
TokenType type;
@NonNull String string;
@NonNull Position start, end;
@NonNull CharSequence line;
@Override
public String toString() {
var type = this.type.toString();
return String.format("%s(type=%s, string=%s, start=%s, end=%s, line=%s)",
getClass().getSimpleName(),
Character.isJavaIdentifierPart(type.charAt(0)) && Character.isJavaIdentifierPart(type.charAt(type.length()-1)) || type.charAt(0) == '\'' && type.charAt(type.length()-1) == '\'' && type.length() > 1? type : " " + type + " ",
'"' + StringEscapeUtils.escapeJava(string) + '"',
start, end,
'"' + StringEscapeUtils.escapeJava(line.toString()) + '"');
}
}
| 930 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
Tester.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/JavaParser/src/jtree/parser/Tester.java | package jtree.parser;
import static jtree.parser.JavaTokenType.*;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.Stack;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.text.StringEscapeUtils;
import jtree.nodes.INode;
import jtree.nodes.Name;
import jtree.nodes.REPLEntry;
import jtree.nodes.Statement;
import jtree.util.Either;
import jtree.util.Utils;
import lombok.SneakyThrows;
public class Tester {
/*public static void main(String[] args) {
new Tester().run();
}*/
protected final Map<String, Function<String, Object>> methods = getMethodMap();
protected final Scanner keys = new Scanner(System.in);
protected boolean loop;
private static final Pattern COMMAND_REGEX = Pattern.compile("^\\s*/(.+)");
public void run() {
System.out.println("Enter commands below. Type \"/help\" for a list of commands.");
loop = true;
do {
String input = input("test> ");
var matcher = COMMAND_REGEX.matcher(input);
if(matcher.find()) {
var commandAndArgs = splitCommand(matcher.group(1));
String command = commandAndArgs.getLeft();
String[] args = commandAndArgs.getRight();
dispatchCommand(command, args);
} else {
parseJshellEntries(input);
}
} while(loop);
}
private String lastCommand, lastArgs[];
protected void dispatchCommand(String command, String[] args) {
if(command.equals("redo") || command.equals("Redo") || command.equals("REDO")) {
redo(args);
return;
}
switch(command) {
case "help", "Help", "HELP" -> {
lastCommand = command;
lastArgs = args;
help(args);
}
case "parse", "Parse", "PARSE" -> {
lastCommand = command;
lastArgs = args;
parse(args);
}
case "tokenize", "Tokenize", "TOKENIZE" -> {
lastCommand = command;
lastArgs = args;
tokenize(args);
}
case "open", "Open", "OPEN" -> {
lastCommand = command;
lastArgs = args;
open(args);
}
case "quit", "Quit", "QUIT" -> loop = false;
default -> {
System.out.println("Unknown command: " + command);
return;
}
}
}
protected void open(String[] args) {
if(args.length != 1) {
System.out.println(args.length == 0? "Missing file top open" : "Too many arguments to command 'open'");
return;
}
File file = new File(args[0]);
if(!file.exists() || !file.isFile()) {
System.out.println("File not found: " + args[0]);
}
try(var scan = new Scanner(file)) {
scan.useDelimiter("\\A");
var text = scan.next();
var parser = createParser(text, file.getName());
printNodeString(parser.parseCompilationUnit());
} catch(Exception e) {
e.printStackTrace(System.out);
}
}
protected Pattern PARSE_REPR_REGEX = Pattern.compile("(?ix) ^ parse \\s+ (-r \\s+ \\w+ | \\w+ \\s+ -r) (\\s|$)"),
PARSE_EXPR_REGEX = Pattern.compile("(?ix) ^ parse \\s+ \\w+ (\\s|$)"),
PARSE_FIND_REGEX = Pattern.compile("(?ix) ^ parse \\s+ -f (\\s|$)"),
PARSE_LIST_REGEX = Pattern.compile("(?ix) ^ parse \\s* $"),
TOKENIZE_REGEX = Pattern.compile("(?ix) ^ tokenize (\\s|$)"),
OPEN_REGEX = Pattern.compile("(?ix) ^ open (\\s|$)");
protected Pair<String, String[]> splitCommand(String input) {
String[] split = input.split("\\s+",
PARSE_REPR_REGEX.matcher(input).find()? 4
: PARSE_FIND_REGEX.matcher(input).find()? 3
: PARSE_EXPR_REGEX.matcher(input).find()? 3
: PARSE_LIST_REGEX.matcher(input).find()? 0
: TOKENIZE_REGEX.matcher(input).find()? 2
: OPEN_REGEX.matcher(input).find()? 2
: 0);
String[] args = new String[split.length-1];
System.arraycopy(split, 1, args, 0, args.length);
return Pair.of(split[0], args);
/*String command, args[];
int i;
for(i = 0; i < input.length(); i++) {
if(Character.isWhitespace(input.charAt(i))) {
break;
}
}
command = input.substring(0, i);
while(i < input.length() && Character.isWhitespace(input.charAt(i))) {
i++;
}
if(i < input.length()) {
if(command.equals("parse")) {
int start = i;
for(; i < input.length(); i++) {
if(Character.isWhitespace(input.charAt(i))) {
break;
}
}
String subcommand = input.substring(start, i);
while(i < input.length() && Character.isWhitespace(input.charAt(i))) {
i++;
}
if(i < input.length()) {
if(subcommand.equals("-r")) {
start = i;
for(; i < input.length(); i++) {
if(Character.isWhitespace(input.charAt(i))) {
break;
}
}
String subcommand2 = input.substring(start, i);
while(i < input.length() && Character.isWhitespace(input.charAt(i))) {
i++;
}
if(i < input.length()) {
args = new String[] {subcommand, subcommand2, input.substring(i)};
} else {
args = new String[] {subcommand, subcommand2};
}
} else {
args = new String[] {subcommand, input.substring(i)};
}
} else {
args = new String[] {subcommand};
}
} else {
args = new String[] {input.substring(i)};
}
} else {
args = new String[0];
}
return Pair.of(command, args);*/
}
protected void help(String[] args) {
if(args.length == 0) {
printHelp();
} else {
System.out.println("Too many arguments to command 'help'");
}
}
protected void printHelp() {
System.out.println(
"Commands:\n"
+ "/help\n"
+ "/parse [[-r] <type> <code>]\n"
+ "/parse -f <search terms>\n"
+ "/tokenize <text>\n"
+ "/open <file>"
);
}
protected void redo(String[] args) {
if(args.length == 0) {
redo();
} else {
System.out.println("Too many arguments to command 'redo'");
}
}
protected void redo() {
if(lastCommand == null) {
System.out.println("No previous command");
} else {
dispatchCommand(lastCommand, lastArgs);
}
}
protected void parse(String[] args) {
if(args.length == 0) {
listParseMethods(methods.keySet());
} else if(args[0].equals("-f")) {
searchForParseMethods(args);
} else {
executeParseMethod(args);
}
}
protected void listParseMethods(Collection<String> parseMethods) {
int count = 0;
for(var word : parseMethods) {
System.out.print(word);
if(count == 5) {
System.out.println();
count = 0;
} else {
count++;
System.out.print(" ");
}
}
if(count != 0) {
System.out.println();
}
}
protected void searchForParseMethods(String[] args) {
assert args.length >= 1;
assert args[0].equals("-f");
var searchTerms = new ArrayList<String>();
if(args.length == 1) {
var arg = input("... > ").strip();
searchTerms.add(arg);
lastArgs = new String[args.length+1];
System.arraycopy(args, 0, lastArgs, 0, args.length);
lastArgs[args.length] = arg;
} else {
for(int i = 1; i < args.length; i++) {
searchTerms.add(args[i]);
}
}
var results = new ArrayList<String>();
for(var name : methods.keySet()) {
boolean matches = false;
for(var searchTerm : searchTerms) {
if(searchTerm.startsWith("-")) {
if(name.toLowerCase().contains(searchTerm.substring(1).toLowerCase())) {
matches = false;
break;
}
} else if(name.toLowerCase().contains(searchTerm.toLowerCase())) {
matches = true;
break;
}
}
if(matches) {
results.add(name);
}
}
if(results.isEmpty()) {
System.out.println("No parse methods matched your search terms.");
} else {
listParseMethods(results);
}
}
static class UnfinishedLineManager {
Stack<Character> stack = new Stack<>();
char stringChar;
boolean inString, inMLString, escape, inSLC, inMLC;
boolean isUnfinished() {
return inString || inMLString || inMLC || !stack.isEmpty();
}
void traverseLine(String line) {
for(int i = 0; i < line.length(); i++) {
char ch = line.charAt(i);
if(inString) {
if(escape) {
escape = false;
} else if(ch == stringChar || ch == '\n') {
inString = false;
stringChar = 0;
} else if(ch == '\\') {
escape = true;
}
} else if(inMLString) {
if(escape) {
escape = false;
} else if(ch == stringChar && line.startsWith(Character.toString(stringChar).repeat(3), i)) {
inMLString = false;
stringChar = 0;
} else if(ch == '\\') {
escape = true;
}
} else if(inSLC) {
if(ch == '\n') {
inSLC = false;
}
} else if(inMLC) {
if(line.startsWith("*/", i)) {
inMLC = false;
i++;
}
} else {
if(!stack.isEmpty() && ch == stack.peek()) {
stack.pop();
} else {
switch(ch) {
case '(' -> stack.push(')');
case '[' -> stack.push(']');
case '{' -> stack.push('}');
case '"' -> {
if(line.startsWith("\"\"\"", i)) {
inMLString = true;
} else {
inString = true;
}
stringChar = ch;
}
case '\'' -> {
inString = true;
stringChar = ch;
}
case '/' -> {
if(line.startsWith("//")) {
inSLC = true;
i++;
} else if(line.startsWith("/*")) {
inMLC = true;
i++;
}
}
}
}
}
}
}
}
protected void parseJshellEntries(String input) {
var lineManager = new UnfinishedLineManager();
lineManager.traverseLine(input);
if(lineManager.isUnfinished() || isBlank(input) || input.charAt(input.length()-1) == '\\') {
var sb = new StringBuilder(input);
try {
do {
String line = '\n' + input("... > ");
if(sb.length() != 0 && sb.charAt(sb.length()-1) == '\\') {
line = line.stripLeading();
sb.delete(sb.length()-1, sb.length());
}
sb.append(line);
lineManager.traverseLine(line);
} while(lineManager.isUnfinished() || isBlank(sb) || sb.charAt(sb.length()-1) == '\\');
} catch(NoSuchElementException e) {
return;
}
input = sb.toString();
}
lastCommand = "parse";
if(lastArgs != null && lastArgs.length == 2) {
lastArgs[0] = "jshellEntries";
lastArgs[1] = input;
} else {
lastArgs = new String[] {"jshellEntries", input};
}
var parser = createParser(input, "<string>");
try {
printJshellEntries(parser.parseJshellEntries());
} catch(Exception e) {
e.printStackTrace(System.out);
System.out.println(e.getClass().getName() + ": " + e.getMessage());
}
}
protected void printJshellEntries(List<REPLEntry> jshellEntries) {
boolean first = true;
for(var elem : jshellEntries) {
if(first) {
first = false;
} else {
System.out.println();
}
printNodeString(elem);
}
}
protected void executeParseMethod(String[] args) {
assert args.length > 0;
Function<String, Object> parseMethod;
String code;
boolean repr = false;
try {
int index = 0;
if(args[0].equals("-r")) {
repr = true;
index = 1;
}
String parseMethodName = args[index];
if(parseMethodName.equals("statement")) {
parseMethodName = "blockStatement";
}
parseMethod = methods.get(parseMethodName);
if(parseMethod == null) {
System.out.println("Unknown parse method: " + args[index]);
return;
}
var sb = new StringBuilder();
var lineManager = new UnfinishedLineManager();
if(args.length-index > 1) {
for(int i = index+1; i < args.length; i++) {
if(i != index+1) {
sb.append(' ');
}
sb.append(args[i]);
lineManager.traverseLine(args[i]);
}
} else {
String line = input("... > ");
sb.append(line);
lineManager.traverseLine(line);
lastArgs = new String[args.length+1];
System.arraycopy(args, 0, lastArgs, 0, args.length);
}
while(lineManager.isUnfinished() || isBlank(sb) || sb.charAt(sb.length()-1) == '\\') {
String line = '\n' + input("... > ");
if(sb.length() != 0 && sb.charAt(sb.length()-1) == '\\') {
line = line.stripLeading();
sb.delete(sb.length()-1, sb.length());
}
sb.append(line);
lineManager.traverseLine(line);
}
lastArgs[lastArgs.length-1] = code = sb.toString();
if(parseMethodName.equals("jshellEntries") && !repr) {
parseJshellEntries(code);
return;
}
} catch(NoSuchElementException e) {
return;
}
try {
var result = parseMethod.apply(code);
if(repr) {
printNodeRepr(result);
} else {
printNodeString(result);
}
} catch(Exception e) {
e.printStackTrace(System.out);
System.out.println(e.getClass().getName() + ": " + e.getMessage());
}
}
protected static boolean isBlank(CharSequence cseq) {
for(int i = 0; i < cseq.length(); i++) {
if(!Character.isWhitespace(cseq.charAt(i))) {
return false;
}
}
return true;
}
protected void tokenize(String[] args) {
var sb = new StringBuilder();
if(args.length > 0) {
for(int i = 0; i < args.length; i++) {
if(i != 0) {
sb.append(' ');
}
sb.append(args[i]);
}
} else {
sb.append(input("... > ").stripTrailing());
}
while(sb.charAt(sb.length()-1) == '\\') {
sb.delete(sb.length()-1, sb.length());
sb.append(input("... > ").stripLeading());
}
String text = sb.toString();
lastArgs = new String[] {"tokenize", text};
var tkzr = createTokenizer(text, "<string>");
for(var token : Utils.iter(tkzr)) {
System.out.println(token);
}
}
protected String input(String prompt) {
System.out.print(prompt);
return keys.nextLine();
}
protected JavaParser createParser(CharSequence text, String filename) {
return new JavaParser(text, filename);
}
protected JavaTokenizer<JavaTokenType> createTokenizer(CharSequence text, String filename) {
return new JavaTokenizer<>(text, filename, ENDMARKER, ERRORTOKEN, STRING, CHARACTER, NUMBER, NAME, COMMENT,
JavaTokenType.NORMAL_TOKENS.stream()
.collect(Collectors.toMap(token -> token.getSymbol().orElseThrow(), token -> token)));
}
@SuppressWarnings("unchecked")
protected Class<? extends JavaParser>[] getParserClasses() {
return new Class[] { JavaParser.class };
}
protected void printNodeString(Object obj) {
if(obj instanceof INode) {
System.out.println(((INode)obj).toCode());
} else if(obj instanceof List) {
boolean first = true;
for(var elem : (List<?>)obj) {
if(first) {
first = false;
} else {
System.out.println();
}
printNodeString(elem);
}
} else if(obj instanceof Either) {
printNodeString(((Either<?,?>)obj).getValue());
} else if(obj instanceof Pair) {
var pair = (Pair<?,?>)obj;
printNodeString(pair.getLeft());
System.out.println();
printNodeString(pair.getRight());
} else if(obj instanceof String) {
System.out.print('"');
System.out.print(StringEscapeUtils.escapeJava((String)obj));
System.out.println('"');
} else {
System.out.println(obj);
}
}
protected void printNodeRepr(Object obj) {
if(obj instanceof INode) {
System.out.println(((INode)obj).toString());
} else if(obj instanceof List) {
boolean first = true;
for(var elem : (List<?>)obj) {
if(first) {
first = false;
} else {
System.out.println();
}
printNodeRepr(elem);
}
} else if(obj instanceof Either) {
printNodeRepr(((Either<?,?>)obj).getValue());
} else if(obj instanceof Pair) {
var pair = (Pair<?,?>)obj;
printNodeRepr(pair.getLeft());
System.out.println();
printNodeRepr(pair.getRight());
} else if(obj instanceof String) {
System.out.print('"');
System.out.print(StringEscapeUtils.escapeJava((String)obj));
System.out.println('"');
} else {
System.out.println(obj);
}
}
@SneakyThrows
private HashMap<String, Function<String,Object>> getMethodMap() {
var methods = new HashMap<String, Function<String, Object>>();
for(var parserType : getParserClasses()) {
for(var method : parserType.getMethods()) {
if(!Modifier.isStatic(method.getModifiers()) && method.getParameterCount() == 0
&& method.getName().startsWith("parse") && method.getReturnType() != void.class) {
methods.put(Character.toLowerCase(method.getName().charAt(5)) + method.getName().substring(6),
new Function<>() {
@SuppressWarnings({ "unchecked", "rawtypes" })
@SneakyThrows
public Object apply(String str) {
var parser = createParser(str, "<string>");
Object result;
try(var $1 = parser.preStmts.enter();
var $2 = parser.typeNames.enter(new Name("$Shell"))) {
var obj = method.invoke(parser);
if(parser.preStmts.isEmpty()) {
result = obj;
} else {
List list = parser.preStmts.get();
if(obj instanceof List) {
list.addAll((List)obj);
result = list;
} else if(obj instanceof Statement) {
result = parser.preStmts.apply((Statement)obj);
} else {
list.add(obj);
result = list;
}
}
} catch(InvocationTargetException e) {
throw e.getCause();
}
if(!parser.accept(ENDMARKER)) {
throw parser.syntaxError("unexpected token " + parser.token, parser.token);
}
return result;
}
});
/*if(INode.class.isAssignableFrom(method.getReturnType())) {
methods.put(Character.toLowerCase(method.getName().charAt(5)) + method.getName().substring(6),
new Function<>() {
@SneakyThrows
public Either<? extends INode, ? extends List<? extends INode>> apply(String str) {
var parser = createParser(str, "<string>");
Either<? extends INode, ? extends List<? extends INode>> result;
try(var $ = parser.preStmts.enter()) {
var node = (Node)method.invoke(parser);
if(parser.preStmts.isEmpty()) {
result = Either.first(node);
} else {
@SuppressWarnings({ "unchecked", "rawtypes" })
ArrayList<INode> list = (ArrayList)parser.preStmts.get();
list.add(node);
result = Either.second(list);
}
} catch(InvocationTargetException e) {
throw e.getCause();
}
if(parser.getTokens().hasNext()) {
var token = parser.getTokens().look(0);
if(token.getType() != ENDMARKER) {
throw new SyntaxError("unexpected token " + token, parser.getFilename(), token.getStart().getLine(), token.getStart().getColumn(), token.getLine());
}
}
return result;
}
});
} else if(List.class.isAssignableFrom(method.getReturnType())) {
var type = method.getGenericReturnType();
if(type instanceof ParameterizedType) {
var ptype = (ParameterizedType)type;
if(ptype.getActualTypeArguments().length == 1) {
var arg = ptype.getActualTypeArguments()[0];
if(arg instanceof Class && INode.class.isAssignableFrom((Class<?>)arg)) {
methods.put(Character.toLowerCase(method.getName().charAt(5)) + method.getName().substring(6),
new Function<>() {
@SuppressWarnings("unchecked")
@SneakyThrows
public Either<? extends INode, ? extends List<? extends INode>> apply(String str) {
var parser = createParser(str, "<string>");
Either<? extends INode, ? extends List<? extends INode>> result;
try(var $ = parser.preStmts.enter()) {
List<INode> list = (List<INode>)method.invoke(parser);
if(!parser.preStmts.isEmpty()) {
if(!(list instanceof ArrayList)) {
list = new ArrayList<>(list);
}
list.addAll(0, parser.preStmts.get());
}
result = Either.second(list);
} catch(InvocationTargetException e) {
throw e.getCause();
}
if(parser.getTokens().hasNext()) {
var token = parser.getTokens().next();
if(token.getType() != ENDMARKER) {
throw new SyntaxError("unexpected token " + token, parser.getFilename(), token.getStart().getLine(), token.getStart().getColumn(), token.getLine());
}
}
return result;
}
});
}
}
}
}*/
}
}
}
return methods;
}
}
| 20,885 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
TokenPredicate.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/JavaParser/src/jtree/parser/TokenPredicate.java | package jtree.parser;
import java.util.function.Predicate;
import org.apache.commons.text.StringEscapeUtils;
import lombok.NonNull;
@FunctionalInterface
public interface TokenPredicate<TokenType> extends Predicate<Token<TokenType>> {
@Override
default TokenPredicate<TokenType> or(@NonNull Predicate<? super Token<TokenType>> pred) {
var oldThis = this;
var str = oldThis.toString() + " || " + pred.toString();
return new TokenPredicate<>() {
public boolean test(Token<TokenType> token) {
return oldThis.test(token) || pred.test(token);
}
public String toString() {
return str;
}
};
}
default TokenPredicate<TokenType> or(@NonNull String str) {
var oldThis = this;
var toString = oldThis.toString() + " || \"" + StringEscapeUtils.escapeJava(str) + '"';
return new TokenPredicate<>() {
public boolean test(Token<TokenType> token) {
return oldThis.test(token) || token.getString().equals(str);
}
public String toString() {
return toString;
}
};
}
@Override
default TokenPredicate<TokenType> and(@NonNull Predicate<? super Token<TokenType>> pred) {
var oldThis = this;
String toString1 = oldThis.toString(), toString2 = pred.toString();
int depth;
boolean inString, escape;
char stringChar;
depth = stringChar = 0;
inString = escape = false;
loop:
for(int i = 0; i < toString1.length(); i++) {
char c = toString1.charAt(i);
if(inString) {
if(escape) {
escape = false;
} else if(c == stringChar) {
inString = false;
} else if(c == '\\') {
escape = true;
}
} else {
switch(c) {
case '(' -> depth++;
case ')' -> depth--;
case '"', '\'' -> {
inString = true;
stringChar = c;
}
case '|' -> {
if(depth == 0 && i + 1 < toString1.length() && toString1.charAt(i+1) == '|') {
toString1 = '(' + toString1 + ')';
break loop;
}
}
}
}
}
depth = stringChar = 0;
inString = escape = false;
loop:
for(int i = 0; i < toString2.length(); i++) {
char c = toString2.charAt(i);
if(inString) {
if(escape) {
escape = false;
} else if(c == stringChar) {
inString = false;
} else if(c == '\\') {
escape = true;
}
} else {
switch(c) {
case '(' -> depth++;
case ')' -> depth--;
case '"', '\'' -> {
inString = true;
stringChar = c;
}
case '|' -> {
if(depth == 0 && i + 1 < toString2.length() && toString2.charAt(i+1) == '|') {
toString2 = '(' + toString2 + ')';
break loop;
}
}
}
}
}
var toString = toString1 + " && " + toString2;
return new TokenPredicate<>() {
public boolean test(Token<TokenType> token) {
return oldThis.test(token) && pred.test(token);
}
public String toString() {
return toString;
}
};
}
default TokenPredicate<TokenType> and(@NonNull String str) {
var oldThis = this;
String toString1 = oldThis.toString();
int depth;
boolean inString, escape;
char stringChar;
depth = stringChar = 0;
inString = escape = false;
loop:
for(int i = 0; i < toString1.length(); i++) {
char c = toString1.charAt(i);
if(inString) {
if(escape) {
escape = false;
} else if(c == stringChar) {
inString = false;
} else if(c == '\\') {
escape = true;
}
} else {
switch(c) {
case '(' -> depth++;
case ')' -> depth--;
case '"', '\'' -> {
inString = true;
stringChar = c;
}
case '|' -> {
if(depth == 0 && i + 1 < toString1.length() && toString1.charAt(i+1) == '|') {
toString1 = '(' + toString1 + ')';
break loop;
}
}
}
}
}
var toString = toString1 + " && \"" + StringEscapeUtils.escapeJava(str) + '"';
return new TokenPredicate<>() {
public boolean test(Token<TokenType> token) {
return oldThis.test(token) && token.getString().equals(str);
}
public String toString() {
return toString;
}
};
}
@Override
default TokenPredicate<TokenType> negate() {
class NotTokenPredicate implements TokenPredicate<TokenType> {
private final TokenPredicate<TokenType> pred;
private final String toString;
public NotTokenPredicate(TokenPredicate<TokenType> pred) {
this.pred = pred;
String toString1 = pred.toString();
int depth;
boolean inString, escape;
char stringChar;
depth = stringChar = 0;
inString = escape = false;
loop:
for(int i = 0; i < toString1.length(); i++) {
char c = toString1.charAt(i);
if(inString) {
if(escape) {
escape = false;
} else if(c == stringChar) {
inString = false;
} else if(c == '\\') {
escape = true;
}
} else {
switch(c) {
case '(' -> depth++;
case ')' -> depth--;
case '"', '\'' -> {
inString = true;
stringChar = c;
}
case '&' -> {
if(depth == 0 && i + 1 < toString1.length() && toString1.charAt(i+1) == '&') {
toString1 = '(' + toString1 + ')';
break loop;
}
}
case '|' -> {
if(depth == 0 && i + 1 < toString1.length() && toString1.charAt(i+1) == '|') {
toString1 = '(' + toString1 + ')';
break loop;
}
}
}
}
}
toString = "!" + toString1;
}
@Override
public boolean test(Token<TokenType> t) {
return !pred.test(t);
}
@Override
public String toString() {
return toString;
}
@Override
public TokenPredicate<TokenType> negate() {
return pred;
}
}
return new NotTokenPredicate(this);
}
static <TokenType> TokenPredicate<TokenType> not(TokenPredicate<TokenType> pred) {
return pred.negate();
}
static <TokenType> TokenPredicate<TokenType> ofString(@NonNull String str) {
var toString = '"' + StringEscapeUtils.escapeJava(str) + '"';
return new TokenPredicate<>() {
@Override
public boolean test(Token<TokenType> t) {
return t.getString().equals(str);
}
public String toString() {
return toString;
}
};
}
static <TokenType> TokenPredicate<TokenType> not(@NonNull String str) {
return TokenPredicate.<TokenType>ofString(str).negate();
}
}
| 6,495 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
SyntaxError.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/JavaParser/src/jtree/parser/SyntaxError.java | package jtree.parser;
import lombok.Setter;
public class SyntaxError extends RuntimeException {
private int lineNumber, column;
private CharSequence line;
@Setter
private String filename;
public SyntaxError(String message, String filename, int lineNumber, int column, CharSequence line) {
super(message);
this.filename = filename;
this.lineNumber = lineNumber;
this.column = column;
this.line = line;
}
@Override
public String getMessage() {
return super.getMessage() + "\n" + (filename == null? "" : "in file " + filename + " ") + "on line " + lineNumber + ":" + formatLine(line, column);
}
private static String formatLine(CharSequence line, int column) {
var sb = new StringBuilder("\n ");
for(int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
if(c == '\t') {
sb.append(" ");
} else if(Character.isWhitespace(c)) {
sb.append(' ');
} else {
sb.append(c);
}
}
sb.append("\n ");
if(column > line.length()) {
column = line.length();
}
for(int i = 1; i < column; i++) {
if(line.charAt(i) == '\t') {
sb.append(" ");
} else {
sb.append(' ');
}
}
sb.append('^');
return sb.toString();
}
}
| 1,203 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
JavaParser.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/JavaParser/src/jtree/parser/JavaParser.java | package jtree.parser;
import static java.util.Collections.singletonList;
import static jtree.parser.JavaTokenType.AMP;
import static jtree.parser.JavaTokenType.AMPAMP;
import static jtree.parser.JavaTokenType.ARROW;
import static jtree.parser.JavaTokenType.ASSERT;
import static jtree.parser.JavaTokenType.AT;
import static jtree.parser.JavaTokenType.BANG;
import static jtree.parser.JavaTokenType.BANGEQ;
import static jtree.parser.JavaTokenType.BAR;
import static jtree.parser.JavaTokenType.BARBAR;
import static jtree.parser.JavaTokenType.BREAK;
import static jtree.parser.JavaTokenType.CARET;
import static jtree.parser.JavaTokenType.CASE;
import static jtree.parser.JavaTokenType.CATCH;
import static jtree.parser.JavaTokenType.CHARACTER;
import static jtree.parser.JavaTokenType.CLASS;
import static jtree.parser.JavaTokenType.COLCOL;
import static jtree.parser.JavaTokenType.COLON;
import static jtree.parser.JavaTokenType.COMMA;
import static jtree.parser.JavaTokenType.COMMENT;
import static jtree.parser.JavaTokenType.DEFAULT;
import static jtree.parser.JavaTokenType.DO;
import static jtree.parser.JavaTokenType.DOT;
import static jtree.parser.JavaTokenType.ELLIPSIS;
import static jtree.parser.JavaTokenType.ELSE;
import static jtree.parser.JavaTokenType.ENDMARKER;
import static jtree.parser.JavaTokenType.ENUM;
import static jtree.parser.JavaTokenType.EQ;
import static jtree.parser.JavaTokenType.EQEQ;
import static jtree.parser.JavaTokenType.ERRORTOKEN;
import static jtree.parser.JavaTokenType.EXPORTS;
import static jtree.parser.JavaTokenType.EXTENDS;
import static jtree.parser.JavaTokenType.FALSE;
import static jtree.parser.JavaTokenType.FINAL;
import static jtree.parser.JavaTokenType.FINALLY;
import static jtree.parser.JavaTokenType.FOR;
import static jtree.parser.JavaTokenType.GT;
import static jtree.parser.JavaTokenType.GTEQ;
import static jtree.parser.JavaTokenType.IF;
import static jtree.parser.JavaTokenType.IMPLEMENTS;
import static jtree.parser.JavaTokenType.IMPORT;
import static jtree.parser.JavaTokenType.INSTANCEOF;
import static jtree.parser.JavaTokenType.INTERFACE;
import static jtree.parser.JavaTokenType.LBRACE;
import static jtree.parser.JavaTokenType.LBRACKET;
import static jtree.parser.JavaTokenType.LPAREN;
import static jtree.parser.JavaTokenType.LT;
import static jtree.parser.JavaTokenType.LTEQ;
import static jtree.parser.JavaTokenType.LTLT;
import static jtree.parser.JavaTokenType.MODULE;
import static jtree.parser.JavaTokenType.NAME;
import static jtree.parser.JavaTokenType.NEW;
import static jtree.parser.JavaTokenType.NULL;
import static jtree.parser.JavaTokenType.NUMBER;
import static jtree.parser.JavaTokenType.OPEN;
import static jtree.parser.JavaTokenType.OPENS;
import static jtree.parser.JavaTokenType.PACKAGE;
import static jtree.parser.JavaTokenType.PERCENT;
import static jtree.parser.JavaTokenType.PLUS;
import static jtree.parser.JavaTokenType.PLUSPLUS;
import static jtree.parser.JavaTokenType.PROVIDES;
import static jtree.parser.JavaTokenType.QUES;
import static jtree.parser.JavaTokenType.RBRACE;
import static jtree.parser.JavaTokenType.RBRACKET;
import static jtree.parser.JavaTokenType.REQUIRES;
import static jtree.parser.JavaTokenType.RETURN;
import static jtree.parser.JavaTokenType.RPAREN;
import static jtree.parser.JavaTokenType.SEMI;
import static jtree.parser.JavaTokenType.SLASH;
import static jtree.parser.JavaTokenType.STAR;
import static jtree.parser.JavaTokenType.STATIC;
import static jtree.parser.JavaTokenType.STRING;
import static jtree.parser.JavaTokenType.SUB;
import static jtree.parser.JavaTokenType.SUBSUB;
import static jtree.parser.JavaTokenType.SUPER;
import static jtree.parser.JavaTokenType.SWITCH;
import static jtree.parser.JavaTokenType.SYNCHRONIZED;
import static jtree.parser.JavaTokenType.THIS;
import static jtree.parser.JavaTokenType.THROW;
import static jtree.parser.JavaTokenType.THROWS;
import static jtree.parser.JavaTokenType.TILDE;
import static jtree.parser.JavaTokenType.TO;
import static jtree.parser.JavaTokenType.TRUE;
import static jtree.parser.JavaTokenType.TRY;
import static jtree.parser.JavaTokenType.USES;
import static jtree.parser.JavaTokenType.VAR;
import static jtree.parser.JavaTokenType.VOID;
import static jtree.parser.JavaTokenType.WHILE;
import static jtree.parser.JavaTokenType.WITH;
import static jtree.parser.JavaTokenType.YIELD;
import static jtree.util.Utils.emptyList;
import static jtree.util.Utils.iter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.text.StringEscapeUtils;
import jtree.nodes.Annotation;
import jtree.nodes.AnnotationArgument;
import jtree.nodes.AnnotationDecl;
import jtree.nodes.AnnotationProperty;
import jtree.nodes.AnnotationValue;
import jtree.nodes.ArrayCreator;
import jtree.nodes.ArrayInitializer;
import jtree.nodes.ArrayType;
import jtree.nodes.AssertStmt;
import jtree.nodes.AssignExpr;
import jtree.nodes.BinaryExpr;
import jtree.nodes.Block;
import jtree.nodes.BreakStmt;
import jtree.nodes.CastExpr;
import jtree.nodes.Catch;
import jtree.nodes.ClassCreator;
import jtree.nodes.ClassDecl;
import jtree.nodes.ClassInitializer;
import jtree.nodes.ClassLiteral;
import jtree.nodes.CompilationUnit;
import jtree.nodes.ConditionalExpr;
import jtree.nodes.ConstructorCall;
import jtree.nodes.ConstructorDecl;
import jtree.nodes.ContinueStmt;
import jtree.nodes.Dimension;
import jtree.nodes.Directive;
import jtree.nodes.DoStmt;
import jtree.nodes.EmptyStmt;
import jtree.nodes.EnumDecl;
import jtree.nodes.EnumField;
import jtree.nodes.ExportsDirective;
import jtree.nodes.Expression;
import jtree.nodes.ExpressionStmt;
import jtree.nodes.ForEachStmt;
import jtree.nodes.ForStmt;
import jtree.nodes.FormalParameter;
import jtree.nodes.FunctionCall;
import jtree.nodes.FunctionDecl;
import jtree.nodes.GenericType;
import jtree.nodes.IfStmt;
import jtree.nodes.ImportDecl;
import jtree.nodes.IndexExpr;
import jtree.nodes.InformalParameter;
import jtree.nodes.Initializer;
import jtree.nodes.InterfaceDecl;
import jtree.nodes.LabeledStmt;
import jtree.nodes.Lambda;
import jtree.nodes.Literal;
import jtree.nodes.Member;
import jtree.nodes.MemberAccess;
import jtree.nodes.MethodReference;
import jtree.nodes.Modifier;
import jtree.nodes.Modifier.Modifiers;
import jtree.nodes.ModuleCompilationUnit;
import jtree.nodes.Name;
import jtree.nodes.NormalCompilationUnit;
import jtree.nodes.OpensDirective;
import jtree.nodes.PackageDecl;
import jtree.nodes.ParensExpr;
import jtree.nodes.PostDecrementExpr;
import jtree.nodes.PostIncrementExpr;
import jtree.nodes.PreDecrementExpr;
import jtree.nodes.PreIncrementExpr;
import jtree.nodes.PrimitiveType;
import jtree.nodes.ProvidesDirective;
import jtree.nodes.QualifiedName;
import jtree.nodes.REPLEntry;
import jtree.nodes.ReferenceType;
import jtree.nodes.RequiresDirective;
import jtree.nodes.ResourceSpecifier;
import jtree.nodes.ReturnStmt;
import jtree.nodes.Size;
import jtree.nodes.Statement;
import jtree.nodes.SuperFunctionCall;
import jtree.nodes.SuperMethodReference;
import jtree.nodes.Switch;
import jtree.nodes.SwitchCase;
import jtree.nodes.SynchronizedStmt;
import jtree.nodes.This;
import jtree.nodes.ThisParameter;
import jtree.nodes.ThrowStmt;
import jtree.nodes.TryStmt;
import jtree.nodes.Type;
import jtree.nodes.TypeArgument;
import jtree.nodes.TypeDecl;
import jtree.nodes.TypeIntersection;
import jtree.nodes.TypeParameter;
import jtree.nodes.TypeTest;
import jtree.nodes.TypeUnion;
import jtree.nodes.UnaryExpr;
import jtree.nodes.UsesDirective;
import jtree.nodes.Variable;
import jtree.nodes.VariableDecl;
import jtree.nodes.VariableDeclarator;
import jtree.nodes.VoidType;
import jtree.nodes.WhileStmt;
import jtree.nodes.WildcardTypeArgument;
import jtree.nodes.YieldStmt;
import jtree.parser.JavaTokenType.Tag;
import jtree.util.ContextManager;
import jtree.util.ContextStack;
import jtree.util.Either;
import jtree.util.LookAheadListIterator;
import lombok.Getter;
import lombok.NonNull;
public class JavaParser {
@Getter
protected LookAheadListIterator<Token<JavaTokenType>> tokens;
protected Token<JavaTokenType> token;
@Getter
protected String filename;
@Getter
protected JavaTokenizer<JavaTokenType> tokenizer;
protected ContextStack<Name> typeNames = new ContextStack<>();
protected class PreStmtManager implements Iterable<Statement> {
private ContextStack<ArrayList<Statement>> stack = new ContextStack<>();
public void append(Statement stmt) {
stack.current().add(stmt);
}
public Block apply(Block stmt) {
if(!stack.isEmpty()) {
var stmts = stack.current();
if(!stmts.isEmpty()) {
stmt.getStatements().addAll(0, stmts);
}
}
return stmt;
}
@SuppressWarnings("unchecked")
public Statement apply(Statement stmt) {
if(stack.isEmpty()) {
return stmt;
}
var stmts = stack.current();
if(stmts.isEmpty()) {
return stmt;
} else if(stmt instanceof Block) {
((Block)stmt).getStatements().addAll(0, stmts);
return stmt;
} else if(stmt instanceof VariableDecl && stack.size() > 1) {
var vardecl = (VariableDecl)stmt;
if((!(vardecl.getType() instanceof GenericType) || !((GenericType)vardecl.getType()).getName().equals("var"))) {
var declarators = vardecl.getDeclarators().stream()
.map(declarator -> new VariableDeclarator(declarator.getName(), declarator.getDimensions()))
.collect(Collectors.toList());
var prevstmts = stack.get(stack.size()-2);
prevstmts.add(0, new VariableDecl(vardecl.getType().clone(), declarators, vardecl.getModifiers(), vardecl.getAnnotations(), vardecl.getDocComment()));
for(var declarator : vardecl.getDeclarators()) {
var initializer = declarator.getInitializer();
if(initializer.isPresent()) {
Initializer init = initializer.get();
Expression value;
if(init instanceof ArrayInitializer) {
var dimensions = new ArrayList<>(declarator.getDimensions());
Type baseType;
if(vardecl.getType() instanceof ArrayType) {
var arrayType = (ArrayType)vardecl.getType();
baseType = arrayType.getBaseType();
dimensions.addAll(arrayType.getDimensions());
} else {
baseType = vardecl.getType();
}
value = new ArrayCreator(baseType, (ArrayInitializer<Initializer>)init, dimensions);
} else {
value = (Expression)init;
}
stmts.add(new ExpressionStmt(new AssignExpr(new Variable(declarator.getName()), value)));
}
}
return new Block(stmts);
}
}
// else
stmts.add(stmt);
return new Block(stmts);
}
public ContextManager enter() {
return stack.enter(new ArrayList<>());
}
public boolean isWithinContext() {
return !stack.isEmpty();
}
public boolean isWithoutContext() {
return stack.isEmpty();
}
public boolean isEmpty() {
return stack.current().isEmpty();
}
@Override
public Iterator<Statement> iterator() {
return stack.current().iterator();
}
public ArrayList<Statement> get() {
return stack.current();
}
}
protected PreStmtManager preStmts = new PreStmtManager();
public JavaParser(CharSequence text) {
this(text, "<unknown source>");
}
public JavaParser(CharSequence text, String filename) {
this.tokens = new LookAheadListIterator<>(iter(this.tokenizer = createTokenizer(text, filename)), token -> {
this.token = token;
if(this.token.getType() == COMMENT) {
nextToken();
}
});
this.filename = filename;
this.token = nextToken();
}
protected JavaTokenizer<JavaTokenType> createTokenizer(CharSequence text, String filename) {
return new JavaTokenizer<>(text, filename, ENDMARKER, ERRORTOKEN, STRING, CHARACTER, NUMBER, NAME, COMMENT,
JavaTokenType.NORMAL_TOKENS.stream()
.collect(Collectors.toMap(token -> token.getSymbol().orElseThrow(), token -> token)));
}
protected Token<JavaTokenType> nextToken() {
do {
token = tokens.next();
} while(token.getType() == COMMENT);
return token;
}
protected Optional<String> getDocComment() {
var token = tokens.look(-2);
if(token.getType() == COMMENT && token.getString().startsWith("/**") && token.getString().length() > 4) {
return Optional.of(token.getString());
} else {
return Optional.empty();
}
}
protected void nextToken(int amount) {
if(amount <= 0) {
throw new IllegalArgumentException("amount <= 0");
}
for(int i = 0; i < amount; i++) {
nextToken();
}
}
protected boolean wouldAccept(TokenPredicate<JavaTokenType> test) {
return test.test(token);
}
protected boolean wouldAccept(String str) {
return token.getString().equals(str);
}
@SafeVarargs
protected final boolean wouldAccept(TokenPredicate<JavaTokenType>... tests) {
if(tests.length == 0) {
throw new IllegalArgumentException("no tests given");
}
if(tests[0].test(token)) {
for(int i = 1; i < tests.length; i++) {
if(!tests[i].test(tokens.look(i - 1))) {
return false;
}
}
return true;
} else {
return false;
}
}
@SafeVarargs
protected final boolean wouldAcceptPseudoOp(TokenPredicate<JavaTokenType>... tests) {
if(tests.length == 0) {
throw new IllegalArgumentException("no tests given");
}
if(tests[0].test(token)) {
var last = token;
for(int i = 1; i < tests.length; i++) {
var nextTok = tokens.look(i - 1);
if(!tests[i].test(nextTok) || !last.getEnd().equals(nextTok.getStart())) {
return false;
}
last = nextTok;
}
return true;
} else {
return false;
}
}
protected boolean wouldAccept(String... strs) {
if(strs.length == 0) {
throw new IllegalArgumentException("no tests given");
}
if(token.getString().equals(strs[0])) {
for(int i = 1; i < strs.length; i++) {
if(!tokens.look(i - 1).getString().equals(strs[i])) {
return false;
}
}
return true;
} else {
return false;
}
}
protected boolean wouldNotAccept(TokenPredicate<JavaTokenType> test) {
return token.getType() != ENDMARKER && !test.test(token);
}
protected boolean wouldNotAccept(String str) {
return token.getType() != ENDMARKER && !token.getString().equals(str);
}
@SafeVarargs
protected final boolean wouldNotAccept(TokenPredicate<JavaTokenType>... tests) {
return token.getType() != ENDMARKER && !wouldAccept(tests);
}
protected boolean accept(TokenPredicate<JavaTokenType> test) {
if(wouldAccept(test)) {
nextToken();
return true;
} else {
return false;
}
}
protected boolean accept(String symbol) {
if(wouldAccept(symbol)) {
nextToken();
return true;
} else {
return false;
}
}
@SafeVarargs
protected final boolean accept(TokenPredicate<JavaTokenType>... tests) {
if(wouldAccept(tests)) {
nextToken(tests.length);
return true;
} else {
return false;
}
}
@SafeVarargs
protected final boolean acceptPseudoOp(TokenPredicate<JavaTokenType>... tests) {
if(wouldAcceptPseudoOp(tests)) {
nextToken(tests.length);
return true;
} else {
return false;
}
}
protected boolean accept(String... strs) {
if(wouldAccept(strs)) {
nextToken(strs.length);
return true;
} else {
return false;
}
}
protected SyntaxError syntaxError(String message) {
return syntaxError(message, token);
}
protected SyntaxError syntaxError(String message, Token<JavaTokenType> token) {
throw new SyntaxError(message, filename, token.getStart().getLine(), token.getStart().getColumn(),
token.getLine());
}
protected void require(TokenPredicate<JavaTokenType> test) {
if(!accept(test)) {
throw syntaxError("expected '" + test + "' here, got " + token);
}
}
protected void require(String test) {
if(!accept(test)) {
throw syntaxError("expected '" + test + "' here, got " + token);
}
}
@SafeVarargs
protected final void require(TokenPredicate<JavaTokenType>... tests) {
if(!accept(tests)) {
throw syntaxError("expected " + Arrays.toString(tests) + " here, got " + token);
}
}
protected final TokenPredicate<JavaTokenType> notInterface = not(INTERFACE);
protected static TokenPredicate<JavaTokenType> test(@NonNull TokenPredicate<JavaTokenType> pred) {
return pred;
}
protected static TokenPredicate<JavaTokenType> test(@NonNull String str) {
return token -> token.getString().equals(str);
}
protected static TokenPredicate<JavaTokenType> not(TokenPredicate<JavaTokenType> pred) {
return TokenPredicate.not(pred);
}
protected static TokenPredicate<JavaTokenType> not(@NonNull String str) {
return TokenPredicate.not(str);
}
public <T> ArrayList<T> listOf(Supplier<T> parser) {
return listOf(COMMA, parser);
}
public <T> ArrayList<T> listOf(TokenPredicate<JavaTokenType> separator, Supplier<T> parser) {
var list = new ArrayList<T>();
do {
list.add(parser.get());
} while(accept(separator));
return list;
}
public String parseIdent() {
var token = this.token;
require(Tag.NAMED);
return token.getString();
}
public Name parseName() {
return new Name(parseIdent());
}
public QualifiedName parseQualName() {
return new QualifiedName(listOf(DOT, this::parseName));
}
public Name parseTypeName() {
if(wouldAccept(VAR)) {
throw syntaxError("'var' is not allowed as a type name");
}
return parseName();
}
public QualifiedName parseQualTypeName() {
var names = new ArrayList<Name>();
Token<JavaTokenType> last;
do {
last = token;
names.add(parseName());
} while(accept(DOT));
if(names.get(names.size() - 1).equals("var") && names.size() > 1) {
throw new SyntaxError("'var' is not allowed as a type name", filename, last.getStart().getLine(),
last.getStart().getColumn(), last.getLine());
}
return new QualifiedName(names);
}
@SuppressWarnings("unchecked")
public List<REPLEntry> parseJshellEntries() {
var entries = new ArrayList<REPLEntry>();
while(!wouldAccept(ENDMARKER)) {
if(wouldAccept(AT.or(KEYWORD_MODIFIER))) {
var docComment = getDocComment();
var modsAndAnnos = new ModsAndAnnotations(emptyList(), parseAnnotations());
if(wouldAccept(PACKAGE)) {
entries.add(parsePackageDecl(docComment, modsAndAnnos.annos));
continue;
}
var modsAndAnnos2 = parseKeywordModsAndAnnotations();
modsAndAnnos2.annos.addAll(0, modsAndAnnos.annos);
modsAndAnnos = modsAndAnnos2;
entries.addAll((List<? extends REPLEntry>)parseClassMember(false, docComment, modsAndAnnos));
} else {
switch(token.getType()) {
case AT, INTERFACE, CLASS, ENUM:
entries.add(parseTypeDecl(getDocComment(), new ModsAndAnnotations()));
break;
case IMPORT:
entries.addAll(parseImportSection());
break;
case VOID: {
var docComment = getDocComment();
nextToken();
entries.addAll((List<? extends REPLEntry>)parseMethod(false, new VoidType(), emptyList(), docComment, new ModsAndAnnotations()));
break;
}
case PACKAGE:
if(wouldAccept(PACKAGE, Tag.NAMED, DOT.or(SEMI).or(ENDMARKER))) {
entries.add(parsePackageDecl(getDocComment(), emptyList()));
break;
}
default: {
vardecl:
if(wouldAccept(Tag.NAMED.or(KEYWORD_MODIFIER).or(PRIMITIVE_TYPES).or(LT))) {
try(var state = tokens.enter()) {
Optional<String> docComment;
ModsAndAnnotations modsAndAnnos;
Type type;
try {
docComment = getDocComment();
modsAndAnnos = parseFinalAndAnnotations();
if(wouldAccept(LT)) {
var typeParams = parseTypeParameters();
type = parseType();
entries.addAll((List<? extends REPLEntry>)parseMethod(false, type, typeParams, docComment, modsAndAnnos));
continue;
}
type = parseType();
if(!wouldAccept(Tag.NAMED)) {
state.reset();
break vardecl;
}
} catch(SyntaxError e) {
state.reset();
break vardecl;
}
if(modsAndAnnos.canBeMethodMods() && wouldAccept(Tag.NAMED, LPAREN)) {
entries.addAll((List<? extends REPLEntry>)parseMethod(false, type, emptyList(), parseName(), docComment, modsAndAnnos));
} else if(modsAndAnnos.canBeFieldMods() || modsAndAnnos.canBeLocalVarMods()) {
entries.addAll((List<? extends REPLEntry>)parseFieldDecl(type, docComment, modsAndAnnos));
} else {
throw syntaxError("Invalid modifiers");
}
continue;
}
}
entries.add(parseBlockStatement());
}
}
}
}
return entries;
}
public CompilationUnit parseCompilationUnit() {
Optional<String> docComment = getDocComment();
var modsAndAnnos = new ModsAndAnnotations(emptyList(), parseAnnotations());
Optional<PackageDecl> pckg;
if(wouldAccept(PACKAGE, Tag.NAMED)) {
pckg = Optional.of(parsePackageDecl(docComment, modsAndAnnos.annos));
docComment = getDocComment();
modsAndAnnos = parseClassModsAndAnnotations();
} else {
pckg = Optional.empty();
var modsAndAnnos2 = parseClassModsAndAnnotations();
modsAndAnnos2.annos.addAll(0, modsAndAnnos.annos);
modsAndAnnos = modsAndAnnos2;
}
List<ImportDecl> imports;
if(modsAndAnnos.isEmpty()) {
imports = parseImportSection();
docComment = getDocComment();
modsAndAnnos = parseClassModsAndAnnotations();
} else {
imports = emptyList();
}
if(modsAndAnnos.mods.isEmpty() && pckg.isEmpty() && wouldAccept(OPEN.or(MODULE))) {
return parseModuleCompilationUnit(imports, docComment, modsAndAnnos.annos);
} else {
return parseNormalCompilationUnit(pckg, imports, docComment, modsAndAnnos);
}
}
public ModuleCompilationUnit parseModuleCompilationUnit() {
return parseModuleCompilationUnit(parseImportSection());
}
public ModuleCompilationUnit parseModuleCompilationUnit(List<ImportDecl> imports) {
return parseModuleCompilationUnit(imports, getDocComment(), parseAnnotations());
}
public ModuleCompilationUnit parseModuleCompilationUnit(List<ImportDecl> imports, Optional<String> docComment, List<Annotation> annotations) {
boolean open = accept(OPEN);
require(MODULE);
var name = parseQualName();
require(LBRACE);
var directives = new ArrayList<Directive>();
while(wouldNotAccept(RBRACE)) {
directives.add(parseDirective());
}
require(RBRACE);
return new ModuleCompilationUnit(imports, name, open, directives, annotations, docComment);
}
public NormalCompilationUnit parseNormalCompilationUnit() {
var docComment = getDocComment();
var modsAndAnnos = new ModsAndAnnotations(emptyList(), parseAnnotations());
Optional<PackageDecl> pckg;
if(wouldAccept(PACKAGE, Tag.NAMED)) {
pckg = Optional.of(parsePackageDecl(docComment, modsAndAnnos.annos));
docComment = getDocComment();
modsAndAnnos = parseClassModsAndAnnotations();
} else {
pckg = Optional.empty();
var modsAndAnnos2 = parseClassModsAndAnnotations();
modsAndAnnos2.annos.addAll(0, modsAndAnnos.annos);
modsAndAnnos = modsAndAnnos2;
}
List<ImportDecl> imports;
if(modsAndAnnos.isEmpty()) {
imports = parseImportSection();
docComment = getDocComment();
modsAndAnnos = parseClassModsAndAnnotations();
} else {
imports = emptyList();
}
return parseNormalCompilationUnit(pckg, imports, docComment, modsAndAnnos);
}
public NormalCompilationUnit parseNormalCompilationUnit(Optional<PackageDecl> pckg) {
return parseNormalCompilationUnit(pckg, parseImportSection());
}
public NormalCompilationUnit parseNormalCompilationUnit(Optional<PackageDecl> pckg, List<ImportDecl> imports) {
var docComment = getDocComment();
return parseNormalCompilationUnit(pckg, imports, docComment, parseClassModsAndAnnotations());
}
public NormalCompilationUnit parseNormalCompilationUnit(Optional<PackageDecl> pckg, List<ImportDecl> imports,
Optional<String> docComment, ModsAndAnnotations modsAndAnnos) {
var types = new ArrayList<TypeDecl>();
if(!modsAndAnnos.isEmpty()) {
types.add(parseTypeDecl(docComment, modsAndAnnos));
}
while(!wouldAccept(ENDMARKER)) {
if(!accept(SEMI)) {
types.add(parseTypeDecl());
}
}
return new NormalCompilationUnit(pckg, imports, types);
}
public PackageDecl parsePackageDecl() {
return parsePackageDecl(getDocComment(), emptyList());
}
public PackageDecl parsePackageDecl(Optional<String> docComment, List<Annotation> annotations) {
require(PACKAGE);
QualifiedName name = parseQualName();
requireSemi();
return new PackageDecl(name, annotations, docComment);
}
public ArrayList<ImportDecl> parseImportSection() {
var imports = new ArrayList<ImportDecl>();
while(wouldAccept(IMPORT)) {
imports.addAll(parseImport());
}
return imports;
}
public List<ImportDecl> parseImport() {
require(IMPORT);
boolean isStatic = accept(STATIC);
boolean wildcard = false;
var names = new ArrayList<Name>();
names.add(parseName());
while(accept(DOT)) {
if(accept(STAR)) {
wildcard = true;
break;
} else {
names.add(parseName());
}
}
requireSemi();
return Collections.singletonList(new ImportDecl(new QualifiedName(names), isStatic, wildcard));
}
public ArrayList<Annotation> parseAnnotations() {
var annos = new ArrayList<Annotation>();
while(wouldAccept(AT, notInterface)) {
annos.add(parseAnnotation());
}
return annos;
}
public ModsAndAnnotations parseKeywordModsAndAnnotations() {
var mods = new LinkedHashSet<Modifier>(3);
var annos = new ArrayList<Annotation>(3);
Token<JavaTokenType> visibilityModifier = null;
for(;;) {
if(wouldAccept(AT, not(INTERFACE))) {
annos.add(parseAnnotation());
} else if(wouldAccept(Tag.VISIBILITY_MODIFIER)) {
if(visibilityModifier != null) {
throw syntaxError("Incompatible modifiers '" + visibilityModifier + "' and '" + token.getString() + "'");
}
if(!mods.add(createModifier(visibilityModifier = token))) {
throw syntaxError("Duplicate modifier '" + token.getString() + "'");
}
nextToken();
} else if(wouldAccept(KEYWORD_MODIFIER)) {
if(!mods.add(createModifier(token))) {
throw syntaxError("Duplicate modifier '" + token.getString() + "'");
}
nextToken();
} else {
return new ModsAndAnnotations(new ArrayList<>(mods), annos);
}
}
}
public ModsAndAnnotations parseFinalAndAnnotations() {
ArrayList<Annotation> annos = parseAnnotations();
List<Modifier> mods;
if(wouldAccept(FINAL)) {
mods = singletonList(createModifier(token));
nextToken();
if(wouldAccept(AT)) {
annos.addAll(parseAnnotations());
}
if(wouldAccept(FINAL)) {
throw syntaxError("Duplicate modifier 'final'");
} else if(wouldAccept(KEYWORD_MODIFIER)) {
throw syntaxError("Modifier '" + token.getString() + "' not allowed here");
}
} else if(wouldAccept(KEYWORD_MODIFIER)) {
throw syntaxError("Modifier '" + token.getString() + "' not allowed here");
} else {
mods = emptyList();
}
return new ModsAndAnnotations(mods, annos);
}
public ModsAndAnnotations parseClassModsAndAnnotations() {
var mods = new LinkedHashSet<Modifier>(3);
var annos = new ArrayList<Annotation>(3);
Token<JavaTokenType> visibilityModifier = null;
for(;;) {
if(wouldAccept(AT, not(INTERFACE))) {
annos.add(parseAnnotation());
} else if(wouldAccept(Tag.VISIBILITY_MODIFIER)) {
if(visibilityModifier != null) {
throw syntaxError("Incompatible modifiers '" + visibilityModifier + "' and '" + token.getString() + "'");
}
if(!mods.add(createModifier(visibilityModifier = token))) {
throw syntaxError("Duplicate modifier '" + token.getString() + "'");
}
nextToken();
} else if(wouldAccept(Tag.CLASS_MODIFIER)) {
if(!mods.add(createModifier(token))) {
throw syntaxError("Duplicate modifier '" + token.getString() + "'");
}
nextToken();
} else if(wouldAccept(KEYWORD_MODIFIER)) {
throw syntaxError("Modifier '" + token.getString() + "' not allowed here");
} else {
return new ModsAndAnnotations(new ArrayList<>(mods), annos);
}
}
}
public ModsAndAnnotations parseMethodModsAndAnnotations() {
var mods = new LinkedHashSet<Modifier>(3);
var annos = new ArrayList<Annotation>(3);
Token<JavaTokenType> visibilityModifier = null;
for(;;) {
if(wouldAccept(AT, not(INTERFACE))) {
annos.add(parseAnnotation());
} else if(wouldAccept(Tag.VISIBILITY_MODIFIER)) {
if(visibilityModifier != null) {
throw syntaxError("Incompatible modifiers '" + visibilityModifier + "' and '" + token.getString() + "'");
}
if(!mods.add(createModifier(visibilityModifier = token))) {
throw syntaxError("Duplicate modifier '" + token.getString() + "'");
}
nextToken();
} else if(wouldAccept(Tag.METHOD_MODIFIER)) {
if(!mods.add(createModifier(token))) {
throw syntaxError("Duplicate modifier '" + token.getString() + "'");
}
nextToken();
} else if(wouldAccept(KEYWORD_MODIFIER)) {
throw syntaxError("Modifier '" + token.getString() + "' not allowed here");
} else {
return new ModsAndAnnotations(new ArrayList<>(mods), annos);
}
}
}
public ModsAndAnnotations parseConstructorModsAndAnnotations() {
var mods = new LinkedHashSet<Modifier>(3);
var annos = new ArrayList<Annotation>(3);
Token<JavaTokenType> visibilityModifier = null;
for(;;) {
if(wouldAccept(AT, not(INTERFACE))) {
annos.add(parseAnnotation());
} else if(wouldAccept(Tag.VISIBILITY_MODIFIER)) {
if(visibilityModifier != null) {
throw syntaxError("Incompatible modifiers '" + visibilityModifier + "' and '" + token.getString() + "'");
}
if(!mods.add(createModifier(visibilityModifier = token))) {
throw syntaxError("Duplicate modifier '" + token.getString() + "'");
}
nextToken();
} else if(wouldAccept(Tag.CONSTRUCTOR_MODIFIER)) {
if(!mods.add(createModifier(token))) {
throw syntaxError("Duplicate modifier '" + token.getString() + "'");
}
nextToken();
} else if(wouldAccept(KEYWORD_MODIFIER)) {
throw syntaxError("Modifier '" + token.getString() + "' not allowed here");
} else {
return new ModsAndAnnotations(new ArrayList<>(mods), annos);
}
}
}
public ModsAndAnnotations parseFieldModsAndAnnotations() {
var mods = new LinkedHashSet<Modifier>(3);
var annos = new ArrayList<Annotation>(3);
Token<JavaTokenType> visibilityModifier = null;
for(;;) {
if(wouldAccept(AT, not(INTERFACE))) {
annos.add(parseAnnotation());
} else if(wouldAccept(Tag.VISIBILITY_MODIFIER)) {
if(visibilityModifier != null) {
throw syntaxError("Incompatible modifiers '" + visibilityModifier + "' and '" + token.getString() + "'");
}
if(!mods.add(createModifier(visibilityModifier = token))) {
throw syntaxError("Duplicate modifier '" + token.getString() + "'");
}
nextToken();
} else if(wouldAccept(Tag.FIELD_MODIFIER)) {
if(!mods.add(createModifier(token))) {
throw syntaxError("Duplicate modifier '" + token.getString() + "'");
}
nextToken();
} else if(wouldAccept(KEYWORD_MODIFIER)) {
throw syntaxError("Modifier '" + token.getString() + "' not allowed here");
} else {
return new ModsAndAnnotations(new ArrayList<>(mods), annos);
}
}
}
/*public Pair<ArrayList<Modifier>, ArrayList<Annotation>> parseModsAndAnnotations() {
ArrayList<Modifier> mods = new ArrayList<>(3);
ArrayList<Annotation> annos = new ArrayList<>(3);
for(;;) {
if(wouldAccept(AT)) {
annos.add(parseAnnotation());
} else if(wouldAccept(Tag.MODIFIER)) {
mods.add(createModifier(token));
nextToken();
} else if(wouldAccept(test("non"), SUB, isNonVisibilityModifier)) {
var next1 = tokens.look(1);
var next2 = tokens.look(2);
if(token.getEnd().equals(next1.getStart()) && next1.getEnd().equals(next2.getStart())) {
nextToken(2);
var mod = "non-" + token.getString();
mods.add(new Modifier(mod));
nextToken();
} else {
break;
}
} else {
break;
}
}
return Pair.of(mods, annos);
}*/
public Modifier createModifier(Token<JavaTokenType> token) {
try {
return createModifier(token.getType());
} catch(IllegalArgumentException e) {
throw syntaxError(e.getMessage(), token);
}
}
public Modifier createModifier(JavaTokenType type) {
return new Modifier(switch(type) {
case PUBLIC -> Modifiers.PUBLIC;
case PRIVATE -> Modifiers.PRIVATE;
case PROTECTED -> Modifiers.PROTECTED;
case STATIC -> Modifiers.STATIC;
case STRICTFP -> Modifiers.STRICTFP;
case TRANSIENT -> Modifiers.TRANSIENT;
case VOLATILE -> Modifiers.VOLATILE;
case NATIVE -> Modifiers.NATIVE;
case FINAL -> Modifiers.FINAL;
case SYNCHRONIZED -> Modifiers.SYNCHRONIZED;
case DEFAULT -> Modifiers.DEFAULT;
case ABSTRACT -> Modifiers.ABSTRACT;
case TRANSITIVE -> Modifiers.TRANSITIVE;
default -> throw new IllegalArgumentException(type + " is not a modifier");
});
}
public Modifier createModifier(String name) {
return new Modifier(Modifiers.fromString(name));
}
public Annotation parseAnnotation() {
require(AT);
Optional<Either<? extends List<AnnotationArgument>,? extends AnnotationValue>> arguments;
var type = new GenericType(parseQualName());
if(accept(LPAREN)) {
if(wouldAccept(RPAREN)) {
arguments = Optional.of(Either.first(emptyList()));
} else if(wouldAccept(NAME, EQ)) {
var args = new ArrayList<AnnotationArgument>();
do {
args.add(parseAnnotationArgument());
} while(accept(COMMA));
arguments = Optional.of(Either.first(args));
} else {
arguments = Optional.of(Either.second(parseAnnotationValue()));
}
require(RPAREN);
} else {
arguments = Optional.empty();
}
return new Annotation(type, arguments);
}
public AnnotationArgument parseAnnotationArgument() {
var name = parseName();
require(EQ);
var value = parseAnnotationValue();
return new AnnotationArgument(name, value);
}
public AnnotationValue parseAnnotationValue() {
if(wouldAccept(LBRACE)) {
return parseArrayInitializer(this::parseAnnotationValue);
} else if(wouldAccept(AT)) {
return parseAnnotation();
} else {
return parseExpression();
}
}
public <T extends AnnotationValue> ArrayInitializer<? extends T> parseArrayInitializer(Supplier<? extends T> elementParser) {
require(LBRACE);
var elems = new ArrayList<T>();
if(!wouldAccept(RBRACE)) {
elems.add(elementParser.get());
while(accept(COMMA)) {
if(wouldAccept(RBRACE)) {
break;
} else {
elems.add(elementParser.get());
}
}
}
require(RBRACE);
return new ArrayInitializer<>(elems);
}
public Directive parseDirective() {
if(wouldAccept(REQUIRES)) {
return parseRequiresDirective();
} else if(wouldAccept(EXPORTS)) {
return parseExportsDirective();
} else if(wouldAccept(OPENS)) {
return parseOpensDirective();
} else if(wouldAccept(USES)) {
return parseUsesDirective();
} else if(wouldAccept(PROVIDES)) {
return parseProvidesDirective();
} else {
throw syntaxError("expected 'requires', 'exports', 'opens', 'uses', or 'provides' here, got " + token);
}
}
public RequiresDirective parseRequiresDirective() {
require(REQUIRES);
var modifiers = new ArrayList<Modifier>();
while(wouldAccept(Tag.REQUIRES_MODIFIER)) {
if(wouldAccept(Tag.NAMED, DOT.or(SEMI))) { // case where it's provides ... transitive.blah; in which case
// transitive is not a modifier
break;
}
modifiers.add(createModifier(token));
nextToken();
}
var name = parseQualName();
requireSemi();
return new RequiresDirective(name, modifiers);
}
public ExportsDirective parseExportsDirective() {
require(EXPORTS);
var name = parseQualName();
if(accept(TO)) {
var friends = listOf(this::parseQualName);
requireSemi();
return new ExportsDirective(name, friends);
} else {
requireSemi();
return new ExportsDirective(name);
}
}
public OpensDirective parseOpensDirective() {
require(OPENS);
var name = parseQualName();
if(accept(TO)) {
var friends = listOf(this::parseQualName);
requireSemi();
return new OpensDirective(name, friends);
} else {
requireSemi();
return new OpensDirective(name);
}
}
public UsesDirective parseUsesDirective() {
require(USES);
var name = parseQualTypeName();
requireSemi();
return new UsesDirective(name);
}
public ProvidesDirective parseProvidesDirective() {
require(PROVIDES);
var name = parseQualTypeName();
require(WITH);
var providers = listOf(this::parseQualTypeName);
requireSemi();
return new ProvidesDirective(name, providers);
}
public TypeDecl parseTypeDecl() {
var docComment = getDocComment();
return parseTypeDecl(docComment, parseClassModsAndAnnotations());
}
public TypeDecl parseTypeDecl(Optional<String> docComment, ModsAndAnnotations modsAndAnnos) {
if(wouldAccept(CLASS)) {
return parseClassDecl(docComment, modsAndAnnos);
} else if(wouldAccept(INTERFACE)) {
return parseInterfaceDecl(docComment, modsAndAnnos);
} else if(wouldAccept(ENUM)) {
return parseEnumDecl(docComment, modsAndAnnos);
} else if(wouldAccept(AT, INTERFACE)) {
return parseAnnotationDecl(docComment, modsAndAnnos);
} else {
throw syntaxError("expected 'class', 'interface', '@interface', or 'enum' here, got " + token);
}
}
public ClassDecl parseClassDecl() {
var docComment = getDocComment();
return parseClassDecl(docComment, parseClassModsAndAnnotations());
}
public ClassDecl parseClassDecl(Optional<String> docComment, ModsAndAnnotations modsAndAnnos) {
assert modsAndAnnos.canBeClassMods();
var modifiers = modsAndAnnos.mods;
var annotations = modsAndAnnos.annos;
require(CLASS);
var name = parseTypeName();
var typeParameters = parseTypeParametersOpt();
Optional<GenericType> superClass;
if(accept(EXTENDS)) {
superClass = Optional.of(parseGenericType());
} else {
superClass = Optional.empty();
}
List<GenericType> interfaces;
if(accept(IMPLEMENTS)) {
interfaces = parseGenericTypeList();
} else {
interfaces = emptyList();
}
List<Member> members;
try(var $ = typeNames.enter(name)) {
members = parseClassBody(() -> this.parseClassMember(false));
}
return new ClassDecl(name, typeParameters, superClass, interfaces, members, modifiers, annotations, docComment);
}
public InterfaceDecl parseInterfaceDecl() {
var docComment = getDocComment();
return parseInterfaceDecl(docComment, parseClassModsAndAnnotations());
}
public InterfaceDecl parseInterfaceDecl(Optional<String> docComment, ModsAndAnnotations modsAndAnnos) {
assert modsAndAnnos.canBeClassMods();
var modifiers = modsAndAnnos.mods;
var annotations = modsAndAnnos.annos;
require(INTERFACE);
var name = parseTypeName();
var typeParameters = parseTypeParametersOpt();
List<GenericType> superInterfaces;
if(accept(EXTENDS)) {
superInterfaces = parseGenericTypeList();
} else {
superInterfaces = emptyList();
}
List<Member> members;
try(var $ = typeNames.enter(name)) {
members = parseClassBody(() -> this.parseClassMember(true));
}
return new InterfaceDecl(name, typeParameters, superInterfaces, members, modifiers, annotations, docComment);
}
public EnumDecl parseEnumDecl() {
var docComment = getDocComment();
return parseEnumDecl(docComment, parseClassModsAndAnnotations());
}
public EnumDecl parseEnumDecl(Optional<String> docComment, ModsAndAnnotations modsAndAnnos) {
assert modsAndAnnos.canBeClassMods();
var modifiers = modsAndAnnos.mods;
var annotations = modsAndAnnos.annos;
require(ENUM);
var name = parseTypeName();
List<GenericType> interfaces;
if(accept(IMPLEMENTS)) {
interfaces = parseGenericTypeList();
} else {
interfaces = emptyList();
}
List<EnumField> fields;
List<Member> members;
try(var $ = typeNames.enter(name)) {
var fieldsAndMembers = parseEnumBody();
fields = fieldsAndMembers.getLeft();
members = fieldsAndMembers.getRight();
}
return new EnumDecl(name, interfaces, fields, members, modifiers, annotations, docComment);
}
public Pair<List<EnumField>,List<Member>> parseEnumBody() {
require(LBRACE);
List<EnumField> fields;
List<Member> members;
if(wouldAccept(AT.or(Tag.NAMED))) {
fields = new ArrayList<>();
fields.add(parseEnumField());
while(accept(COMMA)) {
if(wouldAccept(SEMI.or(RBRACE))) {
break;
}
fields.add(parseEnumField());
}
} else {
fields = emptyList();
}
if(accept(SEMI)) {
members = new ArrayList<>();
while(wouldNotAccept(RBRACE)) {
if(!accept(SEMI)) {
members.addAll(parseClassMember(false));
}
}
} else {
members = emptyList();
}
require(RBRACE);
return Pair.of(fields, members);
}
public EnumField parseEnumField() {
return parseEnumField(getDocComment(), parseAnnotations());
}
public EnumField parseEnumField(Optional<String> docComment, List<Annotation> annotations) {
var name = parseName();
Optional<? extends List<? extends Expression>> arguments;
if(wouldAccept(LPAREN)) {
arguments = Optional.of(parseArguments(true));
} else {
arguments = Optional.empty();
}
Optional<? extends List<Member>> members;
if(wouldAccept(LBRACE)) {
members = Optional.of(parseClassBody(() -> this.parseClassMember(false)));
} else {
members = Optional.empty();
}
return new EnumField(name, arguments, members, annotations, docComment);
}
public AnnotationDecl parseAnnotationDecl() {
var docComment = getDocComment();
return parseAnnotationDecl(docComment, parseClassModsAndAnnotations());
}
public AnnotationDecl parseAnnotationDecl(Optional<String> docComment, ModsAndAnnotations modsAndAnnos) {
assert modsAndAnnos.canBeClassMods();
var modifiers = modsAndAnnos.mods;
var annotations = modsAndAnnos.annos;
require(AT, INTERFACE);
var name = parseTypeName();
List<Member> members;
try(var $ = typeNames.enter(name)) {
members = parseClassBody(this::parseAnnotationMember);
}
return new AnnotationDecl(name, members, modifiers, annotations, docComment);
}
public List<Member> parseAnnotationMember() {
var docComment = getDocComment();
/*var modifiers = new LinkedHashSet<Modifier>(3);
var annotations = parseAnnotations();
while(wouldAccept(Tag.VISIBILITY_MODIFIER)) {
if(!modifiers.add(createModifier(token))) {
throw syntaxError("Duplicate modifier '" + token.getString() + "'");
}
nextToken();
if(wouldAccept(AT)) {
annotations.addAll(parseAnnotations());
}
}
if(wouldAccept(STATIC)) {
} else {
if(wouldAccept(ABSTRACT)) {
modifiers.add(createModifier(token));
nextToken();
if(wouldAccept(AT)) {
annotations.addAll(parseAnnotations());
}
}
if(wouldAccept(Tag.NAMED, LPAREN)) {
return List.of(parseAnnotationProperty(docComment, new ModsAndAnnotations(new ArrayList<>(modifiers), annotations)));
} else {
}
}*/
return parseAnnotationMember(docComment, parseKeywordModsAndAnnotations());
}
public List<Member> parseAnnotationMember(Optional<String> docComment, ModsAndAnnotations modsAndAnnos) {
if(wouldAccept(CLASS.or(INTERFACE).or(ENUM)) || wouldAccept(AT, INTERFACE)) {
return List.of(parseTypeDecl(docComment, modsAndAnnos));
} else if(modsAndAnnos.hasModifier("static")) {
return parseInterfaceMember(false, docComment, modsAndAnnos);
} else {
return List.of(parseAnnotationProperty(docComment, modsAndAnnos));
}
}
public AnnotationProperty parseAnnotationProperty() {
var docComment = getDocComment();
return parseAnnotationProperty(docComment, parseMethodModsAndAnnotations());
}
public AnnotationProperty parseAnnotationProperty(Optional<String> docComment, ModsAndAnnotations modsAndAnnos) {
assert modsAndAnnos.canBeMethodMods();
var modifiers = modsAndAnnos.mods;
var annotations = modsAndAnnos.annos;
var type = parseType();
var name = parseName();
require(LPAREN, RPAREN);
Optional<? extends AnnotationValue> defaultValue;
if(accept(DEFAULT)) {
defaultValue = Optional.of(parseAnnotationValue());
} else {
defaultValue = Optional.empty();
}
endStatement();
return new AnnotationProperty(name, type, defaultValue, modifiers, annotations, docComment);
}
public List<TypeParameter> parseTypeParametersOpt() {
return wouldAccept(LT)? parseTypeParameters() : emptyList();
}
public List<TypeParameter> parseTypeParameters() {
require(LT);
var params = listOf(this::parseTypeParameter);
require(GT);
return params;
}
public TypeParameter parseTypeParameter() {
var annotations = parseAnnotations();
var name = parseTypeName();
Optional<? extends ReferenceType> bound;
if(accept(EXTENDS)) {
bound = Optional.of(parseTypeIntersection());
} else {
bound = Optional.empty();
}
return new TypeParameter(name, bound, annotations);
}
public <M extends Member> ArrayList<M> parseClassBody(Supplier<? extends List<M>> memberParser) {
require(LBRACE);
var members = new ArrayList<M>();
while(wouldNotAccept(RBRACE)) {
if(!accept(SEMI)) {
members.addAll(memberParser.get());
}
}
require(RBRACE);
return members;
}
public List<Member> parseClassMember() {
return parseClassMember(false);
}
public List<Member> parseClassMember(boolean inInterface) {
if(wouldAccept(STATIC, LBRACE)) {
nextToken();
var body = parseBlock();
return List.of(new ClassInitializer(true, body));
} else if(wouldAccept(LBRACE)) {
var body = parseBlock();
return List.of(new ClassInitializer(false, body));
} else {
var docComment = getDocComment();
/*var modifiers = new LinkedHashSet<Modifier>();
var annotations = parseAnnotations();
while(wouldAccept(Tag.VISIBILITY_MODIFIER)) {
if(!modifiers.add(createModifier(token))) {
throw syntaxError("Duplicate modifier '" + token.getString() + "'");
}
nextToken();
if(wouldAccept(AT)) {
annotations.addAll(parseAnnotations());
}
}
if(!inInterface && wouldAccept(Tag.NAMED, LPAREN)) {
return parseConstructor(docComment, new ModsAndAnnotations(new ArrayList<>(modifiers), annotations));
}
while(wouldAccept(STATIC.or(FINAL))) {
if(!modifiers.add(createModifier(token))) {
throw syntaxError("Duplicate modifier '" + token.getString() + "'");
}
nextToken();
if(wouldAccept(AT)) {
annotations.addAll(parseAnnotations());
}
}
if(wouldAccept(TRANSIENT.or(VOLATILE))) {
do {
if(!modifiers.add(createModifier(token))) {
throw syntaxError("Duplicate modifier '" + token.getString() + "'");
}
nextToken();
if(wouldAccept(AT)) {
annotations.addAll(parseAnnotations());
}
} while(wouldAccept(Tag.FIELD_MODIFIER));
if(wouldAccept(KEYWORD_MODIFIERS)) {
throw syntaxError("Illegal field modifier");
}
return parseFieldDecl(docComment, new ModsAndAnnotations(new ArrayList<>(modifiers), annotations));
}
if(wouldAccept(ABSTRACT)) {
do {
if(!modifiers.add(createModifier(token))) {
throw syntaxError("Duplicate modifier '" + token.getString() + "'");
}
nextToken();
if(wouldAccept(AT)) {
annotations.addAll(parseAnnotations());
}
} while(wouldAccept(Tag.CLASS_MODIFIER.and(Tag.METHOD_MODIFIER)));
if(wouldAccept(Tag.METHOD_MODIFIER)) {
do {
if(!modifiers.add(createModifier(token))) {
throw syntaxError("Duplicate modifier '" + token.getString() + "'");
}
nextToken();
if(wouldAccept(AT)) {
annotations.addAll(parseAnnotations());
}
} while(wouldAccept(Tag.METHOD_MODIFIER));
if(wouldAccept(KEYWORD_MODIFIERS)) {
throw syntaxError("Illegal field modifier");
}
return parseMethod(inInterface, docComment, new ModsAndAnnotations(new ArrayList<>(modifiers), annotations));
} else if(accept(VOID)) {
return parseMethod(inInterface, new VoidType(), emptyList(), docComment, new ModsAndAnnotations(new ArrayList<>(modifiers), annotations));
} else if()
} else {
while(wouldAccept(Tag.METHOD_MODIFIER)) {
if(!modifiers.add(createModifier(token))) {
throw syntaxError("Duplicate modifier '" + token.getString() + "'");
}
nextToken();
if(wouldAccept(AT)) {
annotations.addAll(parseAnnotations());
}
}
if(wouldAccept(KEYWORD_MODIFIERS)) {
throw syntaxError("Illegal field modifier");
}
}
}*/
return parseClassMember(inInterface, docComment, parseKeywordModsAndAnnotations());
}
}
public List<Member> parseClassMember(boolean inInterface, Optional<String> docComment, ModsAndAnnotations modsAndAnnos) {
if(!inInterface && modsAndAnnos.canBeConstructorMods() && wouldAccept(Tag.NAMED, LPAREN)) {
return parseConstructor(docComment, modsAndAnnos);
} else if(modsAndAnnos.canBeMethodMods() && wouldAccept(LT)) {
var typeParameters = parseTypeParameters();
if(!inInterface && modsAndAnnos.canBeConstructorMods() && wouldAccept(Tag.NAMED, LPAREN)) {
return parseConstructor(typeParameters, docComment, modsAndAnnos);
} else {
var typeAnnotations = parseAnnotations();
Type type;
if(accept(VOID)) {
type = new VoidType(typeAnnotations);
} else {
type = parseType(typeAnnotations);
}
return parseMethod(inInterface, type, typeParameters, parseName(), docComment, modsAndAnnos);
}
} else {
return parseInterfaceMember(inInterface, docComment, modsAndAnnos);
}
}
public List<Member> parseInterfaceMember() {
return parseInterfaceMember(true);
}
public List<Member> parseInterfaceMember(boolean inInterface) {
var docComment = getDocComment();
return parseInterfaceMember(inInterface, docComment, parseKeywordModsAndAnnotations());
}
public List<Member> parseInterfaceMember(boolean inInterface, Optional<String> docComment, ModsAndAnnotations modsAndAnnos) {
if(modsAndAnnos.canBeClassMods() && wouldAccept(CLASS.or(INTERFACE).or(ENUM).or(AT /* only way AT is possible here is if it is followed by INTERFACE*/))) {
return List.of(parseTypeDecl(docComment, modsAndAnnos));
} else if(modsAndAnnos.canBeMethodMods() && wouldAccept(LT)) {
var typeParameters = parseTypeParameters();
var typeAnnotations = parseAnnotations();
Type type;
if(accept(VOID)) {
type = new VoidType(typeAnnotations);
} else {
type = parseType(typeAnnotations);
}
return parseMethod(inInterface, type, typeParameters, parseName(), docComment, modsAndAnnos);
} else if(modsAndAnnos.canBeMethodMods() && accept(VOID)) {
return parseMethod(inInterface, new VoidType(), emptyList(), parseName(), docComment, modsAndAnnos);
} else {
var type = parseType();
if(modsAndAnnos.canBeMethodMods() && wouldAccept(Tag.NAMED, LPAREN)) {
return parseMethod(inInterface, type, emptyList(), parseName(), docComment, modsAndAnnos);
} else if(modsAndAnnos.canBeFieldMods()) {
return parseFieldDecl(type, docComment, modsAndAnnos);
} else {
throw syntaxError("Invalid modifiers");
}
}
}
public List<Member> parseFieldDecl() {
var docComment = getDocComment();
return parseFieldDecl(docComment, parseFieldModsAndAnnotations());
}
public List<Member> parseFieldDecl(Optional<String> docComment, ModsAndAnnotations modsAndAnnos) {
return parseFieldDecl(parseType(), docComment, modsAndAnnos);
}
public List<Member> parseFieldDecl(Type type, Optional<String> docComment, ModsAndAnnotations modsAndAnnos) {
return List.of(parseVariableDecl(type, docComment, modsAndAnnos));
}
public List<Member> parseMethod() {
return parseMethod(false);
}
public List<Member> parseMethod(boolean inInterface) {
var docComment = getDocComment();
return parseMethod(inInterface, docComment, parseMethodModsAndAnnotations());
}
public List<Member> parseMethod(boolean inInterface, Optional<String> docComment, ModsAndAnnotations modsAndAnnos) {
return parseMethod(inInterface, parseTypeParametersOpt(), docComment, modsAndAnnos);
}
public List<Member> parseMethod(boolean inInterface, List<TypeParameter> typeParameters,
Optional<String> docComment, ModsAndAnnotations modsAndAnnos) {
var typeAnnotations = parseAnnotations();
Type type;
if(accept(VOID)) {
type = new VoidType(typeAnnotations);
} else {
type = parseType(typeAnnotations);
}
return parseMethod(inInterface, type, typeParameters, docComment, modsAndAnnos);
}
public List<Member> parseMethod(boolean inInterface, Type returnType, List<TypeParameter> typeParameters,
Optional<String> docComment, ModsAndAnnotations modsAndAnnos) {
return parseMethod(inInterface, returnType, typeParameters, parseName(), docComment, modsAndAnnos);
}
public List<Member> parseMethod(boolean inInterface, Type returnType, List<TypeParameter> typeParameters,
Name name, Optional<String> docComment, ModsAndAnnotations modsAndAnnos) {
assert modsAndAnnos.canBeMethodMods();
var modifiers = modsAndAnnos.mods;
var annotations = modsAndAnnos.annos;
var thisParameterAndParameters = parseParameters();
var thisParameter = thisParameterAndParameters.getLeft();
var parameters = thisParameterAndParameters.getRight();
List<Dimension> dimensions = returnType instanceof VoidType? emptyList() : parseDimensions();
List<GenericType> exceptions;
if(accept(THROWS)) {
exceptions = parseGenericTypeList();
} else {
exceptions = emptyList();
}
Optional<Block> body = parseMethodBody(returnType instanceof VoidType, parameters);
return List.of(new FunctionDecl(name, typeParameters, returnType, thisParameter, parameters, dimensions,
exceptions, body, modifiers, annotations, docComment));
}
public List<Member> parseConstructor() {
var docComment = getDocComment();
return parseConstructor(docComment, parseConstructorModsAndAnnotations());
}
public List<Member> parseConstructor(Optional<String> docComment, ModsAndAnnotations modsAndAnnos) {
return parseConstructor(parseTypeParametersOpt(), docComment, modsAndAnnos);
}
public List<Member> parseConstructor(List<TypeParameter> typeParameters, Optional<String> docComment, ModsAndAnnotations modsAndAnnos) {
return parseConstructor(parseTypeName(), typeParameters, docComment, modsAndAnnos);
}
public List<Member> parseConstructor(Name name, List<TypeParameter> typeParameters,
Optional<String> docComment, ModsAndAnnotations modsAndAnnos) {
assert modsAndAnnos.canBeConstructorMods();
var modifiers = modsAndAnnos.mods;
var annotations = modsAndAnnos.annos;
var bodyStmts = new ArrayList<Statement>();
var thisParameterAndParameters = parseConstructorParameters(bodyStmts);
var thisParameter = thisParameterAndParameters.getLeft();
var parameters = thisParameterAndParameters.getRight();
List<GenericType> exceptions;
if(accept(THROWS)) {
exceptions = parseGenericTypeList();
} else {
exceptions = emptyList();
}
Block body = parseConstructorBody(parameters);
if(!body.getStatements().isEmpty() && body.getStatements().get(0) instanceof ConstructorCall) {
body.getStatements().addAll(1, bodyStmts);
} else {
body.getStatements().addAll(0, bodyStmts);
}
return List.of(new ConstructorDecl(name, typeParameters, thisParameter, parameters, exceptions, body, modifiers,
annotations, docComment));
}
public Block parseConstructorBody(List<FormalParameter> parameters) {
return parseBlock();
}
public Optional<Block> parseMethodBody(boolean isVoidMethod, List<FormalParameter> parameters) {
if(accept(SEMI)) {
return Optional.empty();
} else {
return Optional.of(parseBlock());
}
}
public Pair<Optional<ThisParameter>,List<FormalParameter>> parseConstructorParameters(ArrayList<Statement> bodyStmts) {
return parseParameters(this::parseName);
}
public Pair<Optional<ThisParameter>,List<FormalParameter>> parseParameters() {
return parseParameters(this::parseName);
}
public Pair<Optional<ThisParameter>,List<FormalParameter>> parseParameters(Supplier<Name> parseName) {
require(LPAREN);
Optional<ThisParameter> thisParameter;
List<FormalParameter> parameters;
if(wouldAccept(RPAREN)) {
thisParameter = Optional.empty();
parameters = emptyList();
} else {
try(var state = tokens.enter()) {
try {
thisParameter = Optional.of(parseThisParameter());
} catch(SyntaxError e) {
state.reset();
thisParameter = Optional.empty();
}
}
if(thisParameter.isPresent()) {
if(accept(COMMA)) {
parameters = parseFormalParameterList(parseName);
} else {
parameters = emptyList();
}
} else {
parameters = parseFormalParameterList(parseName);
}
}
require(RPAREN);
return Pair.of(thisParameter, parameters);
}
public ArrayList<FormalParameter> parseFormalParameterList(Supplier<Name> parseName) {
var params = new ArrayList<FormalParameter>();
var param = parseFormalParameter(parseName);
params.add(param);
while(!param.isVariadic() && accept(COMMA)) {
params.add(param = parseFormalParameter(parseName));
}
return params;
}
public FormalParameter parseFormalParameter() {
return parseFormalParameter(this::parseName);
}
public FormalParameter parseFormalParameter(Supplier<Name> parseName) {
return parseFormalParameter(parseName, parseFinalAndAnnotations());
}
public FormalParameter parseFormalParameter(Supplier<Name> parseName, ModsAndAnnotations modsAndAnnos) {
assert modsAndAnnos.canBeLocalVarMods();
var modifiers = modsAndAnnos.mods;
var annotations = modsAndAnnos.annos;
var type = parseType();
boolean variadic = accept(ELLIPSIS);
var name = parseName.get();
var dimensions = parseDimensions();
return new FormalParameter(type, name, variadic, dimensions, modifiers, annotations);
}
public ThisParameter parseThisParameter() {
return parseThisParameter(parseAnnotations());
}
public ThisParameter parseThisParameter(List<Annotation> annotations) {
var type = parseGenericType();
Optional<Name> qualifier;
if(wouldAccept(Tag.NAMED)) {
qualifier = Optional.of(parseName());
require(DOT);
} else {
qualifier = Optional.empty();
}
require(THIS);
if(qualifier.isEmpty() && wouldAccept(DOT)) {
throw syntaxError("unexpected token " + token);
}
return new ThisParameter(type, qualifier, annotations);
}
public VariableDecl parseVariableDecl() {
var docComment = getDocComment();
return parseVariableDecl(docComment, parseFinalAndAnnotations());
}
public VariableDecl parseVariableDecl(Optional<String> docComment, ModsAndAnnotations modsAndAnnos) {
return parseVariableDecl(parseType(), docComment, modsAndAnnos);
}
public VariableDecl parseVariableDecl(Type type, Optional<String> docComment, ModsAndAnnotations modsAndAnnos) {
assert modsAndAnnos.canBeFieldMods();
var modifiers = modsAndAnnos.mods;
var annotations = modsAndAnnos.annos;
var declarators = listOf(() -> parseVariableDeclarator(type));
endStatement();
return new VariableDecl(type, declarators, modifiers, annotations, docComment);
}
public VariableDeclarator parseVariableDeclarator(Type type) {
var name = parseName();
var dimensions = parseDimensions();
return parseVariableDeclarator(type, name, dimensions);
}
public VariableDeclarator parseVariableDeclarator(Type type, Name name, ArrayList<Dimension> dimensions) {
Optional<? extends Initializer> initializer = parseVariableInitializerOpt(type, dimensions);
return new VariableDeclarator(name, dimensions, initializer);
}
protected int dimensionCount(Type type, List<Dimension> dimensions) {
if(type instanceof ArrayType) {
return ((ArrayType)type).getDimensions().size() + dimensions.size();
} else {
return dimensions.size();
}
}
protected int dimensionCount(Type type) {
if(type instanceof ArrayType) {
return ((ArrayType)type).getDimensions().size();
} else {
return 0;
}
}
public Initializer parseVariableInitializer(Type type, ArrayList<Dimension> dimensions) {
require(EQ);
return parseInitializer(dimensionCount(type, dimensions));
}
public Optional<? extends Initializer> parseVariableInitializerOpt(Type type, ArrayList<Dimension> dimensions) {
if(accept(EQ)) {
return Optional.of(parseInitializer(dimensionCount(type, dimensions)));
} else {
return Optional.empty();
}
}
public ArrayList<Dimension> parseDimensions() {
var dimensions = new ArrayList<Dimension>();
while(wouldAccept(AT.or(LBRACKET))) {
dimensions.add(parseDimension());
}
return dimensions;
}
public Dimension parseDimension() {
var annotations = parseAnnotations();
require(LBRACKET, RBRACKET);
return new Dimension(annotations);
}
public ArrayList<GenericType> parseGenericTypeList() {
return listOf(this::parseGenericType);
}
public Type parseType() {
return parseType(parseAnnotations());
}
protected static final TokenPredicate<JavaTokenType> PRIMITIVE_TYPES = (Token<JavaTokenType> token) -> switch(token.getType()) {
case BOOLEAN, BYTE, SHORT, CHAR, INT, LONG, FLOAT, DOUBLE -> true;
default -> false;
};
protected static final TokenPredicate<JavaTokenType> KEYWORD_MODIFIER = (Token<JavaTokenType> token) -> {
var type = token.getType();
return type.isKeyword() &&
(type.hasTag(Tag.CLASS_MODIFIER)
|| type.hasTag(Tag.METHOD_MODIFIER)
|| type.hasTag(Tag.CONSTRUCTOR_MODIFIER)
|| type.hasTag(Tag.FIELD_MODIFIER)
|| type.hasTag(Tag.LOCAL_VAR_MODIFIER));
};
protected void requireSemi() {
require(SEMI);
}
public Type parseType(List<Annotation> annotations) {
var base = parseNonArrayType(annotations);
if(wouldAccept(AT.or(LBRACKET))) {
var dimensions = parseDimensions();
base.setAnnotations(emptyList());
return new ArrayType(base, dimensions, annotations);
} else {
return base;
}
}
public Type parseNonArrayType() {
return parseNonArrayType(parseAnnotations());
}
public Type parseNonArrayType(List<Annotation> annotations) {
if(wouldAccept(PRIMITIVE_TYPES)) {
var name = token.getString();
nextToken();
return new PrimitiveType(name, annotations);
} else {
return parseGenericType(annotations);
}
}
public ReferenceType parseReferenceType() {
return parseReferenceType(parseAnnotations());
}
public ReferenceType parseReferenceType(List<Annotation> annotations) {
var base = parseNonArrayType(annotations);
if(base instanceof PrimitiveType) {
base.setAnnotations(emptyList());
var dimension = parseDimension();
var dimensions = parseDimensions();
dimensions.add(0, dimension);
return new ArrayType(base, dimensions, annotations);
} else if(wouldAccept(AT.or(LBRACKET))) {
var dimensions = parseDimensions();
base.setAnnotations(emptyList());
return new ArrayType(base, dimensions, annotations);
} else {
return (GenericType)base;
}
}
public GenericType parseGenericType() {
return parseGenericType(parseAnnotations());
}
public GenericType parseGenericType(List<Annotation> annotations) {
var name = parseQualTypeName();
var typeArgs = parseTypeArgumentsOpt();
if(wouldAccept(DOT, Tag.NAMED)) {
nextToken();
var result = new GenericType(name, typeArgs);
do {
name = parseQualTypeName();
typeArgs = parseTypeArgumentsOpt();
result = new GenericType(name, typeArgs, result);
} while(accept(DOT));
result.setAnnotations(annotations);
return result;
} else {
return new GenericType(name, typeArgs, annotations);
}
}
public ReferenceType parseTypeIntersection() {
return parseTypeIntersection(parseAnnotations());
}
public ReferenceType parseTypeIntersection(List<Annotation> annotations) {
var type = parseReferenceType(annotations);
if(accept(AMP)) {
type.setAnnotations(emptyList());
var types = listOf(AMP, this::parseReferenceType);
types.add(0, type);
return new TypeIntersection(types, annotations);
} else {
return type;
}
}
public ReferenceType parseTypeUnion() {
return parseTypeUnion(parseAnnotations());
}
public ReferenceType parseTypeUnion(List<Annotation> annotations) {
var type = parseReferenceType(annotations);
if(accept(BAR)) {
type.setAnnotations(emptyList());
var types = listOf(BAR, this::parseReferenceType);
types.add(0, type);
return new TypeUnion(types, annotations);
} else {
return type;
}
}
public List<? extends TypeArgument> parseTypeArgumentsOpt() {
return wouldAccept(LT, not(GT))? parseTypeArguments() : emptyList();
}
public List<? extends TypeArgument> parseTypeArguments() {
require(LT);
var args = listOf(this::parseTypeArgument);
require(GT);
return args;
}
public TypeArgument parseTypeArgument() {
return parseTypeArgument(parseAnnotations());
}
public TypeArgument parseTypeArgument(List<Annotation> annotations) {
return wouldAccept(QUES)? parseWildcardTypeArgument(annotations) : parseReferenceType(annotations);
}
public WildcardTypeArgument parseWildcardTypeArgument() {
return parseWildcardTypeArgument(parseAnnotations());
}
public WildcardTypeArgument parseWildcardTypeArgument(List<Annotation> annotations) {
require(QUES);
Optional<WildcardTypeArgument.Bound> bound;
if(wouldAccept(SUPER.or(EXTENDS))) {
WildcardTypeArgument.Bound.Kind kind;
if(accept(SUPER)) {
kind = WildcardTypeArgument.Bound.Kind.SUPER;
} else {
require(EXTENDS);
kind = WildcardTypeArgument.Bound.Kind.EXTENDS;
}
var type = parseTypeIntersection();
bound = Optional.of(new WildcardTypeArgument.Bound(kind, type));
} else {
bound = Optional.empty();
}
return new WildcardTypeArgument(bound, annotations);
}
public EmptyStmt parseEmptyStmt() {
require(SEMI);
return new EmptyStmt();
}
public Block parseBlock() {
try(var $ = preStmts.enter()) {
require(LBRACE);
var stmts = new ArrayList<Statement>();
while(wouldNotAccept(RBRACE)) {
stmts.add(parseBlockStatement());
}
require(RBRACE);
return preStmts.apply(new Block(stmts));
}
}
public Statement parseBlockStatement() {
if(wouldAccept(AT)) {
var docComment = getDocComment();
var mods = new ArrayList<Modifier>();
var annos = parseAnnotations();
while(wouldAccept(Tag.LOCAL_VAR_MODIFIER)) {
mods.add(createModifier(token));
nextToken();
if(wouldAccept(AT)) {
annos.addAll(parseAnnotations());
}
}
if(wouldAccept(Tag.CLASS_MODIFIER)) {
do {
mods.add(createModifier(token));
nextToken();
if(wouldAccept(AT)) {
annos.addAll(parseAnnotations());
}
} while(wouldAccept(Tag.CLASS_MODIFIER));
try(var $ = preStmts.enter()) {
return preStmts.apply(parseClassDecl(docComment, new ModsAndAnnotations(mods, annos, EnumSet.of(ModsAndAnnotations.Type.CLASS))));
}
} else if(wouldAccept(CLASS)) {
try(var $ = preStmts.enter()) {
return preStmts.apply(parseClassDecl(docComment, new ModsAndAnnotations(mods, annos, EnumSet.of(ModsAndAnnotations.Type.CLASS))));
}
} else {
try(var $ = preStmts.enter()) {
return preStmts.apply(parseVariableDecl(docComment, new ModsAndAnnotations(mods, annos, EnumSet.of(ModsAndAnnotations.Type.LOCAL_VAR))));
}
}
}
if(wouldAccept(Tag.LOCAL_VAR_MODIFIER)) {
var docComment = getDocComment();
var mods = new ArrayList<Modifier>();
var annos = new ArrayList<Annotation>();
while(wouldAccept(Tag.LOCAL_VAR_MODIFIER)) {
mods.add(createModifier(token));
nextToken();
if(wouldAccept(AT)) {
annos.addAll(parseAnnotations());
}
}
if(wouldAccept(Tag.CLASS_MODIFIER)) {
do {
mods.add(createModifier(token));
nextToken();
if(wouldAccept(AT)) {
annos.addAll(parseAnnotations());
}
} while(wouldAccept(Tag.CLASS_MODIFIER));
try(var $ = preStmts.enter()) {
return preStmts.apply(parseClassDecl(docComment, new ModsAndAnnotations(mods, annos, EnumSet.of(ModsAndAnnotations.Type.CLASS))));
}
} else if(wouldAccept(CLASS)) {
try(var $ = preStmts.enter()) {
return preStmts.apply(parseClassDecl(docComment, new ModsAndAnnotations(mods, annos, EnumSet.of(ModsAndAnnotations.Type.CLASS))));
}
} else {
try(var $ = preStmts.enter()) {
return preStmts.apply(parseVariableDecl(docComment, new ModsAndAnnotations(mods, annos, EnumSet.of(ModsAndAnnotations.Type.LOCAL_VAR))));
}
}
}
if(wouldAccept(Tag.CLASS_MODIFIER)) {
var docComment = getDocComment();
var mods = new ArrayList<Modifier>();
var annos = new ArrayList<Annotation>();
do {
mods.add(createModifier(token));
nextToken();
if(wouldAccept(AT)) {
annos.addAll(parseAnnotations());
}
} while(wouldAccept(Tag.CLASS_MODIFIER));
try(var $ = preStmts.enter()) {
return preStmts.apply(parseClassDecl(docComment, new ModsAndAnnotations(mods, annos, EnumSet.of(ModsAndAnnotations.Type.CLASS))));
}
}
vardecl: if(wouldAccept(Tag.NAMED.or(Tag.PRIMITIVE_TYPE))) {
var docComment = getDocComment();
Type type;
try(var $ = preStmts.enter(); var state = tokens.enter()) {
try {
type = parseType();
} catch(SyntaxError e) {
state.reset();
break vardecl;
}
if(!wouldAccept(Tag.NAMED)) {
state.reset();
break vardecl;
}
return preStmts.apply(parseVariableDecl(type, docComment, new ModsAndAnnotations()));
}
}
return parseStatement();
}
public Statement parseStatement() {
try(var $ = preStmts.enter()) {
return preStmts.apply(switch(token.getType()) {
case IF -> parseIfStmt();
case DO -> parseDoStmt();
case FOR -> parseForStmt();
case WHILE -> parseWhileStmt();
case SYNCHRONIZED -> parseSynchronizedStmt();
case TRY -> parseTryStmt();
case SWITCH -> parseSwitch();
case RETURN -> parseReturnStmt();
case BREAK -> parseBreakStmt();
case CONTINUE -> parseContinueStmt();
case YIELD -> parseYieldStmt();
case THROW -> parseThrowStmt();
case ASSERT -> parseAssertStmt();
case LBRACE -> parseBlock();
case SEMI -> parseEmptyStmt();
case LT -> {
var typeArguments = parseTypeArguments();
ConstructorCall.Type type;
if(accept(SUPER)) {
type = ConstructorCall.Type.SUPER;
} else {
require(THIS);
type = ConstructorCall.Type.THIS;
}
var args = parseConstructorArguments();
endStatement();
break new ConstructorCall(typeArguments, type, args);
}
case THIS -> {
if(wouldAccept(THIS, LPAREN)) {
nextToken();
var args = parseConstructorArguments();
endStatement();
break new ConstructorCall(ConstructorCall.Type.THIS, args);
} else {
break statementDefault();
}
}
case SUPER -> {
assert tokens.look(0).equals(token);
assert !tokens.look(1).equals(token);
if(wouldAccept(SUPER, LPAREN)) {
nextToken();
var args = parseConstructorArguments();
endStatement();
break new ConstructorCall(ConstructorCall.Type.SUPER, args);
} else {
break statementDefault();
}
}
case ELSE -> throw syntaxError("'else' without 'if'");
case CATCH -> throw syntaxError("'catch' without 'try'");
case FINALLY -> throw syntaxError("'finally' without 'try'");
case CASE -> throw syntaxError("'case' without 'switch'");
case DEFAULT -> throw syntaxError("'default' without 'switch'");
default -> statementDefault();
});
}
}
protected Statement statementDefault() {
if(wouldAccept(NAME, COLON)) {
return parseLabeledStmt();
} else {
call:
try(var state = tokens.enter()) {
Expression object;
try {
object = parseSuffix();
require(DOT);
} catch(SyntaxError e) {
state.reset();
break call;
}
List<? extends TypeArgument> typeArguments;
if(wouldAccept(LT)) {
typeArguments = parseTypeArguments();
} else {
typeArguments = emptyList();
}
if(!accept(SUPER)) {
state.reset();
break call;
}
if(wouldAccept(LPAREN)) {
var args = parseConstructorArguments();
endStatement();
return new ConstructorCall(object, typeArguments, ConstructorCall.Type.SUPER, args);
} else {
state.reset();
break call;
}
}
return parseExpressionStmt();
}
}
public void endStatement() {
if(tokens.look(-1).getType() == RBRACE) {
accept(SEMI);
} else {
requireSemi();
}
}
public Expression parseCondition() {
require(LPAREN);
var expr = parseExpression();
require(RPAREN);
return expr;
}
public Block parseBodyAsBlock() {
return parseBlock();
}
public ExpressionStmt parseExpressionStmt() {
var expr = parseExpression();
endStatement();
return new ExpressionStmt(expr);
}
public LabeledStmt parseLabeledStmt() {
var name = parseName();
require(COLON);
var stmt = parseStatement();
return new LabeledStmt(name, stmt);
}
public Statement parseBody() {
return parseStatement();
}
public IfStmt parseIfStmt() {
require(IF);
var condition = parseCondition();
var body = parseBody();
Optional<Statement> elseBody;
if(accept(ELSE)) {
elseBody = Optional.of(parseBody());
} else {
elseBody = Optional.empty();
}
return new IfStmt(condition, body, elseBody);
}
public WhileStmt parseWhileStmt() {
require(WHILE);
var condition = parseCondition();
var body = parseBody();
return new WhileStmt(condition, body);
}
public DoStmt parseDoStmt() {
require(DO);
var body = parseBody();
require(WHILE);
var condition = parseCondition();
endStatement();
return new DoStmt(body, condition);
}
public Statement parseForStmt() {
require(FOR, LPAREN);
boolean mayHaveVariable = wouldAccept(AT.or(Tag.NAMED).or(Tag.PRIMITIVE_TYPE).or(Tag.LOCAL_VAR_MODIFIER));
if(mayHaveVariable) {
foreach:
try(var state = tokens.enter()) {
FormalParameter vardecl;
try {
var modsAndAnnos = parseFinalAndAnnotations();
var type = parseType();
var name = parseName();
var dimensions = parseDimensions();
require(COLON);
vardecl = new FormalParameter(type, name, dimensions, modsAndAnnos.mods, modsAndAnnos.annos);
} catch(SyntaxError e) {
state.reset();
break foreach;
}
var iterable = parseExpression();
require(RPAREN);
var body = parseBody();
return new ForEachStmt(vardecl, iterable, body);
}
}
Optional<Either<VariableDecl,ExpressionStmt>> initializer = Optional.empty();
if(mayHaveVariable) {
vardecl:
try(var state = tokens.enter()) {
var modsAndAnnos = parseFinalAndAnnotations();
Type type;
Name name;
ArrayList<Dimension> dimensions;
try {
type = parseType();
name = parseName();
dimensions = parseDimensions();
} catch(SyntaxError e) {
state.reset();
break vardecl;
}
Optional<? extends Initializer> init = parseVariableInitializerOpt(type, dimensions);
var declarators = new ArrayList<VariableDeclarator>();
declarators.add(new VariableDeclarator(name, dimensions, init));
while(accept(COMMA)) {
declarators.add(parseVariableDeclarator(type));
}
endStatement();
initializer = Optional.of(Either.first(new VariableDecl(type, declarators, modsAndAnnos.mods, modsAndAnnos.annos, Optional.empty())));
}
if(initializer.isEmpty()) {
initializer = Optional.of(Either.second(parseExpressionStmt()));
}
} else if(!accept(SEMI)) {
initializer = Optional.of(Either.second(parseExpressionStmt()));
}
Optional<? extends Expression> condition;
if(accept(SEMI)) {
condition = Optional.empty();
} else {
condition = Optional.of(parseExpression());
endStatement();
}
List<? extends Expression> updates;
if(wouldAccept(RPAREN)) {
updates = emptyList();
} else {
updates = listOf(this::parseExpression);
}
require(RPAREN);
var body = parseBody();
return new ForStmt(initializer, condition, updates, body);
}
public SynchronizedStmt parseSynchronizedStmt() {
require(SYNCHRONIZED);
var lock = parseCondition();
var body = parseBodyAsBlock();
return new SynchronizedStmt(lock, body);
}
public Statement parseTryStmt() {
require(TRY);
List<ResourceSpecifier> resources;
if(accept(LPAREN)) {
resources = new ArrayList<>();
resources.add(parseResourceSpecifier());
while(wouldNotAccept(RPAREN)) {
endStatement();
if(wouldAccept(RPAREN)) {
break;
}
resources.add(parseResourceSpecifier());
}
require(RPAREN);
} else {
resources = emptyList();
}
var body = parseBodyAsBlock();
var catches = parseCatches();
Optional<Block> finallyBody = parseFinally();
if(resources.isEmpty() && catches.isEmpty() && finallyBody.isEmpty()) {
throw syntaxError("expected 'catch' or 'finally' here, got " + token);
}
return new TryStmt(resources, body, catches, finallyBody);
}
public Optional<Block> parseFinally() {
if(accept(FINALLY)) {
return Optional.of(parseBodyAsBlock());
} else {
return Optional.empty();
}
}
public List<Catch> parseCatches() {
var catches = new ArrayList<Catch>();
while(wouldAccept(CATCH)) {
catches.add(parseCatch());
}
return catches;
}
public Catch parseCatch() {
require(CATCH, LPAREN);
var modsAndAnnos = parseFinalAndAnnotations();
var type = parseTypeUnion();
var name = parseName();
require(RPAREN);
var body = parseBodyAsBlock();
return new Catch(new FormalParameter(type, name, modsAndAnnos.mods, modsAndAnnos.annos), body);
}
public ResourceSpecifier parseResourceSpecifier() {
if(wouldAccept(AT.or(Tag.NAMED).or(Tag.PRIMITIVE_TYPE).or(Tag.LOCAL_VAR_MODIFIER))) {
vardecl:
try(var state = tokens.enter()) {
var modsAndAnnos = parseFinalAndAnnotations();
Type type;
Name name;
try {
type = parseType();
name = parseName();
} catch(SyntaxError e) {
state.reset();
break vardecl;
}
var dimensions = parseDimensions();
var init = Optional.of(parseVariableInitializer(type, dimensions));
return new VariableDecl(type, name, dimensions, init, modsAndAnnos.mods, modsAndAnnos.annos,
Optional.empty());
}
}
return new ExpressionStmt(parseExpression());
}
public Switch parseSwitch() {
require(SWITCH);
var expression = parseCondition();
require(LBRACE);
var cases = new ArrayList<SwitchCase>();
while(wouldNotAccept(RBRACE)) {
cases.add(parseSwitchCase());
}
require(RBRACE);
return new Switch(expression, cases);
}
public SwitchCase parseSwitchCase() {
List<Expression> labels;
if(accept(DEFAULT)) {
labels = emptyList();
} else {
require(CASE);
labels = listOf(this::parseSwitchLabel);
}
var body = parseCaseBody();
return new SwitchCase(labels, body);
}
public Either<List<Statement>,Statement> parseCaseBody() {
if(accept(ARROW)) {
Statement stmt = parseArrowCaseBody();
return Either.second(stmt);
} else {
require(COLON);
var stmts = new ArrayList<Statement>();
while(wouldNotAccept(CASE.or(DEFAULT).or(RBRACE))) {
stmts.add(parseBlockStatement());
}
return Either.first(stmts);
}
}
public Statement parseArrowCaseBody() {
if(wouldAccept(THROW)) {
return parseThrowStmt();
} else if(wouldAccept(LBRACE)) {
return parseBlock();
} else {
return parseExpressionStmt();
}
}
public Expression parseSwitchLabel() {
if(wouldAccept(Tag.NAMED, ARROW)) {
return new Variable(parseName());
} else if(wouldAccept(LPAREN, Tag.NAMED, RPAREN, ARROW)) {
require(LPAREN);
var result = new Variable(parseName());
require(RPAREN);
return result;
} else {
return parseExpression();
}
}
public ThrowStmt parseThrowStmt() {
require(THROW);
var expr = parseExpression();
endStatement();
return new ThrowStmt(expr);
}
public ReturnStmt parseReturnStmt() {
require(RETURN);
if(accept(SEMI)) {
return new ReturnStmt();
} else {
var expr = parseExpression();
endStatement();
return new ReturnStmt(expr);
}
}
public BreakStmt parseBreakStmt() {
require(BREAK);
if(accept(SEMI)) {
return new BreakStmt();
} else {
var label = parseName();
endStatement();
return new BreakStmt(label);
}
}
public ContinueStmt parseContinueStmt() {
require(BREAK);
if(accept(SEMI)) {
return new ContinueStmt();
} else {
var label = parseName();
endStatement();
return new ContinueStmt(label);
}
}
public Statement parseYieldStmt() {
parse: try(var state = tokens.enter()) {
require(YIELD);
Expression expr;
try {
expr = parseExpression();
} catch(SyntaxError e) {
state.reset();
break parse;
}
endStatement();
return new YieldStmt(expr);
}
return parseExpressionStmt();
}
public AssertStmt parseAssertStmt() {
require(ASSERT);
var condition = parseExpression();
Optional<? extends Expression> message;
if(accept(COLON)) {
message = Optional.of(parseExpression());
} else {
message = Optional.empty();
}
endStatement();
return new AssertStmt(condition, message);
}
public Initializer parseInitializer(int arrayBracketDepth) {
if(wouldAccept(LBRACE) && arrayBracketDepth > 0) {
return parseArrayInitializer(() -> parseInitializer(arrayBracketDepth-1));
} else {
return parseExpression();
}
}
public Expression parseExpression() {
return parseLambdaOr(this::parseAssignExpr);
}
public Expression parseLambdaOr(Supplier<? extends Expression> parser) {
parse: if(wouldAccept(Tag.NAMED, ARROW) || wouldAccept(LPAREN)) {
Either<? extends List<FormalParameter>,? extends List<InformalParameter>> parameters;
try(var state = tokens.enter()) {
try {
parameters = parseLambdaParameters();
require(ARROW);
} catch(SyntaxError e) {
state.reset();
break parse;
}
return new Lambda(parameters, parseLambdaBody());
}
}
return parser.get();
}
public Either<? extends List<FormalParameter>,? extends List<InformalParameter>> parseLambdaParameters() {
if(wouldAccept(Tag.NAMED)) {
return Either.second(List.of(parseInformalParameter()));
}
require(LPAREN);
if(accept(RPAREN)) {
return Either.first(emptyList());
}
try {
if(wouldAccept(Tag.NAMED, COMMA.or(RPAREN))) {
return Either.second(listOf(this::parseInformalParameter));
} else {
return Either.first(listOf(this::parseFormalParameter));
}
} finally {
require(RPAREN);
}
}
public InformalParameter parseInformalParameter() {
return new InformalParameter(parseName());
}
public Either<Block,? extends Expression> parseLambdaBody() {
return wouldAccept(LBRACE)? Either.first(parseBlock()) : Either.second(parseExpression());
}
public Expression parseAssignExpr() {
var expr = parseConditionalExpr();
if(expr instanceof Variable || expr instanceof IndexExpr || expr instanceof MemberAccess) {
switch(token.getType()) {
case EQ, PLUSEQ, SUBEQ, STAREQ, SLASHEQ, PERCENTEQ, CARETEQ, LTLTEQ, GTGTEQ, GTGTGTEQ, AMPEQ, BAREQ:
var op = AssignExpr.Op.fromString(token.getString());
nextToken();
expr = new AssignExpr(expr, op, parseExpression());
default:
}
}
return expr;
}
public Expression parseConditionalExpr() {
var expr = parseLogicalOrExpr();
if(accept(QUES)) {
var truepart = parseExpression();
require(COLON);
var falsepart = parseLambdaOr(this::parseConditionalExpr);
return new ConditionalExpr(expr, truepart, falsepart);
} else {
return expr;
}
}
public Expression parseLogicalOrExpr() {
var expr = parseLogicalAndExpr();
while(accept(BARBAR)) {
expr = new BinaryExpr(expr, BinaryExpr.Op.OR, parseLogicalAndExpr());
}
return expr;
}
public Expression parseLogicalAndExpr() {
var expr = parseBitOrExpr();
while(accept(AMPAMP)) {
expr = new BinaryExpr(expr, BinaryExpr.Op.AND, parseBitOrExpr());
}
return expr;
}
public Expression parseBitOrExpr() {
var expr = parseXorExpr();
while(accept(BAR)) {
expr = new BinaryExpr(expr, BinaryExpr.Op.BIT_OR, parseXorExpr());
}
return expr;
}
public Expression parseXorExpr() {
var expr = parseBitAndExpr();
while(accept(CARET)) {
expr = new BinaryExpr(expr, BinaryExpr.Op.XOR, parseBitAndExpr());
}
return expr;
}
public Expression parseBitAndExpr() {
var expr = parseEqualityExpr();
while(accept(AMP)) {
expr = new BinaryExpr(expr, BinaryExpr.Op.BIT_AND, parseEqualityExpr());
}
return expr;
}
public Expression parseEqualityExpr() {
var expr = parseRelExpr();
for(;;) {
if(accept(EQEQ)) {
expr = new BinaryExpr(expr, BinaryExpr.Op.EQUAL, parseRelExpr());
} else if(accept(BANGEQ)) {
expr = new BinaryExpr(expr, BinaryExpr.Op.NEQUAL, parseRelExpr());
} else {
return expr;
}
}
}
public Expression parseRelExpr() {
var expr = parseShiftExpr();
for(;;) {
if(accept(LT)) {
expr = new BinaryExpr(expr, BinaryExpr.Op.LTHAN, parseShiftExpr());
} else if(accept(GT)) {
expr = new BinaryExpr(expr, BinaryExpr.Op.GTHAN, parseShiftExpr());
} else if(accept(LTEQ)) {
expr = new BinaryExpr(expr, BinaryExpr.Op.LEQUAL, parseShiftExpr());
} else if(accept(GTEQ)) {
expr = new BinaryExpr(expr, BinaryExpr.Op.GEQUAL, parseShiftExpr());
} else if(accept(INSTANCEOF)) {
expr = new TypeTest(expr, parseReferenceType());
} else {
return expr;
}
}
}
public Expression parseShiftExpr() {
var expr = parseAddExpr();
for(;;) {
if(accept(LTLT)) {
expr = new BinaryExpr(expr, BinaryExpr.Op.LSHIFT, parseAddExpr());
} else if(acceptPseudoOp(GT, GT, GT)) {
expr = new BinaryExpr(expr, BinaryExpr.Op.URSHIFT, parseAddExpr());
} else if(acceptPseudoOp(GT, GT)) {
expr = new BinaryExpr(expr, BinaryExpr.Op.RSHIFT, parseAddExpr());
} else {
return expr;
}
}
}
public Expression parseAddExpr() {
var expr = parseMulExpr();
for(;;) {
if(accept(PLUS)) {
expr = new BinaryExpr(expr, BinaryExpr.Op.PLUS, parseMulExpr());
} else if(accept(SUB)) {
expr = new BinaryExpr(expr, BinaryExpr.Op.MINUS, parseMulExpr());
} else {
return expr;
}
}
}
public Expression parseMulExpr() {
var expr = parseUnaryExpr();
for(;;) {
if(accept(STAR)) {
expr = new BinaryExpr(expr, BinaryExpr.Op.TIMES, parseUnaryExpr());
} else if(accept(SLASH)) {
expr = new BinaryExpr(expr, BinaryExpr.Op.DIVIDE, parseUnaryExpr());
} else if(accept(PERCENT)) {
expr = new BinaryExpr(expr, BinaryExpr.Op.MODULUS, parseUnaryExpr());
} else {
return expr;
}
}
}
public Expression parseUnaryExpr() {
if(accept(PLUSPLUS)) {
return new PreIncrementExpr(parseUnaryExpr());
} else if(accept(SUBSUB)) {
return new PreDecrementExpr(parseUnaryExpr());
} else if(accept(PLUS)) {
return new UnaryExpr(UnaryExpr.Op.POSITIVE, parseUnaryExpr());
} else if(accept(SUB)) {
return new UnaryExpr(UnaryExpr.Op.NEGATE, parseUnaryExpr());
} else {
return parseUnaryExprNotPlusMinus();
}
}
public Expression parseUnaryExprNotPlusMinus() {
if(accept(TILDE)) {
return new UnaryExpr(UnaryExpr.Op.INVERT, parseUnaryExpr());
} else if(accept(BANG)) {
return new UnaryExpr(UnaryExpr.Op.NOT, parseUnaryExpr());
} else {
return parseCastExpr();
}
}
public Expression parseCastExpr() {
cast: if(wouldAccept(LPAREN)) {
try(var state = tokens.enter()) {
try {
require(LPAREN);
Type type;
var annotations = parseAnnotations();
if(wouldAccept(PRIMITIVE_TYPES, RPAREN)) {
type = new PrimitiveType(token.getString(), annotations);
nextToken();
} else {
type = parseTypeIntersection(annotations);
}
require(RPAREN);
Expression expr;
if(type instanceof PrimitiveType) {
expr = parseUnaryExpr();
} else {
expr = parseLambdaOr(this::parseUnaryExprNotPlusMinus);
}
return new CastExpr(type, expr);
} catch(SyntaxError e) {
state.reset();
break cast;
}
}
}
return parsePostfixExpr();
}
public Expression parsePostfixExpr() {
var expr = parseSuffix();
for(;;) {
if(accept(PLUSPLUS)) {
expr = new PostIncrementExpr(expr);
} else if(accept(SUBSUB)) {
expr = new PostDecrementExpr(expr);
} else {
return expr;
}
}
}
public Expression parseSuffix() {
var expr = parsePrimary();
for(;;) {
if(wouldAccept(COLCOL)) {
expr = parseMethodReferenceRest(expr);
} else if(wouldAccept(DOT)
&& (!wouldAccept(DOT, SUPER.or(THIS)) || wouldAccept(DOT, SUPER.or(THIS), not(LPAREN)))) {
List<? extends TypeArgument> typeArguments;
if(wouldAccept(DOT, LT)) {
try(var state = tokens.enter()) {
require(DOT);
typeArguments = parseTypeArguments();
if(wouldAccept(SUPER.or(THIS), LPAREN)) {
state.reset();
return expr;
}
}
} else {
require(DOT);
typeArguments = emptyList();
}
expr = parseMemberAccessRest(expr, typeArguments);
} else if(wouldAccept(LBRACKET)) {
expr = parseIndexRest(expr);
} else {
return expr;
}
}
}
public Expression parseMethodReferenceRest(Expression object) {
require(COLCOL);
var typeArguments = parseTypeArgumentsOpt();
var name = parseName();
return parseExpressionMethodReferenceRest(object, typeArguments, name);
}
public Expression parseExpressionMethodReferenceRest(Expression object, List<? extends TypeArgument> typeArguments,
Name name) {
return new MethodReference(object, typeArguments, name);
}
private static final Name name_new = new Name("new");
public Expression parseTypeMethodReferenceRest(Either<ArrayType,GenericType> type,
List<? extends TypeArgument> typeArguments) {
return new MethodReference((Type)type.getValue(), typeArguments, name_new);
}
public Expression parseSuperMethodReferenceRest(Optional<QualifiedName> qualifier,
List<? extends TypeArgument> typeArguments, Name name) {
return new SuperMethodReference(qualifier, typeArguments, name);
}
public Expression parseMemberAccessRest(Expression object, List<? extends TypeArgument> typeArguments) {
if(!typeArguments.isEmpty()) {
var name = parseName();
var args = parseArguments(false);
return new FunctionCall(object, name, typeArguments, args);
} else if(wouldAccept(NEW)) {
var creator = parseClassCreator();
creator.setObject(object);
return creator;
}
var name = parseName();
if(wouldAccept(LPAREN)) {
var args = parseArguments(false);
return new FunctionCall(object, name, args);
}
return new MemberAccess(object, name);
}
public Expression parseIndexRest(Expression indexed) {
require(LBRACKET);
var index = parseExpression();
require(RBRACKET);
return new IndexExpr(indexed, index);
}
public Expression parsePrimary() {
return switch(token.getType()) {
case NUMBER -> parseNumberLiteral();
case STRING -> parseStringLiteral();
case CHARACTER -> parseCharLiteral();
case NULL -> parseNullLiteral();
case TRUE, FALSE -> parseBooleanLiteral();
case THIS -> parseThis();
case SUPER -> parseSuper();
case NEW -> parseCreator();
case LPAREN -> parseParens();
case SWITCH -> parseSwitch();
case VOID, BOOLEAN, BYTE, SHORT, CHAR, INT, FLOAT, LONG, DOUBLE -> parseClassLiteralOrMethodReference();
default -> {
if(wouldAccept(Tag.NAMED)) {
break parsePrimaryName();
} else {
throw syntaxError("invalid start of expression");
}
}
};
}
public Expression parseStringLiteral() {
var token = this.token;
var str = token.getString();
require(STRING);
str = str.substring(1, str.length() - 1);
try {
return new Literal(StringEscapeUtils.unescapeJava(str), token.getString());
} catch(Exception e) {
throw new SyntaxError("invalid string literal", filename, token.getStart().getLine(),
token.getStart().getColumn(), token.getLine());
}
}
public Expression parseCharLiteral() {
var token = this.token;
var str = token.getString();
require(CHARACTER);
str = str.substring(1, str.length() - 1);
try {
str = StringEscapeUtils.unescapeJava(str);
if(str.length() != 1) {
throw new IllegalArgumentException();
}
return new Literal(str.charAt(0), token.getString());
} catch(Exception e) {
throw new SyntaxError("invalid char literal", filename, token.getStart().getLine(),
token.getStart().getColumn(), token.getLine());
}
}
public Expression parseNullLiteral() {
require(NULL);
return new Literal();
}
public Expression parseBooleanLiteral() {
if(accept(TRUE)) {
return new Literal(true);
} else {
require(FALSE);
return new Literal(false);
}
}
public Expression parseNumberLiteral() {
var token = this.token;
var str = token.getString();
require(NUMBER);
assert !token.equals(this.token);
try {
str = str.replace("_", "");
if(str.endsWith("f") || str.endsWith("F")) {
if((str.startsWith("0x") || str.startsWith("0X")) && !str.contains(".") && !str.contains("p")
&& !str.contains("P")) {
return new Literal(Integer.parseInt(str.substring(2), 16), token.getString());
}
return new Literal(Float.parseFloat(str.substring(0, str.length() - 1)), token.getString());
}
if(str.endsWith("d") || str.endsWith("D")) {
if((str.startsWith("0x") || str.startsWith("0X")) && !str.contains(".") && !str.contains("p")
&& !str.contains("P")) {
return new Literal(Integer.parseInt(str.substring(2), 16), token.getString());
}
return new Literal(Double.parseDouble(str.substring(0, str.length() - 1)), token.getString());
}
if(str.contains(".")) {
return new Literal(Double.parseDouble(str), token.getString());
}
int base = 10;
if(str.startsWith("0x") || str.startsWith("0X")) {
base = 16;
str = str.substring(2);
} else if(str.startsWith("0b") || str.startsWith("0B")) {
base = 2;
str = str.substring(2);
}
if(str.endsWith("l") || str.endsWith("L")) {
return new Literal(Long.parseLong(str.substring(0, str.length() - 1), base), token.getString());
} else {
return new Literal(Integer.parseInt(str, base), token.getString());
}
} catch(NumberFormatException e) {
throw new SyntaxError("invalid number literal", filename, token.getStart().getLine(),
token.getStart().getColumn(), token.getLine());
}
}
public Expression parsePrimaryName() {
try(var state = tokens.enter()) {
try {
var names = new ArrayList<Name>();
names.add(parseName());
while(wouldAccept(DOT, not(THIS.or(SUPER).or(CLASS)))) {
require(DOT);
names.add(parseName());
}
require(DOT);
if(accept(SUPER)) {
if(accept(DOT)) {
var typeArguments = parseTypeArgumentsOpt();
var name = parseName();
var args = parseArguments(false);
return new SuperFunctionCall(new QualifiedName(names), name, typeArguments, args);
} else {
require(COLCOL);
var typeArguments = parseTypeArgumentsOpt();
var name = parseName();
return parseSuperMethodReferenceRest(Optional.of(new QualifiedName(names)), typeArguments,
name);
}
} else if(accept(CLASS)) {
return new ClassLiteral(new GenericType(new QualifiedName(names)));
} else {
require(THIS);
return new This(new QualifiedName(names));
}
} catch(SyntaxError e) {
state.reset();
}
}
try(var state = tokens.enter()) {
try {
var type = parseType(emptyList());
if(accept(COLCOL)) {
if(type instanceof ArrayType) {
require(NEW);
return parseTypeMethodReferenceRest(Either.first((ArrayType)type), emptyList());
} else {
if(!(type instanceof GenericType)) {
throw syntaxError("can only create references to class types or array types");
}
var typeArguments = parseTypeArgumentsOpt();
require(NEW);
return parseTypeMethodReferenceRest(Either.second((GenericType)type), typeArguments);
}
}
require(DOT, CLASS);
return new ClassLiteral(type);
} catch(SyntaxError e) {
state.reset();
}
}
var name = parseName();
if(wouldAccept(LPAREN)) {
var args = parseArguments(false);
return new FunctionCall(name, args);
} else {
return new Variable(name);
}
}
public Expression parseSuper() {
require(SUPER);
if(accept(COLCOL)) {
var typeArguments = parseTypeArgumentsOpt();
var name = parseName();
return parseSuperMethodReferenceRest(Optional.empty(), typeArguments, name);
} else {
require(DOT);
var typeArguments = parseTypeArgumentsOpt();
var name = parseName();
var args = parseArguments(false);
return new SuperFunctionCall(name, typeArguments, args);
}
}
public Expression parseThis() {
require(THIS);
return new This();
}
public Expression parseParens() {
require(LPAREN);
var expr = parseExpression();
require(RPAREN);
return new ParensExpr(expr);
}
public Expression parseClassLiteralOrMethodReference() {
if(accept(VOID)) {
require(DOT, CLASS);
return new ClassLiteral(new VoidType());
}
var type = parseType(emptyList());
if(type instanceof ArrayType && accept(COLCOL)) {
require(NEW);
return parseTypeMethodReferenceRest(Either.first((ArrayType)type), emptyList());
}
require(DOT, CLASS);
return new ClassLiteral(type);
}
public List<? extends Expression> parseConstructorArguments() {
return parseArguments(false);
}
public List<? extends Expression> parseArgumentsOpt(boolean classCreatorArguments) {
return wouldAccept(LPAREN)? parseArguments(classCreatorArguments) : emptyList();
}
public List<? extends Expression> parseArguments(boolean classCreatorArguments) {
require(LPAREN);
if(accept(RPAREN)) {
return emptyList();
} else {
var args = listOf(this::parseArgument);
require(RPAREN);
return args;
}
}
public Expression parseArgument() {
return parseExpression();
}
public Expression parseCreator() {
require(NEW);
if(wouldAccept(LT)) {
var typeArguments = parseTypeArguments();
var type = parseGenericType();
return parseClassCreatorRest(typeArguments, type);
}
var typeAnnotations = parseAnnotations();
if(wouldAccept(PRIMITIVE_TYPES)) {
var base = new PrimitiveType(token.getString(), typeAnnotations);
nextToken();
var annotations = parseAnnotations();
require(LBRACKET);
if(accept(RBRACKET)) {
var dimensions = new ArrayList<Dimension>();
dimensions.add(new Dimension(annotations));
while(wouldAccept(AT.or(LBRACKET))) {
dimensions.add(parseDimension());
}
var initializer = parseArrayInitializer(() -> parseInitializer(dimensions.size()));
return new ArrayCreator(base, initializer, dimensions);
} else {
var sizes = new ArrayList<Size>();
sizes.add(new Size(parseExpression(), annotations));
var dimensions = new ArrayList<Dimension>();
require(RBRACKET);
while(wouldAccept(AT.or(LBRACKET))) {
annotations = parseAnnotations();
require(LBRACKET);
if(accept(RBRACKET)) {
dimensions.add(new Dimension(annotations));
break;
} else {
sizes.add(new Size(parseExpression(), annotations));
require(RBRACKET);
}
}
while(wouldAccept(AT.or(LBRACKET))) {
dimensions.add(parseDimension());
}
return new ArrayCreator(base, sizes, dimensions);
}
} else {
var type = parseGenericType(typeAnnotations);
if(type.getTypeArguments().isEmpty() && wouldAccept(LT, GT)) {
return parseClassCreatorRest(emptyList(), type);
}
if(wouldAccept(AT.or(LBRACKET))) {
var annotations = parseAnnotations();
require(LBRACKET);
if(accept(RBRACKET)) {
var dimensions = new ArrayList<Dimension>();
dimensions.add(new Dimension(annotations));
while(wouldAccept(AT.or(LBRACKET))) {
dimensions.add(parseDimension());
}
var initializer = parseArrayInitializer(() -> parseInitializer(dimensions.size()));
return new ArrayCreator(type, initializer, dimensions);
} else {
var sizes = new ArrayList<Size>();
sizes.add(new Size(parseExpression(), annotations));
var dimensions = new ArrayList<Dimension>();
require(RBRACKET);
while(wouldAccept(AT.or(LBRACKET))) {
annotations = parseAnnotations();
require(LBRACKET);
if(accept(RBRACKET)) {
dimensions.add(new Dimension(annotations));
break;
} else {
sizes.add(new Size(parseExpression(), annotations));
require(RBRACKET);
}
}
while(wouldAccept(AT.or(LBRACKET))) {
dimensions.add(parseDimension());
}
return new ArrayCreator(type, sizes, dimensions);
}
} else {
return parseClassCreatorRest(emptyList(), type);
}
}
}
public ClassCreator parseClassCreator() {
require(NEW);
var typeArguments = parseTypeArgumentsOpt();
var type = parseGenericType();
return parseClassCreatorRest(typeArguments, type);
}
public ClassCreator parseClassCreatorRest(List<? extends TypeArgument> typeArguments, GenericType type) {
boolean hasDiamond = type.getTypeArguments().isEmpty() && accept(LT, GT);
var args = parseArguments(true);
Optional<? extends List<Member>> members;
if(wouldAccept(LBRACE)) {
members = Optional.of(parseClassBody(() -> parseClassMember(false)));
} else {
members = Optional.empty();
}
return new ClassCreator(typeArguments, type, hasDiamond, args, members);
}
} | 102,072 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
ModsAndAnnotations.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/JavaParser/src/jtree/parser/ModsAndAnnotations.java | package jtree.parser;
import static jtree.parser.ModsAndAnnotations.Type.*;
import static jtree.util.Utils.emptyList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jtree.nodes.Annotation;
import jtree.nodes.Modifier;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
@RequiredArgsConstructor
@ToString
public class ModsAndAnnotations {
public final @NonNull List<Modifier> mods;
public final @NonNull List<Annotation> annos;
public final @NonNull EnumSet<ModsAndAnnotations.Type> types;
public ModsAndAnnotations() {
this(emptyList(), emptyList(), EnumSet.allOf(ModsAndAnnotations.Type.class));
}
public ModsAndAnnotations(@NonNull List<Modifier> mods, @NonNull List<Annotation> annos) {
this.mods = mods;
this.annos = annos;
this.types = EnumSet.allOf(ModsAndAnnotations.Type.class);
for(var mod : mods) {
var validTypes = MOD_TYPES.get(mod.toCode());
if(validTypes != null) {
types.retainAll(validTypes);
}
}
}
public boolean isEmpty() {
return mods.isEmpty() && annos.isEmpty();
}
@SuppressWarnings("unlikely-arg-type")
public boolean hasModifier(String modifier) {
for(var mod : mods) {
if(mod.equals(modifier)) {
return true;
}
}
return false;
}
public boolean hasModifier(Modifier modifier) {
return mods.contains(modifier);
}
public boolean canBeLocalVarMods() {
return types.contains(LOCAL_VAR);
}
public boolean canBeClassMods() {
return types.contains(CLASS);
}
public boolean canBeMethodMods() {
return types.contains(METHOD);
}
public boolean canBeConstructorMods() {
assert this.canBeMethodMods();
return types.contains(CONSTRUCTOR);
}
public boolean canBeFieldMods() {
return types.contains(FIELD);
}
public static enum Type {
LOCAL_VAR,
CLASS,
METHOD,
CONSTRUCTOR,
FIELD;
private static final EnumSet<Type> NONE = EnumSet.noneOf(Type.class);
public static EnumSet<Type> fromModifier(Modifier modifier) {
return EnumSet.copyOf(MOD_TYPES.getOrDefault(modifier.toCode(), NONE));
}
}
/*
* Modifier |class?|method?|field?|var? |constructor?|
* ------------+------+-------+------+-----+------------+
* public* |true |true |true |false|true |
* private* |true |true |true |false|true |
* protected* |true |true |true |false|true |
* package** |true |true |true |false|true |
* static |true |true |true |false|false |
* final |true |true |true |true |false |
* abstract |true |true |false |false|false |
* strictfp |true |true |false |false|false |
* native |false |true |false |false|false |
* synchronized|false |true |false |false|false |
* default |false |true |false |false|false |
* transient |false |false |true |false|false |
* volatile |false |false |true |false|false |
* ------------+------+-------+------+-----+------------+
* *: modifier can NOT be prepended with 'non-'
* **: not a modifier in vanilla Java, also can NOT be prepended with 'non-'
*/
private static final Map<String, EnumSet<ModsAndAnnotations.Type>> MOD_TYPES;
static {
var map = new HashMap<String, EnumSet<ModsAndAnnotations.Type>>(22);
put(map, EnumSet.of(CLASS, METHOD, FIELD, CONSTRUCTOR), "public", "private", "protected", "package");
put(map, EnumSet.of(CLASS, METHOD, FIELD), "static", "non-static");
put(map, EnumSet.of(CLASS, METHOD, FIELD, LOCAL_VAR), "final", "non-final");
put(map, EnumSet.of(CLASS, METHOD), "abstract", "non-abstract", "strictfp", "non-strictfp");
put(map, EnumSet.of(METHOD), "native", "non-native", "synchronized", "non-synchronized", "default", "non-default");
put(map, EnumSet.of(FIELD), "transient", "non-transient", "volatile", "non-volatile");
MOD_TYPES = Collections.unmodifiableMap(map);
}
private static void put(Map<String, EnumSet<ModsAndAnnotations.Type>> map, EnumSet<ModsAndAnnotations.Type> set, String... keys) {
for(String key : keys) {
map.put(key, set);
}
}
}
| 4,209 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
ExpressionStmt.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/JavaParser/src/jtree/nodes/ExpressionStmt.java | package jtree.nodes;
import java.util.function.Consumer;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.NonNull;
@EqualsAndHashCode
@Getter @Setter
public class ExpressionStmt extends Node implements ResourceSpecifier {
protected @NonNull Expression expression;
public ExpressionStmt(Expression expression) {
setExpression(expression);
}
@Override
public ExpressionStmt clone() {
return new ExpressionStmt(getExpression().clone());
}
@Override
public String toCode() {
return getExpression().toCode() + ";";
}
@Override
public <N extends INode> void accept(TreeVisitor visitor, Node parent, Consumer<N> replacer) {
if(visitor.visitExpressionStmt(this, parent, cast(replacer))) {
getExpression().accept(visitor, this, this::setExpression);
}
}
}
| 825 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
Member.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/JavaParser/src/jtree/nodes/Member.java | package jtree.nodes;
public interface Member extends INode {
@Override
Member clone();
}
| 92 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
TypeArgumentHolder.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/JavaParser/src/jtree/nodes/TypeArgumentHolder.java | package jtree.nodes;
import static jtree.util.Utils.*;
import java.util.List;
import lombok.NonNull;
public interface TypeArgumentHolder extends INode {
@Override
TypeArgumentHolder clone();
List<? extends TypeArgument> getTypeArguments();
void setTypeArguments(@NonNull List<? extends TypeArgument> typeArguments);
void setTypeArguments(TypeArgument... typeArguments);
default String typeArgumentString() {
return typeArgumentString(getTypeArguments());
}
default String typeArgumentString(List<? extends TypeArgument> typeArguments) {
if(typeArguments.isEmpty()) {
return "";
} else {
return "<" + joinNodes(", ", typeArguments) + ">";
}
}
}
| 684 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
VariableDeclarator.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/JavaParser/src/jtree/nodes/VariableDeclarator.java | package jtree.nodes;
import static jtree.util.Utils.*;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.NonNull;
@EqualsAndHashCode
@Getter @Setter
public class VariableDeclarator extends Node implements Dimensioned {
protected @NonNull List<Dimension> dimensions;
protected @NonNull Name name;
private @NonNull Optional<? extends Initializer> initializer;
public VariableDeclarator(Name name) {
this(name, emptyList());
}
public VariableDeclarator(Name name, List<Dimension> dimensions) {
this(name, dimensions, Optional.empty());
}
public VariableDeclarator(Name name, Dimension... dimensions) {
this(name, List.of(dimensions));
}
public VariableDeclarator(Name name, Optional<? extends Initializer> initializer) {
this(name, emptyList(), initializer);
}
public VariableDeclarator(Name name, Initializer initializer) {
this(name, Optional.ofNullable(initializer));
}
public VariableDeclarator(Name name, List<Dimension> dimensions, Initializer initializer) {
this(name, dimensions, Optional.ofNullable(initializer));
}
public VariableDeclarator(Name name, List<Dimension> dimensions, Optional<? extends Initializer> initializer) {
setName(name);
setDimensions(dimensions);
setInitializer(initializer);
}
@Override
public VariableDeclarator clone() {
return new VariableDeclarator(getName(), clone(getDimensions()), clone(getInitializer()));
}
@Override
public String toCode() {
var dimensionStr = dimensionString();
return getName() + (dimensionStr.startsWith("@")? " " : "") + dimensionStr
+ initializer.map(initializer -> " = " + initializer.toCode()).orElse("");
}
@Override
public void setDimensions(@NonNull List<Dimension> dimensions) {
this.dimensions = newList(dimensions);
}
@Override
public final void setDimensions(Dimension... dimensions) {
setDimensions(List.of(dimensions));
}
public void setInitializer(@NonNull Optional<? extends Initializer> initializer) {
this.initializer = initializer;
}
public final void setInitializer(Initializer initializer) {
setInitializer(Optional.ofNullable(initializer));
}
public final void setInitializer() {
setInitializer(Optional.empty());
}
@Override
public <N extends INode> void accept(TreeVisitor visitor, Node parent, Consumer<N> replacer) {
if(visitor.visitVariableDeclarator(this, parent, cast(replacer))) {
getName().accept(visitor, this, this::setName);
visitList(visitor, getDimensions());
getInitializer().ifPresent(init -> init.<Initializer>accept(visitor, this, this::setInitializer));
}
}
}
| 2,696 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
ThrowStmt.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/JavaParser/src/jtree/nodes/ThrowStmt.java | package jtree.nodes;
import java.util.function.Consumer;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.NonNull;
@EqualsAndHashCode
@Getter @Setter
public class ThrowStmt extends Node implements Statement {
protected @NonNull Expression expression;
public ThrowStmt(Expression expression) {
setExpression(expression);
}
@Override
public ThrowStmt clone() {
return new ThrowStmt(getExpression().clone());
}
@Override
public String toCode() {
return "throw " + expression.toCode() + ";";
}
@Override
public <N extends INode> void accept(TreeVisitor visitor, Node parent, Consumer<N> replacer) {
if(visitor.visitThrowStmt(this, parent, cast(replacer))) {
getExpression().accept(visitor, this, this::setExpression);
}
}
}
| 799 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
FormalParameter.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/JavaParser/src/jtree/nodes/FormalParameter.java | package jtree.nodes;
import static jtree.util.Utils.*;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.NonNull;
@EqualsAndHashCode
@Getter @Setter
public class FormalParameter extends Declaration implements LambdaParameter, Dimensioned {
protected @NonNull Name name;
protected @NonNull Type type;
private @NonNull List<Dimension> dimensions;
private boolean variadic;
public FormalParameter(Type type, Name name) {
this(type, name, false);
}
public FormalParameter(Type type, Name name, boolean variadic) {
this(type, name, variadic, emptyList());
}
public FormalParameter(Type type, Name name, List<Modifier> modifiers, List<Annotation> annotations) {
this(type, name, emptyList(), modifiers, annotations);
}
public FormalParameter(Type type, Name name, List<Dimension> dimensions) {
this(type, name, false, dimensions);
}
public FormalParameter(Type type, Name name, boolean variadic, List<Dimension> dimensions) {
this(type, name, variadic, dimensions, emptyList(), emptyList());
}
public FormalParameter(Type type, Name name, List<Dimension> dimensions, List<Modifier> modifiers, List<Annotation> annotations) {
this(type, name, false, dimensions, modifiers, annotations);
}
public FormalParameter(Type type, Name name, boolean variadic, List<Dimension> dimensions, List<Modifier> modifiers, List<Annotation> annotations) {
super(modifiers, annotations, Optional.empty());
setType(type);
setName(name);
setDimensions(dimensions);
setVariadic(variadic);
}
@Override
public FormalParameter clone() {
return new FormalParameter(getType().clone(), getName(), isVariadic(), clone(getDimensions()), clone(getModifiers()), clone(getAnnotations()));
}
@Override
public String toCode() {
var dimensionString = dimensionString();
if(dimensionString.startsWith("@")) {
dimensionString = " " + dimensionString;
}
return annotationString(false) + modifierString() + getType().toCode()
+ (isVariadic()? "... " : " ")
+ getName() + dimensionString;
}
@Override
public void setDimensions(@NonNull List<Dimension> dimensions) {
this.dimensions = newList(dimensions);
}
@Override
public final void setDimensions(Dimension... dimensions) {
setDimensions(List.of(dimensions));
}
@Override
public void setDocComment(@NonNull Optional<String> docComment) {
if(!docComment.isEmpty()) {
throw new IllegalArgumentException("Formal parameters cannot have doc comments");
}
}
@Override
public Optional<String> getDocComment() {
return Optional.empty();
}
@Override
public <N extends INode> void accept(TreeVisitor visitor, Node parent, Consumer<N> replacer) {
if(visitor.visitFormalParameter(this, parent, cast(replacer))) {
getType().accept(visitor, this, this::setType);
getName().accept(visitor, this, this::setName);
visitList(visitor, getDimensions());
visitList(visitor, getModifiers());
visitList(visitor, getAnnotations());
}
}
}
| 3,092 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
MemberAccess.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/JavaParser/src/jtree/nodes/MemberAccess.java | package jtree.nodes;
import java.util.function.Consumer;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.NonNull;
@EqualsAndHashCode
@Getter @Setter
public class MemberAccess extends Node implements Expression {
protected @NonNull Name name;
protected @NonNull Expression expression;
public MemberAccess(Expression expression, Name name) {
setExpression(expression);
setName(name);
}
@Override
public Precedence precedence() {
return Precedence.PRIMARY;
}
@Override
public MemberAccess clone() {
return new MemberAccess(getExpression().clone(), getName());
}
@Override
public String toCode() {
return wrap(getExpression()).toCode() + "." + getName();
}
@Override
public <N extends INode> void accept(TreeVisitor visitor, Node parent, Consumer<N> replacer) {
if(visitor.visitMemberAccess(this, parent, cast(replacer))) {
getExpression().accept(visitor, this, this::setExpression);
getName().accept(visitor, this, this::setName);
}
}
}
| 1,027 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
GenericDecl.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/JavaParser/src/jtree/nodes/GenericDecl.java | package jtree.nodes;
import static jtree.util.Utils.*;
import java.util.List;
import java.util.Optional;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
@EqualsAndHashCode
@Getter @Setter
public abstract class GenericDecl extends Declaration implements Member, TypeParameterHolder, Documented {
protected @NonNull List<TypeParameter> typeParameters;
protected @NonNull Name name;
public GenericDecl(Name name, List<TypeParameter> typeParameters, List<Modifier> modifiers, List<Annotation> annotations, Optional<String> docComment) {
super(modifiers, annotations, docComment);
setName(name);
setTypeParameters(typeParameters);
}
@Override
public abstract GenericDecl clone();
@Override
public void setTypeParameters(@NonNull List<TypeParameter> typeParameters) {
this.typeParameters = newList(typeParameters);
}
@Override
public final void setTypeParameters(TypeParameter... typeParameters) {
setTypeParameters(List.of(typeParameters));
}
}
| 1,028 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
ForStmt.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/JavaParser/src/jtree/nodes/ForStmt.java | package jtree.nodes;
import static jtree.util.Utils.*;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
import jtree.util.Either;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.NonNull;
@EqualsAndHashCode
@Getter @Setter
public class ForStmt extends Node implements CompoundStmt {
protected @NonNull Optional<Either<VariableDecl,ExpressionStmt>> initializer;
protected @NonNull Optional<? extends Expression> condition;
private @NonNull List<? extends Expression> updates;
private @NonNull Statement body;
public ForStmt(VariableDecl initializer, Optional<? extends Expression> condition,
List<? extends Expression> updates, Statement body) {
this(Either.first(initializer), condition, updates, body);
}
public ForStmt(ExpressionStmt initializer, Optional<? extends Expression> condition,
List<? extends Expression> updates, Statement body) {
this(Either.second(initializer), condition, updates, body);
}
public ForStmt(Either<VariableDecl,ExpressionStmt> initializer, Optional<? extends Expression> condition,
List<? extends Expression> updates, Statement body) {
this(Optional.ofNullable(initializer), condition, updates, body);
}
public ForStmt(VariableDecl initializer, Expression condition,
List<? extends Expression> updates, Statement body) {
this(Either.first(initializer), condition, updates, body);
}
public ForStmt(ExpressionStmt initializer, Expression condition,
List<? extends Expression> updates, Statement body) {
this(Either.second(initializer), condition, updates, body);
}
public ForStmt(Either<VariableDecl,ExpressionStmt> initializer, Expression condition,
List<? extends Expression> updates, Statement body) {
this(Optional.ofNullable(initializer), condition, updates, body);
}
public ForStmt(Optional<Either<VariableDecl,ExpressionStmt>> initializer, Expression condition,
List<? extends Expression> updates, Statement body) {
this(initializer, Optional.ofNullable(condition), updates, body);
}
public ForStmt(Optional<Either<VariableDecl,ExpressionStmt>> initializer, Optional<? extends Expression> condition,
List<? extends Expression> updates, Statement body) {
setInitializer(initializer);
setCondition(condition);
setUpdates(updates);
setBody(body);
}
@Override
public ForStmt clone() {
return new ForStmt(clone(getInitializer()), clone(getCondition()), clone(getUpdates()), getBody().clone());
}
@Override
public String toCode() {
var updates = getUpdates();
return "for(" + getInitializer().map(either -> ((Node)either.getValue()).toCode()).orElse(";")
+ getCondition().map(condition -> " " + condition.toCode()).orElse("") + ";"
+ (updates.isEmpty()? "" : " " + joinNodes(", ", updates))
+ ")" + bodyString(getBody());
}
public void setUpdates(@NonNull List<? extends Expression> updates) {
this.updates = newList(updates);
}
public final void setUpdates(Expression... updates) {
setUpdates(List.of(updates));
}
public void setInitializer(@NonNull Optional<Either<VariableDecl,ExpressionStmt>> initializer) {
initializer.ifPresent(either -> Objects.requireNonNull(either.getValue()));
this.initializer = initializer;
}
public final void setInitializer(Either<VariableDecl,ExpressionStmt> initializer) {
setInitializer(Optional.ofNullable(initializer));
}
public final void setInitializer(VariableDecl initializer) {
setInitializer(Either.first(initializer));
}
public final void setInitializer(ExpressionStmt initializer) {
setInitializer(Either.second(initializer));
}
public final void setInitializer() {
setInitializer(Optional.empty());
}
public void setCondition(@NonNull Optional<? extends Expression> condition) {
this.condition = condition;
}
public final void setCondition(Expression condition) {
setCondition(Optional.ofNullable(condition));
}
public final void setCondition() {
setCondition(Optional.empty());
}
@Override
public <N extends INode> void accept(TreeVisitor visitor, Node parent, Consumer<N> replacer) {
if(visitor.visitForStmt(this, parent, cast(replacer))) {
getInitializer().ifPresent(either -> either.accept(vardecl -> vardecl.<VariableDecl>accept(visitor, this, this::setInitializer), exprstmt -> exprstmt.<ExpressionStmt>accept(visitor, this, this::setInitializer)));
getCondition().ifPresent(condition -> condition.<Expression>accept(visitor, this, this::setCondition));
visitList(visitor, getUpdates());
getBody().accept(visitor, this, this::setBody);
}
}
}
| 4,687 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
WildcardTypeArgument.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/JavaParser/src/jtree/nodes/WildcardTypeArgument.java | package jtree.nodes;
import static jtree.util.Utils.*;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.NonNull;
@EqualsAndHashCode
@Getter @Setter
public class WildcardTypeArgument extends TypeArgument {
protected @NonNull Optional<WildcardTypeArgument.Bound> bound;
public WildcardTypeArgument() {
this(Optional.empty());
}
public WildcardTypeArgument(Optional<WildcardTypeArgument.Bound> bound) {
this(bound, emptyList());
}
public WildcardTypeArgument(List<Annotation> annotations) {
this(Optional.empty(), annotations);
}
public WildcardTypeArgument(Optional<WildcardTypeArgument.Bound> bound, List<Annotation> annotations) {
super(annotations);
setBound(bound);
}
@Override
public WildcardTypeArgument clone() {
return new WildcardTypeArgument(clone(getBound()), clone(getAnnotations()));
}
@Override
public String toCode() {
return getBound().map(bound -> "? " + bound.toCode()).orElse("?");
}
public void setBound(@NonNull Optional<WildcardTypeArgument.Bound> bound) {
this.bound = bound;
}
public final void setBound(WildcardTypeArgument.Bound bound) {
setBound(Optional.ofNullable(bound));
}
public final void setBound() {
setBound(Optional.empty());
}
@Override
public <N extends INode> void accept(TreeVisitor visitor, Node parent, Consumer<N> replacer) {
if(visitor.visitWildcardTypeArgument(this, parent, cast(replacer))) {
getBound().ifPresent(bound -> bound.<WildcardTypeArgument.Bound>accept(visitor, this, this::setBound));
visitList(visitor, getAnnotations());
}
}
@EqualsAndHashCode
@Getter @Setter
public static class Bound extends Node {
protected @NonNull Bound.Kind kind;
protected @NonNull ReferenceType type;
public Bound(Bound.Kind kind, ReferenceType type) {
setKind(kind);
setType(type);
}
@Override
public Bound clone() {
return new Bound(getKind(), getType().clone());
}
@Override
public String toCode() {
return getKind() + " " + getType().toCode();
}
public static enum Kind {
SUPER, EXTENDS;
@Override
public String toString() {
return name().toLowerCase();
}
}
@Override
public <N extends INode> void accept(TreeVisitor visitor, Node parent, Consumer<N> replacer) {
if(visitor.visitWildcardTypeArgumentBound(this, parent, cast(replacer))) {
getType().accept(visitor, this, this::setType);
}
}
}
}
| 2,537 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
PackageDecl.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/JavaParser/src/jtree/nodes/PackageDecl.java | package jtree.nodes;
import static jtree.util.Utils.*;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.NonNull;
@EqualsAndHashCode
@Getter @Setter
public class PackageDecl extends Node implements Annotated, Documented, REPLEntry {
protected @NonNull List<Annotation> annotations;
protected @NonNull QualifiedName name;
protected @NonNull Optional<String> docComment;
public PackageDecl(QualifiedName name) {
this(name, emptyList(), Optional.empty());
}
public PackageDecl(QualifiedName name, List<Annotation> annotations, Optional<String> docComment) {
setName(name);
setAnnotations(annotations);
setDocComment(docComment);
}
@Override
public PackageDecl clone() {
return new PackageDecl(getName(), clone(getAnnotations()), getDocComment());
}
@Override
public String toCode() {
return docString() + annotationString() + "package " + getName() + ";";
}
@Override
public void setAnnotations(@NonNull List<Annotation> annotations) {
this.annotations = newList(annotations);
}
@Override
public final void setAnnotations(Annotation... annotations) {
setAnnotations(List.of(annotations));
}
@Override
public void setDocComment(@NonNull Optional<String> docComment) {
this.docComment = docComment;
}
@Override
public final void setDocComment(String docComment) {
setDocComment(Optional.ofNullable(docComment));
}
@Override
public final void setDocComment() {
setDocComment(Optional.empty());
}
@Override
public <N extends INode> void accept(TreeVisitor visitor, Node parent, Consumer<N> replacer) {
if(visitor.visitPackageDecl(this, parent, cast(replacer))) {
getName().accept(visitor, this, this::setName);
visitList(visitor, getAnnotations());
}
}
}
| 1,863 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
TypeParameter.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/JavaParser/src/jtree/nodes/TypeParameter.java | package jtree.nodes;
import static jtree.util.Utils.*;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.NonNull;
@EqualsAndHashCode
@Getter @Setter
public class TypeParameter extends Node implements Annotated {
protected @NonNull Name name;
protected @NonNull Optional<? extends ReferenceType> bound;
private @NonNull List<Annotation> annotations;
public TypeParameter(Name name) {
this(name, Optional.empty());
}
public TypeParameter(Name name, Optional<? extends ReferenceType> bound) {
this(name, bound, emptyList());
}
public TypeParameter(Name name, ReferenceType bound) {
this(name, Optional.ofNullable(bound));
}
public TypeParameter(Name name, ReferenceType bound, List<Annotation> annotations) {
this(name, Optional.ofNullable(bound), annotations);
}
public TypeParameter(Name name, Optional<? extends ReferenceType> bound, List<Annotation> annotations) {
setName(name);
setBound(bound);
setAnnotations(annotations);
}
@Override
public TypeParameter clone() {
return new TypeParameter(getName(), clone(getBound()), clone(getAnnotations()));
}
@Override
public String toCode() {
return annotationString(false) + getName()
+ bound.map(bound -> " extends " + bound.toCode()).orElse("");
}
@Override
public void setAnnotations(@NonNull List<Annotation> annotations) {
this.annotations = newList(annotations);
}
@Override
public final void setAnnotations(Annotation... annotations) {
setAnnotations(List.of(annotations));
}
public void setBound(@NonNull Optional<? extends ReferenceType> bound) {
this.bound = bound;
}
public final void setBound(ReferenceType bound) {
setBound(Optional.ofNullable(bound));
}
public final void setBound() {
setBound(Optional.empty());
}
@Override
public <N extends INode> void accept(TreeVisitor visitor, Node parent, Consumer<N> replacer) {
if(visitor.visitTypeParameter(this, parent, cast(replacer))) {
getName().accept(visitor, this, this::setName);
getBound().ifPresent(bound -> bound.<ReferenceType>accept(visitor, this, this::setBound));
visitList(visitor, getAnnotations());
}
}
}
| 2,261 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
InformalParameter.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/JavaParser/src/jtree/nodes/InformalParameter.java | package jtree.nodes;
import java.util.function.Consumer;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.NonNull;
@EqualsAndHashCode
@Getter @Setter
public class InformalParameter extends Node implements LambdaParameter {
protected @NonNull Name name;
public InformalParameter(Name name) {
setName(name);
}
@Override
public InformalParameter clone() {
return new InformalParameter(getName());
}
@Override
public String toCode() {
return getName().toCode();
}
@Override
public <N extends INode> void accept(TreeVisitor visitor, Node parent, Consumer<N> replacer) {
if(visitor.visitInformalParameter(this, parent, cast(replacer))) {
getName().accept(visitor, this, this::setName);
}
}
}
| 764 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
CastExpr.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/JavaParser/src/jtree/nodes/CastExpr.java | package jtree.nodes;
import java.util.function.Consumer;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.NonNull;
@EqualsAndHashCode
@Getter @Setter
public class CastExpr extends Node implements Expression {
protected @NonNull Type type;
protected @NonNull Expression expression;
public CastExpr(Type type, Expression expression) {
setType(type);
setExpression(expression);
}
@Override
public Precedence precedence() {
return Precedence.UNARY_AND_CAST;
}
@Override
public CastExpr clone() {
return new CastExpr(getType().clone(), getExpression().clone());
}
@Override
public String toCode() {
return "(" + getType().toCode() + ")" + wrap(getExpression()).toCode();
}
@Override
public Expression wrap(Expression expr) {
if(expr instanceof Lambda) {
var lambda = (Lambda)expr;
if(lambda.getParameters().isSecond() && lambda.getParameters().second().size() == 1 || lambda.getBody().isSecond()) {
return new ParensExpr(lambda);
} else {
return expr;
}
} else if(expr instanceof Switch || expr.precedence().isGreaterThan(this.precedence())) {
return new ParensExpr(expr);
} else {
return expr;
}
}
@Override
public <N extends INode> void accept(TreeVisitor visitor, Node parent, Consumer<N> replacer) {
if(visitor.visitCastExpr(this, parent, cast(replacer))) {
getType().accept(visitor, this, this::setType);
getExpression().accept(visitor, this, this::setExpression);
}
}
}
| 1,502 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
ContinueStmt.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/JavaParser/src/jtree/nodes/ContinueStmt.java | package jtree.nodes;
import java.util.Optional;
import java.util.function.Consumer;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.NonNull;
@EqualsAndHashCode
@Getter @Setter
public class ContinueStmt extends Node implements Statement {
protected @NonNull Optional<Name> label;
public ContinueStmt() {
this(Optional.empty());
}
public ContinueStmt(Name label) {
this(Optional.ofNullable(label));
}
public ContinueStmt(Optional<Name> label) {
setLabel(label);
}
@Override
public ContinueStmt clone() {
return new ContinueStmt(clone(getLabel()));
}
@Override
public String toCode() {
return "continue" + getLabel().map(label -> " " + label.toCode()).orElse("") + ";";
}
public void setLabel(@NonNull Optional<Name> label) {
this.label = label;
}
public final void setLabel(Name label) {
setLabel(Optional.of(label));
}
public final void setLabel() {
setLabel(Optional.empty());
}
@Override
public <N extends INode> void accept(TreeVisitor visitor, Node parent, Consumer<N> replacer) {
if(visitor.visitContinueStmt(this, parent, cast(replacer))) {
getLabel().ifPresent(label -> label.<Name>accept(visitor, this, this::setLabel));
}
}
}
| 1,244 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
Dimension.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/JavaParser/src/jtree/nodes/Dimension.java | package jtree.nodes;
import static jtree.util.Utils.*;
import java.util.List;
import java.util.function.Consumer;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.NonNull;
@EqualsAndHashCode
@Getter @Setter
public class Dimension extends Node implements Annotated {
protected @NonNull List<Annotation> annotations;
public Dimension() {
this.annotations = newList();
}
public Dimension(Annotation... annotations) {
this(List.of(annotations));
}
public Dimension(List<Annotation> annotations) {
setAnnotations(annotations);
}
@Override
public Dimension clone() {
return new Dimension(clone(getAnnotations()));
}
@Override
public String toCode() {
return annotationString(false) + "[]";
}
@Override
public void setAnnotations(@NonNull List<Annotation> annotations) {
this.annotations = newList(annotations);
}
@Override
public final void setAnnotations(Annotation... annotations) {
setAnnotations(List.of(annotations));
}
@Override
public <N extends INode> void accept(TreeVisitor visitor, Node parent, Consumer<N> replacer) {
if(visitor.visitDimension(this, parent, cast(replacer))) {
visitList(visitor, getAnnotations());
}
}
}
| 1,232 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
Block.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/JavaParser/src/jtree/nodes/Block.java | package jtree.nodes;
import static jtree.util.Utils.*;
import java.util.List;
import java.util.function.Consumer;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.NonNull;
@EqualsAndHashCode
@Getter @Setter
public class Block extends Node implements Statement {
protected @NonNull List<Statement> statements;
public Block(List<Statement> statements) {
setStatements(statements);
}
public Block() {
this(emptyList());
}
public Block(Statement... statements) {
this(List.of(statements));
}
@Override
public Block clone() {
return new Block(clone(getStatements()));
}
@Override
public String toCode() {
return "{\n" + join("", getStatements(), statement -> statement.toCode().indent(4)) + "}";
}
public void setStatements(@NonNull List<? extends Statement> statements) {
this.statements = newList(statements);
}
public final void setStatements(Statement... statements) {
setStatements(List.of(statements));
}
public boolean isEmpty() {
return getStatements().isEmpty();
}
@Override
public <N extends INode> void accept(TreeVisitor visitor, Node parent, Consumer<N> replacer) {
if(visitor.visitBlock(this, parent, cast(replacer))) {
visitList(visitor, getStatements());
}
}
}
| 1,282 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
TypeDecl.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/JavaParser/src/jtree/nodes/TypeDecl.java | package jtree.nodes;
import static jtree.util.Utils.*;
import java.util.List;
import java.util.Optional;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
@EqualsAndHashCode
@Getter @Setter
public abstract class TypeDecl extends GenericDecl implements REPLEntry {
protected @NonNull List<? extends Member> members;
public TypeDecl(Name name, List<TypeParameter> typeParameters, List<? extends Member> members, List<Modifier> modifiers, List<Annotation> annotations, Optional<String> docComment) {
super(name, typeParameters, modifiers, annotations, docComment);
setMembers(members);
}
@Override
public abstract TypeDecl clone();
public String bodyString() {
var members = getMembers();
return members.isEmpty()? "{}" : "{\n" + join("", getMembers(), member -> member.toCode().indent(4)) + "}";
}
public void setMembers(@NonNull List<? extends Member> members) {
this.members = newList(members);
}
public final void setMembers(Member... members) {
setMembers(List.of(members));
}
@Override
public void setName(Name name) {
if(name.equals("var")) {
throw new IllegalArgumentException("\"var\" cannot be used as a type name");
}
super.setName(name);
}
}
| 1,252 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
Precedence.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/JavaParser/src/jtree/nodes/Precedence.java | package jtree.nodes;
public enum Precedence {
PRIMARY,
POST_UNARY,
UNARY_AND_CAST,
MULTIPLICATIVE,
ADDITIVE,
BIT_SHIFT,
RELATIONAL,
EQUALITY,
BIT_AND,
BIT_XOR,
BIT_OR,
LOGIC_AND,
LOGIC_OR,
TERNARY,
ASSIGNMENT;
public boolean isLessThan(Precedence other) {
return compareTo(other) < 0;
}
public boolean isGreaterThan(Precedence other) {
return compareTo(other) > 0;
}
public boolean isLessThanOrEqualTo(Precedence other) {
return compareTo(other) <= 0;
}
public boolean isGreaterThanOrEqualTo(Precedence other) {
return compareTo(other) >= 0;
}
}
| 586 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |
ClassLiteral.java | /FileExtraction/Java_unseen/raptor494_JavaPlusPlus/JavaParser/src/jtree/nodes/ClassLiteral.java | package jtree.nodes;
import java.util.function.Consumer;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.NonNull;
@EqualsAndHashCode
@Getter @Setter
public class ClassLiteral extends Node implements Expression {
protected @NonNull Type type;
public ClassLiteral(Type type) {
setType(type);
}
@Override
public Precedence precedence() {
return Precedence.PRIMARY;
}
@Override
public ClassLiteral clone() {
return new ClassLiteral(getType().clone());
}
@Override
public String toCode() {
return getType().toCode() + ".class";
}
@Override
public <N extends INode> void accept(TreeVisitor visitor, Node parent, Consumer<N> replacer) {
if(visitor.visitClassLiteral(this, parent, cast(replacer))) {
getType().accept(visitor, this, this::setType);
}
}
}
| 833 | Java | .java | raptor494/JavaPlusPlus | 10 | 0 | 0 | 2019-07-12T21:47:58Z | 2019-08-13T18:38:44Z |