file_id
int64
1
46.7k
content
stringlengths
14
344k
repo
stringlengths
7
109
path
stringlengths
8
171
45,915
package aQute.tester.junit.platform.test; import static aQute.junit.constants.TesterConstants.TESTER_CONTINUOUS; import static aQute.junit.constants.TesterConstants.TESTER_CONTROLPORT; import static aQute.junit.constants.TesterConstants.TESTER_PORT; import static aQute.junit.constants.TesterConstants.TESTER_UNRESOLVED; import static aQute.tester.test.utils.TestRunData.nameOf; import static org.eclipse.jdt.internal.junit.model.ITestRunListener2.STATUS_FAILURE; import java.io.DataOutputStream; import java.io.File; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.assertj.core.api.Assertions; import org.junit.AssumptionViolatedException; import org.junit.ComparisonFailure; import org.junit.jupiter.api.Test; import org.junit.platform.commons.JUnitException; import org.opentest4j.AssertionFailedError; import org.opentest4j.MultipleFailuresError; import org.opentest4j.TestAbortedException; import org.osgi.framework.Bundle; import org.w3c.dom.Document; import org.xmlunit.assertj.XmlAssert; import aQute.launchpad.LaunchpadBuilder; import aQute.lib.io.IO; import aQute.tester.test.assertions.CustomAssertionError; import aQute.tester.test.utils.ServiceLoaderMask; import aQute.tester.test.utils.TestEntry; import aQute.tester.test.utils.TestFailure; import aQute.tester.test.utils.TestRunData; import aQute.tester.test.utils.TestRunListener; import aQute.tester.testbase.AbstractActivatorTest; import aQute.tester.testclasses.JUnit3Test; import aQute.tester.testclasses.JUnit4Test; import aQute.tester.testclasses.With1Error1Failure; import aQute.tester.testclasses.With2Failures; import aQute.tester.testclasses.junit.platform.JUnit3ComparisonTest; import aQute.tester.testclasses.junit.platform.JUnit4AbortTest; import aQute.tester.testclasses.junit.platform.JUnit4ComparisonTest; import aQute.tester.testclasses.junit.platform.JUnit4Skipper; import aQute.tester.testclasses.junit.platform.JUnit5AbortTest; import aQute.tester.testclasses.junit.platform.JUnit5ContainerSkipped; import aQute.tester.testclasses.junit.platform.JUnit5ContainerSkippedWithCustomDisplayName; import aQute.tester.testclasses.junit.platform.JUnit5DisplayNameTest; import aQute.tester.testclasses.junit.platform.JUnit5ParameterizedTest; import aQute.tester.testclasses.junit.platform.JUnit5SimpleComparisonTest; import aQute.tester.testclasses.junit.platform.JUnit5Skipper; import aQute.tester.testclasses.junit.platform.JUnit5Test; import aQute.tester.testclasses.junit.platform.JUnitMixedComparisonTest; import aQute.tester.testclasses.junit.platform.Mixed35Test; import aQute.tester.testclasses.junit.platform.Mixed45Test; public class ActivatorTest extends AbstractActivatorTest { public ActivatorTest() { super("aQute.tester.junit.platform.Activator", "biz.aQute.tester.junit-platform"); } // We have the Jupiter engine on the classpath so that the tests will run. // This classloader will hide it from the framework-under-test. static final ClassLoader SERVICELOADER_MASK = new ServiceLoaderMask(); @Override protected void createLP() { builder.usingClassLoader(SERVICELOADER_MASK); super.createLP(); } @Test public void multipleMixedTests_areAllRun_withJupiterTest() { final ExitCode exitCode = runTests(JUnit3Test.class, JUnit4Test.class, JUnit5Test.class); assertThat(exitCode.exitCode).as("exit code") .isZero(); assertThat(testBundler.getCurrentThread(JUnit3Test.class)).as("junit3") .isSameAs(Thread.currentThread()); assertThat(testBundler.getCurrentThread(JUnit4Test.class)).as("junit4") .isSameAs(Thread.currentThread()); assertThat(testBundler.getCurrentThread(JUnit5Test.class)).as("junit5") .isSameAs(Thread.currentThread()); } @SuppressWarnings("unchecked") @Test public void multipleMixedTests_inASingleTestCase_areAllRun() { final ExitCode exitCode = runTests(Mixed35Test.class, Mixed45Test.class); assertThat(exitCode.exitCode).as("exit code") .isZero(); assertThat(testBundler.getStatic(Mixed35Test.class, Set.class, "methods")).as("Mixed JUnit 3 & 5") .containsExactlyInAnyOrder("testJUnit3", "junit5Test"); assertThat(testBundler.getStatic(Mixed45Test.class, Set.class, "methods")).as("Mixed JUnit 4 & 5") .containsExactlyInAnyOrder("junit4Test", "junit5Test"); } @Test public void eclipseListener_reportsResults_acrossMultipleBundles() throws InterruptedException { Class<?>[][] tests = { { With2Failures.class, JUnit4Test.class }, { With1Error1Failure.class, JUnit5Test.class } }; TestRunData result = runTestsEclipse(tests); assertThat(result.getTestCount()).as("testCount") .isEqualTo(9); // @formatter:off assertThat(result.getNameMap() .keySet()).as("executed") .contains( nameOf(With2Failures.class), nameOf(With2Failures.class, "test1"), nameOf(With2Failures.class, "test2"), nameOf(With2Failures.class, "test3"), nameOf(JUnit4Test.class), nameOf(JUnit4Test.class, "somethingElse"), nameOf(With1Error1Failure.class), nameOf(With1Error1Failure.class, "test1"), nameOf(With1Error1Failure.class, "test2"), nameOf(With1Error1Failure.class, "test3"), nameOf(JUnit5Test.class, "somethingElseAgain"), nameOf(testBundles.get(0)), nameOf(testBundles.get(1)) ); assertThat(result).as("result") .hasFailedTest(With2Failures.class, "test1", AssertionError.class) .hasSuccessfulTest(With2Failures.class, "test2") .hasFailedTest(With2Failures.class, "test3", CustomAssertionError.class) .hasSuccessfulTest(JUnit4Test.class, "somethingElse") .hasErroredTest(With1Error1Failure.class, "test1", RuntimeException.class) .hasSuccessfulTest(With1Error1Failure.class, "test2") .hasFailedTest(With1Error1Failure.class, "test3", AssertionError.class) .hasSuccessfulTest(JUnit5Test.class, "somethingElseAgain") ; // @formatter:on } private void readWithTimeout(InputStream inStr) throws Exception { long endTime = System.currentTimeMillis() + 10000; int available; while ((available = inStr.available()) == 0 && System.currentTimeMillis() < endTime) { Thread.sleep(10); } if (available == 0) { Assertions.fail("Timeout waiting for data"); } assertThat(available).as("control signal") .isEqualTo(1); int value = inStr.read(); assertThat(value).as("control value") .isNotEqualTo(-1); } @Test public void eclipseListener_worksInContinuousMode_withControlSocket() throws Exception { try (ServerSocket controlSock = new ServerSocket(0)) { controlSock.setSoTimeout(10000); int controlPort = controlSock.getLocalPort(); builder.set("launch.services", "true") .set(TESTER_CONTINUOUS, "true") // This value should be ignored .set(TESTER_PORT, Integer.toString(controlPort - 2)) .set(TESTER_CONTROLPORT, Integer.toString(controlPort)); createLP(); addTestBundle(With2Failures.class, JUnit4Test.class); runTester(); try (Socket sock = controlSock.accept()) { InputStream inStr = sock.getInputStream(); DataOutputStream outStr = new DataOutputStream(sock.getOutputStream()); readWithTimeout(inStr); TestRunListener listener = startEclipseJUnitListener(); outStr.writeInt(eclipseJUnitPort); outStr.flush(); listener.waitForClientToFinish(10000); TestRunData result = listener.getLatestRunData(); if (result == null) { fail("Result was null" + listener); // To prevent NPE and allow any soft assertions to be // displayed. return; } assertThat(result.getTestCount()).as("testCount") .isEqualTo(5); // @formatter:off assertThat(result.getNameMap() .keySet()).as("executed") .contains( nameOf(With2Failures.class), nameOf(With2Failures.class, "test1"), nameOf(With2Failures.class, "test2"), nameOf(With2Failures.class, "test3"), nameOf(JUnit4Test.class), nameOf(JUnit4Test.class, "somethingElse"), nameOf(testBundles.get(0)) ); assertThat(result).as("result") .hasFailedTest(With2Failures.class, "test1", AssertionError.class) .hasSuccessfulTest(With2Failures.class, "test2") .hasFailedTest(With2Failures.class, "test3", CustomAssertionError.class) .hasSuccessfulTest(JUnit4Test.class, "somethingElse") ; // @formatter:on addTestBundle(With1Error1Failure.class, JUnit5Test.class); readWithTimeout(inStr); listener = startEclipseJUnitListener(); outStr.writeInt(eclipseJUnitPort); outStr.flush(); listener.waitForClientToFinish(10000); result = listener.getLatestRunData(); if (result == null) { fail("Eclipse didn't capture output from the second run"); return; } int i = 2; assertThat(result.getTestCount()).as("testCount:" + i) .isEqualTo(4); // @formatter:off assertThat(result.getNameMap() .keySet()).as("executed:2") .contains( nameOf(With1Error1Failure.class), nameOf(With1Error1Failure.class, "test1"), nameOf(With1Error1Failure.class, "test2"), nameOf(With1Error1Failure.class, "test3"), nameOf(JUnit5Test.class, "somethingElseAgain"), nameOf(testBundles.get(1)) ); assertThat(result).as("result:2") .hasErroredTest(With1Error1Failure.class, "test1", RuntimeException.class) .hasSuccessfulTest(With1Error1Failure.class, "test2") .hasFailedTest(With1Error1Failure.class, "test3", AssertionError.class) .hasSuccessfulTest(JUnit5Test.class, "somethingElseAgain") ; // @formatter:on } } } @Test public void eclipseListener_reportsComparisonFailures() throws InterruptedException { Class<?>[] tests = { JUnit3ComparisonTest.class, JUnit4ComparisonTest.class, JUnit5SimpleComparisonTest.class, JUnit5Test.class, JUnitMixedComparisonTest.class }; TestRunData result = runTestsEclipse(tests); final String[] order = { "1", "2", "3.1", "3.2", "3.4", "4" }; // @formatter:off assertThat(result).as("result") .hasFailedTest(JUnit3ComparisonTest.class, "testComparisonFailure", junit.framework.ComparisonFailure.class, "expected", "actual") .hasFailedTest(JUnit4ComparisonTest.class, "comparisonFailure", ComparisonFailure.class, "expected", "actual") .hasFailedTest(JUnit5SimpleComparisonTest.class, "somethingElseThatFailed", AssertionFailedError.class, "expected", "actual") .hasFailedTest(JUnitMixedComparisonTest.class, "multipleComparisonFailure", MultipleFailuresError.class, Stream.of(order).map(x -> "expected" + x).collect(Collectors.joining("\n\n")), Stream.of(order).map(x -> "actual" + x).collect(Collectors.joining("\n\n")) ) ; // @formatter:on TestFailure f = result.getFailureByName(nameOf(JUnit5SimpleComparisonTest.class, "emptyComparisonFailure")); assertThat(f).as("emptyComparisonFailure") .isNotNull(); if (f != null) { assertThat(f.status).as("emptyComparisonFailure:status") .isEqualTo(STATUS_FAILURE); assertThat(f.expected).as("emptyComparisonFailure:expected") .isNull(); assertThat(f.actual).as("emptyComparisonFailure:actual") .isNull(); } } @Test public void eclipseListener_reportsParameterizedTests() throws InterruptedException { TestRunData result = runTestsEclipse(JUnit5ParameterizedTest.class); TestEntry methodTest = result.getTest(JUnit5ParameterizedTest.class, "parameterizedMethod"); if (methodTest == null) { fail("Couldn't find method test entry for " + nameOf(JUnit5ParameterizedTest.class, "parameterizedMethod")); return; } assertThat(methodTest.parameterTypes).as("parameterTypes") .containsExactly("java.lang.String", "float"); List<TestEntry> parameterTests = result.getChildrenOf(methodTest.testId) .stream() .map(x -> result.getById(x)) .collect(Collectors.toList()); assertThat(parameterTests.stream() .map(x -> x.testName)).as("testNames") .allMatch(x -> x.equals(nameOf(JUnit5ParameterizedTest.class, "parameterizedMethod"))); assertThat(parameterTests.stream()).as("dynamic") .allMatch(x -> x.isDynamicTest); assertThat(parameterTests.stream() .map(x -> x.displayName)).as("displayNames") .containsExactlyInAnyOrder("1 ==> param: 'one', param2: 1.0", "2 ==> param: 'two', param2: 2.0", "3 ==> param: 'three', param2: 3.0", "4 ==> param: 'four', param2: 4.0", "5 ==> param: 'five', param2: 5.0"); Optional<TestEntry> test4 = parameterTests.stream() .filter(x -> x.displayName.startsWith("4 ==>")) .findFirst(); if (!test4.isPresent()) { fail("Couldn't find test result for parameter 4"); } else { assertThat(parameterTests.stream() .filter(x -> result.getFailure(x.testId) != null)).as("failures") .containsExactly(test4.get()); } } @Test public void eclipseListener_reportsMisconfiguredParameterizedTests() throws InterruptedException { TestRunData result = runTestsEclipse(JUnit5ParameterizedTest.class); TestEntry methodTest = result.getTest(JUnit5ParameterizedTest.class, "misconfiguredMethod"); if (methodTest == null) { fail("Couldn't find method test entry for " + nameOf(JUnit5ParameterizedTest.class, "misconfiguredMethod")); return; } TestFailure failure = result.getFailure(methodTest.testId); if (failure == null) { fail("Expecting method:\n%s\nto have failed", methodTest); } else { assertThat(failure.trace).as("trace") .startsWith("org.junit.platform.commons.JUnitException: Could not find factory method [unknownMethod]"); } } @Test public void eclipseListener_reportsCustomNames_withOddCharacters() throws InterruptedException { TestRunData result = runTestsEclipse(JUnit5DisplayNameTest.class); final String[] methodList = { "test1", "testWithNonASCII", "testWithNonLatin" }; final String[] displayList = { // "Test 1", "Prüfung 2", "Δοκιμή 3" "Test 1", "Pr\u00fcfung 2", "\u0394\u03bf\u03ba\u03b9\u03bc\u03ae 3" }; for (int i = 0; i < methodList.length; i++) { final String method = methodList[i]; final String display = displayList[i]; TestEntry methodTest = result.getTest(JUnit5DisplayNameTest.class, method); if (methodTest == null) { fail("Couldn't find method test entry for " + nameOf(JUnit5ParameterizedTest.class, method)); continue; } assertThat(methodTest.displayName).as(String.format("[%d] %s", i, method)) .isEqualTo(display); } } @Test public void eclipseListener_reportsSkippedTests() throws InterruptedException { TestRunData result = runTestsEclipse(JUnit5Skipper.class, JUnit5ContainerSkipped.class, JUnit5ContainerSkippedWithCustomDisplayName.class, JUnit4Skipper.class); assertThat(result).as("result") .hasSkippedTest(JUnit5Skipper.class, "disabledTest", "with custom message") .hasSkippedTest(JUnit5ContainerSkipped.class, "with another message") .hasSkippedTest(JUnit5ContainerSkipped.class, "disabledTest2", "ancestor \"JUnit5ContainerSkipped\" was skipped") .hasSkippedTest(JUnit5ContainerSkipped.class, "disabledTest3", "ancestor \"JUnit5ContainerSkipped\" was skipped") .hasSkippedTest(JUnit5ContainerSkippedWithCustomDisplayName.class, "with a third message") .hasSkippedTest(JUnit5ContainerSkippedWithCustomDisplayName.class, "disabledTest2", "ancestor \"Skipper Class\" was skipped") .hasSkippedTest(JUnit5ContainerSkippedWithCustomDisplayName.class, "disabledTest3", "ancestor \"Skipper Class\" was skipped") .hasSkippedTest(JUnit4Skipper.class, "disabledTest", "This is a test"); } @Test public void eclipseListener_reportsAbortedTests() throws InterruptedException { TestRunData result = runTestsEclipse(JUnit5AbortTest.class, JUnit4AbortTest.class); assertThat(result).as("result") .hasAbortedTest(JUnit5AbortTest.class, "abortedTest", new TestAbortedException("Assumption failed: I just can't go on")) .hasAbortedTest(JUnit4AbortTest.class, "abortedTest", new AssumptionViolatedException("Let's get outta here")); } @Test public void eclipseListener_handlesNoEnginesGracefully() throws Exception { try (LaunchpadBuilder builder = new LaunchpadBuilder()) { IO.close(this.builder); builder.bndrun("no-engines.bndrun") .excludeExport("org.junit*") .excludeExport("junit*"); this.builder = builder; setTmpDir(); TestRunData result = runTestsEclipse(JUnit5AbortTest.class, JUnit4AbortTest.class); assertThat(result).hasErroredTest("Initialization Error", new JUnitException("Couldn't find any registered TestEngines")); } } @Test public void eclipseListener_handlesNoJUnit3Gracefully() throws Exception { builder.excludeExport("junit.framework"); Class<?>[] tests = { JUnit4ComparisonTest.class, JUnit5Test.class, JUnit5SimpleComparisonTest.class }; TestRunData result = runTestsEclipse(tests); assertThat(result).as("result") .hasFailedTest(JUnit5SimpleComparisonTest.class, "somethingElseThatFailed", AssertionFailedError.class, "expected", "actual"); TestFailure f = result.getFailureByName(nameOf(JUnit5SimpleComparisonTest.class, "emptyComparisonFailure")); assertThat(f).as("emptyComparisonFailure") .isNotNull(); if (f != null) { assertThat(f.status).as("emptyComparisonFailure:status") .isEqualTo(STATUS_FAILURE); assertThat(f.expected).as("emptyComparisonFailure:expected") .isNull(); assertThat(f.actual).as("emptyComparisonFailure:actual") .isNull(); } } @Test public void eclipseListener_handlesNoJUnit4Gracefully() throws Exception { try (LaunchpadBuilder builder = new LaunchpadBuilder()) { IO.close(this.builder); builder.debug(); builder.bndrun("no-vintage-engine.bndrun") .excludeExport("aQute.tester.bundle.*") .excludeExport("org.junit*") .excludeExport("junit*"); this.builder = builder; setTmpDir(); Class<?>[] tests = { JUnit3ComparisonTest.class, JUnit5Test.class, JUnit5SimpleComparisonTest.class }; TestRunData result = runTestsEclipse(tests); assertThat(result).as("result") .hasFailedTest(JUnit5SimpleComparisonTest.class, "somethingElseThatFailed", AssertionFailedError.class, "expected", "actual"); TestFailure f = result.getFailureByName(nameOf(JUnit5SimpleComparisonTest.class, "emptyComparisonFailure")); assertThat(f).as("emptyComparisonFailure") .isNotNull(); if (f != null) { assertThat(f.status).as("emptyComparisonFailure:status") .isEqualTo(STATUS_FAILURE); assertThat(f.expected).as("emptyComparisonFailure:expected") .isNull(); assertThat(f.actual).as("emptyComparisonFailure:actual") .isNull(); } } } @Test public void testerUnresolvedTrue_isPassedThroughToBundleEngine() { builder.set(TESTER_UNRESOLVED, "true"); AtomicReference<Bundle> bundleRef = new AtomicReference<>(); TestRunData result = runTestsEclipse(() -> { bundleRef.set(bundle().importPackage("some.unknown.package") .install()); }, JUnit3Test.class, JUnit4Test.class); assertThat(result).hasSuccessfulTest("Unresolved bundles"); } @Test public void testerUnresolvedFalse_isPassedThroughToBundleEngine() { builder.set(TESTER_UNRESOLVED, "false"); AtomicReference<Bundle> bundleRef = new AtomicReference<>(); TestRunData result = runTestsEclipse(() -> { bundleRef.set(bundle().importPackage("some.unknown.package") .install()); }, JUnit3Test.class, JUnit4Test.class); assertThat(result.getNameMap() .get("Unresolved bundles")).isNull(); } @Test public void xmlReporter_generatesCompleteXmlFile() throws Exception { final ExitCode exitCode = runTests(JUnit3Test.class, With1Error1Failure.class, With2Failures.class); final String fileName = "TEST-" + testBundle.getSymbolicName() + "-" + testBundle.getVersion() + ".xml"; File xmlFile = new File(getTmpDir(), fileName); Assertions.assertThat(xmlFile) .as("xmlFile") .exists(); AtomicReference<Document> docContainer = new AtomicReference<>(); Assertions.assertThatCode(() -> { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); docContainer.set(dBuilder.parse(xmlFile)); }) .doesNotThrowAnyException(); Document doc = docContainer.get(); XmlAssert.assertThat(doc) .nodesByXPath("/testsuite") .hasSize(1); XmlAssert.assertThat(doc) .nodesByXPath(testSuite() + "/testcase") .hasSize(7); XmlAssert.assertThat(doc) .nodesByXPath(testCase(JUnit3Test.class, "testSomething")) .hasSize(1); XmlAssert.assertThat(doc) .nodesByXPath(testCaseError(With1Error1Failure.class, "test1", RuntimeException.class)) .hasSize(1); XmlAssert.assertThat(doc) .nodesByXPath(testCase(With1Error1Failure.class, "test2")) .hasSize(1); XmlAssert.assertThat(doc) .nodesByXPath(testCaseFailure(With1Error1Failure.class, "test3", AssertionError.class)) .hasSize(1); XmlAssert.assertThat(doc) .nodesByXPath(testCaseFailure(With2Failures.class, "test1", AssertionError.class)) .hasSize(1); XmlAssert.assertThat(doc) .nodesByXPath(testCase(With2Failures.class, "test2")) .hasSize(1); XmlAssert.assertThat(doc) .nodesByXPath(testCaseFailure(With2Failures.class, "test3", CustomAssertionError.class)) .hasSize(1); } }
jameshilliard/bnd
biz.aQute.tester.test/test/aQute/tester/junit/platform/test/ActivatorTest.java
45,916
package aQute.tester.junit.platform.test; import static aQute.junit.constants.TesterConstants.TESTER_CONTINUOUS; import static aQute.junit.constants.TesterConstants.TESTER_CONTROLPORT; import static aQute.junit.constants.TesterConstants.TESTER_NAMES; import static aQute.junit.constants.TesterConstants.TESTER_PORT; import static aQute.junit.constants.TesterConstants.TESTER_UNRESOLVED; import static aQute.tester.test.utils.TestRunData.nameOf; import static org.eclipse.jdt.internal.junit.model.ITestRunListener2.STATUS_FAILURE; import java.io.DataOutputStream; import java.io.File; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.assertj.core.api.Assertions; import org.junit.AssumptionViolatedException; import org.junit.ComparisonFailure; import org.junit.jupiter.api.Test; import org.junit.platform.commons.JUnitException; import org.opentest4j.AssertionFailedError; import org.opentest4j.MultipleFailuresError; import org.opentest4j.TestAbortedException; import org.osgi.framework.Bundle; import org.w3c.dom.Document; import org.xmlunit.assertj.XmlAssert; import aQute.launchpad.LaunchpadBuilder; import aQute.lib.io.IO; import aQute.tester.test.assertions.CustomAssertionError; import aQute.tester.test.utils.ServiceLoaderMask; import aQute.tester.test.utils.TestEntry; import aQute.tester.test.utils.TestFailure; import aQute.tester.test.utils.TestRunData; import aQute.tester.test.utils.TestRunListener; import aQute.tester.testbase.AbstractActivatorTest; import aQute.tester.testclasses.JUnit3Test; import aQute.tester.testclasses.JUnit4Test; import aQute.tester.testclasses.With1Error1Failure; import aQute.tester.testclasses.With2Failures; import aQute.tester.testclasses.junit.platform.JUnit3ComparisonTest; import aQute.tester.testclasses.junit.platform.JUnit4AbortTest; import aQute.tester.testclasses.junit.platform.JUnit4ComparisonTest; import aQute.tester.testclasses.junit.platform.JUnit4Skipper; import aQute.tester.testclasses.junit.platform.JUnit5AbortTest; import aQute.tester.testclasses.junit.platform.JUnit5ContainerSkipped; import aQute.tester.testclasses.junit.platform.JUnit5ContainerSkippedWithCustomDisplayName; import aQute.tester.testclasses.junit.platform.JUnit5DisplayNameTest; import aQute.tester.testclasses.junit.platform.JUnit5ParameterizedTest; import aQute.tester.testclasses.junit.platform.JUnit5SimpleComparisonTest; import aQute.tester.testclasses.junit.platform.JUnit5Skipper; import aQute.tester.testclasses.junit.platform.JUnit5Test; import aQute.tester.testclasses.junit.platform.JUnitMixedComparisonTest; import aQute.tester.testclasses.junit.platform.Mixed35Test; import aQute.tester.testclasses.junit.platform.Mixed45Test; import aQute.tester.testclasses.junit.platform.ParameterizedTesterNamesTest; public class ActivatorTest extends AbstractActivatorTest { public ActivatorTest() { super("aQute.tester.junit.platform.Activator", "biz.aQute.tester.junit-platform"); } // We have the Jupiter engine on the classpath so that the tests will run. // This classloader will hide it from the framework-under-test. static final ClassLoader SERVICELOADER_MASK = new ServiceLoaderMask(); @Override protected void createLP() { builder.usingClassLoader(SERVICELOADER_MASK); super.createLP(); } @Test public void multipleMixedTests_areAllRun_withJupiterTest() { final ExitCode exitCode = runTests(JUnit3Test.class, JUnit4Test.class, JUnit5Test.class); assertThat(exitCode.exitCode).as("exit code") .isZero(); assertThat(testBundler.getCurrentThread(JUnit3Test.class)).as("junit3") .isSameAs(Thread.currentThread()); assertThat(testBundler.getCurrentThread(JUnit4Test.class)).as("junit4") .isSameAs(Thread.currentThread()); assertThat(testBundler.getCurrentThread(JUnit5Test.class)).as("junit5") .isSameAs(Thread.currentThread()); } @SuppressWarnings("unchecked") @Test public void multipleMixedTests_inASingleTestCase_areAllRun() { final ExitCode exitCode = runTests(Mixed35Test.class, Mixed45Test.class); assertThat(exitCode.exitCode).as("exit code") .isZero(); assertThat(testBundler.getStatic(Mixed35Test.class, Set.class, "methods")).as("Mixed JUnit 3 & 5") .containsExactlyInAnyOrder("testJUnit3", "junit5Test"); assertThat(testBundler.getStatic(Mixed45Test.class, Set.class, "methods")).as("Mixed JUnit 4 & 5") .containsExactlyInAnyOrder("junit4Test", "junit5Test"); } @Test public void eclipseListener_reportsResults_acrossMultipleBundles() throws InterruptedException { Class<?>[][] tests = { { With2Failures.class, JUnit4Test.class }, { With1Error1Failure.class, JUnit5Test.class } }; TestRunData result = runTestsEclipse(tests); assertThat(result.getTestCount()).as("testCount") .isEqualTo(9); // @formatter:off assertThat(result.getNameMap() .keySet()).as("executed") .contains( nameOf(With2Failures.class), nameOf(With2Failures.class, "test1"), nameOf(With2Failures.class, "test2"), nameOf(With2Failures.class, "test3"), nameOf(JUnit4Test.class), nameOf(JUnit4Test.class, "somethingElse"), nameOf(With1Error1Failure.class), nameOf(With1Error1Failure.class, "test1"), nameOf(With1Error1Failure.class, "test2"), nameOf(With1Error1Failure.class, "test3"), nameOf(JUnit5Test.class, "somethingElseAgain"), nameOf(testBundles.get(0)), nameOf(testBundles.get(1)) ); assertThat(result).as("result") .hasFailedTest(With2Failures.class, "test1", AssertionError.class) .hasSuccessfulTest(With2Failures.class, "test2") .hasFailedTest(With2Failures.class, "test3", CustomAssertionError.class) .hasSuccessfulTest(JUnit4Test.class, "somethingElse") .hasErroredTest(With1Error1Failure.class, "test1", RuntimeException.class) .hasSuccessfulTest(With1Error1Failure.class, "test2") .hasFailedTest(With1Error1Failure.class, "test3", AssertionError.class) .hasSuccessfulTest(JUnit5Test.class, "somethingElseAgain") ; // @formatter:on } private void readWithTimeout(InputStream inStr) throws Exception { long endTime = System.currentTimeMillis() + 10000; int available; while ((available = inStr.available()) == 0 && System.currentTimeMillis() < endTime) { Thread.sleep(10); } if (available == 0) { Assertions.fail("Timeout waiting for data"); } assertThat(available).as("control signal") .isEqualTo(1); int value = inStr.read(); assertThat(value).as("control value") .isNotEqualTo(-1); } @Test public void eclipseListener_worksInContinuousMode_withControlSocket() throws Exception { try (ServerSocket controlSock = new ServerSocket(0)) { controlSock.setSoTimeout(10000); int controlPort = controlSock.getLocalPort(); builder.set("launch.services", "true") .set(TESTER_CONTINUOUS, "true") // This value should be ignored .set(TESTER_PORT, Integer.toString(controlPort - 2)) .set(TESTER_CONTROLPORT, Integer.toString(controlPort)); createLP(); addTestBundle(With2Failures.class, JUnit4Test.class); runTester(); try (Socket sock = controlSock.accept()) { InputStream inStr = sock.getInputStream(); DataOutputStream outStr = new DataOutputStream(sock.getOutputStream()); readWithTimeout(inStr); TestRunListener listener = startEclipseJUnitListener(); outStr.writeInt(eclipseJUnitPort); outStr.flush(); listener.waitForClientToFinish(10000); TestRunData result = listener.getLatestRunData(); if (result == null) { fail("Result was null" + listener); // To prevent NPE and allow any soft assertions to be // displayed. return; } assertThat(result.getTestCount()).as("testCount") .isEqualTo(5); // @formatter:off assertThat(result.getNameMap() .keySet()).as("executed") .contains( nameOf(With2Failures.class), nameOf(With2Failures.class, "test1"), nameOf(With2Failures.class, "test2"), nameOf(With2Failures.class, "test3"), nameOf(JUnit4Test.class), nameOf(JUnit4Test.class, "somethingElse"), nameOf(testBundles.get(0)) ); assertThat(result).as("result") .hasFailedTest(With2Failures.class, "test1", AssertionError.class) .hasSuccessfulTest(With2Failures.class, "test2") .hasFailedTest(With2Failures.class, "test3", CustomAssertionError.class) .hasSuccessfulTest(JUnit4Test.class, "somethingElse") ; // @formatter:on addTestBundle(With1Error1Failure.class, JUnit5Test.class); readWithTimeout(inStr); listener = startEclipseJUnitListener(); outStr.writeInt(eclipseJUnitPort); outStr.flush(); listener.waitForClientToFinish(10000); result = listener.getLatestRunData(); if (result == null) { fail("Eclipse didn't capture output from the second run"); return; } int i = 2; assertThat(result.getTestCount()).as("testCount:" + i) .isEqualTo(4); // @formatter:off assertThat(result.getNameMap() .keySet()).as("executed:2") .contains( nameOf(With1Error1Failure.class), nameOf(With1Error1Failure.class, "test1"), nameOf(With1Error1Failure.class, "test2"), nameOf(With1Error1Failure.class, "test3"), nameOf(JUnit5Test.class, "somethingElseAgain"), nameOf(testBundles.get(1)) ); assertThat(result).as("result:2") .hasErroredTest(With1Error1Failure.class, "test1", RuntimeException.class) .hasSuccessfulTest(With1Error1Failure.class, "test2") .hasFailedTest(With1Error1Failure.class, "test3", AssertionError.class) .hasSuccessfulTest(JUnit5Test.class, "somethingElseAgain") ; // @formatter:on } } } @Test public void eclipseListener_reportsComparisonFailures() throws InterruptedException { Class<?>[] tests = { JUnit3ComparisonTest.class, JUnit4ComparisonTest.class, JUnit5SimpleComparisonTest.class, JUnit5Test.class, JUnitMixedComparisonTest.class }; TestRunData result = runTestsEclipse(tests); final String[] order = { "1", "2", "3.1", "3.2", "3.4", "4" }; // @formatter:off assertThat(result).as("result") .hasFailedTest(JUnit3ComparisonTest.class, "testComparisonFailure", junit.framework.ComparisonFailure.class, "expected", "actual") .hasFailedTest(JUnit4ComparisonTest.class, "comparisonFailure", ComparisonFailure.class, "expected", "actual") .hasFailedTest(JUnit5SimpleComparisonTest.class, "somethingElseThatFailed", AssertionFailedError.class, "expected", "actual") .hasFailedTest(JUnitMixedComparisonTest.class, "multipleComparisonFailure", MultipleFailuresError.class, Stream.of(order).map(x -> "expected" + x).collect(Collectors.joining("\n\n")), Stream.of(order).map(x -> "actual" + x).collect(Collectors.joining("\n\n")) ) ; // @formatter:on TestFailure f = result.getFailureByName(nameOf(JUnit5SimpleComparisonTest.class, "emptyComparisonFailure")); assertThat(f).as("emptyComparisonFailure") .isNotNull(); if (f != null) { assertThat(f.status).as("emptyComparisonFailure:status") .isEqualTo(STATUS_FAILURE); assertThat(f.expected).as("emptyComparisonFailure:expected") .isNull(); assertThat(f.actual).as("emptyComparisonFailure:actual") .isNull(); } } @Test public void eclipseListener_reportsParameterizedTests() throws InterruptedException { TestRunData result = runTestsEclipse(JUnit5ParameterizedTest.class); TestEntry methodTest = result.getTest(JUnit5ParameterizedTest.class, "parameterizedMethod"); if (methodTest == null) { fail("Couldn't find method test entry for " + nameOf(JUnit5ParameterizedTest.class, "parameterizedMethod")); return; } assertThat(methodTest.parameterTypes).as("parameterTypes") .containsExactly("java.lang.String", "float"); List<TestEntry> parameterTests = result.getChildrenOf(methodTest.testId) .stream() .map(x -> result.getById(x)) .collect(Collectors.toList()); assertThat(parameterTests.stream() .map(x -> x.testName)).as("testNames") .allMatch(x -> x.equals(nameOf(JUnit5ParameterizedTest.class, "parameterizedMethod"))); assertThat(parameterTests.stream()).as("dynamic") .allMatch(x -> x.isDynamicTest); assertThat(parameterTests.stream() .map(x -> x.displayName)).as("displayNames") .containsExactlyInAnyOrder("1 ==> param: 'one', param2: 1.0", "2 ==> param: 'two', param2: 2.0", "3 ==> param: 'three', param2: 3.0", "4 ==> param: 'four', param2: 4.0", "5 ==> param: 'five', param2: 5.0"); Optional<TestEntry> test4 = parameterTests.stream() .filter(x -> x.displayName.startsWith("4 ==>")) .findFirst(); if (!test4.isPresent()) { fail("Couldn't find test result for parameter 4"); } else { assertThat(parameterTests.stream() .filter(x -> result.getFailure(x.testId) != null)).as("failures") .containsExactly(test4.get()); } } @Test public void eclipseListener_reportsMisconfiguredParameterizedTests() throws InterruptedException { TestRunData result = runTestsEclipse(JUnit5ParameterizedTest.class); TestEntry methodTest = result.getTest(JUnit5ParameterizedTest.class, "misconfiguredMethod"); if (methodTest == null) { fail("Couldn't find method test entry for " + nameOf(JUnit5ParameterizedTest.class, "misconfiguredMethod")); return; } TestFailure failure = result.getFailure(methodTest.testId); if (failure == null) { fail("Expecting method:\n%s\nto have failed", methodTest); } else { assertThat(failure.trace).as("trace") .startsWith("org.junit.platform.commons.JUnitException: Could not find factory method [unknownMethod]"); } } @Test public void eclipseListener_reportsCustomNames_withOddCharacters() throws InterruptedException { TestRunData result = runTestsEclipse(JUnit5DisplayNameTest.class); final String[] methodList = { "test1", "testWithNonASCII", "testWithNonLatin" }; final String[] displayList = { // "Test 1", "Prüfung 2", "Δοκιμή 3" "Test 1", "Pr\u00fcfung 2", "\u0394\u03bf\u03ba\u03b9\u03bc\u03ae 3" }; for (int i = 0; i < methodList.length; i++) { final String method = methodList[i]; final String display = displayList[i]; TestEntry methodTest = result.getTest(JUnit5DisplayNameTest.class, method); if (methodTest == null) { fail("Couldn't find method test entry for " + nameOf(JUnit5ParameterizedTest.class, method)); continue; } assertThat(methodTest.displayName).as(String.format("[%d] %s", i, method)) .isEqualTo(display); } } @Test public void eclipseListener_reportsSkippedTests() throws InterruptedException { TestRunData result = runTestsEclipse(JUnit5Skipper.class, JUnit5ContainerSkipped.class, JUnit5ContainerSkippedWithCustomDisplayName.class, JUnit4Skipper.class); assertThat(result).as("result") .hasSkippedTest(JUnit5Skipper.class, "disabledTest", "with custom message") .hasSkippedTest(JUnit5ContainerSkipped.class, "with another message") .hasSkippedTest(JUnit5ContainerSkipped.class, "disabledTest2", "ancestor \"JUnit5ContainerSkipped\" was skipped") .hasSkippedTest(JUnit5ContainerSkipped.class, "disabledTest3", "ancestor \"JUnit5ContainerSkipped\" was skipped") .hasSkippedTest(JUnit5ContainerSkippedWithCustomDisplayName.class, "with a third message") .hasSkippedTest(JUnit5ContainerSkippedWithCustomDisplayName.class, "disabledTest2", "ancestor \"Skipper Class\" was skipped") .hasSkippedTest(JUnit5ContainerSkippedWithCustomDisplayName.class, "disabledTest3", "ancestor \"Skipper Class\" was skipped") .hasSkippedTest(JUnit4Skipper.class, "disabledTest", "This is a test"); } @Test public void eclipseListener_reportsAbortedTests() throws InterruptedException { TestRunData result = runTestsEclipse(JUnit5AbortTest.class, JUnit4AbortTest.class); assertThat(result).as("result") .hasAbortedTest(JUnit5AbortTest.class, "abortedTest", new TestAbortedException("Assumption failed: I just can't go on")) .hasAbortedTest(JUnit4AbortTest.class, "abortedTest", new AssumptionViolatedException("Let's get outta here")); } @Test public void eclipseListener_handlesNoEnginesGracefully() throws Exception { try (LaunchpadBuilder builder = new LaunchpadBuilder()) { IO.close(this.builder); builder.bndrun("no-engines.bndrun") .excludeExport("org.junit*") .excludeExport("junit*"); this.builder = builder; setTmpDir(); TestRunData result = runTestsEclipse(JUnit5AbortTest.class, JUnit4AbortTest.class); assertThat(result).hasErroredTest("Initialization Error", new JUnitException("Couldn't find any registered TestEngines")); } } @Test public void eclipseListener_handlesNoJUnit3Gracefully() throws Exception { builder.excludeExport("junit.framework"); Class<?>[] tests = { JUnit4ComparisonTest.class, JUnit5Test.class, JUnit5SimpleComparisonTest.class }; TestRunData result = runTestsEclipse(tests); assertThat(result).as("result") .hasFailedTest(JUnit5SimpleComparisonTest.class, "somethingElseThatFailed", AssertionFailedError.class, "expected", "actual"); TestFailure f = result.getFailureByName(nameOf(JUnit5SimpleComparisonTest.class, "emptyComparisonFailure")); assertThat(f).as("emptyComparisonFailure") .isNotNull(); if (f != null) { assertThat(f.status).as("emptyComparisonFailure:status") .isEqualTo(STATUS_FAILURE); assertThat(f.expected).as("emptyComparisonFailure:expected") .isNull(); assertThat(f.actual).as("emptyComparisonFailure:actual") .isNull(); } } @Test public void eclipseListener_handlesNoJUnit4Gracefully() throws Exception { try (LaunchpadBuilder builder = new LaunchpadBuilder()) { IO.close(this.builder); builder.debug(); builder.bndrun("no-vintage-engine.bndrun") .excludeExport("aQute.tester.bundle.*") .excludeExport("org.junit*") .excludeExport("junit*"); this.builder = builder; setTmpDir(); Class<?>[] tests = { JUnit3ComparisonTest.class, JUnit5Test.class, JUnit5SimpleComparisonTest.class }; TestRunData result = runTestsEclipse(tests); assertThat(result).as("result") .hasFailedTest(JUnit5SimpleComparisonTest.class, "somethingElseThatFailed", AssertionFailedError.class, "expected", "actual"); TestFailure f = result.getFailureByName(nameOf(JUnit5SimpleComparisonTest.class, "emptyComparisonFailure")); assertThat(f).as("emptyComparisonFailure") .isNotNull(); if (f != null) { assertThat(f.status).as("emptyComparisonFailure:status") .isEqualTo(STATUS_FAILURE); assertThat(f.expected).as("emptyComparisonFailure:expected") .isNull(); assertThat(f.actual).as("emptyComparisonFailure:actual") .isNull(); } } } @Test public void testerUnresolvedTrue_isPassedThroughToBundleEngine() { builder.set(TESTER_UNRESOLVED, "true"); AtomicReference<Bundle> bundleRef = new AtomicReference<>(); TestRunData result = runTestsEclipse(() -> { bundleRef.set(bundle().importPackage("some.unknown.package") .install()); }, JUnit3Test.class, JUnit4Test.class); assertThat(result).hasSuccessfulTest("Unresolved bundles"); } @Test public void testerUnresolvedFalse_isPassedThroughToBundleEngine() { builder.set(TESTER_UNRESOLVED, "false"); AtomicReference<Bundle> bundleRef = new AtomicReference<>(); TestRunData result = runTestsEclipse(() -> { bundleRef.set(bundle().importPackage("some.unknown.package") .install()); }, JUnit3Test.class, JUnit4Test.class); assertThat(result.getNameMap() .get("Unresolved bundles")).isNull(); } @Test public void testerNames_withParameters_isHonouredByTester() { builder.set(TESTER_NAMES, "'" + ParameterizedTesterNamesTest.class.getName() + ":parameterizedMethod(java.lang.String,float)'"); runTests(0, JUnit3Test.class, JUnit4Test.class, ParameterizedTesterNamesTest.class); assertThat(testBundler.getCurrentThread(JUnit3Test.class)).as("JUnit3 thread") .isNull(); assertThat(testBundler.getCurrentThread(JUnit4Test.class)).as("JUnit4 thread") .isNull(); assertThat(testBundler.getInteger("countParameterized", ParameterizedTesterNamesTest.class)) .as("parameterizedMethod") .isEqualTo(5); assertThat(testBundler.getInteger("countOther", ParameterizedTesterNamesTest.class)).as("countOther") .isEqualTo(0); } @Test public void xmlReporter_generatesCompleteXmlFile() throws Exception { final ExitCode exitCode = runTests(JUnit3Test.class, With1Error1Failure.class, With2Failures.class); final String fileName = "TEST-" + testBundle.getSymbolicName() + "-" + testBundle.getVersion() + ".xml"; File xmlFile = new File(getTmpDir(), fileName); Assertions.assertThat(xmlFile) .as("xmlFile") .exists(); AtomicReference<Document> docContainer = new AtomicReference<>(); Assertions.assertThatCode(() -> { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); docContainer.set(dBuilder.parse(xmlFile)); }) .doesNotThrowAnyException(); Document doc = docContainer.get(); XmlAssert.assertThat(doc) .nodesByXPath("/testsuite") .hasSize(1); XmlAssert.assertThat(doc) .nodesByXPath(testSuite() + "/testcase") .hasSize(7); XmlAssert.assertThat(doc) .nodesByXPath(testCase(JUnit3Test.class, "testSomething")) .hasSize(1); XmlAssert.assertThat(doc) .nodesByXPath(testCaseError(With1Error1Failure.class, "test1", RuntimeException.class)) .hasSize(1); XmlAssert.assertThat(doc) .nodesByXPath(testCase(With1Error1Failure.class, "test2")) .hasSize(1); XmlAssert.assertThat(doc) .nodesByXPath(testCaseFailure(With1Error1Failure.class, "test3", AssertionError.class)) .hasSize(1); XmlAssert.assertThat(doc) .nodesByXPath(testCaseFailure(With2Failures.class, "test1", AssertionError.class)) .hasSize(1); XmlAssert.assertThat(doc) .nodesByXPath(testCase(With2Failures.class, "test2")) .hasSize(1); XmlAssert.assertThat(doc) .nodesByXPath(testCaseFailure(With2Failures.class, "test3", CustomAssertionError.class)) .hasSize(1); } }
deepin-community/bnd
biz.aQute.tester.test/test/aQute/tester/junit/platform/test/ActivatorTest.java
45,917
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.handler.codec.socks; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.util.CharsetUtil; import org.junit.Test; import java.net.IDN; import java.nio.CharBuffer; import static org.junit.Assert.*; public class SocksCmdRequestTest { @Test public void testConstructorParamsAreNotNull() { try { new SocksCmdRequest(null, SocksAddressType.UNKNOWN, "", 1); } catch (Exception e) { assertTrue(e instanceof NullPointerException); } try { new SocksCmdRequest(SocksCmdType.UNKNOWN, null, "", 1); } catch (Exception e) { assertTrue(e instanceof NullPointerException); } try { new SocksCmdRequest(SocksCmdType.UNKNOWN, SocksAddressType.UNKNOWN, null, 1); } catch (Exception e) { assertTrue(e instanceof NullPointerException); } } @Test public void testIPv4CorrectAddress() { try { new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.IPv4, "54.54.1111.253", 1); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } @Test public void testIPv6CorrectAddress() { try { new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.IPv6, "xxx:xxx:xxx", 1); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } @Test public void testIDNNotExceeds255CharsLimit() { try { new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.DOMAIN, "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" + "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" + "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" + "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή", 1); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } @Test public void testHostNotEncodedForUnknown() { String asciiHost = "xn--e1aybc.xn--p1ai"; short port = 10000; SocksCmdRequest rq = new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.UNKNOWN, asciiHost, port); assertEquals(asciiHost, rq.host()); ByteBuf buffer = Unpooled.buffer(16); rq.encodeAsByteBuf(buffer); buffer.readerIndex(0); assertEquals(SocksProtocolVersion.SOCKS5.byteValue(), buffer.readByte()); assertEquals(SocksCmdType.BIND.byteValue(), buffer.readByte()); assertEquals((byte) 0x00, buffer.readByte()); assertEquals(SocksAddressType.UNKNOWN.byteValue(), buffer.readByte()); assertFalse(buffer.isReadable()); buffer.release(); } @Test public void testIDNEncodeToAsciiForDomain() { String host = "тест.рф"; CharBuffer asciiHost = CharBuffer.wrap(IDN.toASCII(host)); short port = 10000; SocksCmdRequest rq = new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.DOMAIN, host, port); assertEquals(host, rq.host()); ByteBuf buffer = Unpooled.buffer(24); rq.encodeAsByteBuf(buffer); buffer.readerIndex(0); assertEquals(SocksProtocolVersion.SOCKS5.byteValue(), buffer.readByte()); assertEquals(SocksCmdType.BIND.byteValue(), buffer.readByte()); assertEquals((byte) 0x00, buffer.readByte()); assertEquals(SocksAddressType.DOMAIN.byteValue(), buffer.readByte()); assertEquals((byte) asciiHost.length(), buffer.readUnsignedByte()); assertEquals(asciiHost, CharBuffer.wrap(buffer.readCharSequence(asciiHost.length(), CharsetUtil.US_ASCII))); assertEquals(port, buffer.readUnsignedShort()); buffer.release(); } @Test public void testValidPortRange() { try { new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.DOMAIN, "παράδειγμα.δοκιμήπαράδει", 0); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } try { new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.DOMAIN, "παράδειγμα.δοκιμήπαράδει", 65536); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } }
fredericBregier/netty
codec-socks/src/test/java/io/netty/handler/codec/socks/SocksCmdRequestTest.java
45,918
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.jboss.netty.handler.codec.socks; import org.jboss.netty.handler.codec.embedder.DecoderEmbedder; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; import org.junit.Test; import sun.net.util.IPAddressUtil; import static org.junit.Assert.*; public class SocksCmdRequestDecoderTest { private static final InternalLogger logger = InternalLoggerFactory.getInstance(SocksCmdRequestDecoderTest.class); private static void testSocksCmdRequestDecoderWithDifferentParams(SocksMessage.CmdType cmdType, SocksMessage.AddressType addressType, String host, int port) throws Exception { logger.debug("Testing cmdType: " + cmdType + " addressType: " + addressType + " host: " + host + " port: " + port); SocksCmdRequest msg = new SocksCmdRequest(cmdType, addressType, host, port); SocksCmdRequestDecoder decoder = new SocksCmdRequestDecoder(); DecoderEmbedder<SocksRequest> embedder = new DecoderEmbedder<SocksRequest>(decoder); SocksCommonTestUtils.writeMessageIntoEmbedder(embedder, msg); if (msg.getAddressType() == SocksMessage.AddressType.UNKNOWN) { assertTrue(embedder.poll() instanceof UnknownSocksRequest); } else { msg = (SocksCmdRequest) embedder.poll(); assertSame(msg.getCmdType(), cmdType); assertSame(msg.getAddressType(), addressType); assertEquals(msg.getHost(), host); assertEquals(msg.getPort(), port); } assertNull(embedder.poll()); } @Test public void testCmdRequestDecoderIPv4() throws Exception{ String[] hosts = { "127.0.0.1" }; int[] ports = {0, 32769, 65535 }; for (SocksMessage.CmdType cmdType : SocksMessage.CmdType.values()) { for (String host : hosts) { for (int port : ports) { testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksMessage.AddressType.IPv4, host, port); } } } } @Test public void testCmdRequestDecoderIPv6() throws Exception{ String[] hosts = { SocksCommonUtils.ipv6toStr(IPAddressUtil.textToNumericFormatV6("::1")) }; int[] ports = {0, 32769, 65535}; for (SocksMessage.CmdType cmdType : SocksMessage.CmdType.values()) { for (String host : hosts) { for (int port : ports) { testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksMessage.AddressType.IPv6, host, port); } } } } @Test public void testCmdRequestDecoderDomain() throws Exception{ String[] hosts = {"google.com" , "مثال.إختبار", "παράδειγμα.δοκιμή", "مثال.آزمایشی", "пример.испытание", "בײַשפּיל.טעסט", "例子.测试", "例子.測試", "उदाहरण.परीक्षा", "例え.テスト", "실례.테스트", "உதாரணம்.பரிட்சை"}; int[] ports = {0, 32769, 65535}; for (SocksMessage.CmdType cmdType : SocksMessage.CmdType.values()) { for (String host : hosts) { for (int port : ports) { testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksMessage.AddressType.DOMAIN, host, port); } } } } @Test public void testCmdRequestDecoderUnknown() throws Exception{ String host = "google.com"; int port = 80; for (SocksMessage.CmdType cmdType : SocksMessage.CmdType.values()) { testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksMessage.AddressType.UNKNOWN, host, port); } } }
MifengbushiMifeng/netty-learning
netty-3.7/src/test/java/org/jboss/netty/handler/codec/socks/SocksCmdRequestDecoderTest.java
45,919
/* * Copyright 2021 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.contrib.handler.codec.socks; import io.netty5.channel.embedded.EmbeddedChannel; import io.netty5.util.internal.SocketUtils; import io.netty5.util.internal.logging.InternalLogger; import io.netty5.util.internal.logging.InternalLoggerFactory; import org.junit.jupiter.api.Test; import java.net.UnknownHostException; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; public class SocksCmdRequestDecoderTest { private static final InternalLogger logger = InternalLoggerFactory.getInstance(SocksCmdRequestDecoderTest.class); private static void testSocksCmdRequestDecoderWithDifferentParams(SocksCmdType cmdType, SocksAddressType addressType, String host, int port) { logger.debug("Testing cmdType: " + cmdType + " addressType: " + addressType + " host: " + host + " port: " + port); SocksCmdRequest msg = new SocksCmdRequest(cmdType, addressType, host, port); SocksCmdRequestDecoder decoder = new SocksCmdRequestDecoder(); EmbeddedChannel embedder = new EmbeddedChannel(decoder); SocksCommonTestUtils.writeMessageIntoEmbedder(embedder, msg); if (msg.addressType() == SocksAddressType.UNKNOWN) { assertTrue(embedder.readInbound() instanceof UnknownSocksRequest); } else { msg = embedder.readInbound(); assertSame(msg.cmdType(), cmdType); assertSame(msg.addressType(), addressType); assertEquals(msg.host(), host); assertEquals(msg.port(), port); } assertNull(embedder.readInbound()); } @Test public void testCmdRequestDecoderIPv4() { String[] hosts = {"127.0.0.1", }; int[] ports = {1, 32769, 65535 }; for (SocksCmdType cmdType : SocksCmdType.values()) { for (String host : hosts) { for (int port : ports) { testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksAddressType.IPv4, host, port); } } } } @Test public void testCmdRequestDecoderIPv6() throws UnknownHostException { String[] hosts = {SocksCommonUtils.ipv6toStr(SocketUtils.addressByName("::1").getAddress())}; int[] ports = {1, 32769, 65535}; for (SocksCmdType cmdType : SocksCmdType.values()) { for (String host : hosts) { for (int port : ports) { testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksAddressType.IPv6, host, port); } } } } @Test public void testCmdRequestDecoderDomain() { String[] hosts = {"google.com" , "مثال.إختبار", "παράδειγμα.δοκιμή", "مثال.آزمایشی", "пример.испытание", "בײַשפּיל.טעסט", "例子.测试", "例子.測試", "उदाहरण.परीक्षा", "例え.テスト", "실례.테스트", "உதாரணம்.பரிட்சை"}; int[] ports = {1, 32769, 65535}; for (SocksCmdType cmdType : SocksCmdType.values()) { for (String host : hosts) { for (int port : ports) { testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksAddressType.DOMAIN, host, port); } } } } @Test public void testCmdRequestDecoderUnknown() { String host = "google.com"; int port = 80; for (SocksCmdType cmdType : SocksCmdType.values()) { testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksAddressType.UNKNOWN, host, port); } } }
pderop/socks-proxy
codec-socks/src/test/java/io/netty/contrib/handler/codec/socks/SocksCmdRequestDecoderTest.java
45,920
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.handler.codec.socks; import org.junit.Test; import static org.junit.Assert.*; public class SocksCmdRequestTest { @Test public void testConstructorParamsAreNotNull() { try { new SocksCmdRequest(null, SocksAddressType.UNKNOWN, "", 0); } catch (Exception e) { assertTrue(e instanceof NullPointerException); } try { new SocksCmdRequest(SocksCmdType.UNKNOWN, null, "", 0); } catch (Exception e) { assertTrue(e instanceof NullPointerException); } try { new SocksCmdRequest(SocksCmdType.UNKNOWN, SocksAddressType.UNKNOWN, null, 0); } catch (Exception e) { assertTrue(e instanceof NullPointerException); } } @Test public void testIPv4CorrectAddress() { try { new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.IPv4, "54.54.1111.253", 0); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } @Test public void testIPv6CorrectAddress() { try { new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.IPv6, "xxx:xxx:xxx", 0); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } @Test public void testIDNNotExceeds255CharsLimit() { try { new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.DOMAIN, "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" + "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" + "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" + "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή", 0); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } @Test public void testValidPortRange() { try { new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.DOMAIN, "παράδειγμα.δοκιμήπαράδει", -1); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } try { new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.DOMAIN, "παράδειγμα.δοκιμήπαράδει", 65536); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } }
beykery/netty
codec-socks/src/test/java/io/netty/handler/codec/socks/SocksCmdRequestTest.java
45,921
package com.hanlp.service; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.regex.Pattern; import com.alibaba.excel.EasyExcel; import com.alibaba.fastjson.JSON; import com.hankcs.hanlp.HanLP; import com.hankcs.hanlp.classification.classifiers.IClassifier; import com.hankcs.hanlp.classification.classifiers.NaiveBayesClassifier; import com.hankcs.hanlp.classification.corpus.FileDataSet; import com.hankcs.hanlp.classification.corpus.IDataSet; import com.hankcs.hanlp.classification.corpus.MemoryDataSet; import com.hankcs.hanlp.classification.statistics.evaluations.Evaluator; import com.hankcs.hanlp.classification.statistics.evaluations.FMeasure; import com.hankcs.hanlp.classification.tokenizers.BigramTokenizer; import com.hankcs.hanlp.classification.tokenizers.HanLPTokenizer; import com.hankcs.hanlp.classification.tokenizers.ITokenizer; import com.hankcs.hanlp.corpus.dependency.CoNll.CoNLLSentence; import com.hankcs.hanlp.corpus.document.sentence.word.IWord; import com.hankcs.hanlp.corpus.io.IOUtil; import com.hankcs.hanlp.dependency.IDependencyParser; import com.hankcs.hanlp.dependency.perceptron.parser.KBeamArcEagerDependencyParser; import com.hankcs.hanlp.dictionary.CoreDictionary; import com.hankcs.hanlp.model.crf.CRFLexicalAnalyzer; import com.hankcs.hanlp.model.perceptron.PerceptronLexicalAnalyzer; import com.hankcs.hanlp.seg.Segment; import com.hankcs.hanlp.seg.common.Term; import com.hankcs.hanlp.tokenizer.pipe.LexicalAnalyzerPipeline; import com.hankcs.hanlp.tokenizer.pipe.Pipe; import com.hankcs.hanlp.tokenizer.pipe.RegexRecognizePipe; import com.hanlp.classifiers.LinearSVMClassifier; import com.hanlp.dto.AutoCatData; import com.hanlp.listener.AutoCatDataListener; import com.hanlp.tokenizers.SelfTokenizer; import com.trs.ckm.soap.CATModelInfo; import com.trs.ckm.soap.CATRevDetail; import com.trs.ckm.soap.CkmSoapException; import com.trs.ckm.soap.Constants; import com.trs.ckm.soap.RevDetail; import com.trs.ckm.soap.RevHold; import com.trs.ckm.soap.TrsCkmSoapClient; import org.springframework.stereotype.Service; /** * Title: * Description: * Copyright: 2019 北京拓尔思信息技术股份有限公司 版权所有.保留所有权 * Company:北京拓尔思信息技术股份有限公司(TRS) * Project: SpringBootDemo * Author: 王杰 * Create Time:2019-11-14 22:46 */ @Service public class HanLPDemo { /** * 词典加载测试 * @param dictionaryPath 词典路径 * @throws IOException */ public static void loadDictionaryDemo(String dictionaryPath) throws IOException { TreeMap<String, CoreDictionary.Attribute> dictionary = IOUtil.loadDictionary(dictionaryPath); System.out.println(String.format("词典大小:%s个词条", dictionary.size())); System.out.println(String.format("输出词典的第一个词条为:%s", dictionary.keySet().iterator().next())); } /** * HanLP默认分词 * @param text 待分词 */ private static void segment(String text) { List<Term> termList = HanLP.segment(text); termList.forEach(term -> System.out.println(String.format("word:%s,offset:%s", term.word, term.offset))); } /** * 从内容中获取几个关键词 * @param context 内容 * @param keyWordNum 关键词数量 */ private static void ectractKeyWordDemo(String context, int keyWordNum) { List<String> keyWordList = HanLP.extractKeyword(context, keyWordNum); for (String keyWord : keyWordList) { System.out.println(keyWord); } } /** * HANLP 两种分词器、两种分类器,相互组合 * @throws IOException */ private static void textClassificationDemo() throws IOException { String folderPath = "/Users/wangjie/Development/ELK/hanlp/语料库/搜狗文本分类语料库迷你版"; // folderPath = "/Users/wangjie/Development/iso/share/ckm/autoCat"; String charsetName = "UTF-8"; // textClassificationDemo1(folderPath, charsetName, new NaiveBayesClassifier(), new BigramTokenizer()); // textClassificationDemo1(folderPath, charsetName, new NaiveBayesClassifier(), new HanLPTokenizer()); textClassificationDemo1(folderPath, charsetName, new LinearSVMClassifier(), new BigramTokenizer()); textClassificationDemo1(folderPath, charsetName, new LinearSVMClassifier(), new HanLPTokenizer()); // 使用自定义的Tokenizer textClassificationDemo1(folderPath, charsetName, new LinearSVMClassifier(), new SelfTokenizer()); } /** * HANLP 文本分类 * @param folderPath 待分类的文件路径 * @param charsetName 编码类型 * @param classifier 分类器 * @param tokenizer 分词器 */ private static void textClassificationDemo1(String folderPath, String charsetName, IClassifier classifier, ITokenizer tokenizer) throws IOException { // 前90%作为训练集 IDataSet trainingCorpus = new FileDataSet() .setTokenizer(tokenizer) .load(folderPath, charsetName, 0.9); classifier.train(trainingCorpus); // 后10%作为测试集 IDataSet testingCorpus = new MemoryDataSet(classifier.getModel()). load(folderPath, charsetName, -0.1); // 计算准确率 FMeasure result = Evaluator.evaluate(classifier, testingCorpus); System.out.println(classifier.getClass().getSimpleName() + "+" + tokenizer.getClass().getSimpleName()); System.out.println(result); } /** * 使用CRF条件随机场进行分词 * @throws IOException */ public static void testSelfTokenizer() throws IOException { // 使用自定的Tokenizer String folderPath = "/Users/wangjie/Development/ELK/hanlp/语料库/搜狗文本分类语料库迷你版"; String charsetName = "UTF-8"; SelfTokenizer selfTokenizer = new SelfTokenizer(); Segment selfSegment = new CRFLexicalAnalyzer(); selfSegment.enableAllNamedEntityRecognize(true); // 配置具体的分词算法 selfTokenizer.setSegment(selfSegment); IDataSet trainingCorpus = new FileDataSet() .setTokenizer(selfTokenizer) .load(folderPath, charsetName, 1); LinearSVMClassifier linearSVMClassifier = new LinearSVMClassifier(); linearSVMClassifier.train(trainingCorpus); // System.out.println(JSON.toJSONString(linearSVMClassifier.predict("虽说冯小刚的奔驰车性能特别好,但他从不超速开车。“按规定速度行车,遇到突然的情况,就能够及时处理。否则,就没把握了。“开车上路不要随意超车,尽量少变更车道。超速、超车其实快不了哪儿去,就是你玩儿命超,也就是早个十分钟。前几天在五环路上,唰的一声,一辆车从我车旁飞过,他是从望京的出口出来,在路上正赶上红灯。我跟在他前后脚停住了,但他冒的风险很大。这就是年轻气盛,安全意识不强。要知道,生命是爹妈给的,而生命是非常脆弱的,要保护好。对自己负责,也要对亲人负责。要想想,你还有那么多事要做,还有那么多好日子要过,只是为了把车开快一点,而什么都没有了,太不值了吧!”说起上路感受,冯小刚滔滔不绝。  几乎每年都要推出一部贺岁片的冯小刚,前几年每年也要“推出”一部汽车。"))); // System.out.println(JSON.toJSONString(linearSVMClassifier.predict("先是拉达吉普,后又换了一辆夏利、富康、大宇、三凌轿车。现在,他开的是一辆红色奔驰轿车,原因是听别人说红颜色的车发生事故的机率特别低。"))); // System.out.println(JSON.toJSONString(linearSVMClassifier.predict("汽车之家为汽车消费者提供选车、买车、用车、换车等所有环节的全面、准确、快捷的一站式服务。汽车之家致力于通过产品服务、数据技术、生态规则和资源为用户和"))); // System.out.println(JSON.toJSONString(linearSVMClassifier.predict("我认为,在开车时与前车保持必要的距离也是至关重要的。我曾经吃过一次亏。那天,在北京双安桥上,我紧跟着前车顺行,忽然前车来了一个急刹车,我来不及停就撞在他后面了。当时车速是30迈,可我觉得震动是很大的。试想,如果是高速行车追尾,那后果一定不堪设想。有人想从中间加进来,我也绝不跟他们斗气,避免事故才是最重要的。”  "))); System.out.println(JSON.toJSONString(linearSVMClassifier.predict("12月20日—26日各海关连续查获大量毒品"))); } /** * HANLP 情感分析 */ private static void emotionAnalysisDemo() throws IOException { String folderPathComment = "/Users/wangjie/Development/ELK/hanlp/语料库/ChnSentiCorp情感分析酒店评论"; NaiveBayesClassifier naiveBayesClassifier = new NaiveBayesClassifier(); naiveBayesClassifier.train(folderPathComment); LinearSVMClassifier linearSVMClassifier = new LinearSVMClassifier(); linearSVMClassifier.train(folderPathComment); String text1 = "热水器不热"; System.out.println(String.format("当前需要分类的模板:%s,模板类型为:%s", text1, naiveBayesClassifier.classify(text1))); System.out.println(String.format("当前需要分类的模板:%s,模板类型为:%s", text1, linearSVMClassifier.classify(text1))); String text2 = "结果大失所望,灯光昏暗,空间极其狭小,床垫质量恶劣,房间还伴着一股霉味。"; System.out.println(String.format("当前需要分类的模板:%s,模板类型为:%s", text2, naiveBayesClassifier.classify(text2))); System.out.println(String.format("当前需要分类的模板:%s,模板类型为:%s", text2, linearSVMClassifier.classify(text2))); String text3 = "可利用文本分类实现情感分析,效果还行"; System.out.println(String.format("当前需要分类的模板:%s,模板类型为:%s", text3, naiveBayesClassifier.classify(text3))); System.out.println(String.format("当前需要分类的模板:%s,模板类型为:%s", text3, linearSVMClassifier.classify(text3))); } /** * 依存句法分析 */ private static void dependencyParser() throws IOException, ClassNotFoundException { IDependencyParser parser = new KBeamArcEagerDependencyParser(); CoNLLSentence tree = parser.parse("电池非常棒,机身不长,长的是待机,但是屏幕分辨率不高。"); System.out.println(tree); tree = parser.parse("2019年10月22日,呼和浩特海关所属乌拉特海关监管二科在进境卡口物流监控验环节,对车号为3922的蒙古籍运煤车辆进行机检检查,发现其车厢前部煤层下方位置疑似夹藏。经人工检查查获夹藏于该车辆车厢前部的中药材防风682.5千克。目前该情事已移交缉私部门做进一步处理"); System.out.println(tree); } private static final Pattern WEB_URL = Pattern.compile("((?:(http|https|Http|Https|rtsp|Rtsp):\\/\\/(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?(?:(((([a-zA-Z0-9][a-zA-Z0-9\\-]*)*[a-zA-Z0-9]\\.)+((aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(biz|b[abdefghijmnorstvwyz])|(cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(edu|e[cegrstu])|f[ijkmor]|(gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(info|int|i[delmnoqrst])|(jobs|j[emop])|k[eghimnprwyz]|l[abcikrstuvy]|(mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])|(name|net|n[acefgilopruz])|(org|om)|(pro|p[aefghklmnrstwy])|qa|r[eosuw]|s[abcdeghijklmnortuvyz]|(tel|travel|t[cdfghjklmnoprtvwz])|u[agksyz]|v[aceginu]|w[fs]|(δοκιμή|испытание|рф|срб|טעסט|آزمایشی|إختبار|الاردن|الجزائر|السعودية|المغرب|امارات|بھارت|تونس|سورية|فلسطين|قطر|مصر|परीक्षा|भारत|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|பரிட்சை|భారత్|ලංකා|ไทย|テスト|中国|中國|台湾|台灣|新加坡|测试|測試|香港|테스트|한국|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)|y[et]|z[amw]))|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))))(?:\\:\\d{1,5})?)(\\/(?:(?:[a-zA-Z0-9\\;\\/\\?\\:\\@\\&\\=\\#\\~\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))*)?"); private static final Pattern EMAIL = Pattern.compile("(\\w+(?:[-+.]\\w+)*)@(\\w+(?:[-.]\\w+)*\\.\\w+(?:[-.]\\w+)*)"); /** * 分词之前对内容进行正则匹配避免 邮箱、url地址这种特殊字符被拆分 */ private static void regexBeforeSegment() throws IOException { LexicalAnalyzerPipeline analyzer = new LexicalAnalyzerPipeline(new PerceptronLexicalAnalyzer()); // 管道顺序=优先级,自行调整管道顺序以控制优先级 analyzer.addFirst(new RegexRecognizePipe(WEB_URL, "【网址】")); analyzer.addFirst(new RegexRecognizePipe(EMAIL, "【邮件】")); // 自己写个管道也并非难事 analyzer.addLast(new Pipe<List<IWord>, List<IWord>>() { @Override public List<IWord> flow(List<IWord> input) { for (IWord word : input) { if ("nx".equals(word.getLabel())) { word.setLabel("字母"); } } return input; } }); String text = "HanLP的项目地址是https://github.com/hankcs/HanLP,联系邮箱[email protected]"; System.out.println(analyzer.analyze(text)); } /** * CKM 自动分类 */ private static void createAutoCatFile() { String authCatFileName = "/Users/wangjie/Development/项目/海关/CKM/自动分类训练.xlsx"; EasyExcel.read(authCatFileName, AutoCatData.class, new AutoCatDataListener()).sheet().doRead(); } /** * CKM 自动分类测试 * @throws CkmSoapException */ public static void ckmDemo() throws CkmSoapException { TrsCkmSoapClient trsCkmSoapClient = new TrsCkmSoapClient("http://127.0.0.1:8000", "admin", "trsadmin"); String autoCatModelName = "demo"; // 读取自动分类模板 CATModelInfo catModelInfo = trsCkmSoapClient.CATGetModelInfo(autoCatModelName, Constants.MODEL_TYPE_AUTO_CURRENT); if (catModelInfo != null) { System.out.println(catModelInfo.getcreatedate()); System.out.println(catModelInfo.getxmlcatinfo()); System.out.println(catModelInfo.gettype()); } String detailContent1 = "10月29日,海关总署风险防控局(青岛)布控查获禁止进境固体废物71.4吨\t\n" + "根据该局布控指令,查获经上海口岸申报原产自西班牙的次级铝塑板实为禁止进境固体废物情事,目前已做退运处理。"; String detailContent2 = "10月15日南宁海关依法退运禁止进口固体废物1329.7吨\t\n" + "为上海某公司今年1-3月从北海口岸申报进口的“高碳铬铁”,经鉴定样品中疏松多孔状部分为冶炼过程中残留的炉渣,属我国禁止进口固体废物,该关依法责令退运出境。"; String detailContent3 = "杭州海关缉私局经对前期侦办案件的深挖扩线,于1月2日立案侦办一起走私成品油案,抓获犯罪嫌疑人1名," + "冻结涉案账户资金100余万元。经查,2018年9月至12月,犯罪嫌疑人陈某雇佣、组织人员先后20余次驾驶油船前往东经122度、北纬27度海域过驳柴油走私入境至温州销售牟利," + "查证涉嫌走私柴油1万余吨,案值6000余万元,涉嫌偷逃税款2000余万元。"; String detailContent4 = "1月7日上海海关对某公司进口非抗癌药物实施补税1296.5万元。根据海关总署税收征管局(京津)指令," + "对某制药公司2018年5-9月申报进口的醋酸奥曲肽注射液(善宁)实施验估作业。经验核财务数据、合同、发票等相关资料," + "该商品实为非抗癌药,不应享受抗癌药物税收优惠政策,涉及货值9973.5万元。"; String detailContent5 = "\"2018年6月15日,我科对深圳市恒基拓展实业有限公司委托中国外运华南有限公司黄埔分公司持报关单520120181018027415以一般贸易方式向我关申报的铅矿砂一批进行查验。" + "查验关员现场发现实际到货为灰色泥块状物,与一般铅矿砂原矿呈相对均质颗粒状、有色泽的特征不符。经与风险部门共同研判,需要做固废鉴定检测。" + "6月29日,取样送广州海关化验中心核品名、成份、归类及是否固废。7月13日接广州海关化验中心出具的GZ2018072374号中国海关进出境货物(物品)化验鉴定证书," + "结论为:送检样品主要成份为硫酸铅,送检样品不是正常矿物,请核实来源后确定归类。11月9日,中国检验认证集团广东有限公司派工作人员到现场取样。" + "12月25日,接中国检验认证集团广东有限公司出具的441118110014号检验证书和防城港出入境检验检疫局综合技术服务中心出具的2018FCGWT0009号鉴别报告,结论为:送检样品不是铅矿砂,来源于废铅酸蓄电池渣泥,属于目前我国禁止进口的固体废物。" + "经查并根据上述证书,该单申报进口铅矿砂未到货。另有废铅酸蓄电池渣泥131302千克未申报。2019年1月2日移交处置处理。目前此案正在进一步处理中。企业涉嫌通过伪报品名方式进口国家禁限进口的固体废物,逃避海关监管。" + "建议对上述查发企业及相关货物进行布控,必要时取样送检或送固废鉴定。"; Map<String, String> param = new HashMap<>(); param.put("生态类_1", detailContent1); param.put("生态类_2", detailContent2); param.put("经济类_3", detailContent3); param.put("经济类_4", detailContent4); param.put("生态类_5", detailContent5); for (Map.Entry<String, String> itemMap : param.entrySet()) { CATRevDetail[] catRevDetails = trsCkmSoapClient.CATClassifyText(autoCatModelName, itemMap.getValue()); System.out.println(String.format("正确分类:%s", itemMap.getKey())); if (catRevDetails != null) { for (CATRevDetail catRevDetail : catRevDetails) { System.out.println(String.format("\t 预测:%s,置信度:%s", catRevDetail.getCATName(), catRevDetail.getv())); } } } } /** * CKM相似性检测 */ public static void ckmSimModel() throws CkmSoapException { TrsCkmSoapClient trsCkmSoapClient = new TrsCkmSoapClient("http://127.0.0.1:8000", "admin", "trsadmin"); String simModelName = "contentSimModel"; // 创建相似性模板 // createCkmSimModel(simModelName, trsCkmSoapClient); // 添加相似记录 updateSimUpdateIndex("1", "空调//@海尔空调:#海尔空调牵手中国女排#今天是海尔空调的大日子,本空调终于和@中国女排 “锁”了!这么激动的事儿得让大家和我一起分享,送空调必须安排上!!转+评本微博,说说你理解的“女排精神”,12.13抽一个宝宝送我家新品【海尔多风感系列】挂机一台!#与风同行,再创新高# 抽奖详情", simModelName, trsCkmSoapClient); updateSimUpdateIndex("2", "锦鲤手抄报 空调//@海尔空调:#海尔空调牵手中国女排#今天是海尔空调的大日子,本空调终于和@中国女排 “锁”了!这么激动的事儿得让大家和我一起分享,送空调必须安排上!!转+评本微博,说说你理解的“女排精神”,12.13抽一个宝宝送我家新品【海尔多风感系列】挂机一台!#与风同行,再创新高# 抽奖详情", simModelName, trsCkmSoapClient); updateSimUpdateIndex("3", "超级无敌普_通人 空调//@海尔空调:#海尔空调牵手中国女排#今天是海尔空调的大日子,本空调终于和@中国女排 “锁”了!这么激动的事儿得让大家和我一起分享,送空调必须安排上!!转+评本微博,说说你理解的“女排精神”,12.13抽一个宝宝送我家新品【海尔多风感系列】挂机一台!#与风同行,再创新高# 抽奖详情", simModelName, trsCkmSoapClient); updateSimUpdateIndex("4", "转发微博 //@海尔智家:#智家小科普#冷柜结霜存在各种隐患,清霜工作却又堪比战场。。。交给我们吧~2019.12.1-2020.1.24,海尔智家35周年感恩节推出回馈老用户活动,免费上门为你提供家电保养;更有感恩新品礼,购新家电享各种惊喜好礼~想趁#双十二#换新的,赶紧看过来!", simModelName, trsCkmSoapClient); // 根据文章内容查询相似度 querySimRetrieveByText("空调//@海尔空调:#海尔空调牵手中国女排#今天是海尔空调的大日子,本空调终于和@中国女排 “锁”了!这么激动的事儿得让大家和我一起分享,送空调必须安排上!!转+评本微博,说说你理解的“女排精神”,12.13抽一个宝宝送我家新品【海尔多风感系列】挂机一台!#与风同行,再创新高# 抽奖详情", simModelName, trsCkmSoapClient); querySimRetrieveByText("海尔空调牵手中国女排#说说你理解的“女排精神”,12.13抽一个宝宝送我家新品【海尔多风感系列】挂机一台!#与风同行,再创新高# 抽奖详情", simModelName, trsCkmSoapClient); } /** * 创建相似性模板 * @param simModelName 相似性模板名称 * @param trsCkmSoapClient ckm连接 * @throws CkmSoapException */ private static void createCkmSimModel(String simModelName, TrsCkmSoapClient trsCkmSoapClient) throws CkmSoapException { System.out.println(String.format("相似性模板创建结果:%s", trsCkmSoapClient.SimCreateModel(simModelName))); } /** * 添加相似记录模板 * @param contentId 内容ID * @param contentDetail 内容 * @param simModelName 模板名称 * @param trsCkmSoapClient ckm连接 * @throws CkmSoapException */ private static void updateSimUpdateIndex(String contentId, String contentDetail, String simModelName, TrsCkmSoapClient trsCkmSoapClient) throws CkmSoapException { System.out.println(String.format("添加相似性记录结果:%s", trsCkmSoapClient.SimUpdateIndex(simModelName, contentId, contentDetail))); } /** * 根据文章内容查询相似度 * @param contentDetail 内容 * @param simModelName 模型名称 * @param trsCkmSoapClient ckm连接 * @throws CkmSoapException */ private static void querySimRetrieveByText(String contentDetail, String simModelName, TrsCkmSoapClient trsCkmSoapClient) throws CkmSoapException { RevHold revHold = new RevHold(); RevDetail[] revDetails = trsCkmSoapClient.SimRetrieveByText(simModelName, revHold, contentDetail); if (revDetails != null) { for (RevDetail revDetail : revDetails) { System.out.println(String.format("相似文章Id:%s,相似度:%s", revDetail.getid(), revDetail.getsimv())); } } } public static void main(String[] args) throws Exception { // loadDictionaryDemo("/Users/wangjie/Development/ELK/hanlp/data/dictionary/CoreNatureDictionary.txt"); // textClassificationDemo(); // testSelfTokenizer(); // dependencyParser(); // ckmDemo(); // regexBeforeSegment(); // emotionAnalysisDemo(); // createAutoCatFile(); // ckmSimModel(); PerceptronLexicalAnalyzer perceptronLexicalAnalyzer = new PerceptronLexicalAnalyzer(); System.out.println(perceptronLexicalAnalyzer.analyze("玻璃纤维网格布为玻璃纤维机织物经进一步涂胶处理的产品,从商品的基本特征看,仍属于玻璃纤维机织物的商品范畴,根据归类总规则一及六,经参考w-2-5100-2010-0102归类指导意见,“玻璃纤维网格布”应归入税则号列7019.5900")); System.out.println(perceptronLexicalAnalyzer.analyze("青岛桑迪益科工贸有限公司于2019年5月14日以一般贸易方式申报出口太阳能热水器配件(集热管)等,报关单号425820190000436990。经查验并归类认定,第1项货物应归入税号7020009990(出口退税率为零,无出口监管证件)"));; // segment("东莞海关查获一批进口医疗器械外包装标签违反“一个中国”原则的情事。2019年10月16日,东莞海关查验部门在对一批从中国台湾进口的61套、价值375546元人民币的医疗器械进行查验时,发现该批医疗器械的外包装标签上标注了“ROC”字样,违反了“一个中国”的原则。该关按照规定责令企业进行整改,并清除相关标签。"); } }
AndrewSviridov/SpringBootDemo_V2
HanLP/src/main/java/com/hanlp/service/HanLPDemo.java
45,922
package be.devijver.wikipedia.parser.javacc.table; import java.io.ByteArrayInputStream; import java.io.StringReader; import junit.framework.TestCase; import be.devijver.wikipedia.parser.ast.Attribute; import be.devijver.wikipedia.parser.ast.Cell; import be.devijver.wikipedia.parser.ast.Row; import be.devijver.wikipedia.parser.ast.Table; public class JavaCCTableParserTests extends TestCase { private Table parse(String s) { try { return new JavaCCTableParser( new StringReader(s) ).parseTable(); } catch (ParseException e) { throw new RuntimeException(e); } } public void testEmptyTable() throws Exception { Table t = parse("{| |}"); System.out.println(t); assertNotNull(t); assertNull(t.getCaption()); assertNull(t.getTableOptions()); assertNull(t.getCaptionOptions()); } public void testEmptyTableWithTableOptions() throws Exception { Table t = parse("{| border=\"0\" |}"); System.out.println(t); assertNotNull(t); assertNull(t.getCaption()); assertNull(t.getCaptionOptions()); assertNotNull(t.getTableOptions()); assertEquals(1, t.getTableOptions().getAttributes().length); Attribute attr = t.getTableOptions().getAttributes()[0]; assertEquals("border", attr.getName()); assertEquals("0", attr.getValue()); } public void testEmptyTableWithCaption() throws Exception { Table t = parse("{|\n|+ This is a caption |}"); System.out.println(t); assertNotNull(t); assertEquals(" This is a caption ", t.getCaption()); assertNull(t.getTableOptions()); } public void testTableWithCaptionAndCaptionOptions1() throws Exception { Table t = parse( "{| border=\"0\" \n" + "|+ someoption=\"true\" | This is a caption \n" + "|}"); System.out.println(t); assertNotNull(t); assertNotNull(t.getTableOptions()); assertEquals(" This is a caption ", t.getCaption()); assertNotNull(t.getCaptionOptions()); assertEquals(1, t.getCaptionOptions().getAttributes().length); } public void testTableWithCaptionAndCaptionOptions2() throws Exception { Table t = parse( "{| border=\"0\" \n" + "|+ someoption=\"true\" | '''This is a caption''' \n" + "|}"); System.out.println(t); assertNotNull(t); assertNotNull(t.getTableOptions()); assertEquals(" '''This is a caption''' ", t.getCaption()); assertNotNull(t.getCaptionOptions()); assertEquals(1, t.getCaptionOptions().getAttributes().length); } public void testTableWithOneRowAndOneCell() throws Exception { Table t = parse( "{|\n" + "|-\n" + "| cell1\n" + "|}"); System.out.println(t); } public void testTableWithOneRowWithOneCellWithCellOptions() throws Exception { Table t = parse( "{|\n" + "|-\n" + "| style=\"none\" | cell1 \n" + "|}"); System.out.println(t); } public void testTableWithOneRowWithTwoCellsWithCellOptions() throws Exception { Table t = parse( "{|\n" + "|-\n" + "| style=\"none\" | cell1 || style=\"groovy\" | cell2 \n" + "|}" ); System.out.println(t); assertNotNull(t); assertNull(t.getCaption()); assertNull(t.getCaptionOptions()); assertNull(t.getTableOptions()); assertEquals(1, t.getRows().length); assertEquals(2, t.getRows()[0].getCells().length); Cell cell1 = t.getRows()[0].getCells()[0]; Cell cell2 = t.getRows()[0].getCells()[1]; assertEquals(" cell1 ", cell1.getContent()[0].toString()); assertEquals(1, cell1.getOptions().getAttributes().length); assertEquals("style", cell1.getOptions().getAttributes()[0].getName()); assertEquals("none", cell1.getOptions().getAttributes()[0].getValue()); assertEquals(" cell2 ", cell2.getContent()[0].toString()); assertEquals(1, cell2.getOptions().getAttributes().length); assertEquals("style", cell2.getOptions().getAttributes()[0].getName()); assertEquals("groovy", cell2.getOptions().getAttributes()[0].getValue()); } public void testTableWithOneRowAndTwoCells1() throws Exception { Table t = parse( "{|\n" + "|-\n" + "| cell1 || cell2\n" + "|}"); System.out.println(t); } public void testTableWithOneRowAndTwoCells2() throws Exception { Table t = parse( "{|\n" + "|-\n" + "| cell1 \n" + "| cell2 \n" + "|}"); System.out.println(t); } public void testTableWithOneRowAndTwoCells3() throws Exception { Table t = parse( "{|\n" + "|-\n" + "! cell1 !! cell2\n" + "|}"); System.out.println(t); } public void testTableWithOneRowAndTwoCells4() throws Exception { Table t = parse( "{|\n" + "|-\n" + "! cell1 \n" + "! cell2\n" + "|}"); System.out.println(t); assertNotNull(t); assertNull(t.getCaption()); assertNull(t.getCaptionOptions()); assertNull(t.getTableOptions()); assertEquals(1, t.getRows().length); assertEquals(2, t.getRows()[0].getCells().length); Cell cell1 = t.getRows()[0].getCells()[0]; Cell cell2 = t.getRows()[0].getCells()[1]; assertNull(cell1.getOptions()); assertEquals(" cell1 ", cell1.getContent()[0].toString()); assertNull(cell1.getOptions()); assertEquals(" cell2", cell2.getContent()[0].toString()); } public void testTableWithNestedTable1() throws Exception { Table t = parse( "{|\n" + "|-\n" + "| {| border=\"0\" |}\n" + "|}" ); System.out.println(t); } public void testTableWithNestedTable2() throws Exception { Table t = parse( "{|\n" + "|-\n" + "|{| border=\"0\" |}\n" + "|}" ); System.out.println(t); } public void testTableWithTwoRows() throws Exception { Table t = parse( "{|\n" + "|-\n" + "| row 1, cell 1 || row 1, cell 2\n" + "|-\n" + "| row 2, cell 1 || row 2, cell 2\n" + "|}" ); System.out.println(t); } public void testWebApplicationFrameworksTable1() throws Exception { String content = "{| class=\"wikitable sortable\" style=\"font-size: 90%\"\n" + "|-\n" + "! Project\n" + "! Current Stable Version\n" + "! [[Programming Language|Language]]\n" + "! [[License]]\n" + "|-\n" + "! {{rh}} | [[Agavi_(framework)|Agavi]]\n" + "| 0.11 RC6\n" + "| [[PHP]]\n" + "| [[LGPL]] \n" + "|-\n" + "! {{rh}} | [[AJILE|Ajile]]\n" + "| [http://prdownloads.sourceforge.net/ajile/Ajile.0.9.9.2.zip?download 0.9.9.2]\n" + "| [[JavaScript]]\n" + "| [[MPL|MPL 1.1]] / [[LGPL|LGPL 2.1]] / [[GPL|GPL 2.0]] \n" + "|-\n" + "! {{rh}} | [[Akelos PHP Framework|Akelos]]\n" + "| 0.8\n" + "| [[PHP]]\n" + "| [[LGPL]] \n" + "|-\n" + "! {{rh}} | [[Apache Struts]]\n" + "| 2.0.9\n" + "| [[Java (programming language)|Java]]\n" + "| [[Apache License|Apache]] \n" + "|-\n" + "! {{rh}} | [[Andromeda Database|Andromeda]]\n" + "| 2007.08.08\n" + "| [[PHP]]\n" + "| [[GPL]]\n" + "|-\n" + "! {{rh}} | [[Aranea framework|Aranea MVC]]\n" + "| 1.0.10\n" + "| [[Java (programming language)|Java]]\n" + "| [[Apache License|Apache]]\n" + "|-\n" + "! {{rh}} | [[CakePHP]]\n" + "| 1.1.17.5612\n" + "| [[PHP]]\n" + "| [[MIT License|MIT]]\n" + "|-\n" + "! {{rh}} | [[Camping (microframework)|Camping]]\n" + "| 1.5\n" + "| [[Ruby (programming language)|Ruby]]\n" + "| [[MIT License|MIT]]\n" + "|-\n" + "! {{rh}} | [[Catalyst (software)|Catalyst]]\n" + "| 5.7007\n" + "| [[Perl]]\n" + "| [[GPL]]/[[Artistic License|Artistic]]\n" + "|-\n" + "! {{rh}} | [[CodeIgniter|Code Igniter]]\n" + "| 1.5.4\n" + "| [[PHP]]\n" + "| [http://codeigniter.com/user_guide/license.html Apache/BSD-style open source license]\n" + "|-\n" + "! {{rh}} | [[ColdBox]]\n" + "| 2.0.3\n" + "| [[Adobe ColdFusion|ColdFusion]]\n" + "| [[Apache License|Apache]]\n" + "|-\n" + "! {{rh}} | [[Django (web framework)|Django]]\n" + "| 0.96\n" + "| [[Python (programming language)|Python]]\n| [[BSD]]\n" + "|-\n" + "! {{rh}} | [[DotNetNuke]]\n" + "| 4.6.2\n" + "| [[ASP.NET]]\n" + "| [[BSD]]\n" + "|-\n" + "! {{rh}} | [[Fusebox (programming)|Fusebox]]\n" + "| 5.1\n" + "| [[Adobe ColdFusion|ColdFusion]]\n" + "| [[Apache License|Apache]]\n" + "|-\n" + "! {{rh}} | [http://mdp.cti.depaul.edu/examples Gluon]\n" + "| 1.5\n" + "| [[Python (programming language)|Python]]\n" + "| [[GPL]]\n" + "|-\n" + "! {{rh}} | [[Grails_%28Framework%29|Grails]]\n" + "| 0.6 \n" + "| [[Groovy (programming language)|Groovy]]\n" + "| [[Apache License|Apache]]\n" + "|-\n" + "! {{rh}} | [[JBoss Seam]]\n" + "| 1.2.1 GA\n" + "| [[Java (programming language)|Java]]\n" + "| [[LGPL]]\n" + "|-\n" + "! {{rh}} | [[Jifty]]\n" + "| 0.70824\n" + "| [[Perl]]\n" + "| [[GPL]]/[[Artistic License|Artistic]]\n" + "|-\n" + "! {{rh}} | [[Kumbia]]\n" + "| 0.46RC9\n" + "| [[PHP]]\n" + "| [[GPL]] | [[Apache License|Apache 2.0]] | [[PHP5]]\n" + "|-\n" + "! {{rh}} | [[Lift (web framework)|Lift]]\n" + "| 0.2.0\n" + "| [[Scala (programming language)|Scala]]\n" + "| [[Apache License|Apache 2.0]]\n" + "|-\n" + "! {{rh}} | [[Mach-II]]\n" + "| 1.5\n" + "| [[Adobe ColdFusion|ColdFusion]]\n" + "| [[Apache License|Apache]]\n" + "|-\n" + "! {{rh}} | [[Makumba]]\n" + "| 0.5.16\n" + "| [[Java (programming language)|Java]]\n" + "| [[LGPL]]\n" + "|-\n" + "! {{rh}} | [[Model-Glue]]\n" + "| 2.0\n" + "| [[Adobe ColdFusion|ColdFusion]]\n" + "| [[Apache License|Apache]]\n" + "|-\n" + "! {{rh}} | [[Monorail (.Net)|MonoRail]]\n" + "| 1.0 RC3\n" + "| [[ASP.NET]]\n" + "| [[Apache License|Apache]]\n" + "|-\n" + "! {{rh}} | [[Nitro (web framework)|Nitro]]\n" + "| 0.41\n" + "| [[Ruby (programming language)|Ruby]]\n" + "| [[BSD License]]\n" + "|-\n" + "! {{rh}} | [[OpenACS]]\n" + "| 5.3.2\n" + "| [[Tcl]]\n" + "| [[GPL]]\n" + "|-\n" + "! {{rh}} | [[PHPulse]]\n" + "| 2.0\n" + "| [[PHP]]\n" + "| [[GPL]]\n" + "|-\n" + "! {{rh}} | [[PRADO]]\n" + "| 3.1.1\n" + "| [[PHP]]\n" + "| [[BSD License]]\n" + "|-\n" + "! {{rh}} | [[Pylons (web framework)]]\n" + "| 0.9.6\n" + "| [[Python (programming language)|Python]]\n" + "| [[BSD License]]\n" + "|-\n" + "! {{rh}} | [[Qcodo]]\n" + "| 0.3.32\n" + "| [[PHP]]\n" + "| [[MIT License]]\n" + "|-\n" + "! {{rh}} | [[RIFE]]\n" + "| 1.6.2\n" + "| [[Java]]\n" + "| [[Apache License|Apache]]\n" + "|-\n" + "! {{rh}} | [[Ruby on Rails]]\n" + "| 1.2.3\n" + "| [[Ruby (programming language)|Ruby]]\n" + "| [[MIT License|MIT]]/[[Ruby License|Ruby]]\n" + "|-\n" + "! {{rh}} | [[Seaside web framework|Seaside]]\n" + "| 2.7\n" + "| [[Smalltalk]]\n" + "| [[MIT License]]\n" + "|-\n" + "! {{rh}} | [[Spring Framework]]\n" + "| 2.0.6\n" + "| [[Java (programming language)|Java]]\n" + "| [[Apache License|Apache]]\n" + "|-\n" + "! {{rh}} | [[Stripes]]\n" + "| 1.4.3\n" + "| [[Java]]\n" + "| [[LGPL]]\n" + "|-\n" + "! {{rh}} | [[Symfony]]\n" + "| 1.0.7\n" + "| [[PHP]]\n" + "| [[MIT License|MIT]]\n" + "|-\n" + "! {{rh}} | [[TurboGears]]\n" + "| 1.0.1\n" + "| [[Python (programming language)|Python]]\n" + "| [[MIT License]], [[LGPL]]\n" + "|-\n" + "! {{rh}} | [[WebLeaf]]\n" + "| 2.1\n" + "| [[Java (programming language)|Java]]\n" + "| [[LGPL]]\n" + "|-\n" + "! {{rh}} | [[WebObjects]]\n" + "| 5.3.1\n" + "| [[Java (programming language)|Java]]\n" + "| [[Proprietary]]\n" + "|-\n" + "! {{rh}} | [[Zend Framework]]\n" + "| [http://framework.zend.com/download 1.0.2]\n" + "| [[PHP]]\n" + "| [[BSD_Licenses|BSD License]]\n" + "|-\n" + "! {{rh}} | [[Zoop Framework]]\n" + "| 1.2\n" + "| [[PHP]]\n" + "| [[Zope Public License|ZPL]]\n" + "|-\n" + "! {{rh}} | [[Zope]]2\n" + "| 2.10\n" + "| [[Python]]\n" + "| [[Zope Public License|ZPL]]\n" + "|-\n" + "! {{rh}} | [[Zope]]3\n" + "| 3.3\n" + "| [[Python]]\n" + "| [[Zope Public License|ZPL]]\n" + "|-class=\"sortbottom\"\n" + "! Project\n" + "! Current Stable Version\n" + "! [[Programming Language|Language]]\n" + "! [[License]]\n" + "|}"; Table t = parse(content); System.out.println(t); Row row = t.getRows()[1]; Cell cell = row.getCells()[0]; assertEquals(" [[Agavi_(framework)|Agavi]]", cell.getContent()[0].toString()); assertEquals("{{rh}}", cell.getOptions().getAttributes()[0].getName()); } public void testWebApplicationFrameworks2() throws Exception { String content = "{| class=\"wikitable sortable\" style=\"font-size: 90%\"\n" + "|-\n" + "!Project\n" + "!Language\n" + "![[Ajax (programming)|Ajax]]\n" + "![[Model-view-controller|MVC]] framework\n" + "![[Web_application_framework#Push-based_vs._Pull-based|MVC Push/Pull]]\n" + "![[Internationalization_and_localization|i18n & l10n?]]\n" + "![[Object-relational mapping|ORM]]\n" + "!Testing framework(s)\n" + "!DB migration framework(s)\n" + "!Security Framework(s)\n" + "\n" + "!Template Framework(s)\n" + "!Caching Framework(s)\n" + "!Form Validation Framework(s)\n" + "|-\n" + "|[[Agavi_(framework)|Agavi]]\n" + "| PHP\n" + "| \n" + "| {{Yes}}\n" + "| Push\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "|-\n" + "|[[AJILE|Ajile]]\n" + "| [[JavaScript]]\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| Push & Pull\n" + "| {{Yes}}\n" + "| \n" + "| {{Yes}}, [http://jsunit.net/ jsUnit]\n" + "| \n" + "| \n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| \n" + "|-\n" + "|[[Akelos PHP Framework]]\n" + "| PHP\n" + "| {{Yes}}, [[Prototype JavaScript Framework|Prototype]], [[script.aculo.us]]\n" + "| {{Yes}}, [[Active record pattern|ActiveRecord]]\n" + "| Push\n" + "| {{Yes}}\n" + "| {{Yes}}, [[Active record pattern|ActiveRecord]]\n" + "| {{Yes}}, [[Unit testing|Unit Tests]]\n" + "| {{Yes}}\n" + "| \n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "|-\n" + "|[[Apache Struts]]\n" + "| Java\n" + "| {{Yes}}\n" + "| \n" + "| Push\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}, [[Unit testing|Unit Tests]]\n" + "|\n" + "|\n" + "|{{Yes}}, Jakarta Tiles framework\n" + "|\n" + "|{{Yes}}, Jakarta Validator framework\n" + "|-\n" + "|[[Apache Struts 2 (ex. WebWork)]]\n" + "| Java\n" + "| {{Yes}}\n" + "| \n" + "| Push & Pull\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}, [[Unit testing|Unit Tests]]\n" + "|\n" + "|\n" + "|{{Yes}}\n" + "|\n" + "|{{Yes}}\n" + "|-\n" + "|[[Andromeda Database|Andromeda]]\n" + "| PHP\n" + "|{{Yes}}\n" + "|\n" + "|\n" + "|{{Yes}}\n" + "|{{Yes}}\n" + "|\n" + "|\n" + "|{{Yes}}\n" + "|{{Yes}}\n" + "|\n" + "|{{Yes}}\n" + "|-\n" + "|[[Aranea framework|Aranea MVC]]\n" + "| Java\n" + "| {{Yes}}\n" + "| \n" + "| Pull\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "|\n" + "|\n" + "|\n" + "|\n" + "|\n" + "|\n" + "|-\n" + "|[[CakePHP]]\n" + "| PHP\n" + "| {{Yes}}, [[Prototype JavaScript Framework|Prototype]], [[script.aculo.us]]\n" + "| [[Active record pattern|ActiveRecord]]\n" + "| Push\n" + "| {{Yes}}, Development branch\n" + "| {{Yes}}, [[Active record pattern|ActiveRecord]]\n" + "| {{Yes}}, [[Unit testing|Unit Tests]]\n" + "| {{Yes}}\n" + "| {{Yes}}, [[Access control list|ACL-based]]\n" + "| {{Yes}}\n" + "| {{Yes}}, Development branch\n" + "| {{Yes}}\n" + "|-\n" + "|[[Camping (microframework)|Camping]]\n" + "| Ruby\n" + "| {{No}}\n" + "| {{Yes}}\n" + "| Push\n" + "| {{No}}\n" + "| {{Yes}}, [[Active record pattern|ActiveRecord]]\n" + "| {{Yes}}, via [http://mosquito.rubyforge.org/ Mosquito]\n" + "| {{Yes}}\n" + "| {{No}}\n" + "| {{Yes}}\n" + "| {{No}}\n" + "| {{No}}\n" + "|-\n" + "|[[Catalyst (software)|Catalyst]]\n" + "| Perl\n" + "| {{Yes}}, multiple ([[Prototype JavaScript Framework|Prototype]], [[Dojo Toolkit|Dojo]]...)\n" + "| {{Yes}}\n" + "| Push in its most common usage\n" + "| {{Yes}}\n" + "| {{Yes}}, multiple ([[DBIx::Class]], [[Rose::DB]]...)\n" + "| {{Yes}}<ref name=\"catalysttest\">http://search.cpan.org/dist/Catalyst-Manual/lib/Catalyst/Manual/Tutorial/Testing.pod</ref>\n" + "|\n" + "| {{Yes}}, multiple ([[Access control list|ACL-based]], external engines...)\n" + "| {{Yes}}, multiple (Template::Toolkit, HTML::Template, HTML::Mason...)\n" + "| {{Yes}}, multiple (Memcached, TurckMM, shared memory,...)\n" + "| {{Yes}}, multiple (HTML::FormValidator,...)\n" + "|-\n" + "|[[CodeIgniter]]\n" + "| PHP\n" + "| {{No}}\n" + "| {{Yes}}, Modified [[Active record pattern|ActiveRecord]]\n" + "| Push\n" + "| {{Yes}}\n" + "| {{No}}\n" + "| {{Yes}}, [[Unit testing|Unit Tests]]\n" + "| {{No}}\n" + "| {{Yes}}\n" + "| {{No}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "|-\n" + "|[[ColdBox]]\n" + "| [[ColdFusion]]\n" + "| {{Yes}}, via CF or any JavaScript Library\n" + "| {{Yes}}\n" + "| Push\n" + "| {{Yes}} provided by framework\n" + "| {{Yes}} [[Transfer]], [[Reactor]], [[Hibernate]], ObjectBreeze\n" + "| {{Yes}}, Integrated into Core Framework, [[CFUnit]], [[CFCUnit]]\n" + "| {{No}}\n" + "| {{Yes}}, via plugin or interceptors\n" + "| {{Yes}}\n" + "| {{Yes}}, ColdBox Internal Caching Engine, and via [[ColdSpring]]\n" + "| {{Yes}}, via cf validation or custom interceptors\n" + "|-\n" + "|[[Django (web framework)|Django]]\n" + "| Python\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| Push\n" + "| {{Yes}}\n" + "| {{Yes}}, [[Django ORM]], [[SQLAlchemy]]\n" + "| {{Yes}}\n" + "| {{No}}\n" + "| {{Yes}}, [[Access control list|ACL-based]]\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "|-\n" + "|[[DotNetNuke]]\n" + "| .NET\n" + "| {{Yes}}\n" + "| \n" + "| Pull\n" + "| {{Yes}}\n" + "| {{Yes}}, SubSonic, NHibernate\n" + "|\n" + "|\n" + "|\n" + "|\n" + "|\n" + "|\n" + "|-\n" + "|[[Fusebox (programming)|Fusebox]]\n" + "| [[ColdFusion]], [[PHP]]\n" + "| {{Yes}}\n" + "| {{Yes}}, but not mandatory\n" + "| Push\n" + "| {{No}}, custom\n" + "| {{Yes}}, via lexicons for [http://compoundtheory.com/transfer Transfer] and [http://www.reactorframework.org Reactor]\n" + "| {{Yes}}, [[CFUnit]], [[CFCUnit]]\n" + "|\n" + "| {{Yes}}, multiple plugins available\n" + "|\n" + "| {{Yes}}, via lexicon for [http://coldspringframework.org ColdSpring]\n" + "| {{Yes}}, via qforms or built in cf validation\n" + "|-\n" + "| [http://mdp.cti.depaul.edu/examples Gluon]\n" + "| Python\n" + "| Via third party libraries\n" + "| {{Yes}}\n" + "| Push\n" + "| {{Yes}} provided by framework\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| Via third party wsgi modules\n" + "| {{Yes}}\n" + "|-\n" + "|[[Grails (Framework)|Grails]]\n" + "| [[Groovy (programming language)|Groovy]]\n" + "| {{Yes}}\n" + "| [[Active record pattern|ActiveRecord]]\n" + "| Push\n" + "| {{Yes}}\n" + "| {{Yes}}, GORM, [[Hibernate (Java)|Hibernate]]\n" + "| {{Yes}}, [[Unit Test|Unit Test]]\n" + "| {{No}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "|-\n" + "|[[InterJinn]]\n" + "| PHP\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| Push & Pull\n" + "| {{No}}, custom\n" + "| {{No}}\n" + "|\n" + "|\n" + "|\n" + "| {{Yes}}, TemplateJinn\n" + "| {{Yes}}\n" + "| {{Yes}}, FormJinn\n" + "|-\n" + "|[[JBoss Seam]]\n" + "| Java\n" + "| {{Yes}}\n" + "| \n" + "| Pull\n" + "| {{Yes}}\n" + "| {{Yes}}, [[Java Persistence API|JPA]], [[Hibernate (Java)|Hibernate]]\n" + "| {{Yes}}, [[JUnit]], [[TestNG]]\n" + "|\n" + "| {{Yes}}, [[JAAS]] integration\n" + "| {{Yes}}, [[Facelets]]\n" + "|\n" + "| {{Yes}}, [[Hibernate Validator]]\n" + "|-\n" + "| [[Jifty]]\n" + "| Perl\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| Push\n" + "| {{Yes}}\n" + "| {{Yes}}, [[Jifty::DBI]]\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}, [[Mason (Perl)|Mason]], Template::Declare\n" + "| {{Yes}}, Memcached\n" + "| {{Yes}}\n" + "|-\n" + "|-\n" + "| [[Kumbia]]\n" + "| PHP5\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| x\n" + "| x\n" + "| [[Active record pattern|ActiveRecord]]\n" + "| x\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}, [[Smarty]]\n" + "| {{Yes}}, Memcached\n" + "| {{Yes}}\n" + "|-\n" + "|[[Mach-II]]\n" + "| [[ColdFusion]]\n" + "| {{Yes}}, via CF or any JavaScript Library\n" + "| {{Yes}}\n" + "| Push\n" + "| {{Yes}}, via custom plugin\n" + "| {{Yes}} [[Transfer]], [[Reactor]], [[Hibernate]]\n" + "| {{Yes}}, [[CFUnit]], [[CFCUnit]]\n" + "| \n" + "| {{Yes}}, via plugin\n" + "|\n" + "| {{Yes}}, [[ColdSpring]]\n" + "| \n" + "|-\n" + "|[[Model-Glue::Unity]]\n" + "| [[ColdFusion]]\n" + "| {{Yes}}, via CF or any JavaScript Library\n" + "| {{Yes}}\n" + "| Push\n" + "| {{Yes}}, via custom plugin\n" + "| {{Yes}} [[Transfer]], [[Reactor]], [[Hibernate]]\n" + "| {{Yes}}, [[CFUnit]], [[CFCUnit]]\n" + "|\n" + "| {{Yes}}, via plugin\n" + "| \n" + "| {{Yes}}, [[Coldspring]]\n" + "| {{Yes}}\n" + "|-\n" + "|[[Monorail (.Net)|MonoRail]]\n" + "| .NET\n" + "| {{Yes}}, [[Prototype JavaScript Framework|Prototype]]\n" + "| [[Active record pattern|ActiveRecord]]\n" + "| Push\n" + "| {{Yes}}\n" + "| {{Yes}}, [[Active record pattern|ActiveRecord]]\n" + "| {{Yes}}, [[Unit testing|Unit Tests]]\n" + "|\n" + "| {{Yes}}, via [[ASP.NET]] Forms Authentication\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "|-\n" + "|[[Nitro (web framework)|Nitro]]\n" + "| Ruby\n" + "| {{Yes}}, [[jQuery]]\n" + "| {{Yes}}\n" + "| Push\n" + "| {{Yes}}\n" + "| {{Yes}}, [[Nitro (web framework)#Og|Og]]\n" + "| {{Yes}}, [[RSpec]]\n" + "| {{Yes}} (automatic)\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "|-\n" + "|[[PHPulse]]\n" + "| PHP\n" + "| {{Yes}},\n" + "| {{Yes}},\n" + "| Push\n" + "| {{Yes}},\n" + "| {{Yes}},\n" + "| {{Yes}}, [[Unit Testing|Unit Tests]]\n" + "|\n" + "| {{Yes}}, [[Access control list|ACL-based]]\n" + "| {{Yes}}, [[Smarty]]\n" + "| {{Yes}}, multiple (Memcached, TurckMM, shared memory,...)\n" + "| {{Yes}}\n" + "|-\n" + "|[[PRADO]]\n" + "| PHP5\n" + "| {{Yes}}, [[Active Controls]]\n" + "| {{Yes}}\n" + "| Push\n" + "| {{Yes}}\n" + "| {{Yes}}, [[ActiveRecord]], [[SQLMap]]\n" + "| {{Yes}}, [[PHPUnit]], [[SimpleTest]], [[Selenium]]\n" + "|\n" + "| {{Yes}}, modular and role-based ACL\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "|-\n" + "|[[Pylons (web framework)|Pylons]]\n" + "| Python\n" + "| {{Yes}}, helpers for [[Prototype JavaScript Framework|Prototype]] and [[script.aculo.us]]\n" + "| {{Yes}}\n" + "| Push\n" + "| {{Yes}}\n" + "| {{Yes}}, [[SQLObject]], [[SQLAlchemy]]\n" + "| {{Yes}}, via nose\n" + "|\n" + "|\n" + "| {{Yes}}, pluggable (mako, genshi, mighty, kid, ...)\n" + "| {{Yes}}, Beaker cache (memory, memcached, file, databases)\n" + "| {{Yes}}, preferred formencode\n" + "|-\n" + "| [[Qcodo]]\n" + "| PHP5\n" + "| {{Yes}}, built-in\n" + "| {{Yes}}, QControl\n" + "| Push\n" + "| {{Yes}}\n" + "| {{Yes}}, Code Generation-based\n" + "|\n" + "|\n" + "|\n" + "| {{Yes}}, QForm and QControl\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "|-\n" + "|[[RIFE]]\n" + "| Java\n" + "| {{Yes}}, [[DWR|DWR (Java)]]\n" + "| {{Yes}}\n" + "| Push & Pull\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}, Out of container testing\n" + "| \n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}, [[Terracotta Cluster|Integration with Terracotta]]\n" + "| {{Yes}}\n" + "|-\n" + "|[[Ruby on Rails]]\n" + "| Ruby\n" + "| {{Yes}}, [[Prototype JavaScript Framework|Prototype]], [[script.aculo.us]]\n" + "| [[Active record pattern|ActiveRecord]], [[Ruby on Rails|Action Pack]]\n" + "| Push\n" + "| {{Yes}}, Localization Plug-in\n" + "| {{Yes}}, [[Active record pattern|ActiveRecord]]\n" + "| {{Yes}}, [[Unit testing|Unit Tests]], Functional Tests and Integration Tests\n" + "| {{Yes}}\n" + "| {{Yes}}, Plug-in\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "|-\n" + "|[[Seaside web framework|Seaside]]\n" + "| Smalltalk\n" + "| {{Yes}}, [[Prototype JavaScript Framework|Prototype]], [[script.aculo.us]]\n" + "| \n" + "|\n" + "| {{Yes}}\n" + "| {{Yes}}, [[GLORP]], [[Gemstone Database Management System|Gemstone/S]], ...\n" + "|\n" + "|\n" + "|\n" + "|\n" + "|\n" + "|\n" + "|-\n" + "|[[Stripes]]\n" + "| Java\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| Push\n" + "| {{Yes}}\n" + "| {{Yes}}, [[Hibernate (Java)|Hibernate]]\n" + "| {{Yes}}\n" + "| \n" + "| {{Yes}}, framework extension\n" + "| {{Yes}}\n" + "| \n" + "| {{Yes}}\n" + "|-\n" + "|-\n" + "|[[Symfony]]\n" + "| PHP5\n" + "| {{Yes}}, [[Prototype JavaScript Framework|Prototype]], [[script.aculo.us]], Unobtrusive Ajax with UJS and PJS plugins\n" + "| {{Yes}}\n" + "| Push\n" + "| {{Yes}}\n" + "| {{Yes}}, [[Propel (PHP)|Propel]], [[Doctrine O/RM|Doctrine]]\n" + "| {{Yes}}\n" + "| Plugin exists (alpha code, though)\n" + "| {{Yes}}, plugin\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "|-\n" + "|[[Tigermouse]]\n" + "| PHP5\n" + "| {{Yes}}, it is mostly Ajax-only framework\n" + "| {{Yes}}, [[Active record pattern|ActiveRecord]]\n" + "| Push\n" + "| {{Yes}}\n" + "| {{Yes}}, [[Active record pattern|ActiveRecord]]\n" + "| {{No}}\n" + "| {{No}}, Multiple RBMSes and access libraries supported\n" + "| {{Yes}}, through intercepting filters ([[Access control list|ACL-based]], customizable)\n" + "| {{Yes}}\n" + "| {{No}}\n" + "| {{Yes}}\n" + "|-\n" + "|[[TurboGears]]\n" + "| Python\n" + "| {{Yes}}\n" + "| \n" + "|\n" + "| {{Yes}}\n" + "| {{Yes}}, [[SQLObject]], [[SQLAlchemy]]\n" + "|\n" + "|\n" + "|\n" + "|\n" + "|\n" + "|\n" + "|-\n" + "|[[WebLEAF]]\n" + "| Java\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| Push\n" + "| {{Yes}}\n" + "| {{Yes}} [[Hibernate]], [[EJB]]\n" + "|\n" + "|\n" + "| {{Yes}}, extensible through custom interfaces\n" + "| {{Yes}} [[XSLT]], [[FreeMarker]]\n" + "|\n" + "|\n" + "|-\n" + "|[[WebObjects]]\n" + "| Java\n" + "| {{Yes}}\n" + "| \n" + "|\n" + "| {{Yes}}\n" + "| {{Yes}}, [[Enterprise Objects Framework|EOF]]\n" + "|\n" + "|\n" + "|\n" + "|\n" + "|\n" + "|\n" + "|-\n" + "|[[Zend Framework]]\n" + "| PHP5 (>=5.1.4)\n" + "| {{Yes}}, [[JavaScript library|various libraries]]\n" + "| {{Yes}}\n" + "| Push\n" + "| {{Yes}}\n" + "| {{Yes}}, Table and Row data gateway\n" + "| {{Yes}}, [[Unit testing|Unit Tests]]\n" + "| {{Yes}}\n" + "| {{Yes}}, [[Access control list|ACL-based]]\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "|-\n" + "|[[Zope]]2\n" + "| Python\n" + "|\n" + "| {{Yes}}\n" + "| Pull\n" + "| {{Yes}}\n" + "| {{Yes}}, native OODBMS called [[Zope Object Database|ZODB]], [[SQLObject]], [[SQLAlchemy]]\n" + "| {{Yes}}, [[Unit testing|Unit Tests]]\n" + "| \n" + "| {{Yes}}, [[Access control list|ACL-based]]\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}, CMFFormController\n" + "|-\n" + "|[[Zope]]3\n" + "| Python\n" + "| {{Yes}}, via add-on products, e.g. [[Plone_(software)|Plone]] w/KSS \n" + "| {{Yes}}\n" + "| Pull\n" + "| {{Yes}}\n" + "| {{Yes}}, native OODBMS called [[Zope Object Database|ZODB]], [[SQLObject]], [[SQLAlchemy]]\n" + "| {{Yes}}, [[Unit testing|Unit Tests]], Functional Tests\n" + "| {{Yes}}, ZODB generations\n" + "| {{Yes}}, [[Access control list|ACL-based]]\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "|-class=\"sortbottom\"\n" + "!Project\n" + "!Language\n" + "![[Ajax (programming)|Ajax]]\n" + "![[Model-view-controller|MVC]] framework\n" + "![[Web_application_framework#Push-based_vs._Pull-based|MVC Push/Pull]]\n" + "![[Internationalization_and_localization|i18n & l10n?]]\n" + "![[Object-relational mapping|ORM]]\n" + "!Testing framework(s)\n" + "!DB migration framework(s)\n" + "!Security Framework(s)\n" + "!Template Framework(s)\n" + "!Caching Framework(s)\n" + "!Form Validation Framework(s)\n" + "|}"; Table t = parse(content); System.out.println(t); Row row = t.getRows()[1]; assertEquals(13, row.getCells().length); for (int i = 0; i < row.getCells().length; i++) { assertNull(row.getCells()[i].getOptions()); } assertEquals("[[Agavi_(framework)|Agavi]]", row.getCells()[0].getContent()[0].toString()); assertEquals(" PHP", row.getCells()[1].getContent()[0].toString()); assertEquals(" ", row.getCells()[2].getContent()[0].toString()); assertEquals(" {{Yes}}", row.getCells()[3].getContent()[0].toString()); assertEquals(" Push", row.getCells()[4].getContent()[0].toString()); assertEquals(" {{Yes}}", row.getCells()[5].getContent()[0].toString()); assertEquals(" {{Yes}}", row.getCells()[6].getContent()[0].toString()); assertEquals(" {{Yes}}", row.getCells()[7].getContent()[0].toString()); assertEquals(" {{Yes}}", row.getCells()[8].getContent()[0].toString()); assertEquals(" {{Yes}}", row.getCells()[9].getContent()[0].toString()); assertEquals(" {{Yes}}", row.getCells()[10].getContent()[0].toString()); assertEquals(" {{Yes}}", row.getCells()[11].getContent()[0].toString()); assertEquals(" {{Yes}}", row.getCells()[12].getContent()[0].toString()); } public void testLanguagesTable() throws Exception { String content = "{| class=\"wikitable sortable\"\n" + "|- style=\"background-color: #efefef;\"\n" + "!639-1!!639-2!!639-3!!Language name!!Native name!!comment\n" + "|-\n" + "|aa||aar||aar||[[Afar language|Afar]]||lang=\"aa\"|Afaraf||\n" + "|-\n" + "|ab||abk||abk||[[Abkhaz language|Abkhazian]]||lang=\"ab\"|�?ҧ�?уа||\n" + "|-\n" + "|ae||ave||ave||[[Avestan language|Avestan]]||lang=\"ae\"|avesta||\n" + "|-\n" + "|af||afr||afr||[[Afrikaans]]||lang=\"af\"|Afrikaans||\n" + "|-\n" + "|ak||aka||aka + [[ISO 639:aka|2]]||[[Akan languages|Akan]]||lang=\"ak\"|Akan||\n" + "|-\n" + "|am||amh||amh||[[Amharic language|Amharic]]||lang=\"am\"|አማርኛ||\n" + "|-\n" + "|an||arg||arg||[[Aragonese language|Aragonese]]||lang=\"an\"|Aragonés||\n" + "|-\n" + "|ar||ara||ara + [[ISO 639:ara|30]]||[[Arabic language|Arabic]]||lang=\"ar\" dir=\"rtl\"|‫العربية||Standard Arabic is [arb]\n" + "|-\n" + "|as||asm||asm||[[Assamese language|Assamese]]||lang=\"as\"|অসমীয়া||\n" + "|-\n" + "|av||ava||ava||[[Avar language|Avaric]]||lang=\"av\"|авар мацӀ; магӀарул мацӀ||\n" + "|-\n" + "|ay||aym||aym + [[ISO 639:aym|2]]||[[Aymara language|Aymara]]||lang=\"ay\"|aymar aru||\n" + "|-\n" + "|az||aze||aze + [[ISO 639:aze|2]]||[[Azerbaijani language|Azerbaijani]]||lang=\"az\"|azərbaycan dili||\n" + "|-\n" + "|ba||bak||bak||[[Bashkir language|Bashkir]]||lang=\"ba\"|башҡорт теле||\n" + "|-\n" + "|be||bel||bel||[[Belarusian language|Belarusian]]||lang=\"be\"|Белару�?ка�?||\n" + "|-\n" + "|bg||bul||bul||[[Bulgarian language|Bulgarian]]||lang=\"bg\"|българ�?ки език||\n" + "|-\n" + "|bh||bih||--||[[Bihari languages|Bihari]]||lang=\"bh\"|भोजप�?री||collective language code for Bhojpuri, Magahi, and Maithili\n" + "|-\n" + "|bi||bis||bis||[[Bislama language|Bislama]]||lang=\"bi\"|Bislama||\n" + "|-\n" + "|bm||bam||bam||[[Bambara language|Bambara]]||lang=\"bm\"|bamanankan||\n" + "|-\n" + "|bn||ben||ben||[[Bengali language|Bengali]]||lang=\"bn\"|বাংলা||\n" + "|-\n" + "|bo||tib/bod||bod||[[Tibetan language|Tibetan]]||lang=\"bo\"|བོད་ཡིག||\n" + "|-\n" + "|br||bre||bre||[[Breton language|Breton]]||lang=\"br\"|brezhoneg||\n" + "|-\n" + "|bs||bos||bos||[[Bosnian language|Bosnian]]||lang=\"bs\"|bosanski jezik||\n" + "|-\n" + "|ca||cat||cat||[[Catalan language|Catalan]]||lang=\"ca\"|Català||\n" + "|-\n" + "|ce||che||che||[[Chechen language|Chechen]]||lang=\"ce\"|нохчийн мотт||\n" + "|-\n" + "|ch||cha||cha||[[Chamorro language|Chamorro]]||lang=\"ch\"|Chamoru||\n" + "|-\n" + "|co||cos||cos||[[Corsican language|Corsican]]||lang=\"co\"|corsu; lingua corsa||\n" + "|-\n" + "|cr||cre||cre + [[ISO 639:cre|6]]||[[Cree language|Cree]]||lang=\"cr\"|ᓀ�?��?�ᔭ�??�??�?�||\n" + "|-\n" + "|cs||cze/ces||ces||[[Czech language|Czech]]||lang=\"cs\"|�?esky; �?eština||\n" + "|-\n" + "|cu||chu||chu||[[Old Church Slavonic|Church Slavic]]||||\n" + "|-\n" + "|cv||chv||chv||[[Chuvash language|Chuvash]]||lang=\"cv\"|чӑваш чӗлхи||\n" + "|-\n" + "|cy||wel/cym||cym||[[Welsh language|Welsh]]||lang=\"cy\"|Cymraeg||\n" + "|-\n" + "|da||dan||dan||[[Danish language|Danish]]||lang=\"da\"|dansk||\n" + "|-\n" + "|de||ger/deu||deu||[[German language|German]]||lang=\"de\"|Deutsch||\n" + "|-\n" + "|dv||div||div||[[Dhivehi language|Divehi]]||lang=\"dv\" dir=\"rtl\"|‫ދިވެހި||\n" + "|-\n" + "|dz||dzo||dzo||[[Dzongkha language|Dzongkha]]||lang=\"dz\"|རྫོང་�?||\n" + "|-\n" + "|ee||ewe||ewe||[[Ewe language|Ewe]]||lang=\"ee\"|�?ʋɛgbɛ||\n" + "|-\n" + "|el||gre/ell||ell||[[Greek language|Greek]]||lang=\"el\"|Ελληνικά||\n" + "|-\n" + "|en||eng||eng||[[English language|English]]||lang=\"en\"|English||\n" + "|-\n" + "|eo||epo||epo||[[Esperanto]]||lang=\"eo\"|Esperanto||\n" + "|-\n" + "|es||spa||spa||[[Spanish language|Spanish]]||lang=\"es\"|español; castellano||\n" + "|-\n" + "|et||est||est||[[Estonian language|Estonian]]||lang=\"et\"|Eesti keel||\n" + "|-\n" + "|eu||baq/eus||eus||[[Basque language|Basque]]||lang=\"eu\"|euskara||\n" + "|-\n" + "|fa||per/fas||fas + [[ISO 639:fas|2]]||[[Persian language|Persian]]||lang=\"fa\" dir=\"rtl\"|‫�?ارسی||\n" + "|-\n" + "|ff||ful||ful + [[ISO 639:ful|9]]||[[Fula language|Fulah]]||lang=\"ff\"|Fulfulde||\n" + "|-\n" + "|fi||fin||fin||[[Finnish language|Finnish]]||lang=\"fi\"|suomen kieli||\n" + "|-\n" + "|fj||fij||fij||[[Fijian language|Fijian]]||lang=\"fj\"|vosa Vakaviti||\n" + "|-\n" + "|fo||fao||fao||[[Faroese language|Faroese]]||lang=\"fo\"|Føroyskt||\n" + "|-\n" + "|fr||fre/fra||fra||[[French language|French]]||lang=\"fr\"|français; langue française||\n" + "|-\n" + "|fy||fry||fry + [[ISO 639:fry|3]]||[[West Frisian language|Western Frisian]]||lang=\"fy\"|Frysk||\n" + "|-\n" + "|ga||gle||gle||[[Irish language|Irish]]||lang=\"ga\"|Gaeilge||\n" + "|-\n" + "|gd||gla||gla||[[Scottish Gaelic language|Scottish Gaelic]]||lang=\"gd\"|Gàidhlig||\n" + "|-\n" + "|gl||glg||glg||[[Galician language|Galician]]||lang=\"gl\"|Galego||\n" + "|-\n" + "|gn||grn||grn + [[ISO 639:grn|5]]||[[Guaraní language|Guaraní]]||lang=\"gn\"|Avañe'ẽ||\n" + "|-\n" + "|gu||guj||guj||[[Gujarati language|Gujarati]]||lang=\"gu\"|ગ�?જરાતી||\n" + "|-\n" + "|gv||glv||glv||[[Manx language|Manx]]||lang=\"gv\"|Ghaelg||\n" + "|-\n" + "|ha||hau||hau||[[Hausa language|Hausa]]||lang=\"ha\" dir=\"rtl\"|‫هَو�?سَ||\n" + "|-\n" + "|he||heb||heb||[[Hebrew language|Hebrew]]||lang=\"he\" dir=\"rtl\"|‫עברית||\n" + "|-\n" + "|hi||hin||hin||[[Hindi]]||lang=\"hi\"|हिन�?दी; हिंदी||\n" + "|-\n" + "|ho||hmo||hmo||[[Hiri Motu language|Hiri Motu]]||lang=\"ho\"|Hiri Motu||\n" + "|-\n" + "|hr||scr/hrv||hrv||[[Croatian language|Croatian]]||lang=\"hr\"|Hrvatski||\n" + "|-\n" + "|ht||hat||hat||[[Haitian Creole language|Haitian]]||lang=\"ht\"|Kreyòl ayisyen||\n" + "|-\n" + "|hu||hun||hun||[[Hungarian language|Hungarian]]||lang=\"hu\"|Magyar||\n" + "|-\n" + "|hy||arm/hye||hye||[[Armenian language|Armenian]]||lang=\"hy\"|Հայերեն||\n" + "|-\n" + "|hz||her||her||[[Herero language|Herero]]||lang=\"hz\"|Otjiherero||\n" + "|-\n" + "|ia||ina||ina||[[Interlingua|Interlingua (International Auxiliary Language Association)]]||lang=\"ia\"|interlingua||\n" + "|-\n" + "|id||ind||ind||[[Indonesian language|Indonesian]]||lang=\"id\"|Bahasa Indonesia||\n" + "|-\n" + "|ie||ile||ile||[[Interlingue language|Interlingue]]||lang=\"ie\"|Interlingue||\n" + "|-\n" + "|ig||ibo||ibo||[[Igbo language|Igbo]]||lang=\"ig\"|Igbo||\n" + "|-\n" + "|ii||iii||iii||[[Yi language|Sichuan Yi]]||lang=\"ii\"|ꆇꉙ||\n" + "|-\n" + "|ik||ipk||ipk + [[ISO 639:ipk|2]]||[[Inupiaq language|Inupiaq]]||lang=\"ik\"|Iñupiaq; Iñupiatun||\n" + "|-\n" + "|io||ido||ido||[[Ido]]||lang=\"io\"|Ido||\n" + "|-\n" + "|is||ice/isl||isl||[[Icelandic language|Icelandic]]||lang=\"is\"|�?slenska||\n" + "|-\n" + "|it||ita||ita||[[Italian language|Italian]]||lang=\"it\"|Italiano||\n" + "|-\n" + "|iu||iku||iku + [[ISO 639:iku|2]]||[[Inuktitut]]||lang=\"iu\"|�?�ᓄᒃᑎ�?ᑦ||\n" + "|-\n" + "|ja||jpn||jpn||[[Japanese language|Japanese]]||{{lang|ja-Hani|日本語}} ({{lang|ja-Hira|�?��?�ん�?��?�?��?��?�ん�?�}})||\n" + "|-\n" + "|jv||jav||jav||[[Javanese language|Javanese]]||lang=\"jv\"|basa Jawa||\n" + "|-\n" + "|ka||geo/kat||kat||[[Georgian language|Georgian]]||lang=\"ka\"|ქ�?რთული||\n" + "|-\n" + "|kg||kon||kon + [[ISO 639:kon|3]]||[[Kongo language|Kongo]]||lang=\"kg\"|KiKongo||\n" + "|-\n" + "|ki||kik||kik||[[Gikuyu language|Kikuyu]]||lang=\"ki\"|Gĩkũyũ||\n" + "|-\n" + "|kj||kua||kua||[[Kwanyama|Kwanyama]]||lang=\"kj\"|Kuanyama||\n" + "|-\n" + "|kk||kaz||kaz||[[Kazakh language|Kazakh]]||lang=\"kk\"|Қазақ тілі||\n" + "|-\n" + "|kl||kal||kal||[[Kalaallisut language|Kalaallisut]]||lang=\"kl\"|kalaallisut; kalaallit oqaasii||\n" + "|-\n" + "|km||khm||khm||[[Khmer language|Khmer]]||lang=\"km\"|ភាសា�?្មែរ||\n" + "|-\n" + "|kn||kan||kan||[[Kannada language|Kannada]]||lang=\"kn\"|ಕನ�?ನಡ||\n" + "|-\n" + "|ko||kor||kor||[[Korean language|Korean]]||{{lang|ko-Hang|한국어}} ({{lang|ko-Hani|韓國語}}); {{lang|ko-Hang|조선�?}} ({{lang|ko-Hani|�?鮮語}})<!-- ideograph is used in Korea-->||\n" + "|-\n" + "|kr||kau||kau + [[ISO 639:kau|3]]||[[Kanuri language|Kanuri]]||lang=\"kr\"|Kanuri||\n" + "|-\n" + "|ks||kas||kas||[[Kashmiri language|Kashmiri]]||{{lang|ks-Deva|कश�?मीरी}}; {{rtl-lang|ks-Arb|كشميري}}||\n" + "|-\n" + "|ku||kur||kur + [[ISO 639:kur|3]]||[[Kurdish language|Kurdish]]||{{lang|ku-Latn|Kurdî}}; {{rtl-lang|ku-Arab|كوردی}}||\n" + "|-\n" + "|kv||kom||kom + [[ISO 639:kom|2]]||[[Komi language|Komi]]||lang=\"kv\"|коми кыв||\n" + "|-\n" + "|kw||cor||cor||[[Cornish language|Cornish]]||lang=\"kw\"|Kernewek||\n" + "|-\n" + "|ky||kir||kir||[[Kyrgyz language|Kirghiz]]||lang=\"ky\"|кыргыз тили||\n" + "|-\n" + "|la||lat||lat||[[Latin]]||lang=\"la\"|latine; lingua latina||\n" + "|-\n" + "|lb||ltz||ltz||[[Luxembourgish language|Luxembourgish]]||lang=\"lb\"|Lëtzebuergesch||\n" + "|-\n" + "|lg||lug||lug||[[Luganda language|Ganda]]||lang=\"lg\"|Luganda||\n" + "|-\n" + "|li||lim||lim||[[Limburgish language|Limburgish]]||lang=\"li\"|Limburgs||\n" + "|-\n" + "|ln||lin||lin||[[Lingala language|Lingala]]||lang=\"ln\"|Lingála||\n" + "|-\n" + "|lo||lao||lao||[[Lao language|Lao]]||lang=\"lo\"|ພາສາລາວ||\n" + "|-\n" + "|lt||lit||lit||[[Lithuanian language|Lithuanian]]||lang=\"lt\"|lietuvių kalba||\n" + "|-\n" + "|lu||lub||lub||[[Tshiluba language|Luba-Katanga]]||||\n" + "|-\n" + "|lv||lav||lav||[[Latvian language|Latvian]]||lang=\"lv\"|latviešu valoda||\n" + "|-\n" + "|mg||mlg||mlg + [[ISO 639:mlg|10]]||[[Malagasy language|Malagasy]]||lang=\"mg\"|Malagasy fiteny||\n" + "|-\n" + "|mh||mah||mah||[[Marshallese language|Marshallese]]||lang=\"mh\"|Kajin M̧ajeļ||\n" + "|-\n" + "|mi||mao/mri||mri||[[M�?ori language|M�?ori]]||lang=\"mi\"|te reo M�?ori||\n" + "|-\n" + "|mk /sl ||mac/mkd||mkd||[[Macedonian language|Macedonian]]||lang=\"mk\"|македон�?ки јазик||\n" + "|-\n" + "|ml||mal||mal||[[Malayalam language|Malayalam]]||lang=\"ml\"|മലയാളം||\n" + "|-\n" + "|mn||mon||mon + [[ISO 639:mon|2]]||[[Mongolian language|Mongolian]]||lang=\"mn\"|Монгол||\n" + "|-\n" + "|mo||mol||mol||[[Moldovan language|Moldavian]]||lang=\"mo\"|лимба молдовен�?�?к�?||\n" + "|-\n" + "|mr||mar||mar||[[Marathi language|Marathi]]||lang=\"mr\"|मराठी||\n" + "|-\n" + "|ms||may/msa||msa + [[ISO 639:msa|13]]||[[Malay language|Malay]]||{{lang|ms|bahasa Melayu}}; {{rtl-lang|ms-Arab|بهاس ملايو}} ||Malay (specific) is [mly]\n" + "|-\n" + "|mt||mlt||mlt||[[Maltese language|Maltese]]||lang=\"mt\"|Malti||\n" + "|-\n" + "|my||bur/mya||mya||[[Burmese language|Burmese]]||lang=\"my\"|ဗမာစာ||\n" + "|-\n" + "|na||nau||nau||[[Nauruan language|Nauru]]||lang=\"na\"|Ekakairũ Naoero||\n" + "|-\n" + "|nb||nob||nob||[[Bokmål|Norwegian Bokmål]]||lang=\"nb\"|Norsk bokmål||\n" + "|-\n" + "|nd||nde||nde||[[Northern Ndebele language|North Ndebele]]||lang=\"nd\"|isiNdebele||\n" + "|-\n" + "|ne||nep||nep||[[Nepali language|Nepali]]||lang=\"ne\"|नेपाली||\n" + "|-\n" + "|ng||ndo||ndo||[[Ndonga]]||lang=\"ng\"|Owambo||\n" + "|-\n" + "|nl||dut/nld||nld||[[Dutch language|Dutch]]||lang=\"nl\"|Nederlands||\n" + "|-\n" + "|nn||nno||nno||[[Nynorsk|Norwegian Nynorsk]]||lang=\"nn\"|Norsk nynorsk||\n" + "|-\n" + "|no||nor||nor + [[ISO 639:nor|2]]||[[Norwegian language|Norwegian]]||lang=\"no\"|Norsk||\n" + "|-\n" + "|nr||nbl||nbl||[[Southern Ndebele language|South Ndebele]]||lang=\"nr\"|Ndébélé||\n" + "|-\n" + "|nv||nav||nav||[[Navajo language|Navajo]]||lang=\"nv\"|Diné bizaad; Dinékʼehǰí||\n" + "|-\n" + "|ny||nya||nya||[[Chichewa language|Chichewa]]||lang=\"ny\"|chiCheŵa; chinyanja||\n" + "|-\n" + "|oc||oci||oci + [[ISO 639:oci|5]]||[[Occitan language|Occitan]]||lang=\"oc\"|Occitan||\n" + "|-\n" + "|oj||oji||oji + [[ISO 639:oji|7]]||[[Anishinaabe language|Ojibwa]]||lang=\"oj\"|�?�ᓂᔑᓈ�?�ᒧ�?��?||\n" + "|-\n" + "|om||orm||orm + [[ISO 639:orm|4]]||[[Oromo language|Oromo]]||lang=\"om\"|Afaan Oromoo||\n" + "|-\n" + "|or||ori||ori||[[Oriya language|Oriya]]||lang=\"or\"|ଓଡ଼ିଆ||\n" + "|-\n" + "|os||oss||oss||[[Ossetic language|Ossetian]]||lang=\"os\"|Ирон æвзаг||\n" + "|-\n" + "|pa||pan||pan||[[Punjabi language|Panjabi]]||{{lang|pa|ਪੰਜਾਬੀ}}; {{rtl-lang|pa-Arab|پنجابی}}||\n" + "|-\n" + "|pi||pli||pli||[[P�?li language|P�?li]]||lang=\"pi\"|पािऴ||\n" + "|-\n" + "|pl||pol||pol||[[Polish language|Polish]]||lang=\"pl\"|polski||\n" + "|-\n" + "|ps||pus||pus + [[ISO 639:pus|3]]||[[Pashto language|Pashto]]||lang=\"ps\" dir=\"rtl\"|‫پښتو||\n" + "|-\n" + "|pt||por||por||[[Portuguese language|Portuguese]]||lang=\"pt\"|Português||\n" + "|-\n" + "|qu||que||que + [[ISO 639:que|44]]||[[Quechua]]||lang=\"qu\"|Runa Simi; Kichwa||\n" + "|-\n" + "|rm||roh||roh||[[Romansh|Raeto-Romance]]||lang=\"rm\"|rumantsch grischun||\n" + "|-\n" + "|rn||run||run||[[Kirundi language|Kirundi]]||lang=\"rn\"|kiRundi||\n" + "|-\n" + "|ro||rum/ron||ron||[[Romanian language|Romanian]]||lang=\"ro\"|română||\n" + "|-\n" + "|ru||rus||rus||[[Russian language|Russian]]||lang=\"ru\"|ру�?�?кий �?зык||\n" + "|-\n" + "|rw||kin||kin||[[Kinyarwanda language|Kinyarwanda]]||lang=\"rw\"|Kinyarwanda||\n" + "|-\n" + "|ry||sla/rue||rue||[[Rusyn language|Rusyn]]||lang=\"ry\"|ру�?ин�?ькый �?зык||\n" + "|-\n" + "|sa||san||san||[[Sanskrit]]||lang=\"sa\"|संस�?कृतम�?||\n" + "|-\n" + "|sc||srd||srd + [[ISO 639:srd|4]]||[[Sardinian language|Sardinian]]||lang=\"sc\"|sardu||\n" + "|-\n" + "|sd||snd||snd||[[Sindhi language|Sindhi]]||{{lang|sd-Deva|सिन�?धी}}; {{rtl-lang|sd-Arab|‫سنڌي، سندھی}}||\n" + "|-\n" + "|se||sme||sme||[[Northern Sami]]||lang=\"se\"|Davvisámegiella||\n" + "|-\n" + "|sg||sag||sag||[[Sango language|Sango]]||lang=\"sg\"|yângâ tî sängö||\n" + "|-\n" + "|sh||--||hbs + [[ISO 639:hbs|3]]||[[Serbo-Croatian]]||lang=\"sh\"|Srpskohrvatski/Срп�?кохрват�?ки||\n" + "|-\n" + "|si||sin||sin||[[Sinhalese language|Sinhalese]]||lang=\"si\"|සිංහල||\n" + "|-\n" + "|sk||slo/slk||slk||[[Slovak language|Slovak]]||lang=\"sk\"|sloven�?ina||\n" + "|-\n" + "|sl||slv||slv||[[Slovenian language|Slovenian]]||lang=\"sl\"|slovenš�?ina||\n" + "|-\n" + "|sm||smo||smo||[[Samoan language|Samoan]]||lang=\"sm\"|gagana fa'a Samoa||\n" + "|-\n" + "|sn||sna||sna||[[Shona language|Shona]]||lang=\"sn\"|chiShona||\n" + "|-\n" + "|so||som||som||[[Somali language|Somali]]||lang=\"so\"|Soomaaliga; af Soomaali||\n" + "|-\n" + "|sq||alb/sqi||sqi + [[ISO 639:sqi|4]]||[[Albanian language|Albanian]]||lang=\"sq\"|Shqip||\n" + "|-\n" + "|sr||scc/srp||srp||[[Serbian language|Serbian]]||lang=\"sr\"|�?рп�?ки језик||\n" + "|-\n" + "|ss||ssw||ssw||[[Swati language|Swati]]||lang=\"ss\"|SiSwati||\n" + "|-\n" + "|st||sot||sot||[[Sotho language|Sotho]]||lang=\"st\"|seSotho||\n" + "|-\n" + "|su||sun||sun||[[Sundanese language|Sundanese]]||lang=\"su\"|Basa Sunda||\n" + "|-\n" + "|sv||swe||swe||[[Swedish language|Swedish]]||lang=\"sv\"|Svenska||\n" + "|-\n" + "|sw||swa||swa + [[ISO 639:swa|2]]||[[Swahili language|Swahili]]||lang=\"sw\"|Kiswahili||\n" + "|-\n" + "|ta||tam||tam||[[Tamil language|Tamil]]||lang=\"ta\"|தமிழ�?||\n" + "|-\n" + "|te||tel||tel||[[Telugu language|Telugu]]||lang=\"te\"|తెల�?గ�?||\n" + "|-\n" + "|tg||tgk||tgk||[[Tajik language|Tajik]]||{{lang|tg-Cyrl|тоҷикӣ}}; {{lang|tg-Latn|toğikī}}; {{rtl-lang|tg-Arab|‫تاجیکی}}||\n" + "|-\n" + "|th||tha||tha||[[Thai language|Thai]]||lang=\"th\"|ไทย||\n" + "|-\n" + "|ti||tir||tir||[[Tigrinya language|Tigrinya]]||lang=\"ti\"|ት�?ርኛ||\n" + "|-\n" + "|tk||tuk||tuk||[[Turkmen language|Turkmen]]||lang=\"tk\"|Türkmen; Түркмен||\n" + "|-\n" + "|tl||tgl||tgl||[[Tagalog language|Tagalog]]||lang=\"tl\"|Tagalog||\n" + "|-\n" + "|tn||tsn||tsn||[[Tswana language|Tswana]]||lang=\"tn\"|seTswana||\n" + "|-\n" + "|to||ton||ton||[[Tongan language|Tonga]]||lang=\"to\"|faka Tonga||\n" + "|-\n" + "|tr||tur||tur||[[Turkish language|Turkish]]||lang=\"tr\"|Türkçe||\n" + "|-\n" + "|ts||tso||tso||[[Tsonga language|Tsonga]]||lang=\"ts\"|xiTsonga||\n" + "|-\n" + "|tt||tat||tat||[[Tatar language|Tatar]]||{{lang|tt-Cyrl|татарча}}; {{lang|tt-Latn|tatarça}}; {{rtl-lang|tt-Arab|‫تاتارچا}}||\n" + "|-\n" + "|tw||twi||twi||[[Twi]]||lang=\"tw\"|Twi||\n" + "|-\n" + "|ty||tah||tah||[[Tahitian language|Tahitian]]||lang=\"ty\"|Reo M�?`ohi||\n" + "|-\n" + "|ug||uig||uig||[[Uyghur language|Uighur]]||{{lang|ug-Latn|Uyƣurqə}}; {{rtl-lang|ug-Arab|‫ئۇيغۇرچ }}||\n" + "|-\n" + "|uk||ukr||ukr||[[Ukrainian language|Ukrainian]]||lang=\"uk\"|Україн�?ька||\n" + "|-\n" + "|ur||urd||urd||[[Urdu]]||lang=\"ur\" dir=\"rtl\"|‫اردو||\n" + "|-\n" + "|uz||uzb||uzb + [[ISO 639:uzb|2]]||[[Uzbek language|Uzbek]]|||{{lang|uz-Latn|O'zbek}}; {{lang|uz-Cyrl|Ўзбек}}; {{rtl-lang|uz-Arab|أۇزب�?ك}}||\n" + "|-\n" + "|ve||ven||ven||[[Venda language|Venda]]||lang=\"ve\"|tshiVenḓa||\n" + "|-\n" + "|vi||vie||vie||[[Vietnamese language|Vietnamese]]||lang=\"vi\"|Tiếng Việt||\n" + "|-\n" + "|vo||vol||vol||[[Volapük]]||lang=\"vo\"|Volapük||\n" + "|-\n" + "|wa||wln||wln||[[Walloon language|Walloon]]||lang=\"wa\"|Walon||\n" + "|-\n" + "|wo||wol||wol||[[Wolof language|Wolof]]||lang=\"wo\"|Wollof||\n" + "|-\n" + "|xh||xho||xho||[[Xhosa language|Xhosa]]||lang=\"xh\"|isiXhosa||\n" + "|-\n" + "|yi||yid||yid + [[ISO 639:yid|2]]||[[Yiddish language|Yiddish]]||lang=\"yi\" dir=\"rtl\"|‫ייִדיש||\n" + "|-\n" + "|yo||yor||yor||[[Yoruba language|Yoruba]]||lang=\"yo\"|Yorùbá||\n" + "|-\n" + "|za||zha||zha + [[ISO 639:zha|2]]||[[Zhuang language|Zhuang]]||lang=\"za\"|Saɯ cueŋƅ; Saw cuengh||\n" + "|-\n" + "|zh||chi/zho||zho + [[ISO 639:zho|13]]||[[Chinese language|Chinese]]|||{{lang|zh-Hani|中文}}, {{lang|zh-Hans|汉语}}, {{lang|zh-Hant|漢語}}||\n" + "|-\n" + "|zu||zul||zul||[[Zulu language|Zulu]]||lang=\"zu\"|isiZulu||\n" + "|}"; Table t = parse(content); System.out.println(t); Row row1 = t.getRows()[t.getRows().length - 1]; assertEquals(6, row1.getCells().length); assertEquals("zu", row1.getCells()[0].getContent()[0].toString()); assertEquals("zul", row1.getCells()[1].getContent()[0].toString()); assertEquals("zul", row1.getCells()[2].getContent()[0].toString()); assertEquals("[[Zulu language|Zulu]]", row1.getCells()[3].getContent()[0].toString()); assertEquals("isiZulu", row1.getCells()[4].getContent()[0].toString()); Row row2 = t.getRows()[6]; assertEquals(6, row2.getCells().length); assertEquals("[[Amharic language|Amharic]]", row2.getCells()[3].getContent()[0].toString()); } public void testLengthUnitsTable() throws Exception { String content = "{| class=\"wikitable\"\n" + "|+ [[Length]], l\n" + "|-----\n" + "!Name of unit\n" + "!Symbol\n" + "!Definition\n" + "!Relation to [[SI]] units\n" + "|-----\n" + "| [[ångström]] || Å\n" + "|\n" + "| ≡ 1{{e|−10}} m = 0.1 nm\n" + "|-----\n" + "| [[astronomical unit]] || AU\n" + "| Mean distance from Earth to the Sun\n" + "| = 149 597 870.691 ± 0.030 km\n" + "|-----\n" + "| [[atomic units|atomic unit of length]] || au{{Fact|date=August 2007}}\n" + "| ≡ a<sub>0</sub>\n" + "| ≈ 5.291 772 083{{e|−11}} ± 19{{e|−20}} m\n" + "|-----\n" + "| barley corn || &nbsp;\n" + "| ≡ 1/3 in\n" + "| ≈ 8.466 667 mm\n" + "|-----\n" + "| [[Bohr radius]] || a<sub>0</sub>; b\n" + "| ≡ [[fine structure constant|α]]/(4π[[Rydberg constant|''R''<sub>∞</sub>]])\n" + "| ≈ 5.291 772 083{{e|−11}} ± 19{{e|−20}} m\n" + "|-----\n" + "| cable length (Imperial) || &nbsp;\n" + "| ≡ 608 ft\n" + "| = 185.3184 m\n" + "|-----\n" + "| [[cable length]] (International) || &nbsp;\n" + "| ≡ 1/10 NM\n" + "| = 185.2 m\n" + "|-----\n" + "| cable length (U.S.) || &nbsp;\n" + "| ≡ 720 ft\n" + "| = 219.456 m\n" + "|-----\n" + "| [[calibre]] || cal\n" + "| ≡ 1 in\n" + "| = 25.4 mm\n" + "|-----\n" + "| [[chain (unit)|chain]] ([[Edmund Gunter|Gunter's]]; Surveyor's) || ch\n" + "| ≡ 66.0 ft (4 rods)\n" + "| = 20.1168 m\n" + "|-----\n" + "| [[chain (unit)|chain]] ([[Jesse Ramsden|Ramsden]]'s<!--- Ramsden: http://www.scienceandsociety.co.uk/results.asp?image=10280167&wwwflag=2&imagepos=6 Ramden: [http://aurora.rg.iupui.edu/~schadow/units/UCUM/ucum.html The Unified Code for Units of Measures] --->; Engineer's) || ch\n" + "| ≡ 100 ft\n" + "| = 30.48 m\n" + "|-----\n" + "| cubit || &nbsp;\n" + "| ≡ 18 in\n" + "| = 0.4572 m\n" + "|-----\n" + "| ell || ell\n" + "| ≡ 45 in\n" + "| = 1.143 m\n" + "|-----\n" + "|rowspan=\"2\"| [[fathom]] ||rowspan=\"2\"| fm\n" + "| ≡ 6 ft\n" + "| = 1.8288 m\n" + "|-\n" + "| ≈ 1/1000 NM\n" + "| = 1.852 m\n" + "|-----\n" + "| [[Femtometre|fermi]] || fm\n" + "| ≡ 1{{e|−15}} m\n" + "| = 1{{e|−15}} m\n" + "|-----\n" + "| finger || &nbsp;\n" + "| ≡ 7/8 in\n" + "| = 22.225 mm\n" + "|-----\n" + "| finger (cloth) || &nbsp;\n" + "| ≡ 4 ½ in\n" + "| = 0.1143 m\n" + "|-----\n" + "| [[foot (unit of length)|foot]] (Benoît) || ft (Ben)\n" + "|\n" + "| ≈ 0.304 799 735 m\n" + "|-----\n" + "| [[foot (unit of length)|foot]] (Clarke's; Cape) || ft (Cla)\n" + "|\n" + "| ≈ 0.304 797 265 4 m\n" + "|-----\n" + "| [[foot (unit of length)|foot]] (Indian) || ft Ind\n" + "|\n" + "| ≈ 0.304 799 514 m\n" + "|-----\n" + "| [[foot (unit of length)|foot]] (International) || ft\n" + "| ≡ 1/3 yd\n" + "| = 0.3048 m\n" + "|-----\n" + "| [[foot (unit of length)|foot]] (Sear's) || ft (Sear)\n" + "|\n" + "| ≈ 0.304 799 47 m\n" + "|-----\n" + "| [[foot (unit of length)|foot]] (U.S. Survey) || ft (US)\n" + "| ≡ 1200/3937 m <ref name=nbs>National Bureau of Standards. (June 30, 1959). ''Refinement of values for the yard and the pound''. Federal Register, viewed September 20, 2006 at [http://www.ngs.noaa.gov/PUBS_LIB/FedRegister/FRdoc59-5442.pdf National Geodetic Survey web site].</ref>\n" + "| ≈ 0.304 800 610 m\n" + "|-----\n" + "| [[furlong]] || fur\n" + "| ≡ 660 ft (10 chains)\n" + "| = 201.168 m\n" + "|-----\n" + "| [[geographical mile]] || mi\n" + "| ≡ 6082 ft\n" + "| = 1853.7936 m\n" + "|-----\n" + "| hand || &nbsp;\n" + "| ≡ 4 in\n" + "| = 0.1016 m\n" + "|-----\n" + "| [[inch]] || in\n" + "| ≡ 1/36 yd\n" + "| = 25.4 mm\n" + "|-----\n" + "| [[league (unit)|league]] || lea\n" + "| ≡ 3 mi\n" + "| = 4828.032 m\n" + "|-----\n" + "| [[light-day]] || &nbsp;\n" + "| ≡ 24 light-hours\n" + "| = 2.590 206 837 12{{e|13}} m\n" + "|-----\n" + "| [[light-hour]] || &nbsp;\n" + "| ≡ 60 light-minutes\n" + "| = 1.079 252 848 8{{e|12}} m\n" + "|-----\n" + "| [[light-minute]] || &nbsp;\n" + "| ≡ 60 light-seconds\n" + "| = 1.798 754 748{{e|10}} m\n" + "|-----\n" + "| [[light second|light-second]] || &nbsp;\n" + "|\n" + "| ≡ 2.997 924 58{{e|8}} m\n" + "|-----\n" + "| [[light year|light-year]] || l.y.\n" + "| ≡ ''c''<sub>0</sub> × 86 400 × 365.25\n" + "| = 9.460 730 472 580 8{{e|15}} m\n" + "|-----\n" + "| line || ln\n" + "| ≡ 1/12 in (Klein 1988, 63)\n" + "| ≈ 2.116 667 mm\n" + "|-----\n" + "| link (Gunter's; Surveyor's) || lnk\n" + "| ≡ 1/100 ch\n" + "| = 0.201 168 m\n" + "|-----\n" + "| link (Ramsden's; Engineer's) || lnk\n" + "| ≡ 1 ft\n" + "| = 0.3048 m\n" + "|-----\n" + "| [[metre]] ([[SI base unit]]) || m\n" + "| ≡ 1 m\n" + "| = 1 m\n" + "|-----\n" + "| mickey || &nbsp;\n" + "| ≡ 1/200 in\n" + "| = 1.27{{e|−4}} m\n" + "|-----\n" + "| [[micrometre|micron]]|| µ\n" + "|\n" + "| ≡ 1.000{{e|−6}} m\n" + "|-----\n" + "| [[thou (unit of length)|mil]]; thou || mil\n" + "| ≡ 1.000{{e|−3}} in\n" + "| = 2.54{{e|−5}} m\n" + "|-----\n" + "| [[Norwegian/Swedish mil|mil]] (Sweden and Norway) || mil\n" + "| ≡ 10 km\n" + "| = 10000 m\n" + "|-----\n" + "| [[mile]] || mi\n" + "| ≡ 1760 yd = 5280 ft\n" + "| = 1609.344 m\n" + "|-----\n" + "| [[mile]] (U.S. Survey) || mi\n" + "| ≡ 5280 ft (US)\n" + "| = 5280 × 1200/3937 m ≈ 1609.347 219 m\n" + "|-----\n" + "| nail (cloth) || &nbsp;\n" + "| ≡ 2 ¼ in\n" + "| = 57.15 mm\n" + "|-----\n" + "| nautical league || NL; nl\n" + "| ≡ 3 NM\n" + "| = 5556 m\n" + "|-----\n" + "| [[nautical mile]] || NM; nmi\n" + "| ≡ 1852 m\n" + "| ≡ 1852 m\n" + "|-----\n" + "| [[nautical mile]] (Admiralty) || NM (Adm); nmi (Adm)\n" + "| ≡ 6080 ft\n" + "| = 1853.184 m\n" + "|-----\n" + "| pace || &nbsp;\n" + "| ≡ 2.5 ft\n" + "| = 0.762 m\n" + "|-----\n" + "| palm || &nbsp;\n" + "| ≡ 3 in\n" + "| = 76.2 mm\n" + "|-----\n" + "| [[parsec]] || pc\n" + "| ≈ 180 × 60 × 60/π AU<br>\n" + "= 206264.8062 AU<br>\n" + "= 3.26156378 light-years\n" + "| = 3.08567782 {{e|16}} ± 6{{e|6}} m <ref name=Seidelmann>P. Kenneth Seidelmann, Ed. (1992). ''Explanatory Supplement to the Astronomical Almanac.'' Sausalito, CA: University Science Books. p. 716 and s.v. parsec in Glossary.</ref>\n" + "|-----\n" + "| point ([[American Typefounders Association|ATA]]) || pt\n" + "| ≡ 0.013837 in\n" + "| = 0.351 459 8 mm\n" + "|-----\n" + "| point (Didot; European) || pt\n" + "|\n" + "| ≡ 0.376 065 mm\n" + "|-----\n" + "| point (metric) || pt\n" + "| ≡ 3/8 mm\n" + "| = 0.375 mm\n" + "|-----\n" + "| point ([[PostScript]])|| pt\n" + "| ≡ 1/72 in\n" + "| ≈ 0.352 778 mm\n" + "|-----\n" + "| quarter || &nbsp;\n" + "| ≡ ¼ yd\n" + "| = 0.2286 m\n" + "|-----\n" + "| [[rod (unit)|rod]]; pole; perch || rd\n" + "| ≡ 16 ½ ft\n" + "| = 5.0292 m\n" + "|-----\n" + "| rope || rope\n" + "| ≡ 20 ft\n" + "| = 6.096 m\n" + "|-----\n" + "| span || &nbsp;\n" + "| ≡ 6 in\n" + "| = 0.1524 m\n" + "|-----\n" + "| span (cloth) || &nbsp;\n" + "| ≡ 9 in\n" + "| = 0.2286 m\n" + "|-----\n" + "| spat[http://www.unc.edu/~rowlett/units/dictS.html] ||\n" + "| ≡ 10<sup>12</sup> m\n" + "| = 1 Tm\n" + "|-----\n" + "| stick || &nbsp;\n" + "| ≡ 2 in\n" + "| = 50.8 mm\n" + "|-----\n" + "| [[stigma (unit)|stigma]]; pm|| &nbsp;\n" + "| ≡ 1.000{{e|−12}} m\n" + "| ≡ 1.000{{e|−12}} m\n" + "|-----\n" + "| telegraph [[mile]] || mi\n" + "| ≡ 6087 ft\n" + "| = 1855.3176 m\n" + "|-----\n" + "| [[twip]] || twp\n" + "| ≡ 1/1440 in\n" + "| ≈ 1.763 889{{e|−5}} m\n" + "|-----\n" + "| [[x unit]]; [[siegbahn]] || xu\n" + "|\n" + "| ≈ 1.0021{{e|−13}} m\n" + "|-----\n" + "| [[yard]] (International) || yd\n" + "| ≡3 ft ≡ 0.9144 m <ref name=nbs/>\n" + "| = 0.9144 m\n" + "|}"; Table t = parse(content); } public void testTableInternetTLDs() throws Exception { String content = "{| class=\"wikitable\"\n" + "|- style=\"background-color: #a0d0ff;\"\n" + "!iTLD!!Entity!!Notes\n" + "|-\n" + "\n" + "| [[.arpa]] || Address and Routing Parameter Area || This is an internet infrastructure TLD.\n" + "|-\n" + "| [[.root]] || N/A|| Diagnostic marker to indicate a root zone load was not truncated.\n" + "|- style=\"background-color: #a0d0ff;\"\n" + "![[gTLD]]!!Entity!!Notes\n" + "|-\n" + "| [[.aero]] || air-transport industry || Must verify eligibility for registration; only those in various categories of air-travel-related entities may register.\n" + "|-\n" + "| [[.asia]] || Asia-Pacific region || This is a TLD for companies, organizations, and individuals based in the region of Asia, Australia, and the Pacific.\n" + "|-\n" + "| [[.biz]] || business || This is an open TLD; any person or entity is permitted to register; however, registrations may be challenged later if they are not by commercial entities in accordance with the domain's charter.\n" + "|-\n" + "| [[.cat]] || Catalan || This is a TLD for websites in the [[Catalan language]] or related to Catalan culture.\n" + "|-\n" + "| [[.com]] || commercial || This is an open TLD; any person or entity is permitted to register.\n" + "|-\n" + "| [[.coop]] || cooperatives || The .coop TLD is limited to cooperatives as defined by the [[Rochdale Principles]].\n" + "|-\n" + "| [[.edu]] || educational || The .edu TLD is limited to institutions of learning (mostly U.S.), such as 2 and 4-year colleges and universities.\n" + "|-\n" + "| [[.gov]] || governmental || The .gov TLD is limited to U.S. governmental entities and agencies (commonly [[U.S. Federal Government | federal-level]]).\n" + "|-\n" + "| [[.info]] || information || This is an open TLD; any person or entity is permitted to register.\n" + "|-\n" + "| [[.int]] || international organizations || The .int TLD is strictly limited to organizations, offices, and programs which are endorsed by a treaty between two or more nations.\n" + "|-\n" + "| [[.jobs]] || companies || The .jobs TLD is designed to be added after the names of established companies with jobs to advertise. At this time, owners of a \"company.jobs\" domain are not permitted to post jobs of third party employers.\n" + "|-\n" + "| [[.mil]] || [[Military of the United States|United States Military]] || The .mil TLD is limited to use by the U.S. military.\n" + "|-\n" + "| [[.mobi]] || mobile devices || Must be used for mobile-compatible sites in accordance with standards.\n" + "|-\n" + "| [[.museum]] || museums || Must be verified as a legitimate museum.\n" + "|-\n" + "| [[.name]] || individuals, by name || This is an open TLD; any person or entity is permitted to register; however, registrations may be challenged later if they are not by individuals (or the owners of fictional characters) in accordance with the domain's charter\n" + "|-\n" + "| [[.net]] || network || This is an open TLD; any person or entity is permitted to register.\n" + "|-\n" + "| [[.org]] || organization || This is an open TLD; any person or entity is permitted to register.\n" + "|-\n" + "| [[.pro]] || professions || Currently, .pro is reserved for licensed doctors, attorneys, and certified public accountants only. A professional seeking to register a .pro domain must provide their registrar with the appropriate credentials.\n" + "|-\n" + "| [[.tel]] || Internet communication services ||\n" + "|-\n" + "| [[.travel]] || travel and travel-agency related sites || Must be verified as a legitimate travel-related entity.\n" + "|-\n" + "<!--\n" + "|-\n" + "| [[.xxx]] || [[Pornography|Pornographic]] websites || &nbsp;\n" + "ICANN has approved this TLD in principle, but it has not been added to the root yet.\n" + "-->\n" + "|- style=\"background-color: #a0d0ff;\"\n" + "![[ccTLD]]!!Country/dependency/region!!Notes\n" + "|-\n" + "| [[.ac]] || [[Ascension Island]] || &nbsp;\n" + "|-\n" + "| [[.ad]] || [[Andorra]] || &nbsp;\n" + "|-\n" + "| [[.ae]] || [[United Arab Emirates]] || &nbsp;\n" + "|-\n" + "| [[.af]] || [[Afghanistan]] || &nbsp;\n" + "|-\n" + "| [[.ag]] || [[Antigua and Barbuda]] || &nbsp;\n" + "|-\n" + "| [[.ai]] || [[Anguilla]] || &nbsp;\n" + "|-\n" + "| [[.al]] || [[Albania]] || &nbsp;\n" + "|-\n" + "| [[.am]] || [[Armenia]] || &nbsp;\n" + "|-\n" + "| [[.an]] || [[Netherlands Antilles]] || &nbsp;\n" + "|-\n" + "| [[.ao]] || [[Angola]] || &nbsp;\n" + "|-\n" + "| [[.aq]] || [[Antarctica]] || Defined as per the [[Antarctic Treaty System|Antarctic Treaty]] as everything south of latitude 60°S\n" + "|-\n" + "| [[.ar]] || [[Argentina]] || &nbsp;\n" + "|-\n" + "| [[.as]] || [[American Samoa]] || &nbsp;\n" + "|-\n" + "| [[.at]] || [[Austria]] || &nbsp;\n" + "|-\n" + "| [[.au]] || [[Australia]] || Includes [[Ashmore and Cartier Islands]] and [[Coral Sea Islands]]\n" + "|-\n" + "| [[.aw]] || [[Aruba]] || &nbsp;\n" + "|-\n" + "| [[.ax]] || [[Åland]] || &nbsp;\n" + "|-\n" + "| [[.az]] || [[Azerbaijan]] || &nbsp;\n" + "|-\n" + "| [[.ba]] || [[Bosnia and Herzegovina]] || &nbsp;\n" + "|-\n" + "| [[.bb]] || [[Barbados]] || &nbsp;\n" + "|-\n" + "| [[.bd]] || [[Bangladesh]] || &nbsp;\n" + "|-\n" + "| [[.be]] || [[Belgium]] || &nbsp;\n" + "|-\n" + "| [[.bf]] || [[Burkina Faso]] || &nbsp;\n" + "|-\n" + "| [[.bg]] || [[Bulgaria]] || &nbsp;\n" + "|-\n" + "| [[.bh]] || [[Bahrain]] || &nbsp;\n" + "|-\n" + "| [[.bi]] || [[Burundi]] || &nbsp;\n" + "|-\n" + "| [[.bj]] || [[Benin]] || &nbsp;\n" + "|-\n" + "| [[.bm]] || [[Bermuda]] || &nbsp;\n" + "|-\n" + "| [[.bn]] || [[Brunei|Brunei Darussalam]] || &nbsp;\n" + "|-\n" + "| [[.bo]] || [[Bolivia]] || &nbsp;\n" + "|-\n" + "| [[.br]] || [[Brazil]] || &nbsp;\n" + "|-\n" + "| [[.bs]] || [[Bahamas]] || &nbsp;\n" + "|-\n" + "| [[.bt]] || [[Bhutan]] || &nbsp;\n" + "|-\n" + "| [[.bv]] || [[Bouvet Island]] || Not in use (Norwegian dependency; see .no)\n" + "|-\n" + "| [[.bw]] || [[Botswana]] || &nbsp;\n" + "|-\n" + "| [[.by]] || [[Belarus]] || &nbsp;\n" + "|-\n" + "| [[.bz]] || [[Belize]] || &nbsp;\n" + "|-\n" + "| [[.ca]] || [[Canada]] || Subject to Canadian Presence Requirements, see [[.ca]]\n" + "|-\n" + "| [[.cc]] || [[Cocos Islands|Cocos (Keeling) Islands]] || &nbsp;\n" + "|-\n" + "| [[.cd]] || [[Democratic Republic of the Congo]] || Formerly [[Zaire]]\n" + "|-\n" + "| [[.cf]] || [[Central African Republic]] || &nbsp;\n" + "|-\n" + "| [[.cg]] || [[Republic of the Congo]] || &nbsp;\n" + "|-\n" + "| [[.ch]] || [[Switzerland]] (Confoederatio Helvetica) || &nbsp;\n" + "|-\n" + "| [[.ci]] || [[Côte d'Ivoire]] || &nbsp;\n" + "|-\n" + "| [[.ck]] || [[Cook Islands]] || &nbsp;\n" + "|-\n" + "| [[.cl]] || [[Chile]] || &nbsp;\n" + "|-\n" + "| [[.cm]] || [[Cameroon]] || &nbsp;\n" + "|-\n" + "| [[.cn]] || [[People's Republic of China|China, mainland]] || [[Mainland China]] only: [[Hong Kong]], [[Macau]] and [[Taiwan]] use separate TLDs.\n" + "|-\n" + "| [[.co]] || [[Colombia]] || &nbsp;\n" + "|-\n" + "| [[.cr]] || [[Costa Rica]] || &nbsp;\n" + "|-\n" + "| [[.cu]] || [[Cuba]] || &nbsp;\n" + "|-\n" + "| [[.cv]] || [[Cape Verde]] || &nbsp;\n" + "|-\n" + "| [[.cx]] || [[Christmas Island]] || &nbsp;\n" + "|-\n" + "| [[.cy]] || [[Cyprus]] || &nbsp;\n" + "|-\n" + "| [[.cz]] || [[Czech Republic]] || &nbsp;\n" + "|-\n" + "| [[.de]] || [[Germany]] (Deutschland) || &nbsp;\n" + "|-\n" + "| [[.dj]] || [[Djibouti]] || &nbsp;\n" + "|-\n" + "| [[.dk]] || [[Denmark]] || &nbsp;\n" + "|-\n" + "| [[.dm]] || [[Dominica]] || &nbsp;\n" + "|-\n" + "| [[.do]] || [[Dominican Republic]] || &nbsp;\n" + "|-\n" + "| [[.dz]] || [[Algeria]] (Dzayer) || Not available for private use\n" + "|-\n" + "| [[.ec]] || [[Ecuador]] || &nbsp;\n" + "|-\n" + "| [[.ee]] || [[Estonia]] || &nbsp;\n" + "|-\n" + "| [[.eg]] || [[Egypt]] || &nbsp;\n" + "<!--\n" + "|-\n" + ".eh is reserved for Western Sahara, but does not exist in the root\n" + "| [[.eh]] || [[Western Sahara]] || &nbsp;\n" + "-->\n" + "|-\n" + "| [[.er]] || [[Eritrea]] || &nbsp;\n" + "|-\n" + "| [[.es]] || [[Spain]] (España) || &nbsp;\n" + "|-\n" + "| [[.et]] || [[Ethiopia]] || &nbsp;\n" + "|-\n" + "| [[.eu]] || [[European Union]] || Restricted to companies and individuals in the European Union\n" + "|-\n" + "| [[.fi]] || [[Finland]] || &nbsp;\n" + "|-\n" + "| [[.fj]] || [[Fiji]] || &nbsp;\n" + "|-\n" + "| [[.fk]] || [[Falkland Islands]] || &nbsp;\n" + "|-\n" + "| [[.fm]] || [[Federated States of Micronesia]] || Used for some radio related websites outside Micronesia\n" + "|-\n" + "| [[.fo]] || [[Faroe Islands]] || &nbsp;\n" + "|-\n" + "| [[.fr]] || [[France]] || Can only be used by organisations or persons with a presence in France.\n" + "|-\n" + "| [[.ga]] || [[Gabon]] || &nbsp;\n" + "|-\n" + "| [[.gb]] || [[United Kingdom]] || Seldom used; the primary ccTLD used is [[.uk]] for [[United Kingdom]]\n" + "|-\n" + "| [[.gd]] || [[Grenada]] || &nbsp;\n" + "|-\n" + "| [[.ge]] || [[Georgia (country)|Georgia]] || &nbsp;\n" + "|-\n" + "| [[.gf]] || [[French Guiana]] || &nbsp;\n" + "|-\n" + "| [[.gg]] || [[Guernsey]] || &nbsp;\n" + "|-\n" + "| [[.gh]] || [[Ghana]] || &nbsp;\n" + "|-\n" + "| [[.gi]] || [[Gibraltar]] || &nbsp;\n" + "|-\n" + "| [[.gl]] || [[Greenland]] || &nbsp;\n" + "|-\n" + "| [[.gm]] || [[The Gambia]] || &nbsp;\n" + "|-\n" + "| [[.gn]] || [[Guinea]] || &nbsp;\n" + "|-\n" + "| [[.gp]] || [[Guadeloupe]] || &nbsp;\n" + "|-\n" + "| [[.gq]] || [[Equatorial Guinea]] || &nbsp;\n" + "|-\n" + "| [[.gr]] || [[Greece]] || &nbsp;\n" + "|-\n" + "| [[.gs]] || [[South Georgia and the South Sandwich Islands]] || &nbsp;\n" + "|-\n" + "| [[.gt]] || [[Guatemala]] || &nbsp;\n" + "|-\n" + "| [[.gu]] || [[Guam]] || &nbsp;\n" + "|-\n" + "| [[.gw]] || [[Guinea-Bissau]] || &nbsp;\n" + "|-\n" + "| [[.gy]] || [[Guyana]] || &nbsp;\n" + "|-\n" + "| [[.hk]] || [[Hong Kong]] || [[Special administrative region]] of the [[People's Republic of China]].\n" + "|-\n" + "| [[.hm]] || [[Heard Island and McDonald Islands]] || &nbsp;\n" + "|-\n" + "| [[.hn]] || [[Honduras]] || &nbsp;\n" + "|-\n" + "| [[.hr]] || [[Croatia]] (Hrvatska) || &nbsp;\n" + "|-\n" + "| [[.ht]] || [[Haiti]] || &nbsp;\n" + "|-\n" + "| [[.hu]] || [[Hungary]] || &nbsp;\n" + "|-\n" + "| [[.id]] || [[Indonesia]] || &nbsp;\n" + "|-\n" + "| [[.ie]] || [[Republic of Ireland|Ireland]] (Éire)|| &nbsp;\n" + "|-\n" + "| [[.il]] || [[Israel]] || &nbsp;\n" + "|-\n" + "| [[.im]] || [[Isle of Man]] || &nbsp;\n" + "|-\n" + "| [[.in]] || [[India]] || Under [[INRegistry]] since April 2005 except: gov.in, mil.in, ac.in, edu.in, res.in\n" + "|-\n" + "| [[.io]] || [[British Indian Ocean Territory]] || &nbsp;\n" + "|-\n" + "| [[.iq]] || [[Iraq]] || &nbsp;\n" + "|-\n" + "| [[.ir]] || [[Iran]] || &nbsp;\n" + "|-\n" + "| [[.is]] || [[Iceland]] (�?sland) || &nbsp;\n" + "|-\n" + "| [[.it]] || [[Italy]] || Restricted to companies and individuals in the [[European Union]]\n" + "|-\n" + "| [[.je]] || [[Jersey]] || &nbsp;\n" + "|-\n" + "| [[.jm]] || [[Jamaica]] || &nbsp;\n" + "|-\n" + "| [[.jo]] || [[Jordan]] || &nbsp;\n" + "|-\n" + "| [[.jp]] || [[Japan]] || &nbsp;\n" + "|-\n" + "| [[.ke]] || [[Kenya]] || &nbsp;\n" + "|-\n" + "| [[.kg]] || [[Kyrgyzstan]] || &nbsp;\n" + "|-\n" + "| [[.kh]] || [[Cambodia]] (Khmer) || &nbsp;\n" + "|-\n" + "| [[.ki]] || [[Kiribati]] || &nbsp;\n" + "|-\n" + "| [[.km]] || [[Comoros]] || &nbsp;\n" + "|-\n" + "| [[.kn]] || [[Saint Kitts and Nevis]] || &nbsp;\n" + "|-\n" + "| [[.kp]] || [[North Korea]] || &nbsp;\n" + "|-\n" + "| [[.kr]] || [[South Korea]] || &nbsp;\n" + "|-\n" + "| [[.kw]] || [[Kuwait]] || &nbsp;\n" + "|-\n" + "| [[.ky]] || [[Cayman Islands]] || &nbsp;\n" + "|-\n" + "| [[.kz]] || [[Kazakhstan]] || &nbsp;\n" + "|-\n" + "| [[.la]] || [[Laos]] || Currently being marketed as the official domain for [[Los Angeles]].\n" + "|-\n" + "| [[.lb]] || [[Lebanon]] || &nbsp;\n" + "|-\n" + "| [[.lc]] || [[Saint Lucia]] || &nbsp;\n" + "|-\n" + "| [[.li]] || [[Liechtenstein]] || &nbsp;\n" + "|-\n" + "| [[.lk]] || [[Sri Lanka]] || &nbsp;\n" + "|-\n" + "| [[.lr]] || [[Liberia]] || &nbsp;\n" + "|-\n" + "| [[.ls]] || [[Lesotho]] || &nbsp;\n" + "|-\n" + "| [[.lt]] || [[Lithuania]] || &nbsp;\n" + "|-\n" + "| [[.lu]] || [[Luxembourg]] || &nbsp;\n" + "|-\n" + "| [[.lv]] || [[Latvia]] || &nbsp;\n" + "|-\n" + "| [[.ly]] || [[Libya]] || &nbsp;\n" + "|-\n" + "| [[.ma]] || [[Morocco]] || &nbsp;\n" + "|-\n" + "| [[.mc]] || [[Monaco]] || &nbsp;\n" + "|-\n" + "| [[.md]] || [[Moldova]] || &nbsp;\n" + "|-\n" + "| [[.me]] || [[Montenegro]] || &nbsp;\n" + "|-\n" + "| [[.mg]] || [[Madagascar]] || &nbsp;\n" + "|-\n" + "| [[.mh]] || [[Marshall Islands]] || &nbsp;\n" + "|-\n" + "| [[.mk]] || [[Republic of Macedonia]] || &nbsp;\n" + "|-\n" + "| [[.ml]] || [[Mali]] || &nbsp;\n" + "|-\n" + "| [[.mm]] || [[Myanmar]] || &nbsp;\n" + "|-\n" + "| [[.mn]] || [[Mongolia]] || &nbsp;\n" + "|-\n" + "| [[.mo]] || [[Macau]] || [[Special administrative region]] of the [[People's Republic of China]].\n" + "|-\n" + "| [[.mp]] || [[Northern Mariana Islands]] || &nbsp;\n" + "|-\n" + "| [[.mq]] || [[Martinique]] || &nbsp;\n" + "|-\n" + "| [[.mr]] || [[Mauritania]] || &nbsp;\n" + "|-\n" + "| [[.ms]] || [[Montserrat]] || &nbsp;\n" + "|-\n" + "| [[.mt]] || [[Malta]] || &nbsp;\n" + "|-\n" + "| [[.mu]] || [[Mauritius]] || &nbsp;\n" + "|-\n" + "| [[.mv]] || [[Maldives]] || &nbsp;\n" + "|-\n" + "| [[.mw]] || [[Malawi]] || &nbsp;\n" + "|-\n" + "| [[.mx]] || [[Mexico]] || &nbsp;\n" + "|-\n" + "| [[.my]] || [[Malaysia]] || Must be registered with a company in [[Malaysia]] to register. Currently famous for the literal word '[[my]]'.\n" + "|-\n" + "| [[.mz]] || [[Mozambique]] || &nbsp;\n" + "|-\n" + "| [[.na]] || [[Namibia]] || &nbsp;\n" + "|-\n" + "| [[.nc]] || [[New Caledonia]] || &nbsp;\n" + "|-\n" + "| [[.ne]] || [[Niger]] || &nbsp;\n" + "|-\n" + "| [[.nf]] || [[Norfolk Island]] || &nbsp;\n" + "|-\n" + "| [[.ng]] || [[Nigeria]] || &nbsp;\n" + "|-\n" + "| [[.ni]] || [[Nicaragua]] || &nbsp;\n" + "|-\n" + "| [[.nl]] || [[Netherlands]] || &nbsp;\n" + "|-\n" + "| [[.no]] || [[Norway]] || Must be registered with a company in [[Norway]] to register.\n" + "|-\n" + "| [[.np]] || [[Nepal]] || &nbsp;\n" + "|-\n" + "| [[.nr]] || [[Nauru]] || &nbsp;\n" + "|-\n" + "| [[.nu]] || [[Niue]] || Commonly used for Scandinavian and Dutch websites, because in those languages 'nu' means 'now'.\n" + "|-\n" + "| [[.nz]] || [[New Zealand]] || &nbsp;\n" + "|-\n" + "| [[.om]] || [[Oman]] || &nbsp;\n" + "|-\n" + "| [[.pa]] || [[Panama]] || &nbsp;\n" + "|-\n" + "| [[.pe]] || [[Peru]] || &nbsp;\n" + "|-\n" + "| [[.pf]] || [[French Polynesia]] || With [[Clipperton Island]]\n" + "|-\n" + "| [[.pg]] || [[Papua New Guinea]] || &nbsp;\n" + "|-\n" + "| [[.ph]] || [[Philippines]] || &nbsp;\n" + "|-\n" + "| [[.pk]] || [[Pakistan]] || &nbsp;\n" + "|-\n" + "| [[.pl]] || [[Poland]] || &nbsp;\n" + "|-\n" + "| [[.pm]] || [[Saint-Pierre and Miquelon]] || &nbsp;\n" + "|-\n" + "| [[.pn]] || [[Pitcairn Islands]] || &nbsp;\n" + "|-\n" + "| [[.pr]] || [[Puerto Rico]] || &nbsp;\n" + "|-\n" + "| [[.ps]] || [[Palestinian territories]] || PA-controlled [[West Bank]] and [[Gaza Strip]]\n" + "|-\n" + "| [[.pt]] || [[Portugal]] || Only available for Portuguese registered brands and companies\n" + "|-\n" + "| [[.pw]] || [[Palau]] || &nbsp;\n" + "|-\n" + "| [[.py]] || [[Paraguay]] || &nbsp;\n" + "|-\n" + "| [[.qa]] || [[Qatar]] || &nbsp;\n" + "|-\n" + "| [[.re]] || [[Réunion]] || &nbsp;\n" + "|-\n" + "| [[.ro]] || [[Romania]] || &nbsp;\n" + "|-\n" + "| [[.rs]] || [[Serbia]] || &nbsp;\n" + "|-\n" + "| [[.ru]] || [[Russia]] || &nbsp;\n" + "|-\n" + "| [[.rw]] || [[Rwanda]] || &nbsp;\n" + "|-\n" + "| [[.sa]] || [[Saudi Arabia]] || &nbsp;\n" + "|-\n" + "| [[.sb]] || [[Solomon Islands]] || &nbsp;\n" + "|-\n" + "| [[.sc]] || [[Seychelles]] || &nbsp;\n" + "|-\n" + "| [[.sd]] || [[Sudan]] || &nbsp;\n" + "|-\n" + "| [[.se]] || [[Sweden]] || &nbsp;\n" + "|-\n" + "| [[.sg]] || [[Singapore]] || &nbsp;\n" + "|-\n" + "| [[.sh]] || [[Saint Helena]] || &nbsp;\n" + "|-\n" + "| [[.si]] || [[Slovenia]] || &nbsp;\n" + "|-\n" + "| [[.sj]] || [[Svalbard]] and [[Jan Mayen]] Islands || Not in use (Norwegian dependencies; see .no)\n" + "|-\n" + "| [[.sk]] || [[Slovakia]] || &nbsp;\n" + "|-\n" + "| [[.sl]] || [[Sierra Leone]] || &nbsp;\n" + "|-\n" + "| [[.sm]] || [[San Marino]] || &nbsp;\n" + "|-\n" + "| [[.sn]] || [[Senegal]] || &nbsp;\n" + "|-\n" + "| [[.so (domain name)|.so]] || [[Somalia]] || &nbsp;\n" + "|-\n" + "| [[.sr]] || [[Suriname]] || &nbsp;\n" + "|-\n" + "| [[.st]] || [[São Tomé and Príncipe]] || &nbsp;\n" + "|-\n" + "| [[.su]] || former [[Soviet Union]] || Still in use\n" + "|-\n" + "| [[.sv]] || [[El Salvador]] || &nbsp;\n" + "|-\n" + "| [[.sy]] || [[Syria]] || &nbsp;\n" + "|-\n" + "| [[.sz]] || [[Swaziland]] || &nbsp;\n" + "|-\n" + "| [[.tc]] || [[Turks and Caicos Islands]] || &nbsp;\n" + "|-\n" + "| [[.td]] || [[Chad]] || &nbsp;\n" + "|-\n" + "| [[.tf]] || [[French Southern and Antarctic Lands]] || &nbsp;\n" + "|-\n" + "| [[.tg]] || [[Togo]] || &nbsp;\n" + "|-\n" + "| [[.th]] || [[Thailand]] || &nbsp;\n" + "|-\n" + "| [[.tj]] || [[Tajikistan]] || &nbsp;\n" + "|-\n" + "| [[.tk]] || [[Tokelau]] || Also used as a free domain service to the public\n" + "|-\n" + "| [[.tl]] || [[East Timor]] || Old code .tp is still in use\n" + "|-\n" + "| [[.tm]] || [[Turkmenistan]] || &nbsp;\n" + "|-\n" + "| [[.tn]] || [[Tunisia]] || &nbsp;\n" + "|-\n" + "| [[.to]] || [[Tonga]] || &nbsp;\n" + "|-\n" + "| [[.tp]] || [[East Timor]] || ISO code has changed to TL; .tl is now assigned but .tp is still in use\n" + "|-\n" + "| [[.tr]] || [[Turkey]] || &nbsp;\n" + "|-\n" + "| [[.tt]] || [[Trinidad and Tobago]] || &nbsp;\n" + "|-\n" + "| [[.tv]] || [[Tuvalu]] ||Much used by television broadcasters. Also sold as advertising domains\n" + "|-\n" + "| [[.tw]] || [[Taiwan]], [[Republic of China]] || Used in the [[Republic of China]], namely [[Taiwan]], [[Penghu]], [[Kinmen]], and [[Matsu Islands|Matsu]].\n" + "|-\n" + "| [[.tz]] || [[Tanzania]] || &nbsp;\n" + "|-\n" + "| [[.ua]] || [[Ukraine]] || &nbsp;\n" + "|-\n" + "| [[.ug]] || [[Uganda]] || &nbsp;\n" + "|-\n" + "| [[.uk]] || [[United Kingdom]] || &nbsp;\n" + "|-\n" + "| [[.um]] || [[United States Minor Outlying Islands]] || &nbsp;\n" + "|-\n" + "| [[.us]] || [[United States|United States of America]] || Commonly used by [[List_of_U.S._state_legislatures#External links | U.S. State]] and [[Local government in the United States|local governments]] instead of .gov TLD || &nbsp;\n" + "|-\n" + "| [[.uy]] || [[Uruguay]] || &nbsp;\n" + "|-\n" + "| [[.uz]] || [[Uzbekistan]] || &nbsp;\n" + "|-\n" + "| [[.va]] || [[Vatican City|Vatican City State]] || &nbsp;\n" + "|-\n" + "| [[.vc]] || [[Saint Vincent and the Grenadines]] || &nbsp;\n" + "|-\n" + "| [[.ve]] || [[Venezuela]] || &nbsp;\n" + "|-\n" + "| [[.vg]] || [[British Virgin Islands]] || &nbsp;\n" + "|-\n" + "| [[.vi]] || [[U.S. Virgin Islands]] || &nbsp;\n" + "|-\n" + "| [[.vn]] || [[Vietnam]] || &nbsp;\n" + "|-\n" + "| [[.vu]] || [[Vanuatu]] || &nbsp;\n" + "|-\n" + "| [[.wf]] || [[Wallis and Futuna]] || &nbsp;\n" + "|-\n" + "| [[.ws]] || [[Samoa]] || Formerly Western Samoa\n" + "|-\n" + "| [[.ye]] || [[Yemen]] || &nbsp;\n" + "|-\n" + "| [[.yt]] || [[Mayotte]] || &nbsp;\n" + "|-\n" + "| [[.yu]] || [[Federal Republic of Yugoslavia|Yugoslavia]] || Now used for [[Serbia]] and [[Montenegro]]\n" + "|-\n" + "| [[.za]] || [[South Africa]] (Zuid-Afrika) || &nbsp;\n" + "|-\n" + "| [[.zm]] || [[Zambia]] || &nbsp;\n" + "|-\n" + "| [[.zw]] || [[Zimbabwe]] || &nbsp;\n" + "|- style=\"background-color: #a0d0ff;\"\n" + "![[IDNA]] TLD<ref>The IDNA TLDs have been added for the purpose of testing the use of IDNA at the top level, and are likely to be temporary. Each of the eleven TLDs encodes a word meaning \"test\" in some language. See the [http://www.icann.org/announcements/announcement-15oct07.htm ICANN announcement of 15 October 2007] and the [http://idn.icann.org/ IDN TLD evaluation gateway].</ref>!!Language!!Word\n" + "|-\n" + "| .xn--0zwm56d || [[simplified Chinese]] || 测试\n" + "|-\n" + "| .xn--11b5bs3a9aj6g || [[Hindi]] || परीक�?षा\n" + "|-\n" + "| .xn--80akhbyknj4f || [[Russian language|Russian]] || и�?пытание\n" + "|-\n" + "| .xn--9t4b11yi5a || [[Korean language|Korean]] || 테스트\n" + "|-\n" + "| .xn--deba0ad || [[Yiddish]] || טעסט\n" + "|-\n" + "| .xn--g6w251d || [[traditional Chinese]] || 測試\n" + "|-\n" + "| .xn--hgbk6aj7f53bba || [[Persian language|Persian]] || آزمایشی\n" + "|-\n" + "| .xn--hlcj6aya9esc7a || [[Tamil language|Tamil]] || பரிட�?சை\n" + "|-\n" + "| .xn--jxalpdlp || [[Greek language|Greek]] || δοκιμή\n" + "|-\n" + "| .xn--kgbechtv || [[Arabic language|Arabic]] || إختبار\n" + "|-\n" + "| .xn--zckzah || [[Japanese language|Japanese]] || テスト\n" + "|}"; Table t = parse(content); } }
PtrMan/wikipedia-extract
src/test/be/devijver/wikipedia/parser/javacc/table/JavaCCTableParserTests.java
45,923
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.handler.codec.socks; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.util.CharsetUtil; import org.junit.Test; import java.net.IDN; import java.nio.CharBuffer; import static org.junit.Assert.*; public class SocksCmdRequestTest { @Test public void testConstructorParamsAreNotNull() { try { new SocksCmdRequest(null, SocksAddressType.UNKNOWN, "", 1); } catch (Exception e) { assertTrue(e instanceof NullPointerException); } try { new SocksCmdRequest(SocksCmdType.UNKNOWN, null, "", 1); } catch (Exception e) { assertTrue(e instanceof NullPointerException); } try { new SocksCmdRequest(SocksCmdType.UNKNOWN, SocksAddressType.UNKNOWN, null, 1); } catch (Exception e) { assertTrue(e instanceof NullPointerException); } } @Test public void testIPv4CorrectAddress() { try { new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.IPv4, "54.54.1111.253", 1); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } @Test public void testIPv6CorrectAddress() { try { new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.IPv6, "xxx:xxx:xxx", 1); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } @Test public void testIDNNotExceeds255CharsLimit() { try { new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.DOMAIN, "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" + "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" + "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" + "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή", 1); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } @Test public void testHostNotEncodedForUnknown() { String asciiHost = "xn--e1aybc.xn--p1ai"; short port = 10000; SocksCmdRequest rq = new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.UNKNOWN, asciiHost, port); assertEquals(asciiHost, rq.host()); ByteBuf buffer = Unpooled.buffer(16); rq.encodeAsByteBuf(buffer); buffer.resetReaderIndex(); assertEquals(SocksProtocolVersion.SOCKS5.byteValue(), buffer.readByte()); assertEquals(SocksCmdType.BIND.byteValue(), buffer.readByte()); assertEquals((byte) 0x00, buffer.readByte()); assertEquals(SocksAddressType.UNKNOWN.byteValue(), buffer.readByte()); assertFalse(buffer.isReadable()); buffer.release(); } @Test public void testIDNEncodeToAsciiForDomain() { String host = "тест.рф"; CharBuffer asciiHost = CharBuffer.wrap(IDN.toASCII(host)); short port = 10000; SocksCmdRequest rq = new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.DOMAIN, host, port); assertEquals(host, rq.host()); ByteBuf buffer = Unpooled.buffer(24); rq.encodeAsByteBuf(buffer); buffer.resetReaderIndex(); assertEquals(SocksProtocolVersion.SOCKS5.byteValue(), buffer.readByte()); assertEquals(SocksCmdType.BIND.byteValue(), buffer.readByte()); assertEquals((byte) 0x00, buffer.readByte()); assertEquals(SocksAddressType.DOMAIN.byteValue(), buffer.readByte()); assertEquals((byte) asciiHost.length(), buffer.readUnsignedByte()); assertEquals(asciiHost, CharBuffer.wrap(buffer.readCharSequence(asciiHost.length(), CharsetUtil.US_ASCII))); assertEquals(port, buffer.readUnsignedShort()); buffer.release(); } @Test public void testValidPortRange() { try { new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.DOMAIN, "παράδειγμα.δοκιμήπαράδει", 0); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } try { new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.DOMAIN, "παράδειγμα.δοκιμήπαράδει", 65536); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } }
wangjiangtao2/netty-4.1.31.Final
codec-socks/src/test/java/io/netty/handler/codec/socks/SocksCmdRequestTest.java
45,924
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.handler.codec.socks; import org.junit.Test; import static org.junit.Assert.assertTrue; public class SocksCmdRequestTest { @Test public void testConstructorParamsAreNotNull(){ try { new SocksCmdRequest(null, SocksMessage.AddressType.UNKNOWN, "", 0); } catch (Exception e){ assertTrue(e instanceof NullPointerException); } try { new SocksCmdRequest(SocksMessage.CmdType.UNKNOWN, null, "", 0); } catch (Exception e){ assertTrue(e instanceof NullPointerException); } try { new SocksCmdRequest(SocksMessage.CmdType.UNKNOWN, SocksMessage.AddressType.UNKNOWN, null, 0); } catch (Exception e){ assertTrue(e instanceof NullPointerException); } } @Test public void testIPv4CorrectAddress(){ try { new SocksCmdRequest(SocksMessage.CmdType.BIND, SocksMessage.AddressType.IPv4, "54.54.1111.253", 0); } catch (Exception e){ assertTrue(e instanceof IllegalArgumentException); } } @Test public void testIPv6CorrectAddress(){ try { new SocksCmdRequest(SocksMessage.CmdType.BIND, SocksMessage.AddressType.IPv6, "xxx:xxx:xxx", 0); } catch (Exception e){ assertTrue(e instanceof IllegalArgumentException); } } @Test public void testIDNNotExceeds255CharsLimit(){ try { new SocksCmdRequest(SocksMessage.CmdType.BIND, SocksMessage.AddressType.DOMAIN, "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" + "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" + "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" + "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή", 0); } catch (Exception e){ assertTrue(e instanceof IllegalArgumentException); } } @Test public void testValidPortRange(){ try { new SocksCmdRequest(SocksMessage.CmdType.BIND, SocksMessage.AddressType.DOMAIN, "παράδειγμα.δοκιμήπαράδει", -1); } catch (Exception e){ assertTrue(e instanceof IllegalArgumentException); } try { new SocksCmdRequest(SocksMessage.CmdType.BIND, SocksMessage.AddressType.DOMAIN, "παράδειγμα.δοκιμήπαράδει", 65536); } catch (Exception e){ assertTrue(e instanceof IllegalArgumentException); } } }
la3lma/netty
codec-socks/src/test/java/io/netty/handler/codec/socks/SocksCmdRequestTest.java
45,925
/** * Copyright (C) 2013-2016 Vasilis Vryniotis <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.datumbox.framework.utilities.text.cleaners; import com.datumbox.tests.bases.BaseTest; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Vasilis Vryniotis <[email protected]> */ public class StringCleanerTest extends BaseTest { /** * Test of tokenizeURLs method, of class StringCleaner. */ @Test public void testTokenizeURLs() { logger.info("tokenizeURLs"); String text = "Test, test δοκιμή http://wWw.Google.com/page?query=1#hash test test"; String expResult = "Test, test δοκιμή PREPROCESSDOC_URL test test"; String result = StringCleaner.tokenizeURLs(text); assertEquals(expResult, result); } /** * Test of tokenizeSmileys method, of class StringCleaner. */ @Test public void testTokenizeSmileys() { logger.info("tokenizeSmileys"); String text = "Test, test δοκιμή :) :( :] :[ test test"; String expResult = "Test, test δοκιμή PREPROCESSDOC_EM1 PREPROCESSDOC_EM3 PREPROCESSDOC_EM8 PREPROCESSDOC_EM9 test test"; String result = StringCleaner.tokenizeSmileys(text); assertEquals(expResult, result); } /** * Test of removeExtraSpaces method, of class StringCleaner. */ @Test public void testRemoveExtraSpaces() { logger.info("removeExtraSpaces"); String text = " test test test test test\n\n\n\r\n\r\r test\n"; String expResult = "test test test test test test"; String result = StringCleaner.removeExtraSpaces(text); assertEquals(expResult, result); } /** * Test of removeSymbols method, of class StringCleaner. */ @Test public void testRemoveSymbols() { logger.info("removeSymbols"); String text = "test ` ~ ! @ # $ % ^ & * ( ) _ - + = < , > . ? / \" ' : ; [ { } ] | \\ test `~!@#$%^&*()_-+=<,>.?/\\\"':;[{}]|\\\\ test"; String expResult = "test _ test _ test"; String result = StringCleaner.removeExtraSpaces(StringCleaner.removeSymbols(text)); assertEquals(expResult, result); } /** * Test of unifyTerminators method, of class StringCleaner. */ @Test public void testUnifyTerminators() { logger.info("unifyTerminators"); String text = " This is amazing!!! ! How is this possible?!?!?!?!!!???! "; String expResult = "This is amazing. How is this possible."; String result = StringCleaner.unifyTerminators(text); assertEquals(expResult, result); } /** * Test of removeAccents method, of class StringCleaner. */ @Test public void testRemoveAccents() { logger.info("removeAccents"); String text = "'ά','ό','έ','ί','ϊ','ΐ','ή','ύ','ϋ','ΰ','ώ','à','á','â','ã','ä','ç','è','é','ê','ë','ì','í','î','ï','ñ','ò','ó','ô','õ','ö','ù','ú','û','ü','ý','ÿ','Ά','Ό','Έ','Ί','Ϊ','Ή','Ύ','Ϋ','Ώ','À','Á','Â','Ã','Ä','Ç','È','É','Ê','Ë','Ì','Í','Î','Ï','Ñ','Ò','Ó','Ô','Õ','Ö','Ù','Ú','Û','Ü','Ý'"; String expResult = "'α','ο','ε','ι','ι','ι','η','υ','υ','υ','ω','a','a','a','a','a','c','e','e','e','e','i','i','i','i','n','o','o','o','o','o','u','u','u','u','y','y','Α','Ο','Ε','Ι','Ι','Η','Υ','Υ','Ω','A','A','A','A','A','C','E','E','E','E','I','I','I','I','N','O','O','O','O','O','U','U','U','U','Y'"; String result = StringCleaner.removeAccents(text); assertEquals(expResult, result); } }
asteriq/datumbox-framework
src/test/java/com/datumbox/framework/utilities/text/cleaners/StringCleanerTest.java
45,926
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.handler.codec.socks; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.util.CharsetUtil; import org.junit.jupiter.api.Test; import java.net.IDN; import java.nio.CharBuffer; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; public class SocksCmdRequestTest { @Test public void testConstructorParamsAreNotNull() { try { new SocksCmdRequest(null, SocksAddressType.UNKNOWN, "", 1); } catch (Exception e) { assertTrue(e instanceof NullPointerException); } try { new SocksCmdRequest(SocksCmdType.UNKNOWN, null, "", 1); } catch (Exception e) { assertTrue(e instanceof NullPointerException); } try { new SocksCmdRequest(SocksCmdType.UNKNOWN, SocksAddressType.UNKNOWN, null, 1); } catch (Exception e) { assertTrue(e instanceof NullPointerException); } } @Test public void testIPv4CorrectAddress() { try { new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.IPv4, "54.54.1111.253", 1); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } @Test public void testIPv6CorrectAddress() { try { new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.IPv6, "xxx:xxx:xxx", 1); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } @Test public void testIDNNotExceeds255CharsLimit() { try { new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.DOMAIN, "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" + "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" + "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" + "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή", 1); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } @Test public void testHostNotEncodedForUnknown() { String asciiHost = "xn--e1aybc.xn--p1ai"; short port = 10000; SocksCmdRequest rq = new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.UNKNOWN, asciiHost, port); assertEquals(asciiHost, rq.host()); ByteBuf buffer = Unpooled.buffer(16); rq.encodeAsByteBuf(buffer); buffer.readerIndex(0); assertEquals(SocksProtocolVersion.SOCKS5.byteValue(), buffer.readByte()); assertEquals(SocksCmdType.BIND.byteValue(), buffer.readByte()); assertEquals((byte) 0x00, buffer.readByte()); assertEquals(SocksAddressType.UNKNOWN.byteValue(), buffer.readByte()); assertFalse(buffer.isReadable()); buffer.release(); } @Test public void testIDNEncodeToAsciiForDomain() { String host = "тест.рф"; CharBuffer asciiHost = CharBuffer.wrap(IDN.toASCII(host)); short port = 10000; SocksCmdRequest rq = new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.DOMAIN, host, port); assertEquals(host, rq.host()); ByteBuf buffer = Unpooled.buffer(24); rq.encodeAsByteBuf(buffer); buffer.readerIndex(0); assertEquals(SocksProtocolVersion.SOCKS5.byteValue(), buffer.readByte()); assertEquals(SocksCmdType.BIND.byteValue(), buffer.readByte()); assertEquals((byte) 0x00, buffer.readByte()); assertEquals(SocksAddressType.DOMAIN.byteValue(), buffer.readByte()); assertEquals((byte) asciiHost.length(), buffer.readUnsignedByte()); assertEquals(asciiHost, CharBuffer.wrap(buffer.readCharSequence(asciiHost.length(), CharsetUtil.US_ASCII))); assertEquals(port, buffer.readUnsignedShort()); buffer.release(); } @Test public void testValidPortRange() { try { new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.DOMAIN, "παράδειγμα.δοκιμήπαράδει", 0); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } try { new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.DOMAIN, "παράδειγμα.δοκιμήπαράδει", 65536); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } }
algobot76/netty
codec-socks/src/test/java/io/netty/handler/codec/socks/SocksCmdRequestTest.java
45,927
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.handler.codec.socks; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.util.CharsetUtil; import org.junit.Test; import java.net.IDN; import static org.junit.Assert.*; public class SocksCmdRequestTest { @Test public void testConstructorParamsAreNotNull() { try { new SocksCmdRequest(null, SocksAddressType.UNKNOWN, "", 1); } catch (Exception e) { assertTrue(e instanceof NullPointerException); } try { new SocksCmdRequest(SocksCmdType.UNKNOWN, null, "", 1); } catch (Exception e) { assertTrue(e instanceof NullPointerException); } try { new SocksCmdRequest(SocksCmdType.UNKNOWN, SocksAddressType.UNKNOWN, null, 1); } catch (Exception e) { assertTrue(e instanceof NullPointerException); } } @Test public void testIPv4CorrectAddress() { try { new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.IPv4, "54.54.1111.253", 1); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } @Test public void testIPv6CorrectAddress() { try { new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.IPv6, "xxx:xxx:xxx", 1); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } @Test public void testIDNNotExceeds255CharsLimit() { try { new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.DOMAIN, "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" + "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" + "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" + "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή", 1); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } @Test public void testHostNotEncodedForUnknown() { String asciiHost = "xn--e1aybc.xn--p1ai"; short port = 10000; SocksCmdRequest rq = new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.UNKNOWN, asciiHost, port); assertEquals(asciiHost, rq.host()); ByteBuf buffer = Unpooled.buffer(16); rq.encodeAsByteBuf(buffer); buffer.resetReaderIndex(); assertEquals(SocksProtocolVersion.SOCKS5.byteValue(), buffer.readByte()); assertEquals(SocksCmdType.BIND.byteValue(), buffer.readByte()); assertEquals((byte) 0x00, buffer.readByte()); assertEquals(SocksAddressType.UNKNOWN.byteValue(), buffer.readByte()); assertFalse(buffer.isReadable()); buffer.release(); } @Test public void testIDNEncodeToAsciiForDomain() { String host = "тест.рф"; String asciiHost = IDN.toASCII(host); short port = 10000; SocksCmdRequest rq = new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.DOMAIN, host, port); assertEquals(host, rq.host()); ByteBuf buffer = Unpooled.buffer(24); rq.encodeAsByteBuf(buffer); buffer.resetReaderIndex(); assertEquals(SocksProtocolVersion.SOCKS5.byteValue(), buffer.readByte()); assertEquals(SocksCmdType.BIND.byteValue(), buffer.readByte()); assertEquals((byte) 0x00, buffer.readByte()); assertEquals(SocksAddressType.DOMAIN.byteValue(), buffer.readByte()); assertEquals((byte) asciiHost.length(), buffer.readUnsignedByte()); assertEquals(asciiHost, buffer.readCharSequence(asciiHost.length(), CharsetUtil.US_ASCII)); assertEquals(port, buffer.readUnsignedShort()); buffer.release(); } @Test public void testValidPortRange() { try { new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.DOMAIN, "παράδειγμα.δοκιμήπαράδει", 0); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } try { new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.DOMAIN, "παράδειγμα.δοκιμήπαράδει", 65536); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } }
hxwab/netty
codec-socks/src/test/java/io/netty/handler/codec/socks/SocksCmdRequestTest.java
45,928
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.handler.codec.socksx.v5; import org.junit.Test; import static org.junit.Assert.*; public class DefaultSocks5CommandRequestTest { @Test public void testConstructorParamsAreNotNull() { try { new DefaultSocks5CommandRequest(null, Socks5AddressType.DOMAIN, "", 1); } catch (Exception e) { assertTrue(e instanceof NullPointerException); } try { new DefaultSocks5CommandRequest(Socks5CommandType.CONNECT, null, "", 1); } catch (Exception e) { assertTrue(e instanceof NullPointerException); } try { new DefaultSocks5CommandRequest(Socks5CommandType.CONNECT, Socks5AddressType.DOMAIN, null, 1); } catch (Exception e) { assertTrue(e instanceof NullPointerException); } } @Test public void testIPv4CorrectAddress() { try { new DefaultSocks5CommandRequest(Socks5CommandType.BIND, Socks5AddressType.IPv4, "54.54.1111.253", 1); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } @Test public void testIPv6CorrectAddress() { try { new DefaultSocks5CommandRequest(Socks5CommandType.BIND, Socks5AddressType.IPv6, "xxx:xxx:xxx", 1); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } @Test public void testIDNNotExceeds255CharsLimit() { try { new DefaultSocks5CommandRequest(Socks5CommandType.BIND, Socks5AddressType.DOMAIN, "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" + "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" + "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" + "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή", 1); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } @Test public void testValidPortRange() { try { new DefaultSocks5CommandRequest(Socks5CommandType.BIND, Socks5AddressType.DOMAIN, "παράδειγμα.δοκιμήπαράδει", -1); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } try { new DefaultSocks5CommandRequest(Socks5CommandType.BIND, Socks5AddressType.DOMAIN, "παράδειγμα.δοκιμήπαράδει", 65536); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } new DefaultSocks5CommandRequest(Socks5CommandType.BIND, Socks5AddressType.DOMAIN, "παράδειγμα.δοκιμήπαράδει", 0); new DefaultSocks5CommandRequest(Socks5CommandType.BIND, Socks5AddressType.DOMAIN, "παράδειγμα.δοκιμήπαράδει", 65535); } }
codeclimate-testing/netty
codec-socks/src/test/java/io/netty/handler/codec/socksx/v5/DefaultSocks5CommandRequestTest.java
45,929
package be.devijver.wikipedia.parser.javacc.table; import java.io.ByteArrayInputStream; import java.io.StringReader; import junit.framework.TestCase; import be.devijver.wikipedia.parser.ast.Attribute; import be.devijver.wikipedia.parser.ast.Cell; import be.devijver.wikipedia.parser.ast.Row; import be.devijver.wikipedia.parser.ast.Table; public class JavaCCTableParserTests extends TestCase { private Table parse(String s) { try { return new JavaCCTableParser( new StringReader(s) ).parseTable(); } catch (ParseException e) { throw new RuntimeException(e); } } public void testEmptyTable() throws Exception { Table t = parse("{| |}"); System.out.println(t); assertNotNull(t); assertNull(t.getCaption()); assertNull(t.getTableOptions()); assertNull(t.getCaptionOptions()); } public void testEmptyTableWithTableOptions() throws Exception { Table t = parse("{| border=\"0\" |}"); System.out.println(t); assertNotNull(t); assertNull(t.getCaption()); assertNull(t.getCaptionOptions()); assertNotNull(t.getTableOptions()); assertEquals(1, t.getTableOptions().getAttributes().length); Attribute attr = t.getTableOptions().getAttributes()[0]; assertEquals("border", attr.getName()); assertEquals("0", attr.getValue()); } public void testEmptyTableWithCaption() throws Exception { Table t = parse("{|\n|+ This is a caption |}"); System.out.println(t); assertNotNull(t); assertEquals(" This is a caption ", t.getCaption()); assertNull(t.getTableOptions()); } public void testTableWithCaptionAndCaptionOptions1() throws Exception { Table t = parse( "{| border=\"0\" \n" + "|+ someoption=\"true\" | This is a caption \n" + "|}"); System.out.println(t); assertNotNull(t); assertNotNull(t.getTableOptions()); assertEquals(" This is a caption ", t.getCaption()); assertNotNull(t.getCaptionOptions()); assertEquals(1, t.getCaptionOptions().getAttributes().length); } public void testTableWithCaptionAndCaptionOptions2() throws Exception { Table t = parse( "{| border=\"0\" \n" + "|+ someoption=\"true\" | '''This is a caption''' \n" + "|}"); System.out.println(t); assertNotNull(t); assertNotNull(t.getTableOptions()); assertEquals(" '''This is a caption''' ", t.getCaption()); assertNotNull(t.getCaptionOptions()); assertEquals(1, t.getCaptionOptions().getAttributes().length); } public void testTableWithOneRowAndOneCell() throws Exception { Table t = parse( "{|\n" + "|-\n" + "| cell1\n" + "|}"); System.out.println(t); } public void testTableWithOneRowWithOneCellWithCellOptions() throws Exception { Table t = parse( "{|\n" + "|-\n" + "| style=\"none\" | cell1 \n" + "|}"); System.out.println(t); } public void testTableWithOneRowWithTwoCellsWithCellOptions() throws Exception { Table t = parse( "{|\n" + "|-\n" + "| style=\"none\" | cell1 || style=\"groovy\" | cell2 \n" + "|}" ); System.out.println(t); assertNotNull(t); assertNull(t.getCaption()); assertNull(t.getCaptionOptions()); assertNull(t.getTableOptions()); assertEquals(1, t.getRows().length); assertEquals(2, t.getRows()[0].getCells().length); Cell cell1 = t.getRows()[0].getCells()[0]; Cell cell2 = t.getRows()[0].getCells()[1]; assertEquals(" cell1 ", cell1.getContent()[0].toString()); assertEquals(1, cell1.getOptions().getAttributes().length); assertEquals("style", cell1.getOptions().getAttributes()[0].getName()); assertEquals("none", cell1.getOptions().getAttributes()[0].getValue()); assertEquals(" cell2 ", cell2.getContent()[0].toString()); assertEquals(1, cell2.getOptions().getAttributes().length); assertEquals("style", cell2.getOptions().getAttributes()[0].getName()); assertEquals("groovy", cell2.getOptions().getAttributes()[0].getValue()); } public void testTableWithOneRowAndTwoCells1() throws Exception { Table t = parse( "{|\n" + "|-\n" + "| cell1 || cell2\n" + "|}"); System.out.println(t); } public void testTableWithOneRowAndTwoCells2() throws Exception { Table t = parse( "{|\n" + "|-\n" + "| cell1 \n" + "| cell2 \n" + "|}"); System.out.println(t); } public void testTableWithOneRowAndTwoCells3() throws Exception { Table t = parse( "{|\n" + "|-\n" + "! cell1 !! cell2\n" + "|}"); System.out.println(t); } public void testTableWithOneRowAndTwoCells4() throws Exception { Table t = parse( "{|\n" + "|-\n" + "! cell1 \n" + "! cell2\n" + "|}"); System.out.println(t); assertNotNull(t); assertNull(t.getCaption()); assertNull(t.getCaptionOptions()); assertNull(t.getTableOptions()); assertEquals(1, t.getRows().length); assertEquals(2, t.getRows()[0].getCells().length); Cell cell1 = t.getRows()[0].getCells()[0]; Cell cell2 = t.getRows()[0].getCells()[1]; assertNull(cell1.getOptions()); assertEquals(" cell1 ", cell1.getContent()[0].toString()); assertNull(cell1.getOptions()); assertEquals(" cell2", cell2.getContent()[0].toString()); } public void testTableWithNestedTable1() throws Exception { Table t = parse( "{|\n" + "|-\n" + "| {| border=\"0\" |}\n" + "|}" ); System.out.println(t); } public void testTableWithNestedTable2() throws Exception { Table t = parse( "{|\n" + "|-\n" + "|{| border=\"0\" |}\n" + "|}" ); System.out.println(t); } public void testTableWithTwoRows() throws Exception { Table t = parse( "{|\n" + "|-\n" + "| row 1, cell 1 || row 1, cell 2\n" + "|-\n" + "| row 2, cell 1 || row 2, cell 2\n" + "|}" ); System.out.println(t); } public void testWebApplicationFrameworksTable1() throws Exception { String content = "{| class=\"wikitable sortable\" style=\"font-size: 90%\"\n" + "|-\n" + "! Project\n" + "! Current Stable Version\n" + "! [[Programming Language|Language]]\n" + "! [[License]]\n" + "|-\n" + "! {{rh}} | [[Agavi_(framework)|Agavi]]\n" + "| 0.11 RC6\n" + "| [[PHP]]\n" + "| [[LGPL]] \n" + "|-\n" + "! {{rh}} | [[AJILE|Ajile]]\n" + "| [http://prdownloads.sourceforge.net/ajile/Ajile.0.9.9.2.zip?download 0.9.9.2]\n" + "| [[JavaScript]]\n" + "| [[MPL|MPL 1.1]] / [[LGPL|LGPL 2.1]] / [[GPL|GPL 2.0]] \n" + "|-\n" + "! {{rh}} | [[Akelos PHP Framework|Akelos]]\n" + "| 0.8\n" + "| [[PHP]]\n" + "| [[LGPL]] \n" + "|-\n" + "! {{rh}} | [[Apache Struts]]\n" + "| 2.0.9\n" + "| [[Java (programming language)|Java]]\n" + "| [[Apache License|Apache]] \n" + "|-\n" + "! {{rh}} | [[Andromeda Database|Andromeda]]\n" + "| 2007.08.08\n" + "| [[PHP]]\n" + "| [[GPL]]\n" + "|-\n" + "! {{rh}} | [[Aranea framework|Aranea MVC]]\n" + "| 1.0.10\n" + "| [[Java (programming language)|Java]]\n" + "| [[Apache License|Apache]]\n" + "|-\n" + "! {{rh}} | [[CakePHP]]\n" + "| 1.1.17.5612\n" + "| [[PHP]]\n" + "| [[MIT License|MIT]]\n" + "|-\n" + "! {{rh}} | [[Camping (microframework)|Camping]]\n" + "| 1.5\n" + "| [[Ruby (programming language)|Ruby]]\n" + "| [[MIT License|MIT]]\n" + "|-\n" + "! {{rh}} | [[Catalyst (software)|Catalyst]]\n" + "| 5.7007\n" + "| [[Perl]]\n" + "| [[GPL]]/[[Artistic License|Artistic]]\n" + "|-\n" + "! {{rh}} | [[CodeIgniter|Code Igniter]]\n" + "| 1.5.4\n" + "| [[PHP]]\n" + "| [http://codeigniter.com/user_guide/license.html Apache/BSD-style open source license]\n" + "|-\n" + "! {{rh}} | [[ColdBox]]\n" + "| 2.0.3\n" + "| [[Adobe ColdFusion|ColdFusion]]\n" + "| [[Apache License|Apache]]\n" + "|-\n" + "! {{rh}} | [[Django (web framework)|Django]]\n" + "| 0.96\n" + "| [[Python (programming language)|Python]]\n| [[BSD]]\n" + "|-\n" + "! {{rh}} | [[DotNetNuke]]\n" + "| 4.6.2\n" + "| [[ASP.NET]]\n" + "| [[BSD]]\n" + "|-\n" + "! {{rh}} | [[Fusebox (programming)|Fusebox]]\n" + "| 5.1\n" + "| [[Adobe ColdFusion|ColdFusion]]\n" + "| [[Apache License|Apache]]\n" + "|-\n" + "! {{rh}} | [http://mdp.cti.depaul.edu/examples Gluon]\n" + "| 1.5\n" + "| [[Python (programming language)|Python]]\n" + "| [[GPL]]\n" + "|-\n" + "! {{rh}} | [[Grails_%28Framework%29|Grails]]\n" + "| 0.6 \n" + "| [[Groovy (programming language)|Groovy]]\n" + "| [[Apache License|Apache]]\n" + "|-\n" + "! {{rh}} | [[JBoss Seam]]\n" + "| 1.2.1 GA\n" + "| [[Java (programming language)|Java]]\n" + "| [[LGPL]]\n" + "|-\n" + "! {{rh}} | [[Jifty]]\n" + "| 0.70824\n" + "| [[Perl]]\n" + "| [[GPL]]/[[Artistic License|Artistic]]\n" + "|-\n" + "! {{rh}} | [[Kumbia]]\n" + "| 0.46RC9\n" + "| [[PHP]]\n" + "| [[GPL]] | [[Apache License|Apache 2.0]] | [[PHP5]]\n" + "|-\n" + "! {{rh}} | [[Lift (web framework)|Lift]]\n" + "| 0.2.0\n" + "| [[Scala (programming language)|Scala]]\n" + "| [[Apache License|Apache 2.0]]\n" + "|-\n" + "! {{rh}} | [[Mach-II]]\n" + "| 1.5\n" + "| [[Adobe ColdFusion|ColdFusion]]\n" + "| [[Apache License|Apache]]\n" + "|-\n" + "! {{rh}} | [[Makumba]]\n" + "| 0.5.16\n" + "| [[Java (programming language)|Java]]\n" + "| [[LGPL]]\n" + "|-\n" + "! {{rh}} | [[Model-Glue]]\n" + "| 2.0\n" + "| [[Adobe ColdFusion|ColdFusion]]\n" + "| [[Apache License|Apache]]\n" + "|-\n" + "! {{rh}} | [[Monorail (.Net)|MonoRail]]\n" + "| 1.0 RC3\n" + "| [[ASP.NET]]\n" + "| [[Apache License|Apache]]\n" + "|-\n" + "! {{rh}} | [[Nitro (web framework)|Nitro]]\n" + "| 0.41\n" + "| [[Ruby (programming language)|Ruby]]\n" + "| [[BSD License]]\n" + "|-\n" + "! {{rh}} | [[OpenACS]]\n" + "| 5.3.2\n" + "| [[Tcl]]\n" + "| [[GPL]]\n" + "|-\n" + "! {{rh}} | [[PHPulse]]\n" + "| 2.0\n" + "| [[PHP]]\n" + "| [[GPL]]\n" + "|-\n" + "! {{rh}} | [[PRADO]]\n" + "| 3.1.1\n" + "| [[PHP]]\n" + "| [[BSD License]]\n" + "|-\n" + "! {{rh}} | [[Pylons (web framework)]]\n" + "| 0.9.6\n" + "| [[Python (programming language)|Python]]\n" + "| [[BSD License]]\n" + "|-\n" + "! {{rh}} | [[Qcodo]]\n" + "| 0.3.32\n" + "| [[PHP]]\n" + "| [[MIT License]]\n" + "|-\n" + "! {{rh}} | [[RIFE]]\n" + "| 1.6.2\n" + "| [[Java]]\n" + "| [[Apache License|Apache]]\n" + "|-\n" + "! {{rh}} | [[Ruby on Rails]]\n" + "| 1.2.3\n" + "| [[Ruby (programming language)|Ruby]]\n" + "| [[MIT License|MIT]]/[[Ruby License|Ruby]]\n" + "|-\n" + "! {{rh}} | [[Seaside web framework|Seaside]]\n" + "| 2.7\n" + "| [[Smalltalk]]\n" + "| [[MIT License]]\n" + "|-\n" + "! {{rh}} | [[Spring Framework]]\n" + "| 2.0.6\n" + "| [[Java (programming language)|Java]]\n" + "| [[Apache License|Apache]]\n" + "|-\n" + "! {{rh}} | [[Stripes]]\n" + "| 1.4.3\n" + "| [[Java]]\n" + "| [[LGPL]]\n" + "|-\n" + "! {{rh}} | [[Symfony]]\n" + "| 1.0.7\n" + "| [[PHP]]\n" + "| [[MIT License|MIT]]\n" + "|-\n" + "! {{rh}} | [[TurboGears]]\n" + "| 1.0.1\n" + "| [[Python (programming language)|Python]]\n" + "| [[MIT License]], [[LGPL]]\n" + "|-\n" + "! {{rh}} | [[WebLeaf]]\n" + "| 2.1\n" + "| [[Java (programming language)|Java]]\n" + "| [[LGPL]]\n" + "|-\n" + "! {{rh}} | [[WebObjects]]\n" + "| 5.3.1\n" + "| [[Java (programming language)|Java]]\n" + "| [[Proprietary]]\n" + "|-\n" + "! {{rh}} | [[Zend Framework]]\n" + "| [http://framework.zend.com/download 1.0.2]\n" + "| [[PHP]]\n" + "| [[BSD_Licenses|BSD License]]\n" + "|-\n" + "! {{rh}} | [[Zoop Framework]]\n" + "| 1.2\n" + "| [[PHP]]\n" + "| [[Zope Public License|ZPL]]\n" + "|-\n" + "! {{rh}} | [[Zope]]2\n" + "| 2.10\n" + "| [[Python]]\n" + "| [[Zope Public License|ZPL]]\n" + "|-\n" + "! {{rh}} | [[Zope]]3\n" + "| 3.3\n" + "| [[Python]]\n" + "| [[Zope Public License|ZPL]]\n" + "|-class=\"sortbottom\"\n" + "! Project\n" + "! Current Stable Version\n" + "! [[Programming Language|Language]]\n" + "! [[License]]\n" + "|}"; Table t = parse(content); System.out.println(t); Row row = t.getRows()[1]; Cell cell = row.getCells()[0]; assertEquals(" [[Agavi_(framework)|Agavi]]", cell.getContent()[0].toString()); assertEquals("{{rh}}", cell.getOptions().getAttributes()[0].getName()); } public void testWebApplicationFrameworks2() throws Exception { String content = "{| class=\"wikitable sortable\" style=\"font-size: 90%\"\n" + "|-\n" + "!Project\n" + "!Language\n" + "![[Ajax (programming)|Ajax]]\n" + "![[Model-view-controller|MVC]] framework\n" + "![[Web_application_framework#Push-based_vs._Pull-based|MVC Push/Pull]]\n" + "![[Internationalization_and_localization|i18n & l10n?]]\n" + "![[Object-relational mapping|ORM]]\n" + "!Testing framework(s)\n" + "!DB migration framework(s)\n" + "!Security Framework(s)\n" + "\n" + "!Template Framework(s)\n" + "!Caching Framework(s)\n" + "!Form Validation Framework(s)\n" + "|-\n" + "|[[Agavi_(framework)|Agavi]]\n" + "| PHP\n" + "| \n" + "| {{Yes}}\n" + "| Push\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "|-\n" + "|[[AJILE|Ajile]]\n" + "| [[JavaScript]]\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| Push & Pull\n" + "| {{Yes}}\n" + "| \n" + "| {{Yes}}, [http://jsunit.net/ jsUnit]\n" + "| \n" + "| \n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| \n" + "|-\n" + "|[[Akelos PHP Framework]]\n" + "| PHP\n" + "| {{Yes}}, [[Prototype JavaScript Framework|Prototype]], [[script.aculo.us]]\n" + "| {{Yes}}, [[Active record pattern|ActiveRecord]]\n" + "| Push\n" + "| {{Yes}}\n" + "| {{Yes}}, [[Active record pattern|ActiveRecord]]\n" + "| {{Yes}}, [[Unit testing|Unit Tests]]\n" + "| {{Yes}}\n" + "| \n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "|-\n" + "|[[Apache Struts]]\n" + "| Java\n" + "| {{Yes}}\n" + "| \n" + "| Push\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}, [[Unit testing|Unit Tests]]\n" + "|\n" + "|\n" + "|{{Yes}}, Jakarta Tiles framework\n" + "|\n" + "|{{Yes}}, Jakarta Validator framework\n" + "|-\n" + "|[[Apache Struts 2 (ex. WebWork)]]\n" + "| Java\n" + "| {{Yes}}\n" + "| \n" + "| Push & Pull\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}, [[Unit testing|Unit Tests]]\n" + "|\n" + "|\n" + "|{{Yes}}\n" + "|\n" + "|{{Yes}}\n" + "|-\n" + "|[[Andromeda Database|Andromeda]]\n" + "| PHP\n" + "|{{Yes}}\n" + "|\n" + "|\n" + "|{{Yes}}\n" + "|{{Yes}}\n" + "|\n" + "|\n" + "|{{Yes}}\n" + "|{{Yes}}\n" + "|\n" + "|{{Yes}}\n" + "|-\n" + "|[[Aranea framework|Aranea MVC]]\n" + "| Java\n" + "| {{Yes}}\n" + "| \n" + "| Pull\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "|\n" + "|\n" + "|\n" + "|\n" + "|\n" + "|\n" + "|-\n" + "|[[CakePHP]]\n" + "| PHP\n" + "| {{Yes}}, [[Prototype JavaScript Framework|Prototype]], [[script.aculo.us]]\n" + "| [[Active record pattern|ActiveRecord]]\n" + "| Push\n" + "| {{Yes}}, Development branch\n" + "| {{Yes}}, [[Active record pattern|ActiveRecord]]\n" + "| {{Yes}}, [[Unit testing|Unit Tests]]\n" + "| {{Yes}}\n" + "| {{Yes}}, [[Access control list|ACL-based]]\n" + "| {{Yes}}\n" + "| {{Yes}}, Development branch\n" + "| {{Yes}}\n" + "|-\n" + "|[[Camping (microframework)|Camping]]\n" + "| Ruby\n" + "| {{No}}\n" + "| {{Yes}}\n" + "| Push\n" + "| {{No}}\n" + "| {{Yes}}, [[Active record pattern|ActiveRecord]]\n" + "| {{Yes}}, via [http://mosquito.rubyforge.org/ Mosquito]\n" + "| {{Yes}}\n" + "| {{No}}\n" + "| {{Yes}}\n" + "| {{No}}\n" + "| {{No}}\n" + "|-\n" + "|[[Catalyst (software)|Catalyst]]\n" + "| Perl\n" + "| {{Yes}}, multiple ([[Prototype JavaScript Framework|Prototype]], [[Dojo Toolkit|Dojo]]...)\n" + "| {{Yes}}\n" + "| Push in its most common usage\n" + "| {{Yes}}\n" + "| {{Yes}}, multiple ([[DBIx::Class]], [[Rose::DB]]...)\n" + "| {{Yes}}<ref name=\"catalysttest\">http://search.cpan.org/dist/Catalyst-Manual/lib/Catalyst/Manual/Tutorial/Testing.pod</ref>\n" + "|\n" + "| {{Yes}}, multiple ([[Access control list|ACL-based]], external engines...)\n" + "| {{Yes}}, multiple (Template::Toolkit, HTML::Template, HTML::Mason...)\n" + "| {{Yes}}, multiple (Memcached, TurckMM, shared memory,...)\n" + "| {{Yes}}, multiple (HTML::FormValidator,...)\n" + "|-\n" + "|[[CodeIgniter]]\n" + "| PHP\n" + "| {{No}}\n" + "| {{Yes}}, Modified [[Active record pattern|ActiveRecord]]\n" + "| Push\n" + "| {{Yes}}\n" + "| {{No}}\n" + "| {{Yes}}, [[Unit testing|Unit Tests]]\n" + "| {{No}}\n" + "| {{Yes}}\n" + "| {{No}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "|-\n" + "|[[ColdBox]]\n" + "| [[ColdFusion]]\n" + "| {{Yes}}, via CF or any JavaScript Library\n" + "| {{Yes}}\n" + "| Push\n" + "| {{Yes}} provided by framework\n" + "| {{Yes}} [[Transfer]], [[Reactor]], [[Hibernate]], ObjectBreeze\n" + "| {{Yes}}, Integrated into Core Framework, [[CFUnit]], [[CFCUnit]]\n" + "| {{No}}\n" + "| {{Yes}}, via plugin or interceptors\n" + "| {{Yes}}\n" + "| {{Yes}}, ColdBox Internal Caching Engine, and via [[ColdSpring]]\n" + "| {{Yes}}, via cf validation or custom interceptors\n" + "|-\n" + "|[[Django (web framework)|Django]]\n" + "| Python\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| Push\n" + "| {{Yes}}\n" + "| {{Yes}}, [[Django ORM]], [[SQLAlchemy]]\n" + "| {{Yes}}\n" + "| {{No}}\n" + "| {{Yes}}, [[Access control list|ACL-based]]\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "|-\n" + "|[[DotNetNuke]]\n" + "| .NET\n" + "| {{Yes}}\n" + "| \n" + "| Pull\n" + "| {{Yes}}\n" + "| {{Yes}}, SubSonic, NHibernate\n" + "|\n" + "|\n" + "|\n" + "|\n" + "|\n" + "|\n" + "|-\n" + "|[[Fusebox (programming)|Fusebox]]\n" + "| [[ColdFusion]], [[PHP]]\n" + "| {{Yes}}\n" + "| {{Yes}}, but not mandatory\n" + "| Push\n" + "| {{No}}, custom\n" + "| {{Yes}}, via lexicons for [http://compoundtheory.com/transfer Transfer] and [http://www.reactorframework.org Reactor]\n" + "| {{Yes}}, [[CFUnit]], [[CFCUnit]]\n" + "|\n" + "| {{Yes}}, multiple plugins available\n" + "|\n" + "| {{Yes}}, via lexicon for [http://coldspringframework.org ColdSpring]\n" + "| {{Yes}}, via qforms or built in cf validation\n" + "|-\n" + "| [http://mdp.cti.depaul.edu/examples Gluon]\n" + "| Python\n" + "| Via third party libraries\n" + "| {{Yes}}\n" + "| Push\n" + "| {{Yes}} provided by framework\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| Via third party wsgi modules\n" + "| {{Yes}}\n" + "|-\n" + "|[[Grails (Framework)|Grails]]\n" + "| [[Groovy (programming language)|Groovy]]\n" + "| {{Yes}}\n" + "| [[Active record pattern|ActiveRecord]]\n" + "| Push\n" + "| {{Yes}}\n" + "| {{Yes}}, GORM, [[Hibernate (Java)|Hibernate]]\n" + "| {{Yes}}, [[Unit Test|Unit Test]]\n" + "| {{No}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "|-\n" + "|[[InterJinn]]\n" + "| PHP\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| Push & Pull\n" + "| {{No}}, custom\n" + "| {{No}}\n" + "|\n" + "|\n" + "|\n" + "| {{Yes}}, TemplateJinn\n" + "| {{Yes}}\n" + "| {{Yes}}, FormJinn\n" + "|-\n" + "|[[JBoss Seam]]\n" + "| Java\n" + "| {{Yes}}\n" + "| \n" + "| Pull\n" + "| {{Yes}}\n" + "| {{Yes}}, [[Java Persistence API|JPA]], [[Hibernate (Java)|Hibernate]]\n" + "| {{Yes}}, [[JUnit]], [[TestNG]]\n" + "|\n" + "| {{Yes}}, [[JAAS]] integration\n" + "| {{Yes}}, [[Facelets]]\n" + "|\n" + "| {{Yes}}, [[Hibernate Validator]]\n" + "|-\n" + "| [[Jifty]]\n" + "| Perl\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| Push\n" + "| {{Yes}}\n" + "| {{Yes}}, [[Jifty::DBI]]\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}, [[Mason (Perl)|Mason]], Template::Declare\n" + "| {{Yes}}, Memcached\n" + "| {{Yes}}\n" + "|-\n" + "|-\n" + "| [[Kumbia]]\n" + "| PHP5\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| x\n" + "| x\n" + "| [[Active record pattern|ActiveRecord]]\n" + "| x\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}, [[Smarty]]\n" + "| {{Yes}}, Memcached\n" + "| {{Yes}}\n" + "|-\n" + "|[[Mach-II]]\n" + "| [[ColdFusion]]\n" + "| {{Yes}}, via CF or any JavaScript Library\n" + "| {{Yes}}\n" + "| Push\n" + "| {{Yes}}, via custom plugin\n" + "| {{Yes}} [[Transfer]], [[Reactor]], [[Hibernate]]\n" + "| {{Yes}}, [[CFUnit]], [[CFCUnit]]\n" + "| \n" + "| {{Yes}}, via plugin\n" + "|\n" + "| {{Yes}}, [[ColdSpring]]\n" + "| \n" + "|-\n" + "|[[Model-Glue::Unity]]\n" + "| [[ColdFusion]]\n" + "| {{Yes}}, via CF or any JavaScript Library\n" + "| {{Yes}}\n" + "| Push\n" + "| {{Yes}}, via custom plugin\n" + "| {{Yes}} [[Transfer]], [[Reactor]], [[Hibernate]]\n" + "| {{Yes}}, [[CFUnit]], [[CFCUnit]]\n" + "|\n" + "| {{Yes}}, via plugin\n" + "| \n" + "| {{Yes}}, [[Coldspring]]\n" + "| {{Yes}}\n" + "|-\n" + "|[[Monorail (.Net)|MonoRail]]\n" + "| .NET\n" + "| {{Yes}}, [[Prototype JavaScript Framework|Prototype]]\n" + "| [[Active record pattern|ActiveRecord]]\n" + "| Push\n" + "| {{Yes}}\n" + "| {{Yes}}, [[Active record pattern|ActiveRecord]]\n" + "| {{Yes}}, [[Unit testing|Unit Tests]]\n" + "|\n" + "| {{Yes}}, via [[ASP.NET]] Forms Authentication\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "|-\n" + "|[[Nitro (web framework)|Nitro]]\n" + "| Ruby\n" + "| {{Yes}}, [[jQuery]]\n" + "| {{Yes}}\n" + "| Push\n" + "| {{Yes}}\n" + "| {{Yes}}, [[Nitro (web framework)#Og|Og]]\n" + "| {{Yes}}, [[RSpec]]\n" + "| {{Yes}} (automatic)\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "|-\n" + "|[[PHPulse]]\n" + "| PHP\n" + "| {{Yes}},\n" + "| {{Yes}},\n" + "| Push\n" + "| {{Yes}},\n" + "| {{Yes}},\n" + "| {{Yes}}, [[Unit Testing|Unit Tests]]\n" + "|\n" + "| {{Yes}}, [[Access control list|ACL-based]]\n" + "| {{Yes}}, [[Smarty]]\n" + "| {{Yes}}, multiple (Memcached, TurckMM, shared memory,...)\n" + "| {{Yes}}\n" + "|-\n" + "|[[PRADO]]\n" + "| PHP5\n" + "| {{Yes}}, [[Active Controls]]\n" + "| {{Yes}}\n" + "| Push\n" + "| {{Yes}}\n" + "| {{Yes}}, [[ActiveRecord]], [[SQLMap]]\n" + "| {{Yes}}, [[PHPUnit]], [[SimpleTest]], [[Selenium]]\n" + "|\n" + "| {{Yes}}, modular and role-based ACL\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "|-\n" + "|[[Pylons (web framework)|Pylons]]\n" + "| Python\n" + "| {{Yes}}, helpers for [[Prototype JavaScript Framework|Prototype]] and [[script.aculo.us]]\n" + "| {{Yes}}\n" + "| Push\n" + "| {{Yes}}\n" + "| {{Yes}}, [[SQLObject]], [[SQLAlchemy]]\n" + "| {{Yes}}, via nose\n" + "|\n" + "|\n" + "| {{Yes}}, pluggable (mako, genshi, mighty, kid, ...)\n" + "| {{Yes}}, Beaker cache (memory, memcached, file, databases)\n" + "| {{Yes}}, preferred formencode\n" + "|-\n" + "| [[Qcodo]]\n" + "| PHP5\n" + "| {{Yes}}, built-in\n" + "| {{Yes}}, QControl\n" + "| Push\n" + "| {{Yes}}\n" + "| {{Yes}}, Code Generation-based\n" + "|\n" + "|\n" + "|\n" + "| {{Yes}}, QForm and QControl\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "|-\n" + "|[[RIFE]]\n" + "| Java\n" + "| {{Yes}}, [[DWR|DWR (Java)]]\n" + "| {{Yes}}\n" + "| Push & Pull\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}, Out of container testing\n" + "| \n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}, [[Terracotta Cluster|Integration with Terracotta]]\n" + "| {{Yes}}\n" + "|-\n" + "|[[Ruby on Rails]]\n" + "| Ruby\n" + "| {{Yes}}, [[Prototype JavaScript Framework|Prototype]], [[script.aculo.us]]\n" + "| [[Active record pattern|ActiveRecord]], [[Ruby on Rails|Action Pack]]\n" + "| Push\n" + "| {{Yes}}, Localization Plug-in\n" + "| {{Yes}}, [[Active record pattern|ActiveRecord]]\n" + "| {{Yes}}, [[Unit testing|Unit Tests]], Functional Tests and Integration Tests\n" + "| {{Yes}}\n" + "| {{Yes}}, Plug-in\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "|-\n" + "|[[Seaside web framework|Seaside]]\n" + "| Smalltalk\n" + "| {{Yes}}, [[Prototype JavaScript Framework|Prototype]], [[script.aculo.us]]\n" + "| \n" + "|\n" + "| {{Yes}}\n" + "| {{Yes}}, [[GLORP]], [[Gemstone Database Management System|Gemstone/S]], ...\n" + "|\n" + "|\n" + "|\n" + "|\n" + "|\n" + "|\n" + "|-\n" + "|[[Stripes]]\n" + "| Java\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| Push\n" + "| {{Yes}}\n" + "| {{Yes}}, [[Hibernate (Java)|Hibernate]]\n" + "| {{Yes}}\n" + "| \n" + "| {{Yes}}, framework extension\n" + "| {{Yes}}\n" + "| \n" + "| {{Yes}}\n" + "|-\n" + "|-\n" + "|[[Symfony]]\n" + "| PHP5\n" + "| {{Yes}}, [[Prototype JavaScript Framework|Prototype]], [[script.aculo.us]], Unobtrusive Ajax with UJS and PJS plugins\n" + "| {{Yes}}\n" + "| Push\n" + "| {{Yes}}\n" + "| {{Yes}}, [[Propel (PHP)|Propel]], [[Doctrine O/RM|Doctrine]]\n" + "| {{Yes}}\n" + "| Plugin exists (alpha code, though)\n" + "| {{Yes}}, plugin\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "|-\n" + "|[[Tigermouse]]\n" + "| PHP5\n" + "| {{Yes}}, it is mostly Ajax-only framework\n" + "| {{Yes}}, [[Active record pattern|ActiveRecord]]\n" + "| Push\n" + "| {{Yes}}\n" + "| {{Yes}}, [[Active record pattern|ActiveRecord]]\n" + "| {{No}}\n" + "| {{No}}, Multiple RBMSes and access libraries supported\n" + "| {{Yes}}, through intercepting filters ([[Access control list|ACL-based]], customizable)\n" + "| {{Yes}}\n" + "| {{No}}\n" + "| {{Yes}}\n" + "|-\n" + "|[[TurboGears]]\n" + "| Python\n" + "| {{Yes}}\n" + "| \n" + "|\n" + "| {{Yes}}\n" + "| {{Yes}}, [[SQLObject]], [[SQLAlchemy]]\n" + "|\n" + "|\n" + "|\n" + "|\n" + "|\n" + "|\n" + "|-\n" + "|[[WebLEAF]]\n" + "| Java\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| Push\n" + "| {{Yes}}\n" + "| {{Yes}} [[Hibernate]], [[EJB]]\n" + "|\n" + "|\n" + "| {{Yes}}, extensible through custom interfaces\n" + "| {{Yes}} [[XSLT]], [[FreeMarker]]\n" + "|\n" + "|\n" + "|-\n" + "|[[WebObjects]]\n" + "| Java\n" + "| {{Yes}}\n" + "| \n" + "|\n" + "| {{Yes}}\n" + "| {{Yes}}, [[Enterprise Objects Framework|EOF]]\n" + "|\n" + "|\n" + "|\n" + "|\n" + "|\n" + "|\n" + "|-\n" + "|[[Zend Framework]]\n" + "| PHP5 (>=5.1.4)\n" + "| {{Yes}}, [[JavaScript library|various libraries]]\n" + "| {{Yes}}\n" + "| Push\n" + "| {{Yes}}\n" + "| {{Yes}}, Table and Row data gateway\n" + "| {{Yes}}, [[Unit testing|Unit Tests]]\n" + "| {{Yes}}\n" + "| {{Yes}}, [[Access control list|ACL-based]]\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "|-\n" + "|[[Zope]]2\n" + "| Python\n" + "|\n" + "| {{Yes}}\n" + "| Pull\n" + "| {{Yes}}\n" + "| {{Yes}}, native OODBMS called [[Zope Object Database|ZODB]], [[SQLObject]], [[SQLAlchemy]]\n" + "| {{Yes}}, [[Unit testing|Unit Tests]]\n" + "| \n" + "| {{Yes}}, [[Access control list|ACL-based]]\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}, CMFFormController\n" + "|-\n" + "|[[Zope]]3\n" + "| Python\n" + "| {{Yes}}, via add-on products, e.g. [[Plone_(software)|Plone]] w/KSS \n" + "| {{Yes}}\n" + "| Pull\n" + "| {{Yes}}\n" + "| {{Yes}}, native OODBMS called [[Zope Object Database|ZODB]], [[SQLObject]], [[SQLAlchemy]]\n" + "| {{Yes}}, [[Unit testing|Unit Tests]], Functional Tests\n" + "| {{Yes}}, ZODB generations\n" + "| {{Yes}}, [[Access control list|ACL-based]]\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "| {{Yes}}\n" + "|-class=\"sortbottom\"\n" + "!Project\n" + "!Language\n" + "![[Ajax (programming)|Ajax]]\n" + "![[Model-view-controller|MVC]] framework\n" + "![[Web_application_framework#Push-based_vs._Pull-based|MVC Push/Pull]]\n" + "![[Internationalization_and_localization|i18n & l10n?]]\n" + "![[Object-relational mapping|ORM]]\n" + "!Testing framework(s)\n" + "!DB migration framework(s)\n" + "!Security Framework(s)\n" + "!Template Framework(s)\n" + "!Caching Framework(s)\n" + "!Form Validation Framework(s)\n" + "|}"; Table t = parse(content); System.out.println(t); Row row = t.getRows()[1]; assertEquals(13, row.getCells().length); for (int i = 0; i < row.getCells().length; i++) { assertNull(row.getCells()[i].getOptions()); } assertEquals("[[Agavi_(framework)|Agavi]]", row.getCells()[0].getContent()[0].toString()); assertEquals(" PHP", row.getCells()[1].getContent()[0].toString()); assertEquals(" ", row.getCells()[2].getContent()[0].toString()); assertEquals(" {{Yes}}", row.getCells()[3].getContent()[0].toString()); assertEquals(" Push", row.getCells()[4].getContent()[0].toString()); assertEquals(" {{Yes}}", row.getCells()[5].getContent()[0].toString()); assertEquals(" {{Yes}}", row.getCells()[6].getContent()[0].toString()); assertEquals(" {{Yes}}", row.getCells()[7].getContent()[0].toString()); assertEquals(" {{Yes}}", row.getCells()[8].getContent()[0].toString()); assertEquals(" {{Yes}}", row.getCells()[9].getContent()[0].toString()); assertEquals(" {{Yes}}", row.getCells()[10].getContent()[0].toString()); assertEquals(" {{Yes}}", row.getCells()[11].getContent()[0].toString()); assertEquals(" {{Yes}}", row.getCells()[12].getContent()[0].toString()); } public void testLanguagesTable() throws Exception { String content = "{| class=\"wikitable sortable\"\n" + "|- style=\"background-color: #efefef;\"\n" + "!639-1!!639-2!!639-3!!Language name!!Native name!!comment\n" + "|-\n" + "|aa||aar||aar||[[Afar language|Afar]]||lang=\"aa\"|Afaraf||\n" + "|-\n" + "|ab||abk||abk||[[Abkhaz language|Abkhazian]]||lang=\"ab\"|�?ҧ�?уа||\n" + "|-\n" + "|ae||ave||ave||[[Avestan language|Avestan]]||lang=\"ae\"|avesta||\n" + "|-\n" + "|af||afr||afr||[[Afrikaans]]||lang=\"af\"|Afrikaans||\n" + "|-\n" + "|ak||aka||aka + [[ISO 639:aka|2]]||[[Akan languages|Akan]]||lang=\"ak\"|Akan||\n" + "|-\n" + "|am||amh||amh||[[Amharic language|Amharic]]||lang=\"am\"|አማርኛ||\n" + "|-\n" + "|an||arg||arg||[[Aragonese language|Aragonese]]||lang=\"an\"|Aragonés||\n" + "|-\n" + "|ar||ara||ara + [[ISO 639:ara|30]]||[[Arabic language|Arabic]]||lang=\"ar\" dir=\"rtl\"|‫العربية||Standard Arabic is [arb]\n" + "|-\n" + "|as||asm||asm||[[Assamese language|Assamese]]||lang=\"as\"|অসমীয়া||\n" + "|-\n" + "|av||ava||ava||[[Avar language|Avaric]]||lang=\"av\"|авар мацӀ; магӀарул мацӀ||\n" + "|-\n" + "|ay||aym||aym + [[ISO 639:aym|2]]||[[Aymara language|Aymara]]||lang=\"ay\"|aymar aru||\n" + "|-\n" + "|az||aze||aze + [[ISO 639:aze|2]]||[[Azerbaijani language|Azerbaijani]]||lang=\"az\"|azərbaycan dili||\n" + "|-\n" + "|ba||bak||bak||[[Bashkir language|Bashkir]]||lang=\"ba\"|башҡорт теле||\n" + "|-\n" + "|be||bel||bel||[[Belarusian language|Belarusian]]||lang=\"be\"|Белару�?ка�?||\n" + "|-\n" + "|bg||bul||bul||[[Bulgarian language|Bulgarian]]||lang=\"bg\"|българ�?ки език||\n" + "|-\n" + "|bh||bih||--||[[Bihari languages|Bihari]]||lang=\"bh\"|भोजप�?री||collective language code for Bhojpuri, Magahi, and Maithili\n" + "|-\n" + "|bi||bis||bis||[[Bislama language|Bislama]]||lang=\"bi\"|Bislama||\n" + "|-\n" + "|bm||bam||bam||[[Bambara language|Bambara]]||lang=\"bm\"|bamanankan||\n" + "|-\n" + "|bn||ben||ben||[[Bengali language|Bengali]]||lang=\"bn\"|বাংলা||\n" + "|-\n" + "|bo||tib/bod||bod||[[Tibetan language|Tibetan]]||lang=\"bo\"|བོད་ཡིག||\n" + "|-\n" + "|br||bre||bre||[[Breton language|Breton]]||lang=\"br\"|brezhoneg||\n" + "|-\n" + "|bs||bos||bos||[[Bosnian language|Bosnian]]||lang=\"bs\"|bosanski jezik||\n" + "|-\n" + "|ca||cat||cat||[[Catalan language|Catalan]]||lang=\"ca\"|Català||\n" + "|-\n" + "|ce||che||che||[[Chechen language|Chechen]]||lang=\"ce\"|нохчийн мотт||\n" + "|-\n" + "|ch||cha||cha||[[Chamorro language|Chamorro]]||lang=\"ch\"|Chamoru||\n" + "|-\n" + "|co||cos||cos||[[Corsican language|Corsican]]||lang=\"co\"|corsu; lingua corsa||\n" + "|-\n" + "|cr||cre||cre + [[ISO 639:cre|6]]||[[Cree language|Cree]]||lang=\"cr\"|ᓀ�?��?�ᔭ�??�??�?�||\n" + "|-\n" + "|cs||cze/ces||ces||[[Czech language|Czech]]||lang=\"cs\"|�?esky; �?eština||\n" + "|-\n" + "|cu||chu||chu||[[Old Church Slavonic|Church Slavic]]||||\n" + "|-\n" + "|cv||chv||chv||[[Chuvash language|Chuvash]]||lang=\"cv\"|чӑваш чӗлхи||\n" + "|-\n" + "|cy||wel/cym||cym||[[Welsh language|Welsh]]||lang=\"cy\"|Cymraeg||\n" + "|-\n" + "|da||dan||dan||[[Danish language|Danish]]||lang=\"da\"|dansk||\n" + "|-\n" + "|de||ger/deu||deu||[[German language|German]]||lang=\"de\"|Deutsch||\n" + "|-\n" + "|dv||div||div||[[Dhivehi language|Divehi]]||lang=\"dv\" dir=\"rtl\"|‫ދިވެހި||\n" + "|-\n" + "|dz||dzo||dzo||[[Dzongkha language|Dzongkha]]||lang=\"dz\"|རྫོང་�?||\n" + "|-\n" + "|ee||ewe||ewe||[[Ewe language|Ewe]]||lang=\"ee\"|�?ʋɛgbɛ||\n" + "|-\n" + "|el||gre/ell||ell||[[Greek language|Greek]]||lang=\"el\"|Ελληνικά||\n" + "|-\n" + "|en||eng||eng||[[English language|English]]||lang=\"en\"|English||\n" + "|-\n" + "|eo||epo||epo||[[Esperanto]]||lang=\"eo\"|Esperanto||\n" + "|-\n" + "|es||spa||spa||[[Spanish language|Spanish]]||lang=\"es\"|español; castellano||\n" + "|-\n" + "|et||est||est||[[Estonian language|Estonian]]||lang=\"et\"|Eesti keel||\n" + "|-\n" + "|eu||baq/eus||eus||[[Basque language|Basque]]||lang=\"eu\"|euskara||\n" + "|-\n" + "|fa||per/fas||fas + [[ISO 639:fas|2]]||[[Persian language|Persian]]||lang=\"fa\" dir=\"rtl\"|‫�?ارسی||\n" + "|-\n" + "|ff||ful||ful + [[ISO 639:ful|9]]||[[Fula language|Fulah]]||lang=\"ff\"|Fulfulde||\n" + "|-\n" + "|fi||fin||fin||[[Finnish language|Finnish]]||lang=\"fi\"|suomen kieli||\n" + "|-\n" + "|fj||fij||fij||[[Fijian language|Fijian]]||lang=\"fj\"|vosa Vakaviti||\n" + "|-\n" + "|fo||fao||fao||[[Faroese language|Faroese]]||lang=\"fo\"|Føroyskt||\n" + "|-\n" + "|fr||fre/fra||fra||[[French language|French]]||lang=\"fr\"|français; langue française||\n" + "|-\n" + "|fy||fry||fry + [[ISO 639:fry|3]]||[[West Frisian language|Western Frisian]]||lang=\"fy\"|Frysk||\n" + "|-\n" + "|ga||gle||gle||[[Irish language|Irish]]||lang=\"ga\"|Gaeilge||\n" + "|-\n" + "|gd||gla||gla||[[Scottish Gaelic language|Scottish Gaelic]]||lang=\"gd\"|Gàidhlig||\n" + "|-\n" + "|gl||glg||glg||[[Galician language|Galician]]||lang=\"gl\"|Galego||\n" + "|-\n" + "|gn||grn||grn + [[ISO 639:grn|5]]||[[Guaraní language|Guaraní]]||lang=\"gn\"|Avañe'ẽ||\n" + "|-\n" + "|gu||guj||guj||[[Gujarati language|Gujarati]]||lang=\"gu\"|ગ�?જરાતી||\n" + "|-\n" + "|gv||glv||glv||[[Manx language|Manx]]||lang=\"gv\"|Ghaelg||\n" + "|-\n" + "|ha||hau||hau||[[Hausa language|Hausa]]||lang=\"ha\" dir=\"rtl\"|‫هَو�?سَ||\n" + "|-\n" + "|he||heb||heb||[[Hebrew language|Hebrew]]||lang=\"he\" dir=\"rtl\"|‫עברית||\n" + "|-\n" + "|hi||hin||hin||[[Hindi]]||lang=\"hi\"|हिन�?दी; हिंदी||\n" + "|-\n" + "|ho||hmo||hmo||[[Hiri Motu language|Hiri Motu]]||lang=\"ho\"|Hiri Motu||\n" + "|-\n" + "|hr||scr/hrv||hrv||[[Croatian language|Croatian]]||lang=\"hr\"|Hrvatski||\n" + "|-\n" + "|ht||hat||hat||[[Haitian Creole language|Haitian]]||lang=\"ht\"|Kreyòl ayisyen||\n" + "|-\n" + "|hu||hun||hun||[[Hungarian language|Hungarian]]||lang=\"hu\"|Magyar||\n" + "|-\n" + "|hy||arm/hye||hye||[[Armenian language|Armenian]]||lang=\"hy\"|Հայերեն||\n" + "|-\n" + "|hz||her||her||[[Herero language|Herero]]||lang=\"hz\"|Otjiherero||\n" + "|-\n" + "|ia||ina||ina||[[Interlingua|Interlingua (International Auxiliary Language Association)]]||lang=\"ia\"|interlingua||\n" + "|-\n" + "|id||ind||ind||[[Indonesian language|Indonesian]]||lang=\"id\"|Bahasa Indonesia||\n" + "|-\n" + "|ie||ile||ile||[[Interlingue language|Interlingue]]||lang=\"ie\"|Interlingue||\n" + "|-\n" + "|ig||ibo||ibo||[[Igbo language|Igbo]]||lang=\"ig\"|Igbo||\n" + "|-\n" + "|ii||iii||iii||[[Yi language|Sichuan Yi]]||lang=\"ii\"|ꆇꉙ||\n" + "|-\n" + "|ik||ipk||ipk + [[ISO 639:ipk|2]]||[[Inupiaq language|Inupiaq]]||lang=\"ik\"|Iñupiaq; Iñupiatun||\n" + "|-\n" + "|io||ido||ido||[[Ido]]||lang=\"io\"|Ido||\n" + "|-\n" + "|is||ice/isl||isl||[[Icelandic language|Icelandic]]||lang=\"is\"|�?slenska||\n" + "|-\n" + "|it||ita||ita||[[Italian language|Italian]]||lang=\"it\"|Italiano||\n" + "|-\n" + "|iu||iku||iku + [[ISO 639:iku|2]]||[[Inuktitut]]||lang=\"iu\"|�?�ᓄᒃᑎ�?ᑦ||\n" + "|-\n" + "|ja||jpn||jpn||[[Japanese language|Japanese]]||{{lang|ja-Hani|日本語}} ({{lang|ja-Hira|�?��?�ん�?��?�?��?��?�ん�?�}})||\n" + "|-\n" + "|jv||jav||jav||[[Javanese language|Javanese]]||lang=\"jv\"|basa Jawa||\n" + "|-\n" + "|ka||geo/kat||kat||[[Georgian language|Georgian]]||lang=\"ka\"|ქ�?რთული||\n" + "|-\n" + "|kg||kon||kon + [[ISO 639:kon|3]]||[[Kongo language|Kongo]]||lang=\"kg\"|KiKongo||\n" + "|-\n" + "|ki||kik||kik||[[Gikuyu language|Kikuyu]]||lang=\"ki\"|Gĩkũyũ||\n" + "|-\n" + "|kj||kua||kua||[[Kwanyama|Kwanyama]]||lang=\"kj\"|Kuanyama||\n" + "|-\n" + "|kk||kaz||kaz||[[Kazakh language|Kazakh]]||lang=\"kk\"|Қазақ тілі||\n" + "|-\n" + "|kl||kal||kal||[[Kalaallisut language|Kalaallisut]]||lang=\"kl\"|kalaallisut; kalaallit oqaasii||\n" + "|-\n" + "|km||khm||khm||[[Khmer language|Khmer]]||lang=\"km\"|ភាសា�?្មែរ||\n" + "|-\n" + "|kn||kan||kan||[[Kannada language|Kannada]]||lang=\"kn\"|ಕನ�?ನಡ||\n" + "|-\n" + "|ko||kor||kor||[[Korean language|Korean]]||{{lang|ko-Hang|한국어}} ({{lang|ko-Hani|韓國語}}); {{lang|ko-Hang|조선�?}} ({{lang|ko-Hani|�?鮮語}})<!-- ideograph is used in Korea-->||\n" + "|-\n" + "|kr||kau||kau + [[ISO 639:kau|3]]||[[Kanuri language|Kanuri]]||lang=\"kr\"|Kanuri||\n" + "|-\n" + "|ks||kas||kas||[[Kashmiri language|Kashmiri]]||{{lang|ks-Deva|कश�?मीरी}}; {{rtl-lang|ks-Arb|كشميري}}||\n" + "|-\n" + "|ku||kur||kur + [[ISO 639:kur|3]]||[[Kurdish language|Kurdish]]||{{lang|ku-Latn|Kurdî}}; {{rtl-lang|ku-Arab|كوردی}}||\n" + "|-\n" + "|kv||kom||kom + [[ISO 639:kom|2]]||[[Komi language|Komi]]||lang=\"kv\"|коми кыв||\n" + "|-\n" + "|kw||cor||cor||[[Cornish language|Cornish]]||lang=\"kw\"|Kernewek||\n" + "|-\n" + "|ky||kir||kir||[[Kyrgyz language|Kirghiz]]||lang=\"ky\"|кыргыз тили||\n" + "|-\n" + "|la||lat||lat||[[Latin]]||lang=\"la\"|latine; lingua latina||\n" + "|-\n" + "|lb||ltz||ltz||[[Luxembourgish language|Luxembourgish]]||lang=\"lb\"|Lëtzebuergesch||\n" + "|-\n" + "|lg||lug||lug||[[Luganda language|Ganda]]||lang=\"lg\"|Luganda||\n" + "|-\n" + "|li||lim||lim||[[Limburgish language|Limburgish]]||lang=\"li\"|Limburgs||\n" + "|-\n" + "|ln||lin||lin||[[Lingala language|Lingala]]||lang=\"ln\"|Lingála||\n" + "|-\n" + "|lo||lao||lao||[[Lao language|Lao]]||lang=\"lo\"|ພາສາລາວ||\n" + "|-\n" + "|lt||lit||lit||[[Lithuanian language|Lithuanian]]||lang=\"lt\"|lietuvių kalba||\n" + "|-\n" + "|lu||lub||lub||[[Tshiluba language|Luba-Katanga]]||||\n" + "|-\n" + "|lv||lav||lav||[[Latvian language|Latvian]]||lang=\"lv\"|latviešu valoda||\n" + "|-\n" + "|mg||mlg||mlg + [[ISO 639:mlg|10]]||[[Malagasy language|Malagasy]]||lang=\"mg\"|Malagasy fiteny||\n" + "|-\n" + "|mh||mah||mah||[[Marshallese language|Marshallese]]||lang=\"mh\"|Kajin M̧ajeļ||\n" + "|-\n" + "|mi||mao/mri||mri||[[M�?ori language|M�?ori]]||lang=\"mi\"|te reo M�?ori||\n" + "|-\n" + "|mk /sl ||mac/mkd||mkd||[[Macedonian language|Macedonian]]||lang=\"mk\"|македон�?ки јазик||\n" + "|-\n" + "|ml||mal||mal||[[Malayalam language|Malayalam]]||lang=\"ml\"|മലയാളം||\n" + "|-\n" + "|mn||mon||mon + [[ISO 639:mon|2]]||[[Mongolian language|Mongolian]]||lang=\"mn\"|Монгол||\n" + "|-\n" + "|mo||mol||mol||[[Moldovan language|Moldavian]]||lang=\"mo\"|лимба молдовен�?�?к�?||\n" + "|-\n" + "|mr||mar||mar||[[Marathi language|Marathi]]||lang=\"mr\"|मराठी||\n" + "|-\n" + "|ms||may/msa||msa + [[ISO 639:msa|13]]||[[Malay language|Malay]]||{{lang|ms|bahasa Melayu}}; {{rtl-lang|ms-Arab|بهاس ملايو}} ||Malay (specific) is [mly]\n" + "|-\n" + "|mt||mlt||mlt||[[Maltese language|Maltese]]||lang=\"mt\"|Malti||\n" + "|-\n" + "|my||bur/mya||mya||[[Burmese language|Burmese]]||lang=\"my\"|ဗမာစာ||\n" + "|-\n" + "|na||nau||nau||[[Nauruan language|Nauru]]||lang=\"na\"|Ekakairũ Naoero||\n" + "|-\n" + "|nb||nob||nob||[[Bokmål|Norwegian Bokmål]]||lang=\"nb\"|Norsk bokmål||\n" + "|-\n" + "|nd||nde||nde||[[Northern Ndebele language|North Ndebele]]||lang=\"nd\"|isiNdebele||\n" + "|-\n" + "|ne||nep||nep||[[Nepali language|Nepali]]||lang=\"ne\"|नेपाली||\n" + "|-\n" + "|ng||ndo||ndo||[[Ndonga]]||lang=\"ng\"|Owambo||\n" + "|-\n" + "|nl||dut/nld||nld||[[Dutch language|Dutch]]||lang=\"nl\"|Nederlands||\n" + "|-\n" + "|nn||nno||nno||[[Nynorsk|Norwegian Nynorsk]]||lang=\"nn\"|Norsk nynorsk||\n" + "|-\n" + "|no||nor||nor + [[ISO 639:nor|2]]||[[Norwegian language|Norwegian]]||lang=\"no\"|Norsk||\n" + "|-\n" + "|nr||nbl||nbl||[[Southern Ndebele language|South Ndebele]]||lang=\"nr\"|Ndébélé||\n" + "|-\n" + "|nv||nav||nav||[[Navajo language|Navajo]]||lang=\"nv\"|Diné bizaad; Dinékʼehǰí||\n" + "|-\n" + "|ny||nya||nya||[[Chichewa language|Chichewa]]||lang=\"ny\"|chiCheŵa; chinyanja||\n" + "|-\n" + "|oc||oci||oci + [[ISO 639:oci|5]]||[[Occitan language|Occitan]]||lang=\"oc\"|Occitan||\n" + "|-\n" + "|oj||oji||oji + [[ISO 639:oji|7]]||[[Anishinaabe language|Ojibwa]]||lang=\"oj\"|�?�ᓂᔑᓈ�?�ᒧ�?��?||\n" + "|-\n" + "|om||orm||orm + [[ISO 639:orm|4]]||[[Oromo language|Oromo]]||lang=\"om\"|Afaan Oromoo||\n" + "|-\n" + "|or||ori||ori||[[Oriya language|Oriya]]||lang=\"or\"|ଓଡ଼ିଆ||\n" + "|-\n" + "|os||oss||oss||[[Ossetic language|Ossetian]]||lang=\"os\"|Ирон æвзаг||\n" + "|-\n" + "|pa||pan||pan||[[Punjabi language|Panjabi]]||{{lang|pa|ਪੰਜਾਬੀ}}; {{rtl-lang|pa-Arab|پنجابی}}||\n" + "|-\n" + "|pi||pli||pli||[[P�?li language|P�?li]]||lang=\"pi\"|पािऴ||\n" + "|-\n" + "|pl||pol||pol||[[Polish language|Polish]]||lang=\"pl\"|polski||\n" + "|-\n" + "|ps||pus||pus + [[ISO 639:pus|3]]||[[Pashto language|Pashto]]||lang=\"ps\" dir=\"rtl\"|‫پښتو||\n" + "|-\n" + "|pt||por||por||[[Portuguese language|Portuguese]]||lang=\"pt\"|Português||\n" + "|-\n" + "|qu||que||que + [[ISO 639:que|44]]||[[Quechua]]||lang=\"qu\"|Runa Simi; Kichwa||\n" + "|-\n" + "|rm||roh||roh||[[Romansh|Raeto-Romance]]||lang=\"rm\"|rumantsch grischun||\n" + "|-\n" + "|rn||run||run||[[Kirundi language|Kirundi]]||lang=\"rn\"|kiRundi||\n" + "|-\n" + "|ro||rum/ron||ron||[[Romanian language|Romanian]]||lang=\"ro\"|română||\n" + "|-\n" + "|ru||rus||rus||[[Russian language|Russian]]||lang=\"ru\"|ру�?�?кий �?зык||\n" + "|-\n" + "|rw||kin||kin||[[Kinyarwanda language|Kinyarwanda]]||lang=\"rw\"|Kinyarwanda||\n" + "|-\n" + "|ry||sla/rue||rue||[[Rusyn language|Rusyn]]||lang=\"ry\"|ру�?ин�?ькый �?зык||\n" + "|-\n" + "|sa||san||san||[[Sanskrit]]||lang=\"sa\"|संस�?कृतम�?||\n" + "|-\n" + "|sc||srd||srd + [[ISO 639:srd|4]]||[[Sardinian language|Sardinian]]||lang=\"sc\"|sardu||\n" + "|-\n" + "|sd||snd||snd||[[Sindhi language|Sindhi]]||{{lang|sd-Deva|सिन�?धी}}; {{rtl-lang|sd-Arab|‫سنڌي، سندھی}}||\n" + "|-\n" + "|se||sme||sme||[[Northern Sami]]||lang=\"se\"|Davvisámegiella||\n" + "|-\n" + "|sg||sag||sag||[[Sango language|Sango]]||lang=\"sg\"|yângâ tî sängö||\n" + "|-\n" + "|sh||--||hbs + [[ISO 639:hbs|3]]||[[Serbo-Croatian]]||lang=\"sh\"|Srpskohrvatski/Срп�?кохрват�?ки||\n" + "|-\n" + "|si||sin||sin||[[Sinhalese language|Sinhalese]]||lang=\"si\"|සිංහල||\n" + "|-\n" + "|sk||slo/slk||slk||[[Slovak language|Slovak]]||lang=\"sk\"|sloven�?ina||\n" + "|-\n" + "|sl||slv||slv||[[Slovenian language|Slovenian]]||lang=\"sl\"|slovenš�?ina||\n" + "|-\n" + "|sm||smo||smo||[[Samoan language|Samoan]]||lang=\"sm\"|gagana fa'a Samoa||\n" + "|-\n" + "|sn||sna||sna||[[Shona language|Shona]]||lang=\"sn\"|chiShona||\n" + "|-\n" + "|so||som||som||[[Somali language|Somali]]||lang=\"so\"|Soomaaliga; af Soomaali||\n" + "|-\n" + "|sq||alb/sqi||sqi + [[ISO 639:sqi|4]]||[[Albanian language|Albanian]]||lang=\"sq\"|Shqip||\n" + "|-\n" + "|sr||scc/srp||srp||[[Serbian language|Serbian]]||lang=\"sr\"|�?рп�?ки језик||\n" + "|-\n" + "|ss||ssw||ssw||[[Swati language|Swati]]||lang=\"ss\"|SiSwati||\n" + "|-\n" + "|st||sot||sot||[[Sotho language|Sotho]]||lang=\"st\"|seSotho||\n" + "|-\n" + "|su||sun||sun||[[Sundanese language|Sundanese]]||lang=\"su\"|Basa Sunda||\n" + "|-\n" + "|sv||swe||swe||[[Swedish language|Swedish]]||lang=\"sv\"|Svenska||\n" + "|-\n" + "|sw||swa||swa + [[ISO 639:swa|2]]||[[Swahili language|Swahili]]||lang=\"sw\"|Kiswahili||\n" + "|-\n" + "|ta||tam||tam||[[Tamil language|Tamil]]||lang=\"ta\"|தமிழ�?||\n" + "|-\n" + "|te||tel||tel||[[Telugu language|Telugu]]||lang=\"te\"|తెల�?గ�?||\n" + "|-\n" + "|tg||tgk||tgk||[[Tajik language|Tajik]]||{{lang|tg-Cyrl|тоҷикӣ}}; {{lang|tg-Latn|toğikī}}; {{rtl-lang|tg-Arab|‫تاجیکی}}||\n" + "|-\n" + "|th||tha||tha||[[Thai language|Thai]]||lang=\"th\"|ไทย||\n" + "|-\n" + "|ti||tir||tir||[[Tigrinya language|Tigrinya]]||lang=\"ti\"|ት�?ርኛ||\n" + "|-\n" + "|tk||tuk||tuk||[[Turkmen language|Turkmen]]||lang=\"tk\"|Türkmen; Түркмен||\n" + "|-\n" + "|tl||tgl||tgl||[[Tagalog language|Tagalog]]||lang=\"tl\"|Tagalog||\n" + "|-\n" + "|tn||tsn||tsn||[[Tswana language|Tswana]]||lang=\"tn\"|seTswana||\n" + "|-\n" + "|to||ton||ton||[[Tongan language|Tonga]]||lang=\"to\"|faka Tonga||\n" + "|-\n" + "|tr||tur||tur||[[Turkish language|Turkish]]||lang=\"tr\"|Türkçe||\n" + "|-\n" + "|ts||tso||tso||[[Tsonga language|Tsonga]]||lang=\"ts\"|xiTsonga||\n" + "|-\n" + "|tt||tat||tat||[[Tatar language|Tatar]]||{{lang|tt-Cyrl|татарча}}; {{lang|tt-Latn|tatarça}}; {{rtl-lang|tt-Arab|‫تاتارچا}}||\n" + "|-\n" + "|tw||twi||twi||[[Twi]]||lang=\"tw\"|Twi||\n" + "|-\n" + "|ty||tah||tah||[[Tahitian language|Tahitian]]||lang=\"ty\"|Reo M�?`ohi||\n" + "|-\n" + "|ug||uig||uig||[[Uyghur language|Uighur]]||{{lang|ug-Latn|Uyƣurqə}}; {{rtl-lang|ug-Arab|‫ئۇيغۇرچ }}||\n" + "|-\n" + "|uk||ukr||ukr||[[Ukrainian language|Ukrainian]]||lang=\"uk\"|Україн�?ька||\n" + "|-\n" + "|ur||urd||urd||[[Urdu]]||lang=\"ur\" dir=\"rtl\"|‫اردو||\n" + "|-\n" + "|uz||uzb||uzb + [[ISO 639:uzb|2]]||[[Uzbek language|Uzbek]]|||{{lang|uz-Latn|O'zbek}}; {{lang|uz-Cyrl|Ўзбек}}; {{rtl-lang|uz-Arab|أۇزب�?ك}}||\n" + "|-\n" + "|ve||ven||ven||[[Venda language|Venda]]||lang=\"ve\"|tshiVenḓa||\n" + "|-\n" + "|vi||vie||vie||[[Vietnamese language|Vietnamese]]||lang=\"vi\"|Tiếng Việt||\n" + "|-\n" + "|vo||vol||vol||[[Volapük]]||lang=\"vo\"|Volapük||\n" + "|-\n" + "|wa||wln||wln||[[Walloon language|Walloon]]||lang=\"wa\"|Walon||\n" + "|-\n" + "|wo||wol||wol||[[Wolof language|Wolof]]||lang=\"wo\"|Wollof||\n" + "|-\n" + "|xh||xho||xho||[[Xhosa language|Xhosa]]||lang=\"xh\"|isiXhosa||\n" + "|-\n" + "|yi||yid||yid + [[ISO 639:yid|2]]||[[Yiddish language|Yiddish]]||lang=\"yi\" dir=\"rtl\"|‫ייִדיש||\n" + "|-\n" + "|yo||yor||yor||[[Yoruba language|Yoruba]]||lang=\"yo\"|Yorùbá||\n" + "|-\n" + "|za||zha||zha + [[ISO 639:zha|2]]||[[Zhuang language|Zhuang]]||lang=\"za\"|Saɯ cueŋƅ; Saw cuengh||\n" + "|-\n" + "|zh||chi/zho||zho + [[ISO 639:zho|13]]||[[Chinese language|Chinese]]|||{{lang|zh-Hani|中文}}, {{lang|zh-Hans|汉语}}, {{lang|zh-Hant|漢語}}||\n" + "|-\n" + "|zu||zul||zul||[[Zulu language|Zulu]]||lang=\"zu\"|isiZulu||\n" + "|}"; Table t = parse(content); System.out.println(t); Row row1 = t.getRows()[t.getRows().length - 1]; assertEquals(6, row1.getCells().length); assertEquals("zu", row1.getCells()[0].getContent()[0].toString()); assertEquals("zul", row1.getCells()[1].getContent()[0].toString()); assertEquals("zul", row1.getCells()[2].getContent()[0].toString()); assertEquals("[[Zulu language|Zulu]]", row1.getCells()[3].getContent()[0].toString()); assertEquals("isiZulu", row1.getCells()[4].getContent()[0].toString()); Row row2 = t.getRows()[6]; assertEquals(6, row2.getCells().length); assertEquals("[[Amharic language|Amharic]]", row2.getCells()[3].getContent()[0].toString()); } public void testLengthUnitsTable() throws Exception { String content = "{| class=\"wikitable\"\n" + "|+ [[Length]], l\n" + "|-----\n" + "!Name of unit\n" + "!Symbol\n" + "!Definition\n" + "!Relation to [[SI]] units\n" + "|-----\n" + "| [[ångström]] || Å\n" + "|\n" + "| ≡ 1{{e|−10}} m = 0.1 nm\n" + "|-----\n" + "| [[astronomical unit]] || AU\n" + "| Mean distance from Earth to the Sun\n" + "| = 149 597 870.691 ± 0.030 km\n" + "|-----\n" + "| [[atomic units|atomic unit of length]] || au{{Fact|date=August 2007}}\n" + "| ≡ a<sub>0</sub>\n" + "| ≈ 5.291 772 083{{e|−11}} ± 19{{e|−20}} m\n" + "|-----\n" + "| barley corn || &nbsp;\n" + "| ≡ 1/3 in\n" + "| ≈ 8.466 667 mm\n" + "|-----\n" + "| [[Bohr radius]] || a<sub>0</sub>; b\n" + "| ≡ [[fine structure constant|α]]/(4π[[Rydberg constant|''R''<sub>∞</sub>]])\n" + "| ≈ 5.291 772 083{{e|−11}} ± 19{{e|−20}} m\n" + "|-----\n" + "| cable length (Imperial) || &nbsp;\n" + "| ≡ 608 ft\n" + "| = 185.3184 m\n" + "|-----\n" + "| [[cable length]] (International) || &nbsp;\n" + "| ≡ 1/10 NM\n" + "| = 185.2 m\n" + "|-----\n" + "| cable length (U.S.) || &nbsp;\n" + "| ≡ 720 ft\n" + "| = 219.456 m\n" + "|-----\n" + "| [[calibre]] || cal\n" + "| ≡ 1 in\n" + "| = 25.4 mm\n" + "|-----\n" + "| [[chain (unit)|chain]] ([[Edmund Gunter|Gunter's]]; Surveyor's) || ch\n" + "| ≡ 66.0 ft (4 rods)\n" + "| = 20.1168 m\n" + "|-----\n" + "| [[chain (unit)|chain]] ([[Jesse Ramsden|Ramsden]]'s<!--- Ramsden: http://www.scienceandsociety.co.uk/results.asp?image=10280167&wwwflag=2&imagepos=6 Ramden: [http://aurora.rg.iupui.edu/~schadow/units/UCUM/ucum.html The Unified Code for Units of Measures] --->; Engineer's) || ch\n" + "| ≡ 100 ft\n" + "| = 30.48 m\n" + "|-----\n" + "| cubit || &nbsp;\n" + "| ≡ 18 in\n" + "| = 0.4572 m\n" + "|-----\n" + "| ell || ell\n" + "| ≡ 45 in\n" + "| = 1.143 m\n" + "|-----\n" + "|rowspan=\"2\"| [[fathom]] ||rowspan=\"2\"| fm\n" + "| ≡ 6 ft\n" + "| = 1.8288 m\n" + "|-\n" + "| ≈ 1/1000 NM\n" + "| = 1.852 m\n" + "|-----\n" + "| [[Femtometre|fermi]] || fm\n" + "| ≡ 1{{e|−15}} m\n" + "| = 1{{e|−15}} m\n" + "|-----\n" + "| finger || &nbsp;\n" + "| ≡ 7/8 in\n" + "| = 22.225 mm\n" + "|-----\n" + "| finger (cloth) || &nbsp;\n" + "| ≡ 4 ½ in\n" + "| = 0.1143 m\n" + "|-----\n" + "| [[foot (unit of length)|foot]] (Benoît) || ft (Ben)\n" + "|\n" + "| ≈ 0.304 799 735 m\n" + "|-----\n" + "| [[foot (unit of length)|foot]] (Clarke's; Cape) || ft (Cla)\n" + "|\n" + "| ≈ 0.304 797 265 4 m\n" + "|-----\n" + "| [[foot (unit of length)|foot]] (Indian) || ft Ind\n" + "|\n" + "| ≈ 0.304 799 514 m\n" + "|-----\n" + "| [[foot (unit of length)|foot]] (International) || ft\n" + "| ≡ 1/3 yd\n" + "| = 0.3048 m\n" + "|-----\n" + "| [[foot (unit of length)|foot]] (Sear's) || ft (Sear)\n" + "|\n" + "| ≈ 0.304 799 47 m\n" + "|-----\n" + "| [[foot (unit of length)|foot]] (U.S. Survey) || ft (US)\n" + "| ≡ 1200/3937 m <ref name=nbs>National Bureau of Standards. (June 30, 1959). ''Refinement of values for the yard and the pound''. Federal Register, viewed September 20, 2006 at [http://www.ngs.noaa.gov/PUBS_LIB/FedRegister/FRdoc59-5442.pdf National Geodetic Survey web site].</ref>\n" + "| ≈ 0.304 800 610 m\n" + "|-----\n" + "| [[furlong]] || fur\n" + "| ≡ 660 ft (10 chains)\n" + "| = 201.168 m\n" + "|-----\n" + "| [[geographical mile]] || mi\n" + "| ≡ 6082 ft\n" + "| = 1853.7936 m\n" + "|-----\n" + "| hand || &nbsp;\n" + "| ≡ 4 in\n" + "| = 0.1016 m\n" + "|-----\n" + "| [[inch]] || in\n" + "| ≡ 1/36 yd\n" + "| = 25.4 mm\n" + "|-----\n" + "| [[league (unit)|league]] || lea\n" + "| ≡ 3 mi\n" + "| = 4828.032 m\n" + "|-----\n" + "| [[light-day]] || &nbsp;\n" + "| ≡ 24 light-hours\n" + "| = 2.590 206 837 12{{e|13}} m\n" + "|-----\n" + "| [[light-hour]] || &nbsp;\n" + "| ≡ 60 light-minutes\n" + "| = 1.079 252 848 8{{e|12}} m\n" + "|-----\n" + "| [[light-minute]] || &nbsp;\n" + "| ≡ 60 light-seconds\n" + "| = 1.798 754 748{{e|10}} m\n" + "|-----\n" + "| [[light second|light-second]] || &nbsp;\n" + "|\n" + "| ≡ 2.997 924 58{{e|8}} m\n" + "|-----\n" + "| [[light year|light-year]] || l.y.\n" + "| ≡ ''c''<sub>0</sub> × 86 400 × 365.25\n" + "| = 9.460 730 472 580 8{{e|15}} m\n" + "|-----\n" + "| line || ln\n" + "| ≡ 1/12 in (Klein 1988, 63)\n" + "| ≈ 2.116 667 mm\n" + "|-----\n" + "| link (Gunter's; Surveyor's) || lnk\n" + "| ≡ 1/100 ch\n" + "| = 0.201 168 m\n" + "|-----\n" + "| link (Ramsden's; Engineer's) || lnk\n" + "| ≡ 1 ft\n" + "| = 0.3048 m\n" + "|-----\n" + "| [[metre]] ([[SI base unit]]) || m\n" + "| ≡ 1 m\n" + "| = 1 m\n" + "|-----\n" + "| mickey || &nbsp;\n" + "| ≡ 1/200 in\n" + "| = 1.27{{e|−4}} m\n" + "|-----\n" + "| [[micrometre|micron]]|| µ\n" + "|\n" + "| ≡ 1.000{{e|−6}} m\n" + "|-----\n" + "| [[thou (unit of length)|mil]]; thou || mil\n" + "| ≡ 1.000{{e|−3}} in\n" + "| = 2.54{{e|−5}} m\n" + "|-----\n" + "| [[Norwegian/Swedish mil|mil]] (Sweden and Norway) || mil\n" + "| ≡ 10 km\n" + "| = 10000 m\n" + "|-----\n" + "| [[mile]] || mi\n" + "| ≡ 1760 yd = 5280 ft\n" + "| = 1609.344 m\n" + "|-----\n" + "| [[mile]] (U.S. Survey) || mi\n" + "| ≡ 5280 ft (US)\n" + "| = 5280 × 1200/3937 m ≈ 1609.347 219 m\n" + "|-----\n" + "| nail (cloth) || &nbsp;\n" + "| ≡ 2 ¼ in\n" + "| = 57.15 mm\n" + "|-----\n" + "| nautical league || NL; nl\n" + "| ≡ 3 NM\n" + "| = 5556 m\n" + "|-----\n" + "| [[nautical mile]] || NM; nmi\n" + "| ≡ 1852 m\n" + "| ≡ 1852 m\n" + "|-----\n" + "| [[nautical mile]] (Admiralty) || NM (Adm); nmi (Adm)\n" + "| ≡ 6080 ft\n" + "| = 1853.184 m\n" + "|-----\n" + "| pace || &nbsp;\n" + "| ≡ 2.5 ft\n" + "| = 0.762 m\n" + "|-----\n" + "| palm || &nbsp;\n" + "| ≡ 3 in\n" + "| = 76.2 mm\n" + "|-----\n" + "| [[parsec]] || pc\n" + "| ≈ 180 × 60 × 60/π AU<br>\n" + "= 206264.8062 AU<br>\n" + "= 3.26156378 light-years\n" + "| = 3.08567782 {{e|16}} ± 6{{e|6}} m <ref name=Seidelmann>P. Kenneth Seidelmann, Ed. (1992). ''Explanatory Supplement to the Astronomical Almanac.'' Sausalito, CA: University Science Books. p. 716 and s.v. parsec in Glossary.</ref>\n" + "|-----\n" + "| point ([[American Typefounders Association|ATA]]) || pt\n" + "| ≡ 0.013837 in\n" + "| = 0.351 459 8 mm\n" + "|-----\n" + "| point (Didot; European) || pt\n" + "|\n" + "| ≡ 0.376 065 mm\n" + "|-----\n" + "| point (metric) || pt\n" + "| ≡ 3/8 mm\n" + "| = 0.375 mm\n" + "|-----\n" + "| point ([[PostScript]])|| pt\n" + "| ≡ 1/72 in\n" + "| ≈ 0.352 778 mm\n" + "|-----\n" + "| quarter || &nbsp;\n" + "| ≡ ¼ yd\n" + "| = 0.2286 m\n" + "|-----\n" + "| [[rod (unit)|rod]]; pole; perch || rd\n" + "| ≡ 16 ½ ft\n" + "| = 5.0292 m\n" + "|-----\n" + "| rope || rope\n" + "| ≡ 20 ft\n" + "| = 6.096 m\n" + "|-----\n" + "| span || &nbsp;\n" + "| ≡ 6 in\n" + "| = 0.1524 m\n" + "|-----\n" + "| span (cloth) || &nbsp;\n" + "| ≡ 9 in\n" + "| = 0.2286 m\n" + "|-----\n" + "| spat[http://www.unc.edu/~rowlett/units/dictS.html] ||\n" + "| ≡ 10<sup>12</sup> m\n" + "| = 1 Tm\n" + "|-----\n" + "| stick || &nbsp;\n" + "| ≡ 2 in\n" + "| = 50.8 mm\n" + "|-----\n" + "| [[stigma (unit)|stigma]]; pm|| &nbsp;\n" + "| ≡ 1.000{{e|−12}} m\n" + "| ≡ 1.000{{e|−12}} m\n" + "|-----\n" + "| telegraph [[mile]] || mi\n" + "| ≡ 6087 ft\n" + "| = 1855.3176 m\n" + "|-----\n" + "| [[twip]] || twp\n" + "| ≡ 1/1440 in\n" + "| ≈ 1.763 889{{e|−5}} m\n" + "|-----\n" + "| [[x unit]]; [[siegbahn]] || xu\n" + "|\n" + "| ≈ 1.0021{{e|−13}} m\n" + "|-----\n" + "| [[yard]] (International) || yd\n" + "| ≡3 ft ≡ 0.9144 m <ref name=nbs/>\n" + "| = 0.9144 m\n" + "|}"; Table t = parse(content); } public void testTableInternetTLDs() throws Exception { String content = "{| class=\"wikitable\"\n" + "|- style=\"background-color: #a0d0ff;\"\n" + "!iTLD!!Entity!!Notes\n" + "|-\n" + "\n" + "| [[.arpa]] || Address and Routing Parameter Area || This is an internet infrastructure TLD.\n" + "|-\n" + "| [[.root]] || N/A|| Diagnostic marker to indicate a root zone load was not truncated.\n" + "|- style=\"background-color: #a0d0ff;\"\n" + "![[gTLD]]!!Entity!!Notes\n" + "|-\n" + "| [[.aero]] || air-transport industry || Must verify eligibility for registration; only those in various categories of air-travel-related entities may register.\n" + "|-\n" + "| [[.asia]] || Asia-Pacific region || This is a TLD for companies, organizations, and individuals based in the region of Asia, Australia, and the Pacific.\n" + "|-\n" + "| [[.biz]] || business || This is an open TLD; any person or entity is permitted to register; however, registrations may be challenged later if they are not by commercial entities in accordance with the domain's charter.\n" + "|-\n" + "| [[.cat]] || Catalan || This is a TLD for websites in the [[Catalan language]] or related to Catalan culture.\n" + "|-\n" + "| [[.com]] || commercial || This is an open TLD; any person or entity is permitted to register.\n" + "|-\n" + "| [[.coop]] || cooperatives || The .coop TLD is limited to cooperatives as defined by the [[Rochdale Principles]].\n" + "|-\n" + "| [[.edu]] || educational || The .edu TLD is limited to institutions of learning (mostly U.S.), such as 2 and 4-year colleges and universities.\n" + "|-\n" + "| [[.gov]] || governmental || The .gov TLD is limited to U.S. governmental entities and agencies (commonly [[U.S. Federal Government | federal-level]]).\n" + "|-\n" + "| [[.info]] || information || This is an open TLD; any person or entity is permitted to register.\n" + "|-\n" + "| [[.int]] || international organizations || The .int TLD is strictly limited to organizations, offices, and programs which are endorsed by a treaty between two or more nations.\n" + "|-\n" + "| [[.jobs]] || companies || The .jobs TLD is designed to be added after the names of established companies with jobs to advertise. At this time, owners of a \"company.jobs\" domain are not permitted to post jobs of third party employers.\n" + "|-\n" + "| [[.mil]] || [[Military of the United States|United States Military]] || The .mil TLD is limited to use by the U.S. military.\n" + "|-\n" + "| [[.mobi]] || mobile devices || Must be used for mobile-compatible sites in accordance with standards.\n" + "|-\n" + "| [[.museum]] || museums || Must be verified as a legitimate museum.\n" + "|-\n" + "| [[.name]] || individuals, by name || This is an open TLD; any person or entity is permitted to register; however, registrations may be challenged later if they are not by individuals (or the owners of fictional characters) in accordance with the domain's charter\n" + "|-\n" + "| [[.net]] || network || This is an open TLD; any person or entity is permitted to register.\n" + "|-\n" + "| [[.org]] || organization || This is an open TLD; any person or entity is permitted to register.\n" + "|-\n" + "| [[.pro]] || professions || Currently, .pro is reserved for licensed doctors, attorneys, and certified public accountants only. A professional seeking to register a .pro domain must provide their registrar with the appropriate credentials.\n" + "|-\n" + "| [[.tel]] || Internet communication services ||\n" + "|-\n" + "| [[.travel]] || travel and travel-agency related sites || Must be verified as a legitimate travel-related entity.\n" + "|-\n" + "<!--\n" + "|-\n" + "| [[.xxx]] || [[Pornography|Pornographic]] websites || &nbsp;\n" + "ICANN has approved this TLD in principle, but it has not been added to the root yet.\n" + "-->\n" + "|- style=\"background-color: #a0d0ff;\"\n" + "![[ccTLD]]!!Country/dependency/region!!Notes\n" + "|-\n" + "| [[.ac]] || [[Ascension Island]] || &nbsp;\n" + "|-\n" + "| [[.ad]] || [[Andorra]] || &nbsp;\n" + "|-\n" + "| [[.ae]] || [[United Arab Emirates]] || &nbsp;\n" + "|-\n" + "| [[.af]] || [[Afghanistan]] || &nbsp;\n" + "|-\n" + "| [[.ag]] || [[Antigua and Barbuda]] || &nbsp;\n" + "|-\n" + "| [[.ai]] || [[Anguilla]] || &nbsp;\n" + "|-\n" + "| [[.al]] || [[Albania]] || &nbsp;\n" + "|-\n" + "| [[.am]] || [[Armenia]] || &nbsp;\n" + "|-\n" + "| [[.an]] || [[Netherlands Antilles]] || &nbsp;\n" + "|-\n" + "| [[.ao]] || [[Angola]] || &nbsp;\n" + "|-\n" + "| [[.aq]] || [[Antarctica]] || Defined as per the [[Antarctic Treaty System|Antarctic Treaty]] as everything south of latitude 60°S\n" + "|-\n" + "| [[.ar]] || [[Argentina]] || &nbsp;\n" + "|-\n" + "| [[.as]] || [[American Samoa]] || &nbsp;\n" + "|-\n" + "| [[.at]] || [[Austria]] || &nbsp;\n" + "|-\n" + "| [[.au]] || [[Australia]] || Includes [[Ashmore and Cartier Islands]] and [[Coral Sea Islands]]\n" + "|-\n" + "| [[.aw]] || [[Aruba]] || &nbsp;\n" + "|-\n" + "| [[.ax]] || [[Åland]] || &nbsp;\n" + "|-\n" + "| [[.az]] || [[Azerbaijan]] || &nbsp;\n" + "|-\n" + "| [[.ba]] || [[Bosnia and Herzegovina]] || &nbsp;\n" + "|-\n" + "| [[.bb]] || [[Barbados]] || &nbsp;\n" + "|-\n" + "| [[.bd]] || [[Bangladesh]] || &nbsp;\n" + "|-\n" + "| [[.be]] || [[Belgium]] || &nbsp;\n" + "|-\n" + "| [[.bf]] || [[Burkina Faso]] || &nbsp;\n" + "|-\n" + "| [[.bg]] || [[Bulgaria]] || &nbsp;\n" + "|-\n" + "| [[.bh]] || [[Bahrain]] || &nbsp;\n" + "|-\n" + "| [[.bi]] || [[Burundi]] || &nbsp;\n" + "|-\n" + "| [[.bj]] || [[Benin]] || &nbsp;\n" + "|-\n" + "| [[.bm]] || [[Bermuda]] || &nbsp;\n" + "|-\n" + "| [[.bn]] || [[Brunei|Brunei Darussalam]] || &nbsp;\n" + "|-\n" + "| [[.bo]] || [[Bolivia]] || &nbsp;\n" + "|-\n" + "| [[.br]] || [[Brazil]] || &nbsp;\n" + "|-\n" + "| [[.bs]] || [[Bahamas]] || &nbsp;\n" + "|-\n" + "| [[.bt]] || [[Bhutan]] || &nbsp;\n" + "|-\n" + "| [[.bv]] || [[Bouvet Island]] || Not in use (Norwegian dependency; see .no)\n" + "|-\n" + "| [[.bw]] || [[Botswana]] || &nbsp;\n" + "|-\n" + "| [[.by]] || [[Belarus]] || &nbsp;\n" + "|-\n" + "| [[.bz]] || [[Belize]] || &nbsp;\n" + "|-\n" + "| [[.ca]] || [[Canada]] || Subject to Canadian Presence Requirements, see [[.ca]]\n" + "|-\n" + "| [[.cc]] || [[Cocos Islands|Cocos (Keeling) Islands]] || &nbsp;\n" + "|-\n" + "| [[.cd]] || [[Democratic Republic of the Congo]] || Formerly [[Zaire]]\n" + "|-\n" + "| [[.cf]] || [[Central African Republic]] || &nbsp;\n" + "|-\n" + "| [[.cg]] || [[Republic of the Congo]] || &nbsp;\n" + "|-\n" + "| [[.ch]] || [[Switzerland]] (Confoederatio Helvetica) || &nbsp;\n" + "|-\n" + "| [[.ci]] || [[Côte d'Ivoire]] || &nbsp;\n" + "|-\n" + "| [[.ck]] || [[Cook Islands]] || &nbsp;\n" + "|-\n" + "| [[.cl]] || [[Chile]] || &nbsp;\n" + "|-\n" + "| [[.cm]] || [[Cameroon]] || &nbsp;\n" + "|-\n" + "| [[.cn]] || [[People's Republic of China|China, mainland]] || [[Mainland China]] only: [[Hong Kong]], [[Macau]] and [[Taiwan]] use separate TLDs.\n" + "|-\n" + "| [[.co]] || [[Colombia]] || &nbsp;\n" + "|-\n" + "| [[.cr]] || [[Costa Rica]] || &nbsp;\n" + "|-\n" + "| [[.cu]] || [[Cuba]] || &nbsp;\n" + "|-\n" + "| [[.cv]] || [[Cape Verde]] || &nbsp;\n" + "|-\n" + "| [[.cx]] || [[Christmas Island]] || &nbsp;\n" + "|-\n" + "| [[.cy]] || [[Cyprus]] || &nbsp;\n" + "|-\n" + "| [[.cz]] || [[Czech Republic]] || &nbsp;\n" + "|-\n" + "| [[.de]] || [[Germany]] (Deutschland) || &nbsp;\n" + "|-\n" + "| [[.dj]] || [[Djibouti]] || &nbsp;\n" + "|-\n" + "| [[.dk]] || [[Denmark]] || &nbsp;\n" + "|-\n" + "| [[.dm]] || [[Dominica]] || &nbsp;\n" + "|-\n" + "| [[.do]] || [[Dominican Republic]] || &nbsp;\n" + "|-\n" + "| [[.dz]] || [[Algeria]] (Dzayer) || Not available for private use\n" + "|-\n" + "| [[.ec]] || [[Ecuador]] || &nbsp;\n" + "|-\n" + "| [[.ee]] || [[Estonia]] || &nbsp;\n" + "|-\n" + "| [[.eg]] || [[Egypt]] || &nbsp;\n" + "<!--\n" + "|-\n" + ".eh is reserved for Western Sahara, but does not exist in the root\n" + "| [[.eh]] || [[Western Sahara]] || &nbsp;\n" + "-->\n" + "|-\n" + "| [[.er]] || [[Eritrea]] || &nbsp;\n" + "|-\n" + "| [[.es]] || [[Spain]] (España) || &nbsp;\n" + "|-\n" + "| [[.et]] || [[Ethiopia]] || &nbsp;\n" + "|-\n" + "| [[.eu]] || [[European Union]] || Restricted to companies and individuals in the European Union\n" + "|-\n" + "| [[.fi]] || [[Finland]] || &nbsp;\n" + "|-\n" + "| [[.fj]] || [[Fiji]] || &nbsp;\n" + "|-\n" + "| [[.fk]] || [[Falkland Islands]] || &nbsp;\n" + "|-\n" + "| [[.fm]] || [[Federated States of Micronesia]] || Used for some radio related websites outside Micronesia\n" + "|-\n" + "| [[.fo]] || [[Faroe Islands]] || &nbsp;\n" + "|-\n" + "| [[.fr]] || [[France]] || Can only be used by organisations or persons with a presence in France.\n" + "|-\n" + "| [[.ga]] || [[Gabon]] || &nbsp;\n" + "|-\n" + "| [[.gb]] || [[United Kingdom]] || Seldom used; the primary ccTLD used is [[.uk]] for [[United Kingdom]]\n" + "|-\n" + "| [[.gd]] || [[Grenada]] || &nbsp;\n" + "|-\n" + "| [[.ge]] || [[Georgia (country)|Georgia]] || &nbsp;\n" + "|-\n" + "| [[.gf]] || [[French Guiana]] || &nbsp;\n" + "|-\n" + "| [[.gg]] || [[Guernsey]] || &nbsp;\n" + "|-\n" + "| [[.gh]] || [[Ghana]] || &nbsp;\n" + "|-\n" + "| [[.gi]] || [[Gibraltar]] || &nbsp;\n" + "|-\n" + "| [[.gl]] || [[Greenland]] || &nbsp;\n" + "|-\n" + "| [[.gm]] || [[The Gambia]] || &nbsp;\n" + "|-\n" + "| [[.gn]] || [[Guinea]] || &nbsp;\n" + "|-\n" + "| [[.gp]] || [[Guadeloupe]] || &nbsp;\n" + "|-\n" + "| [[.gq]] || [[Equatorial Guinea]] || &nbsp;\n" + "|-\n" + "| [[.gr]] || [[Greece]] || &nbsp;\n" + "|-\n" + "| [[.gs]] || [[South Georgia and the South Sandwich Islands]] || &nbsp;\n" + "|-\n" + "| [[.gt]] || [[Guatemala]] || &nbsp;\n" + "|-\n" + "| [[.gu]] || [[Guam]] || &nbsp;\n" + "|-\n" + "| [[.gw]] || [[Guinea-Bissau]] || &nbsp;\n" + "|-\n" + "| [[.gy]] || [[Guyana]] || &nbsp;\n" + "|-\n" + "| [[.hk]] || [[Hong Kong]] || [[Special administrative region]] of the [[People's Republic of China]].\n" + "|-\n" + "| [[.hm]] || [[Heard Island and McDonald Islands]] || &nbsp;\n" + "|-\n" + "| [[.hn]] || [[Honduras]] || &nbsp;\n" + "|-\n" + "| [[.hr]] || [[Croatia]] (Hrvatska) || &nbsp;\n" + "|-\n" + "| [[.ht]] || [[Haiti]] || &nbsp;\n" + "|-\n" + "| [[.hu]] || [[Hungary]] || &nbsp;\n" + "|-\n" + "| [[.id]] || [[Indonesia]] || &nbsp;\n" + "|-\n" + "| [[.ie]] || [[Republic of Ireland|Ireland]] (Éire)|| &nbsp;\n" + "|-\n" + "| [[.il]] || [[Israel]] || &nbsp;\n" + "|-\n" + "| [[.im]] || [[Isle of Man]] || &nbsp;\n" + "|-\n" + "| [[.in]] || [[India]] || Under [[INRegistry]] since April 2005 except: gov.in, mil.in, ac.in, edu.in, res.in\n" + "|-\n" + "| [[.io]] || [[British Indian Ocean Territory]] || &nbsp;\n" + "|-\n" + "| [[.iq]] || [[Iraq]] || &nbsp;\n" + "|-\n" + "| [[.ir]] || [[Iran]] || &nbsp;\n" + "|-\n" + "| [[.is]] || [[Iceland]] (�?sland) || &nbsp;\n" + "|-\n" + "| [[.it]] || [[Italy]] || Restricted to companies and individuals in the [[European Union]]\n" + "|-\n" + "| [[.je]] || [[Jersey]] || &nbsp;\n" + "|-\n" + "| [[.jm]] || [[Jamaica]] || &nbsp;\n" + "|-\n" + "| [[.jo]] || [[Jordan]] || &nbsp;\n" + "|-\n" + "| [[.jp]] || [[Japan]] || &nbsp;\n" + "|-\n" + "| [[.ke]] || [[Kenya]] || &nbsp;\n" + "|-\n" + "| [[.kg]] || [[Kyrgyzstan]] || &nbsp;\n" + "|-\n" + "| [[.kh]] || [[Cambodia]] (Khmer) || &nbsp;\n" + "|-\n" + "| [[.ki]] || [[Kiribati]] || &nbsp;\n" + "|-\n" + "| [[.km]] || [[Comoros]] || &nbsp;\n" + "|-\n" + "| [[.kn]] || [[Saint Kitts and Nevis]] || &nbsp;\n" + "|-\n" + "| [[.kp]] || [[North Korea]] || &nbsp;\n" + "|-\n" + "| [[.kr]] || [[South Korea]] || &nbsp;\n" + "|-\n" + "| [[.kw]] || [[Kuwait]] || &nbsp;\n" + "|-\n" + "| [[.ky]] || [[Cayman Islands]] || &nbsp;\n" + "|-\n" + "| [[.kz]] || [[Kazakhstan]] || &nbsp;\n" + "|-\n" + "| [[.la]] || [[Laos]] || Currently being marketed as the official domain for [[Los Angeles]].\n" + "|-\n" + "| [[.lb]] || [[Lebanon]] || &nbsp;\n" + "|-\n" + "| [[.lc]] || [[Saint Lucia]] || &nbsp;\n" + "|-\n" + "| [[.li]] || [[Liechtenstein]] || &nbsp;\n" + "|-\n" + "| [[.lk]] || [[Sri Lanka]] || &nbsp;\n" + "|-\n" + "| [[.lr]] || [[Liberia]] || &nbsp;\n" + "|-\n" + "| [[.ls]] || [[Lesotho]] || &nbsp;\n" + "|-\n" + "| [[.lt]] || [[Lithuania]] || &nbsp;\n" + "|-\n" + "| [[.lu]] || [[Luxembourg]] || &nbsp;\n" + "|-\n" + "| [[.lv]] || [[Latvia]] || &nbsp;\n" + "|-\n" + "| [[.ly]] || [[Libya]] || &nbsp;\n" + "|-\n" + "| [[.ma]] || [[Morocco]] || &nbsp;\n" + "|-\n" + "| [[.mc]] || [[Monaco]] || &nbsp;\n" + "|-\n" + "| [[.md]] || [[Moldova]] || &nbsp;\n" + "|-\n" + "| [[.me]] || [[Montenegro]] || &nbsp;\n" + "|-\n" + "| [[.mg]] || [[Madagascar]] || &nbsp;\n" + "|-\n" + "| [[.mh]] || [[Marshall Islands]] || &nbsp;\n" + "|-\n" + "| [[.mk]] || [[Republic of Macedonia]] || &nbsp;\n" + "|-\n" + "| [[.ml]] || [[Mali]] || &nbsp;\n" + "|-\n" + "| [[.mm]] || [[Myanmar]] || &nbsp;\n" + "|-\n" + "| [[.mn]] || [[Mongolia]] || &nbsp;\n" + "|-\n" + "| [[.mo]] || [[Macau]] || [[Special administrative region]] of the [[People's Republic of China]].\n" + "|-\n" + "| [[.mp]] || [[Northern Mariana Islands]] || &nbsp;\n" + "|-\n" + "| [[.mq]] || [[Martinique]] || &nbsp;\n" + "|-\n" + "| [[.mr]] || [[Mauritania]] || &nbsp;\n" + "|-\n" + "| [[.ms]] || [[Montserrat]] || &nbsp;\n" + "|-\n" + "| [[.mt]] || [[Malta]] || &nbsp;\n" + "|-\n" + "| [[.mu]] || [[Mauritius]] || &nbsp;\n" + "|-\n" + "| [[.mv]] || [[Maldives]] || &nbsp;\n" + "|-\n" + "| [[.mw]] || [[Malawi]] || &nbsp;\n" + "|-\n" + "| [[.mx]] || [[Mexico]] || &nbsp;\n" + "|-\n" + "| [[.my]] || [[Malaysia]] || Must be registered with a company in [[Malaysia]] to register. Currently famous for the literal word '[[my]]'.\n" + "|-\n" + "| [[.mz]] || [[Mozambique]] || &nbsp;\n" + "|-\n" + "| [[.na]] || [[Namibia]] || &nbsp;\n" + "|-\n" + "| [[.nc]] || [[New Caledonia]] || &nbsp;\n" + "|-\n" + "| [[.ne]] || [[Niger]] || &nbsp;\n" + "|-\n" + "| [[.nf]] || [[Norfolk Island]] || &nbsp;\n" + "|-\n" + "| [[.ng]] || [[Nigeria]] || &nbsp;\n" + "|-\n" + "| [[.ni]] || [[Nicaragua]] || &nbsp;\n" + "|-\n" + "| [[.nl]] || [[Netherlands]] || &nbsp;\n" + "|-\n" + "| [[.no]] || [[Norway]] || Must be registered with a company in [[Norway]] to register.\n" + "|-\n" + "| [[.np]] || [[Nepal]] || &nbsp;\n" + "|-\n" + "| [[.nr]] || [[Nauru]] || &nbsp;\n" + "|-\n" + "| [[.nu]] || [[Niue]] || Commonly used for Scandinavian and Dutch websites, because in those languages 'nu' means 'now'.\n" + "|-\n" + "| [[.nz]] || [[New Zealand]] || &nbsp;\n" + "|-\n" + "| [[.om]] || [[Oman]] || &nbsp;\n" + "|-\n" + "| [[.pa]] || [[Panama]] || &nbsp;\n" + "|-\n" + "| [[.pe]] || [[Peru]] || &nbsp;\n" + "|-\n" + "| [[.pf]] || [[French Polynesia]] || With [[Clipperton Island]]\n" + "|-\n" + "| [[.pg]] || [[Papua New Guinea]] || &nbsp;\n" + "|-\n" + "| [[.ph]] || [[Philippines]] || &nbsp;\n" + "|-\n" + "| [[.pk]] || [[Pakistan]] || &nbsp;\n" + "|-\n" + "| [[.pl]] || [[Poland]] || &nbsp;\n" + "|-\n" + "| [[.pm]] || [[Saint-Pierre and Miquelon]] || &nbsp;\n" + "|-\n" + "| [[.pn]] || [[Pitcairn Islands]] || &nbsp;\n" + "|-\n" + "| [[.pr]] || [[Puerto Rico]] || &nbsp;\n" + "|-\n" + "| [[.ps]] || [[Palestinian territories]] || PA-controlled [[West Bank]] and [[Gaza Strip]]\n" + "|-\n" + "| [[.pt]] || [[Portugal]] || Only available for Portuguese registered brands and companies\n" + "|-\n" + "| [[.pw]] || [[Palau]] || &nbsp;\n" + "|-\n" + "| [[.py]] || [[Paraguay]] || &nbsp;\n" + "|-\n" + "| [[.qa]] || [[Qatar]] || &nbsp;\n" + "|-\n" + "| [[.re]] || [[Réunion]] || &nbsp;\n" + "|-\n" + "| [[.ro]] || [[Romania]] || &nbsp;\n" + "|-\n" + "| [[.rs]] || [[Serbia]] || &nbsp;\n" + "|-\n" + "| [[.ru]] || [[Russia]] || &nbsp;\n" + "|-\n" + "| [[.rw]] || [[Rwanda]] || &nbsp;\n" + "|-\n" + "| [[.sa]] || [[Saudi Arabia]] || &nbsp;\n" + "|-\n" + "| [[.sb]] || [[Solomon Islands]] || &nbsp;\n" + "|-\n" + "| [[.sc]] || [[Seychelles]] || &nbsp;\n" + "|-\n" + "| [[.sd]] || [[Sudan]] || &nbsp;\n" + "|-\n" + "| [[.se]] || [[Sweden]] || &nbsp;\n" + "|-\n" + "| [[.sg]] || [[Singapore]] || &nbsp;\n" + "|-\n" + "| [[.sh]] || [[Saint Helena]] || &nbsp;\n" + "|-\n" + "| [[.si]] || [[Slovenia]] || &nbsp;\n" + "|-\n" + "| [[.sj]] || [[Svalbard]] and [[Jan Mayen]] Islands || Not in use (Norwegian dependencies; see .no)\n" + "|-\n" + "| [[.sk]] || [[Slovakia]] || &nbsp;\n" + "|-\n" + "| [[.sl]] || [[Sierra Leone]] || &nbsp;\n" + "|-\n" + "| [[.sm]] || [[San Marino]] || &nbsp;\n" + "|-\n" + "| [[.sn]] || [[Senegal]] || &nbsp;\n" + "|-\n" + "| [[.so (domain name)|.so]] || [[Somalia]] || &nbsp;\n" + "|-\n" + "| [[.sr]] || [[Suriname]] || &nbsp;\n" + "|-\n" + "| [[.st]] || [[São Tomé and Príncipe]] || &nbsp;\n" + "|-\n" + "| [[.su]] || former [[Soviet Union]] || Still in use\n" + "|-\n" + "| [[.sv]] || [[El Salvador]] || &nbsp;\n" + "|-\n" + "| [[.sy]] || [[Syria]] || &nbsp;\n" + "|-\n" + "| [[.sz]] || [[Swaziland]] || &nbsp;\n" + "|-\n" + "| [[.tc]] || [[Turks and Caicos Islands]] || &nbsp;\n" + "|-\n" + "| [[.td]] || [[Chad]] || &nbsp;\n" + "|-\n" + "| [[.tf]] || [[French Southern and Antarctic Lands]] || &nbsp;\n" + "|-\n" + "| [[.tg]] || [[Togo]] || &nbsp;\n" + "|-\n" + "| [[.th]] || [[Thailand]] || &nbsp;\n" + "|-\n" + "| [[.tj]] || [[Tajikistan]] || &nbsp;\n" + "|-\n" + "| [[.tk]] || [[Tokelau]] || Also used as a free domain service to the public\n" + "|-\n" + "| [[.tl]] || [[East Timor]] || Old code .tp is still in use\n" + "|-\n" + "| [[.tm]] || [[Turkmenistan]] || &nbsp;\n" + "|-\n" + "| [[.tn]] || [[Tunisia]] || &nbsp;\n" + "|-\n" + "| [[.to]] || [[Tonga]] || &nbsp;\n" + "|-\n" + "| [[.tp]] || [[East Timor]] || ISO code has changed to TL; .tl is now assigned but .tp is still in use\n" + "|-\n" + "| [[.tr]] || [[Turkey]] || &nbsp;\n" + "|-\n" + "| [[.tt]] || [[Trinidad and Tobago]] || &nbsp;\n" + "|-\n" + "| [[.tv]] || [[Tuvalu]] ||Much used by television broadcasters. Also sold as advertising domains\n" + "|-\n" + "| [[.tw]] || [[Taiwan]], [[Republic of China]] || Used in the [[Republic of China]], namely [[Taiwan]], [[Penghu]], [[Kinmen]], and [[Matsu Islands|Matsu]].\n" + "|-\n" + "| [[.tz]] || [[Tanzania]] || &nbsp;\n" + "|-\n" + "| [[.ua]] || [[Ukraine]] || &nbsp;\n" + "|-\n" + "| [[.ug]] || [[Uganda]] || &nbsp;\n" + "|-\n" + "| [[.uk]] || [[United Kingdom]] || &nbsp;\n" + "|-\n" + "| [[.um]] || [[United States Minor Outlying Islands]] || &nbsp;\n" + "|-\n" + "| [[.us]] || [[United States|United States of America]] || Commonly used by [[List_of_U.S._state_legislatures#External links | U.S. State]] and [[Local government in the United States|local governments]] instead of .gov TLD || &nbsp;\n" + "|-\n" + "| [[.uy]] || [[Uruguay]] || &nbsp;\n" + "|-\n" + "| [[.uz]] || [[Uzbekistan]] || &nbsp;\n" + "|-\n" + "| [[.va]] || [[Vatican City|Vatican City State]] || &nbsp;\n" + "|-\n" + "| [[.vc]] || [[Saint Vincent and the Grenadines]] || &nbsp;\n" + "|-\n" + "| [[.ve]] || [[Venezuela]] || &nbsp;\n" + "|-\n" + "| [[.vg]] || [[British Virgin Islands]] || &nbsp;\n" + "|-\n" + "| [[.vi]] || [[U.S. Virgin Islands]] || &nbsp;\n" + "|-\n" + "| [[.vn]] || [[Vietnam]] || &nbsp;\n" + "|-\n" + "| [[.vu]] || [[Vanuatu]] || &nbsp;\n" + "|-\n" + "| [[.wf]] || [[Wallis and Futuna]] || &nbsp;\n" + "|-\n" + "| [[.ws]] || [[Samoa]] || Formerly Western Samoa\n" + "|-\n" + "| [[.ye]] || [[Yemen]] || &nbsp;\n" + "|-\n" + "| [[.yt]] || [[Mayotte]] || &nbsp;\n" + "|-\n" + "| [[.yu]] || [[Federal Republic of Yugoslavia|Yugoslavia]] || Now used for [[Serbia]] and [[Montenegro]]\n" + "|-\n" + "| [[.za]] || [[South Africa]] (Zuid-Afrika) || &nbsp;\n" + "|-\n" + "| [[.zm]] || [[Zambia]] || &nbsp;\n" + "|-\n" + "| [[.zw]] || [[Zimbabwe]] || &nbsp;\n" + "|- style=\"background-color: #a0d0ff;\"\n" + "![[IDNA]] TLD<ref>The IDNA TLDs have been added for the purpose of testing the use of IDNA at the top level, and are likely to be temporary. Each of the eleven TLDs encodes a word meaning \"test\" in some language. See the [http://www.icann.org/announcements/announcement-15oct07.htm ICANN announcement of 15 October 2007] and the [http://idn.icann.org/ IDN TLD evaluation gateway].</ref>!!Language!!Word\n" + "|-\n" + "| .xn--0zwm56d || [[simplified Chinese]] || 测试\n" + "|-\n" + "| .xn--11b5bs3a9aj6g || [[Hindi]] || परीक�?षा\n" + "|-\n" + "| .xn--80akhbyknj4f || [[Russian language|Russian]] || и�?пытание\n" + "|-\n" + "| .xn--9t4b11yi5a || [[Korean language|Korean]] || 테스트\n" + "|-\n" + "| .xn--deba0ad || [[Yiddish]] || טעסט\n" + "|-\n" + "| .xn--g6w251d || [[traditional Chinese]] || 測試\n" + "|-\n" + "| .xn--hgbk6aj7f53bba || [[Persian language|Persian]] || آزمایشی\n" + "|-\n" + "| .xn--hlcj6aya9esc7a || [[Tamil language|Tamil]] || பரிட�?சை\n" + "|-\n" + "| .xn--jxalpdlp || [[Greek language|Greek]] || δοκιμή\n" + "|-\n" + "| .xn--kgbechtv || [[Arabic language|Arabic]] || إختبار\n" + "|-\n" + "| .xn--zckzah || [[Japanese language|Japanese]] || テスト\n" + "|}"; Table t = parse(content); } public void testPreInTable() throws Exception { String content = "{|\n" + "|-\n" + "|<pre><nowiki>\n" + "This is no wiki\n" + "</nowiki></pre>\n" + "|}"; Table t = parse(content); assertEquals(1, t.getRows().length); Row row = t.getRows()[0]; assertEquals(1, row.getCells().length); Cell cell = row.getCells()[0]; assertEquals("<pre><nowiki>\n" + "This is no wiki\n" + "</nowiki></pre>", cell.getContent()[0].toString()); } public void testMultiLineWiki() throws Exception { String content = "{|\n" + "|-\n" + "|<multi>\n" + "This is one paragraph.\n" + "This is another paragraph.\n" + "</multi>\n" + "|}"; Table t = parse(content); assertEquals(1, t.getRows().length); Row row = t.getRows()[0]; assertEquals(1, row.getCells().length); Cell cell = row.getCells()[0]; assertEquals("\n" + "This is one paragraph.\n" + "This is another paragraph.\n", cell.getContent()[0].toString()); } }
RuedigerMoeller/java-wikipedia-parser
src/test/be/devijver/wikipedia/parser/javacc/table/JavaCCTableParserTests.java
45,931
/* * Copyright (C) 2014 Vasilis Vryniotis <bbriniotis at datumbox.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.datumbox.framework.utilities.text.cleaners; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Vasilis Vryniotis <bbriniotis at datumbox.com> */ public class StringCleanerTest { public StringCleanerTest() { } /** * Test of tokenizeURLs method, of class StringCleaner. */ @Test public void testTokenizeURLs() { System.out.println("tokenizeURLs"); String text = "Test, test δοκιμή http://wWw.Google.com/page?query=1#hash test test"; String expResult = "Test, test δοκιμή PREPROCESSDOC_URL test test"; String result = StringCleaner.tokenizeURLs(text); assertEquals(expResult, result); } /** * Test of tokenizeSmileys method, of class StringCleaner. */ @Test public void testTokenizeSmileys() { System.out.println("tokenizeSmileys"); String text = "Test, test δοκιμή :) :( :] :[ test test"; String expResult = "Test, test δοκιμή PREPROCESSDOC_EM1 PREPROCESSDOC_EM3 PREPROCESSDOC_EM8 PREPROCESSDOC_EM9 test test"; String result = StringCleaner.tokenizeSmileys(text); assertEquals(expResult, result); } /** * Test of removeExtraSpaces method, of class StringCleaner. */ @Test public void testRemoveExtraSpaces() { System.out.println("removeExtraSpaces"); String text = " test test test test test\n\n\n\r\n\r\r test\n"; String expResult = "test test test test test test"; String result = StringCleaner.removeExtraSpaces(text); assertEquals(expResult, result); } /** * Test of removeSymbols method, of class StringCleaner. */ @Test public void testRemoveSymbols() { System.out.println("removeSymbols"); String text = "test ` ~ ! @ # $ % ^ & * ( ) _ - + = < , > . ? / \" ' : ; [ { } ] | \\ test `~!@#$%^&*()_-+=<,>.?/\\\"':;[{}]|\\\\ test"; String expResult = "test _ test _ test"; String result = StringCleaner.removeExtraSpaces(StringCleaner.removeSymbols(text)); assertEquals(expResult, result); } /** * Test of unifyTerminators method, of class StringCleaner. */ @Test public void testUnifyTerminators() { System.out.println("unifyTerminators"); String text = " This is amazing!!! ! How is this possible?!?!?!?!!!???! "; String expResult = "This is amazing. How is this possible."; String result = StringCleaner.unifyTerminators(text); assertEquals(expResult, result); } /** * Test of removeAccents method, of class StringCleaner. */ @Test public void testRemoveAccents() { System.out.println("removeAccents"); String text = "'ά','ό','έ','ί','ϊ','ΐ','ή','ύ','ϋ','ΰ','ώ','à','á','â','ã','ä','ç','è','é','ê','ë','ì','í','î','ï','ñ','ò','ó','ô','õ','ö','ù','ú','û','ü','ý','ÿ','Ά','Ό','Έ','Ί','Ϊ','Ή','Ύ','Ϋ','Ώ','À','Á','Â','Ã','Ä','Ç','È','É','Ê','Ë','Ì','Í','Î','Ï','Ñ','Ò','Ó','Ô','Õ','Ö','Ù','Ú','Û','Ü','Ý'"; String expResult = "'α','ο','ε','ι','ι','ι','η','υ','υ','υ','ω','a','a','a','a','a','c','e','e','e','e','i','i','i','i','n','o','o','o','o','o','u','u','u','u','y','y','Α','Ο','Ε','Ι','Ι','Η','Υ','Υ','Ω','A','A','A','A','A','C','E','E','E','E','I','I','I','I','N','O','O','O','O','O','U','U','U','U','Y'"; String result = StringCleaner.removeAccents(text); assertEquals(expResult, result); } }
sheltowt/datumbox-framework
src/test/java/com/datumbox/framework/utilities/text/cleaners/StringCleanerTest.java
45,932
/** * Copyright (C) 2013-2015 Vasilis Vryniotis <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.datumbox.framework.utilities.text.cleaners; import com.datumbox.tests.bases.BaseTest; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Vasilis Vryniotis <[email protected]> */ public class StringCleanerTest extends BaseTest { /** * Test of tokenizeURLs method, of class StringCleaner. */ @Test public void testTokenizeURLs() { logger.info("tokenizeURLs"); String text = "Test, test δοκιμή http://wWw.Google.com/page?query=1#hash test test"; String expResult = "Test, test δοκιμή PREPROCESSDOC_URL test test"; String result = StringCleaner.tokenizeURLs(text); assertEquals(expResult, result); } /** * Test of tokenizeSmileys method, of class StringCleaner. */ @Test public void testTokenizeSmileys() { logger.info("tokenizeSmileys"); String text = "Test, test δοκιμή :) :( :] :[ test test"; String expResult = "Test, test δοκιμή PREPROCESSDOC_EM1 PREPROCESSDOC_EM3 PREPROCESSDOC_EM8 PREPROCESSDOC_EM9 test test"; String result = StringCleaner.tokenizeSmileys(text); assertEquals(expResult, result); } /** * Test of removeExtraSpaces method, of class StringCleaner. */ @Test public void testRemoveExtraSpaces() { logger.info("removeExtraSpaces"); String text = " test test test test test\n\n\n\r\n\r\r test\n"; String expResult = "test test test test test test"; String result = StringCleaner.removeExtraSpaces(text); assertEquals(expResult, result); } /** * Test of removeSymbols method, of class StringCleaner. */ @Test public void testRemoveSymbols() { logger.info("removeSymbols"); String text = "test ` ~ ! @ # $ % ^ & * ( ) _ - + = < , > . ? / \" ' : ; [ { } ] | \\ test `~!@#$%^&*()_-+=<,>.?/\\\"':;[{}]|\\\\ test"; String expResult = "test _ test _ test"; String result = StringCleaner.removeExtraSpaces(StringCleaner.removeSymbols(text)); assertEquals(expResult, result); } /** * Test of unifyTerminators method, of class StringCleaner. */ @Test public void testUnifyTerminators() { logger.info("unifyTerminators"); String text = " This is amazing!!! ! How is this possible?!?!?!?!!!???! "; String expResult = "This is amazing. How is this possible."; String result = StringCleaner.unifyTerminators(text); assertEquals(expResult, result); } /** * Test of removeAccents method, of class StringCleaner. */ @Test public void testRemoveAccents() { logger.info("removeAccents"); String text = "'ά','ό','έ','ί','ϊ','ΐ','ή','ύ','ϋ','ΰ','ώ','à','á','â','ã','ä','ç','è','é','ê','ë','ì','í','î','ï','ñ','ò','ó','ô','õ','ö','ù','ú','û','ü','ý','ÿ','Ά','Ό','Έ','Ί','Ϊ','Ή','Ύ','Ϋ','Ώ','À','Á','Â','Ã','Ä','Ç','È','É','Ê','Ë','Ì','Í','Î','Ï','Ñ','Ò','Ó','Ô','Õ','Ö','Ù','Ú','Û','Ü','Ý'"; String expResult = "'α','ο','ε','ι','ι','ι','η','υ','υ','υ','ω','a','a','a','a','a','c','e','e','e','e','i','i','i','i','n','o','o','o','o','o','u','u','u','u','y','y','Α','Ο','Ε','Ι','Ι','Η','Υ','Υ','Ω','A','A','A','A','A','C','E','E','E','E','I','I','I','I','N','O','O','O','O','O','U','U','U','U','Y'"; String result = StringCleaner.removeAccents(text); assertEquals(expResult, result); } }
codeaudit/datumbox-framework
src/test/java/com/datumbox/framework/utilities/text/cleaners/StringCleanerTest.java
45,933
package com.coinomi.core.wallet; import com.coinomi.core.coins.BitcoinMain; import com.coinomi.core.coins.CoinType; import com.coinomi.core.coins.DogecoinTest; import com.coinomi.core.coins.NuBitsMain; import com.coinomi.core.coins.Value; import com.coinomi.core.coins.VpncoinMain; import com.coinomi.core.exceptions.AddressMalformedException; import com.coinomi.core.exceptions.Bip44KeyLookAheadExceededException; import com.coinomi.core.exceptions.KeyIsEncryptedException; import com.coinomi.core.exceptions.MissingPrivateKeyException; import com.coinomi.core.network.AddressStatus; import com.coinomi.core.network.BlockHeader; import com.coinomi.core.network.ServerClient.HistoryTx; import com.coinomi.core.network.ServerClient.UnspentTx; import com.coinomi.core.network.interfaces.ConnectionEventListener; import com.coinomi.core.network.interfaces.TransactionEventListener; import com.coinomi.core.protos.Protos; import com.coinomi.core.wallet.families.bitcoin.BitAddress; import com.coinomi.core.wallet.families.bitcoin.BitBlockchainConnection; import com.coinomi.core.wallet.families.bitcoin.BitSendRequest; import com.coinomi.core.wallet.families.bitcoin.BitTransaction; import com.coinomi.core.wallet.families.bitcoin.BitTransactionEventListener; import com.coinomi.core.wallet.families.bitcoin.OutPointOutput; import com.coinomi.core.wallet.families.bitcoin.TrimmedOutPoint; import com.google.common.collect.ImmutableList; import org.bitcoinj.core.ChildMessage; import org.bitcoinj.core.Coin; import org.bitcoinj.core.ECKey; import org.bitcoinj.core.Sha256Hash; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.TransactionConfidence.Source; import org.bitcoinj.core.TransactionInput; import org.bitcoinj.core.TransactionOutput; import org.bitcoinj.core.Utils; import org.bitcoinj.crypto.DeterministicHierarchy; import org.bitcoinj.crypto.DeterministicKey; import org.bitcoinj.crypto.HDKeyDerivation; import org.bitcoinj.crypto.KeyCrypter; import org.bitcoinj.crypto.KeyCrypterScrypt; import org.bitcoinj.store.UnreadableWalletException; import org.bitcoinj.utils.BriefLogFormatter; import org.bitcoinj.wallet.DeterministicSeed; import org.bitcoinj.wallet.KeyChain; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.spongycastle.crypto.params.KeyParameter; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.coinomi.core.Preconditions.checkNotNull; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; /** * @author John L. Jegutanis */ public class WalletPocketHDTest { static final CoinType BTC = BitcoinMain.get(); static final CoinType DOGE = DogecoinTest.get(); static final CoinType NBT = NuBitsMain.get(); static final CoinType VPN = VpncoinMain.get(); static final List<String> MNEMONIC = ImmutableList.of("citizen", "fever", "scale", "nurse", "brief", "round", "ski", "fiction", "car", "fitness", "pluck", "act"); static final byte[] AES_KEY_BYTES = {0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7}; static final long AMOUNT_TO_SEND = 2700000000L; static final String MESSAGE = "test"; static final String MESSAGE_UNICODE = "δοκιμή испытание 测试"; static final String EXPECTED_BITCOIN_SIG = "IMBbIFDDuUwomYlvSjwWytqP/CXYym2yOKbJUx8Y+ujzZKBwoCFMr73GUxpr1Ird/DvnNZcsQLphvx18ftqN54o="; static final String EXPECTED_BITCOIN_SIG_UNICODE = "IGGZEOBsVny5dozTOfc2/3UuvmZGdDI4XK/03HIk34PILd2oXbnq+87GINT3lumeXcgSO2NkGzUFcQ1SCSVI3Hk="; static final String EXPECTED_NUBITS_SIG = "IMuzNZTZIjZjLicyDFGzqFl21vqNBGW1N5m4qHBRqbTvLBbkQeGjraeLmZEt7mRH4MSMPLFXW2T3Maz+HYx1tEc="; static final String EXPECTED_NUBITS_SIG_UNICODE = "Hx7xkBbboXrp96dbQrJFzm2unTGwLstjbWlKa1/N1E4LJqbwJAJR1qIvwXm6LHQFnLOzwoQA45zYNjwUEPMc8sg="; DeterministicSeed seed = new DeterministicSeed(MNEMONIC, null, "", 0); DeterministicKey masterKey = HDKeyDerivation.createMasterPrivateKey(checkNotNull(seed.getSeedBytes())); DeterministicHierarchy hierarchy = new DeterministicHierarchy(masterKey); DeterministicKey rootKey = hierarchy.get(DOGE.getBip44Path(0), false, true); KeyParameter aesKey = new KeyParameter(AES_KEY_BYTES); KeyCrypter crypter = new KeyCrypterScrypt(); WalletPocketHD pocket; @Before public void setup() { BriefLogFormatter.init(); pocket = new WalletPocketHD(rootKey, DOGE, null, null); pocket.keys.setLookaheadSize(20); } @Test public void testId() throws Exception { assertEquals("8747886e9a77fe2a1588df3168b867648434d6d339b0b448793ae1db8f283f41", pocket.getId()); } @Test public void testSingleAddressWallet() throws Exception { ECKey key = pocket.keys.getCurrentUnusedKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); BitWalletSingleKey bitWalletSingleKey = new BitWalletSingleKey(DOGE, key); bitWalletSingleKey.onConnection(getBlockchainConnection(DOGE)); assertEquals(DOGE.value("10"), bitWalletSingleKey.getBalance()); } @Test public void xpubWallet() { String xpub = "xpub67tVq9TLPPoaHVSiYu8mqahm3eztTPUts6JUftNq3pZF1PJwjknrTqQhjc2qRGd6vS8wANu7mLnqkiUzFZ1xZsAZoUMi8o6icMhzGCAhcSW"; DeterministicKey key = DeterministicKey.deserializeB58(null, xpub); WalletPocketHD account = new WalletPocketHD(key, BTC, null, null); assertEquals("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", account.getReceiveAddress().toString()); account = new WalletPocketHD(key, NBT, null, null); assertEquals("BNvJUwg3BgkbQk5br1CxvHxdcDp1EC3saE", account.getReceiveAddress().toString()); } @Test public void xpubWalletSerialized() throws Exception { WalletPocketHD account = new WalletPocketHD(rootKey, BTC, null, null); Protos.WalletPocket proto = account.toProtobuf(); WalletPocketHD newAccount = new WalletPocketProtobufSerializer().readWallet(proto, null); assertEquals(account.getPublicKeySerialized(), newAccount.getPublicKeySerialized()); } @Test public void signMessage() throws AddressMalformedException, MissingPrivateKeyException, KeyIsEncryptedException { WalletPocketHD pocketHD = new WalletPocketHD(rootKey, BTC, null, null); pocketHD.getReceiveAddress(); // Generate the first key SignedMessage signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE); pocketHD.signMessage(signedMessage, null); assertEquals(EXPECTED_BITCOIN_SIG, signedMessage.getSignature()); signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE_UNICODE); pocketHD.signMessage(signedMessage, null); assertEquals(EXPECTED_BITCOIN_SIG_UNICODE, signedMessage.getSignature()); pocketHD = new WalletPocketHD(rootKey, NBT, null, null); pocketHD.getReceiveAddress(); // Generate the first key signedMessage = new SignedMessage("BNvJUwg3BgkbQk5br1CxvHxdcDp1EC3saE", MESSAGE); pocketHD.signMessage(signedMessage, null); assertEquals(EXPECTED_NUBITS_SIG, signedMessage.getSignature()); signedMessage = new SignedMessage("BNvJUwg3BgkbQk5br1CxvHxdcDp1EC3saE", MESSAGE_UNICODE); pocketHD.signMessage(signedMessage, null); assertEquals(EXPECTED_NUBITS_SIG_UNICODE, signedMessage.getSignature()); } @Test public void signMessageEncrypted() throws AddressMalformedException, MissingPrivateKeyException, KeyIsEncryptedException { WalletPocketHD pocketHD = new WalletPocketHD(rootKey, BTC, null, null); pocketHD.getReceiveAddress(); // Generate the first key pocketHD.encrypt(crypter, aesKey); SignedMessage signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE); pocketHD.signMessage(signedMessage, aesKey); assertEquals(EXPECTED_BITCOIN_SIG, signedMessage.getSignature()); signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE_UNICODE); pocketHD.signMessage(signedMessage, aesKey); assertEquals(EXPECTED_BITCOIN_SIG_UNICODE, signedMessage.getSignature()); } @Test public void signMessageEncryptedFailed() throws AddressMalformedException, MissingPrivateKeyException, KeyIsEncryptedException { WalletPocketHD pocketHD = new WalletPocketHD(rootKey, BTC, null, null); pocketHD.getReceiveAddress(); // Generate the first key pocketHD.encrypt(crypter, aesKey); SignedMessage signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE); pocketHD.signMessage(signedMessage, null); assertEquals(SignedMessage.Status.KeyIsEncrypted, signedMessage.status); } @Test public void watchingAddresses() { List<AbstractAddress> watchingAddresses = pocket.getAddressesToWatch(); assertEquals(40, watchingAddresses.size()); // 20 + 20 lookahead size for (int i = 0; i < addresses.size(); i++) { assertEquals(addresses.get(i), watchingAddresses.get(i).toString()); } } @Test public void issuedKeys() throws Bip44KeyLookAheadExceededException { List<BitAddress> issuedAddresses = new ArrayList<>(); assertEquals(0, pocket.getIssuedReceiveAddresses().size()); assertEquals(0, pocket.keys.getNumIssuedExternalKeys()); issuedAddresses.add(0, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS)); BitAddress freshAddress = pocket.getFreshReceiveAddress(); assertEquals(freshAddress, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS)); assertEquals(1, pocket.getIssuedReceiveAddresses().size()); assertEquals(1, pocket.keys.getNumIssuedExternalKeys()); assertEquals(issuedAddresses, pocket.getIssuedReceiveAddresses()); issuedAddresses.add(0, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS)); freshAddress = pocket.getFreshReceiveAddress(); assertEquals(freshAddress, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS)); assertEquals(2, pocket.getIssuedReceiveAddresses().size()); assertEquals(2, pocket.keys.getNumIssuedExternalKeys()); assertEquals(issuedAddresses, pocket.getIssuedReceiveAddresses()); } @Test public void issuedKeysLimit() throws Exception { assertTrue(pocket.canCreateFreshReceiveAddress()); try { for (int i = 0; i < 100; i++) { pocket.getFreshReceiveAddress(); } } catch (Bip44KeyLookAheadExceededException e) { assertFalse(pocket.canCreateFreshReceiveAddress()); // We haven't used any key so the total must be 20 - 1 (the unused key) assertEquals(19, pocket.getNumberIssuedReceiveAddresses()); assertEquals(19, pocket.getIssuedReceiveAddresses().size()); } pocket.onConnection(getBlockchainConnection(DOGE)); assertTrue(pocket.canCreateFreshReceiveAddress()); try { for (int i = 0; i < 100; i++) { pocket.getFreshReceiveAddress(); } } catch (Bip44KeyLookAheadExceededException e) { // try { // pocket.getFreshReceiveAddress(); // } catch (Bip44KeyLookAheadExceededException e1) { /* ignore */ } assertFalse(pocket.canCreateFreshReceiveAddress()); // We used 18, so the total must be (20-1)+18=37 assertEquals(37, pocket.getNumberIssuedReceiveAddresses()); assertEquals(37, pocket.getIssuedReceiveAddresses().size()); } } @Test public void issuedKeysLimit2() throws Exception { assertTrue(pocket.canCreateFreshReceiveAddress()); try { for (int i = 0; i < 100; i++) { pocket.getFreshReceiveAddress(); } } catch (Bip44KeyLookAheadExceededException e) { assertFalse(pocket.canCreateFreshReceiveAddress()); // We haven't used any key so the total must be 20 - 1 (the unused key) assertEquals(19, pocket.getNumberIssuedReceiveAddresses()); assertEquals(19, pocket.getIssuedReceiveAddresses().size()); } } @Test public void usedAddresses() throws Exception { assertEquals(0, pocket.getUsedAddresses().size()); pocket.onConnection(getBlockchainConnection(DOGE)); // Receive and change addresses assertEquals(13, pocket.getUsedAddresses().size()); } private Sha256Hash send(Value value, WalletPocketHD w1, WalletPocketHD w2) throws Exception { assertEquals(w1.getCoinType(), w2.getCoinType()); CoinType type = w1.getCoinType(); BitSendRequest req = w1.sendCoinsOffline(w2.getReceiveAddress(), value); req.feePerTxSize = type.value("0.01"); w1.completeAndSignTx(req); byte[] txBytes = req.tx.bitcoinSerialize(); w1.addNewTransactionIfNeeded(new BitTransaction(type, txBytes)); w2.addNewTransactionIfNeeded(new BitTransaction(type, txBytes)); return req.tx.getHash(); } @Test public void testSendingAndBalances() throws Exception { DeterministicHierarchy h = new DeterministicHierarchy(masterKey); WalletPocketHD account1 = new WalletPocketHD(h.get(BTC.getBip44Path(0), false, true), BTC, null, null); WalletPocketHD account2 = new WalletPocketHD(h.get(BTC.getBip44Path(1), false, true), BTC, null, null); WalletPocketHD account3 = new WalletPocketHD(h.get(BTC.getBip44Path(2), false, true), BTC, null, null); Transaction tx = new Transaction(BTC); tx.addOutput(BTC.oneCoin().toCoin(), account1.getReceiveAddress()); tx.getConfidence().setSource(Source.SELF); account1.addNewTransactionIfNeeded(tx); assertEquals(BTC.value("1"), account1.getBalance()); assertEquals(BTC.value("0"), account2.getBalance()); assertEquals(BTC.value("0"), account3.getBalance()); Sha256Hash txId = send(BTC.value("0.05"), account1, account2); assertEquals(BTC.value("0.94"), account1.getBalance()); assertEquals(BTC.value("0"), account2.getBalance()); assertEquals(BTC.value("0"), account3.getBalance()); setTrustedTransaction(account1, txId); setTrustedTransaction(account2, txId); assertEquals(BTC.value("0.94"), account1.getBalance()); assertEquals(BTC.value("0.05"), account2.getBalance()); txId = send(BTC.value("0.07"), account1, account3); setTrustedTransaction(account1, txId); setTrustedTransaction(account3, txId); assertEquals(BTC.value("0.86"), account1.getBalance()); assertEquals(BTC.value("0.05"), account2.getBalance()); assertEquals(BTC.value("0.07"), account3.getBalance()); txId = send(BTC.value("0.03"), account2, account3); setTrustedTransaction(account2, txId); setTrustedTransaction(account3, txId); assertEquals(BTC.value("0.86"), account1.getBalance()); assertEquals(BTC.value("0.01"), account2.getBalance()); assertEquals(BTC.value("0.1"), account3.getBalance()); } private void setTrustedTransaction(WalletPocketHD account, Sha256Hash txId) { BitTransaction tx = checkNotNull(account.getTransaction(txId)); tx.setSource(Source.SELF); } @Test public void testLoading() throws Exception { assertFalse(pocket.isLoading()); pocket.onConnection(getBlockchainConnection(DOGE)); // TODO add fine grained control to the blockchain connection in order to test the loading status assertFalse(pocket.isLoading()); } @Test public void fillTransactions() throws Exception { pocket.onConnection(getBlockchainConnection(DOGE)); checkUnspentOutputs(getDummyUtxoSet(), pocket); assertEquals(11000000000L, pocket.getBalance().value); // Issued keys assertEquals(18, pocket.keys.getNumIssuedExternalKeys()); assertEquals(9, pocket.keys.getNumIssuedInternalKeys()); // No addresses left to subscribe List<AbstractAddress> addressesToWatch = pocket.getAddressesToWatch(); assertEquals(0, addressesToWatch.size()); // 18 external issued + 20 lookahead + 9 external issued + 20 lookahead assertEquals(67, pocket.addressesStatus.size()); assertEquals(67, pocket.addressesSubscribed.size()); BitAddress receiveAddr = pocket.getReceiveAddress(); // This key is not issued assertEquals(18, pocket.keys.getNumIssuedExternalKeys()); assertEquals(67, pocket.addressesStatus.size()); assertEquals(67, pocket.addressesSubscribed.size()); DeterministicKey key = pocket.keys.findKeyFromPubHash(receiveAddr.getHash160()); assertNotNull(key); // 18 here is the key index, not issued keys count assertEquals(18, key.getChildNumber().num()); assertEquals(11000000000L, pocket.getBalance().value); } @Test public void serializeTransactionsBtc() throws Exception, Bip44KeyLookAheadExceededException { WalletPocketHD account = new WalletPocketHD(rootKey, BTC, null, null); Transaction tx = new Transaction(BTC); tx.addOutput(BTC.oneCoin().toCoin(), account.getReceiveAddress()); account.addNewTransactionIfNeeded(tx); testWalletSerializationForCoin(account); } @Test public void serializeTransactionsNbt() throws Exception, Bip44KeyLookAheadExceededException { WalletPocketHD account = new WalletPocketHD(rootKey, NBT, null, null); Transaction tx = new Transaction(NBT); tx.addOutput(NBT.oneCoin().toCoin(), account.getReceiveAddress()); account.addNewTransactionIfNeeded(tx); testWalletSerializationForCoin(account); } @Test public void serializeTransactionsVpn() throws Exception, Bip44KeyLookAheadExceededException { WalletPocketHD account = new WalletPocketHD(rootKey, VPN, null, null); // Test tx with null extra bytes Transaction tx = new Transaction(VPN); tx.setTime(0x99999999); tx.addOutput(VPN.oneCoin().toCoin(), account.getFreshReceiveAddress()); account.addNewTransactionIfNeeded(tx); WalletPocketHD newAccount = testWalletSerializationForCoin(account); Transaction newTx = newAccount.getRawTransaction(tx.getHash()); assertNotNull(newTx); assertNotNull(newTx.getExtraBytes()); assertEquals(0, newTx.getExtraBytes().length); // Test tx with empty extra bytes tx = new Transaction(VPN); tx.setTime(0x99999999); tx.setExtraBytes(new byte[0]); tx.addOutput(VPN.oneCoin().toCoin(), account.getFreshReceiveAddress()); account.addNewTransactionIfNeeded(tx); newAccount = testWalletSerializationForCoin(account); newTx = newAccount.getRawTransaction(tx.getHash()); assertNotNull(newTx); assertNotNull(newTx.getExtraBytes()); assertEquals(0, newTx.getExtraBytes().length); // Test tx with extra bytes tx = new Transaction(VPN); tx.setTime(0x99999999); byte[] bytes = {0x1, 0x2, 0x3}; tx.setExtraBytes(bytes); tx.addOutput(VPN.oneCoin().toCoin(), account.getFreshReceiveAddress()); account.addNewTransactionIfNeeded(tx); newAccount = testWalletSerializationForCoin(account); newTx = newAccount.getRawTransaction(tx.getHash()); assertNotNull(newTx); assertArrayEquals(bytes, newTx.getExtraBytes()); } private WalletPocketHD testWalletSerializationForCoin(WalletPocketHD account) throws UnreadableWalletException { Protos.WalletPocket proto = account.toProtobuf(); WalletPocketHD newAccount = new WalletPocketProtobufSerializer().readWallet(proto, null); assertEquals(account.getBalance().value, newAccount.getBalance().value); Map<Sha256Hash, BitTransaction> transactions = account.getTransactions(); Map<Sha256Hash, BitTransaction> newTransactions = newAccount.getTransactions(); for (Sha256Hash txId : transactions.keySet()) { assertTrue(newTransactions.containsKey(txId)); assertEquals(transactions.get(txId), newTransactions.get(txId)); } return newAccount; } @Test public void serializeUnencryptedNormal() throws Exception { pocket.onConnection(getBlockchainConnection(DOGE)); Protos.WalletPocket walletPocketProto = pocket.toProtobuf(); System.out.println(walletPocketProto.toString()); WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(walletPocketProto, null); assertEquals(pocket.getBalance().value, newPocket.getBalance().value); assertEquals(DOGE.value(11000000000l), newPocket.getBalance()); Map<TrimmedOutPoint, OutPointOutput> expectedUtxoSet = getDummyUtxoSet(); checkUnspentOutputs(expectedUtxoSet, pocket); checkUnspentOutputs(expectedUtxoSet, newPocket); assertEquals(pocket.getCoinType(), newPocket.getCoinType()); assertEquals(pocket.getDescriptionOrCoinName(), newPocket.getDescriptionOrCoinName()); assertEquals(pocket.keys.toProtobuf().toString(), newPocket.keys.toProtobuf().toString()); assertEquals(pocket.getLastBlockSeenHash(), newPocket.getLastBlockSeenHash()); assertEquals(pocket.getLastBlockSeenHeight(), newPocket.getLastBlockSeenHeight()); assertEquals(pocket.getLastBlockSeenTimeSecs(), newPocket.getLastBlockSeenTimeSecs()); for (BitTransaction tx : pocket.getTransactions().values()) { assertEquals(tx, newPocket.getTransaction(tx.getHash())); BitTransaction txNew = checkNotNull(newPocket.getTransaction(tx.getHash())); assertInputsEquals(tx.getInputs(), txNew.getInputs()); assertOutputsEquals(tx.getOutputs(false), txNew.getOutputs(false)); } for (AddressStatus status : pocket.getAllAddressStatus()) { if (status.getStatus() == null) continue; assertEquals(status, newPocket.getAddressStatus(status.getAddress())); } // Issued keys assertEquals(18, newPocket.keys.getNumIssuedExternalKeys()); assertEquals(9, newPocket.keys.getNumIssuedInternalKeys()); newPocket.onConnection(getBlockchainConnection(DOGE)); // No addresses left to subscribe List<AbstractAddress> addressesToWatch = newPocket.getAddressesToWatch(); assertEquals(0, addressesToWatch.size()); // 18 external issued + 20 lookahead + 9 external issued + 20 lookahead assertEquals(67, newPocket.addressesStatus.size()); assertEquals(67, newPocket.addressesSubscribed.size()); } private void assertInputsEquals(List<TransactionInput> expected, List<TransactionInput> actual) { assertEquals(expected.size(), actual.size()); for (int i = 0; i < expected.size(); i++) { assertArrayEquals(expected.get(i).bitcoinSerialize(), actual.get(i).bitcoinSerialize()); } } private void assertOutputsEquals(List<TransactionOutput> expected, List<TransactionOutput> actual) { assertEquals(expected.size(), actual.size()); for (int i = 0; i < expected.size(); i++) { assertArrayEquals(expected.get(i).bitcoinSerialize(), actual.get(i).bitcoinSerialize()); } } @Test public void serializeUnencryptedEmpty() throws Exception { pocket.maybeInitializeAllKeys(); Protos.WalletPocket walletPocketProto = pocket.toProtobuf(); WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(walletPocketProto, null); assertEquals(walletPocketProto.toString(), newPocket.toProtobuf().toString()); // Issued keys assertEquals(0, newPocket.keys.getNumIssuedExternalKeys()); assertEquals(0, newPocket.keys.getNumIssuedInternalKeys()); // 20 lookahead + 20 lookahead assertEquals(40, newPocket.keys.getActiveKeys().size()); } @Test public void serializeEncryptedEmpty() throws Exception { pocket.maybeInitializeAllKeys(); pocket.encrypt(crypter, aesKey); Protos.WalletPocket walletPocketProto = pocket.toProtobuf(); WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(walletPocketProto, crypter); assertEquals(walletPocketProto.toString(), newPocket.toProtobuf().toString()); pocket.decrypt(aesKey); // One is encrypted, so they should not match assertNotEquals(pocket.toProtobuf().toString(), newPocket.toProtobuf().toString()); newPocket.decrypt(aesKey); assertEquals(pocket.toProtobuf().toString(), newPocket.toProtobuf().toString()); } @Test public void serializeEncryptedNormal() throws Exception { pocket.maybeInitializeAllKeys(); pocket.encrypt(crypter, aesKey); pocket.onConnection(getBlockchainConnection(DOGE)); assertEquals(DOGE.value(11000000000l), pocket.getBalance()); assertAllKeysEncrypted(pocket); WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(pocket.toProtobuf(), crypter); assertEquals(DOGE.value(11000000000l), newPocket.getBalance()); Map<TrimmedOutPoint, OutPointOutput> expectedUtxoSet = getDummyUtxoSet(); checkUnspentOutputs(expectedUtxoSet, pocket); checkUnspentOutputs(expectedUtxoSet, newPocket); assertAllKeysEncrypted(newPocket); pocket.decrypt(aesKey); newPocket.decrypt(aesKey); assertAllKeysDecrypted(pocket); assertAllKeysDecrypted(newPocket); } private void checkUnspentOutputs(Map<TrimmedOutPoint, OutPointOutput> expectedUtxoSet, WalletPocketHD pocket) { Map<TrimmedOutPoint, OutPointOutput> pocketUtxoSet = pocket.getUnspentOutputs(false); for (OutPointOutput utxo : expectedUtxoSet.values()) { assertEquals(utxo, pocketUtxoSet.get(utxo.getOutPoint())); } } private void assertAllKeysDecrypted(WalletPocketHD pocket) { List<ECKey> keys = pocket.keys.getKeys(false); for (ECKey k : keys) { DeterministicKey key = (DeterministicKey) k; assertFalse(key.isEncrypted()); } } private void assertAllKeysEncrypted(WalletPocketHD pocket) { List<ECKey> keys = pocket.keys.getKeys(false); for (ECKey k : keys) { DeterministicKey key = (DeterministicKey) k; assertTrue(key.isEncrypted()); } } @Test public void createDustTransactionFee() throws Exception { pocket.onConnection(getBlockchainConnection(DOGE)); BitAddress toAddr = BitAddress.from(DOGE, "nZB8PHkfgJvuCJqchSexmfY3ABXa2aE1vp"); Value softDust = DOGE.getSoftDustLimit(); assertNotNull(softDust); // Send a soft dust BitSendRequest sendRequest = pocket.sendCoinsOffline(toAddr, softDust.subtract(DOGE.value(1))); pocket.completeTransaction(sendRequest); assertEquals(DOGE.getFeeValue().multiply(2), sendRequest.tx.getFee()); } @Test public void createTransactionAndBroadcast() throws Exception { pocket.onConnection(getBlockchainConnection(DOGE)); BitAddress toAddr = BitAddress.from(DOGE, "nZB8PHkfgJvuCJqchSexmfY3ABXa2aE1vp"); Value orgBalance = pocket.getBalance(); BitSendRequest sendRequest = pocket.sendCoinsOffline(toAddr, DOGE.value(AMOUNT_TO_SEND)); sendRequest.shuffleOutputs = false; sendRequest.feePerTxSize = DOGE.value(0); pocket.completeTransaction(sendRequest); // FIXME, mock does not work here // pocket.broadcastTx(tx); pocket.addNewTransactionIfNeeded(sendRequest.tx); assertEquals(orgBalance.subtract(AMOUNT_TO_SEND), pocket.getBalance()); } // Util methods //////////////////////////////////////////////////////////////////////////////////////////////// public class MessageComparator implements Comparator<ChildMessage> { @Override public int compare(ChildMessage o1, ChildMessage o2) { String s1 = Utils.HEX.encode(o1.bitcoinSerialize()); String s2 = Utils.HEX.encode(o2.bitcoinSerialize()); return s1.compareTo(s2); } } HashMap<AbstractAddress, AddressStatus> getDummyStatuses() throws AddressMalformedException { HashMap<AbstractAddress, AddressStatus> status = new HashMap<>(40); for (int i = 0; i < addresses.size(); i++) { AbstractAddress address = DOGE.newAddress(addresses.get(i)); status.put(address, new AddressStatus(address, statuses[i])); } return status; } private HashMap<AbstractAddress, ArrayList<HistoryTx>> getDummyHistoryTXs() throws AddressMalformedException, JSONException { HashMap<AbstractAddress, ArrayList<HistoryTx>> htxs = new HashMap<>(40); for (int i = 0; i < statuses.length; i++) { JSONArray jsonArray = new JSONArray(history[i]); ArrayList<HistoryTx> list = new ArrayList<>(); for (int j = 0; j < jsonArray.length(); j++) { list.add(new HistoryTx(jsonArray.getJSONObject(j))); } htxs.put(DOGE.newAddress(addresses.get(i)), list); } return htxs; } private HashMap<AbstractAddress, ArrayList<UnspentTx>> getDummyUnspentTXs() throws AddressMalformedException, JSONException { HashMap<AbstractAddress, ArrayList<UnspentTx>> utxs = new HashMap<>(40); for (int i = 0; i < statuses.length; i++) { JSONArray jsonArray = new JSONArray(unspent[i]); ArrayList<UnspentTx> list = new ArrayList<>(); for (int j = 0; j < jsonArray.length(); j++) { list.add(new UnspentTx(jsonArray.getJSONObject(j))); } utxs.put(DOGE.newAddress(addresses.get(i)), list); } return utxs; } private Map<TrimmedOutPoint, OutPointOutput> getDummyUtxoSet() throws AddressMalformedException, JSONException { final HashMap<TrimmedOutPoint, OutPointOutput> unspentOutputs = new HashMap<>(); for (int i = 0; i < statuses.length; i++) { BitAddress address = (BitAddress) DOGE.newAddress(addresses.get(i)); JSONArray utxoArray = new JSONArray(unspent[i]); for (int j = 0; j < utxoArray.length(); j++) { JSONObject utxoObject = utxoArray.getJSONObject(j); //"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 11, \"value\": 500000000, \"height\": 160267}]", TrimmedOutPoint outPoint = new TrimmedOutPoint(DOGE, utxoObject.getInt("tx_pos"), new Sha256Hash(utxoObject.getString("tx_hash"))); TransactionOutput output = new TransactionOutput(DOGE, null, Coin.valueOf(utxoObject.getLong("value")), address); OutPointOutput utxo = new OutPointOutput(outPoint, output, false); unspentOutputs.put(outPoint, utxo); } } return unspentOutputs; } private HashMap<Sha256Hash, byte[]> getDummyRawTXs() throws AddressMalformedException, JSONException { HashMap<Sha256Hash, byte[]> rawTxs = new HashMap<>(); for (String[] tx : txs) { rawTxs.put(new Sha256Hash(tx[0]), Utils.HEX.decode(tx[1])); } return rawTxs; } class MockBlockchainConnection implements BitBlockchainConnection { final HashMap<AbstractAddress, AddressStatus> statuses; final HashMap<AbstractAddress, ArrayList<HistoryTx>> historyTxs; final HashMap<AbstractAddress, ArrayList<UnspentTx>> unspentTxs; final HashMap<Sha256Hash, byte[]> rawTxs; private CoinType coinType; MockBlockchainConnection(CoinType coinType) throws Exception { this.coinType = coinType; statuses = getDummyStatuses(); historyTxs = getDummyHistoryTXs(); unspentTxs = getDummyUnspentTXs(); rawTxs = getDummyRawTXs(); } @Override public void getBlock(int height, TransactionEventListener<BitTransaction> listener) { } @Override public void subscribeToBlockchain(TransactionEventListener<BitTransaction> listener) { listener.onNewBlock(new BlockHeader(coinType, blockTimestamp, blockHeight)); } @Override public void subscribeToAddresses(List<AbstractAddress> addresses, TransactionEventListener<BitTransaction> listener) { for (AbstractAddress a : addresses) { AddressStatus status = statuses.get(a); if (status == null) { status = new AddressStatus(a, null); } listener.onAddressStatusUpdate(status); } } @Override public void getHistoryTx(AddressStatus status, TransactionEventListener<BitTransaction> listener) { List<HistoryTx> htx = historyTxs.get(status.getAddress()); if (htx == null) { htx = ImmutableList.of(); } listener.onTransactionHistory(status, htx); } @Override public void getUnspentTx(AddressStatus status, BitTransactionEventListener listener) { List<UnspentTx> utx = unspentTxs.get(status.getAddress()); if (utx == null) { utx = ImmutableList.of(); } listener.onUnspentTransactionUpdate(status, utx); } @Override public void getTransaction(Sha256Hash txHash, TransactionEventListener<BitTransaction> listener) { BitTransaction tx = new BitTransaction(coinType, rawTxs.get(txHash)); listener.onTransactionUpdate(tx); } @Override public void broadcastTx(BitTransaction tx, TransactionEventListener<BitTransaction> listener) { // List<AddressStatus> newStatuses = new ArrayList<AddressStatus>(); // Random rand = new Random(); // byte[] randBytes = new byte[32]; // // Get spent outputs and modify statuses // for (TransactionInput txi : tx.getInputs()) { // UnspentTx unspentTx = new UnspentTx( // txi.getOutpoint(), txi.getValue().value, 0); // // for (Map.Entry<Address, ArrayList<UnspentTx>> entry : utxs.entrySet()) { // if (entry.getValue().remove(unspentTx)) { // rand.nextBytes(randBytes); // AddressStatus newStatus = new AddressStatus(entry.getKey(), Utils.HEX.encode(randBytes)); // statuses.put(entry.getKey(), newStatus); // newStatuses.add(newStatus); // } // } // } // // for (TransactionOutput txo : tx.getOutputs()) { // if (txo.getAddressFromP2PKHScript(coinType) != null) { // Address address = txo.getAddressFromP2PKHScript(coinType); // if (addresses.contains(address.toString())) { // AddressStatus newStatus = new AddressStatus(address, tx.getHashAsString()); // statuses.put(address, newStatus); // newStatuses.add(newStatus); // if (!utxs.containsKey(address)) { // utxs.put(address, new ArrayList<UnspentTx>()); // } // ArrayList<UnspentTx> unspentTxs = utxs.get(address); // unspentTxs.add(new UnspentTx(txo.getOutPointFor(), // txo.getValue().value, 0)); // if (!historyTxs.containsKey(address)) { // historyTxs.put(address, new ArrayList<HistoryTx>()); // } // ArrayList<HistoryTx> historyTxes = historyTxs.get(address); // historyTxes.add(new HistoryTx(txo.getOutPointFor(), 0)); // } // } // } // // rawTxs.put(tx.getHash(), tx.bitcoinSerialize()); // // for (AddressStatus newStatus : newStatuses) { // listener.onAddressStatusUpdate(newStatus); // } } @Override public boolean broadcastTxSync(BitTransaction tx) { return false; } @Override public void ping(String versionString) {} @Override public void addEventListener(ConnectionEventListener listener) { } @Override public void resetConnection() { } @Override public void stopAsync() { } @Override public boolean isActivelyConnected() { return false; } @Override public void startAsync() { } } private MockBlockchainConnection getBlockchainConnection(CoinType coinType) throws Exception { return new MockBlockchainConnection(coinType); } // Mock data long blockTimestamp = 1411000000l; int blockHeight = 200000; List<String> addresses = ImmutableList.of( "nnfP8VuPfZXhNtMDzvX1bKurzcV1k7HNrQ", "nf4AUKiaGdx4GTbbh222KvtuCbAuvbcdE2", "npGkmbWtdWybFNSZQXUK6zZxbEocMtrTzz", "nVaN45bbs6AUc1EUpP71hHGBGb2qciNrJc", "nrdHFZP1AfdKBrjsSQmwFm8R2i2mzMef75", "niGZgfbhFYn6tJqksmC8CnzSRL1GHNsu7e", "nh6w8yu1zoKYoT837ffkVmuPjTaP69Pc5E", "nbyMgmEghsL9tpk7XfdH9gLGudh6Lrbbuf", "naX9akzYuWY1gKbcZo3t36aBKc1gqbzgSs", "nqcPVTGeAfCowELB2D5PdVF3FWFjFtkkFf", "nd4vVvPTpp2LfcsMPsmG3Dh7MFAsqRHp4g", "nVK4Uz5Sf56ygrr6RiwXcRvH8AuUVbjjHi", "nbipkRwT1NCSXZSrm8uAAEgQAA2s2NWMkG", "nZU6QAMAdCQcVDxEmL7GEY6ykFm8m6u6am", "nbFqayssM5s7hLjLFwf2d95JXKRWBk2pBH", "nacZfcNgVi47hamLscWdUGQhUQGGpSdgq8", "niiMT7ZYeFnaLPYtqQFBBX1sP3dT5JtcEw", "ns6GyTaniLWaiYrvAf5tk4D8tWrbcCLGyj", "nhdwQfptLTzLJGbLF3vvtqyBaqPMPecDmE", "neMUAGeTzwxLbSkXMsdmWf1fTKS1UsJjXY", "nXsAMeXxtpx8jaxnU3Xv9ZQ6ZcRcD1xYhR", "ns35rKnnWf6xP3KSj5WPkMCVVaADGi6Ndk", "nk4wcXYBEWs5HkhNLsuaQJoAjJHoK6SQmG", "npsJQWu8fsALoTPum8D4j8FDkyeusk8fU8", "nZNhZo4Vz3DnwQGPL3SJTZgUw2Kh4g9oay", "nnxDTYB8WMHMgLnCY2tuaEtysvdhRnWehZ", "nb2iaDXG1EqkcE47H87WQFkQNkeVK66Z21", "nWHAkpn2DB3DJRsbiK3vpbigoa3M2uVuF8", "nViKdC7Gm6TMmCuWTBwVE9i4rJhyfwbfqg", "nZQV5BifbGPzaxTrB4efgHruWH5rufemqP", "nVvZaLvnkCVAzpLYPoHeqU4w9zJ5yrZgUn", "nrMp6pRCk98WYWkCWq9Pqthz9HbpQu8BT3", "nnA3aYsLqysKT6gAu1dr4EKm586cmKiRxS", "nVfcVgMY7DL6nqoSxwJy7B7hKXirQwj6ic", "ni4oAzi6nCVuEdjoHyVMVKWb1DqTd3qY3H", "nnpf3gx442yomniRJPMGPapgjHrraPZXxJ", "nkuFnF8wUmHFkMycaFMvyjBoiMeR5KBKGd", "nXKccwjaUyrQkLrdqKT6aq6cDiFgBBVgNz", "nZMSNsXSAL7i1YD6KP5FrhATuZ2CWvnxqR", "nUEkQ3LjH9m4ScbP6NGtnAdnnUsdtWv99Q" ); String[] statuses = { "fe7c109d8bd90551a406cf0b3499117db04bc9c4f48e1df27ac1cf3ddcb3d464", "8a53babd831c6c3a857e20190e884efe75a005bdd7cd273c4f27ab1b8ec81c2d", "86bc2f0cf0112fd59c9aadfe5c887062c21d7a873db260dff68dcfe4417fe212", "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, null, null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, null, null, null, null, null, null, null, null, null }; String[] unspent = { "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 0, \"value\": 500000000, \"height\": 160267}, {\"tx_hash\": \"89a72ba4732505ce9b09c30668db985952701252ce0adbd7c43336396697d6ae\", \"tx_pos\": 0, \"value\": 500000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 1, \"value\": 1000000000, \"height\": 160267}, {\"tx_hash\": \"edaf445288d8e65cf7963bc8047c90f53681acaadc5ccfc5ecc67aedbd73cddb\", \"tx_pos\": 0, \"value\": 500000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 2, \"value\": 500000000, \"height\": 160267}, {\"tx_hash\": \"81a1f0f8242d5e71e65ff9e8ec51e8e85d641b607d7f691c1770d4f25918ebd7\", \"tx_pos\": 0, \"value\": 1000000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 3, \"value\": 500000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 4, \"value\": 1000000000, \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 11, \"value\": 500000000, \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 12, \"value\": 1000000000, \"height\": 160267}]", "[]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 13, \"value\": 500000000, \"height\": 160267}]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 6, \"value\": 500000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 7, \"value\": 1000000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 8, \"value\": 500000000, \"height\": 160267}]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 9, \"value\": 500000000, \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 10, \"value\": 1000000000, \"height\": 160267}]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]" }; String[] history = { "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}, {\"tx_hash\": \"89a72ba4732505ce9b09c30668db985952701252ce0adbd7c43336396697d6ae\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}, {\"tx_hash\": \"edaf445288d8e65cf7963bc8047c90f53681acaadc5ccfc5ecc67aedbd73cddb\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}, {\"tx_hash\": \"81a1f0f8242d5e71e65ff9e8ec51e8e85d641b607d7f691c1770d4f25918ebd7\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]" }; String[][] txs = { {"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f", "0100000001b8778dff640ccb144346d9db48201639b2707a0cc59e19672d2dd76cc6d1a5a6010000006b48304502210098d2e5b8a6c72442430bc09f2f4bcb56612c5b9e5eee821d65b412d099bb723402204f7f008ac052e5d7be0ab5b0c85ea5e627d725a521bd9e9b193d1fdf81c317a0012102d26e423c9da9ff4a7bf6b756b2dafb75cca34fbd34f64c4c3b77c37179c5bba2ffffffff0e0065cd1d000000001976a914ca983c2da690de3cdc693ca013d93e569810c52c88ac00ca9a3b000000001976a91477263ab93a49b1d3eb5887187704cdb82e1c60ce88ac0065cd1d000000001976a914dc40fbbc8caa1f7617d275aec9a3a14ce8d8652188ac0065cd1d000000001976a9140f2b1e5b376e22c5d1e635233eb90cf50ad9095188ac00ca9a3b000000001976a914f612ffd50b6a69df5e34ee0c5b529dfaaedca03d88ac00f633bce60000001976a914937258e3a8c463ec07e78ce62326c488170ad25e88ac0065cd1d000000001976a9142848ad5ff4cc32df3649646017c47bc04e8d211788ac00ca9a3b000000001976a914fa937737a6df2b8a5e39cce8b0bdd9510683023a88ac0065cd1d000000001976a914ae248a5d710143b6b309aaab9ce17059536e2aa388ac0065cd1d000000001976a91438d6eb11eca405be497a7183c50e437851425e0088ac00ca9a3b000000001976a91410ac6b2704146b50a1dd8f6df70736856ebf8b3488ac0065cd1d000000001976a914456816dccb3a4f33ae2dbd3ba623997075d5c73d88ac00ca9a3b000000001976a91452957c44e5bee9a60402a739fc8959c2850ea98488ac0065cd1d000000001976a914fb2dffa402d05f74335d137e21e41d8920c745fb88ac00000000"}, {"89a72ba4732505ce9b09c30668db985952701252ce0adbd7c43336396697d6ae", "01000000011a656d67706db286d1e6fad57eb4f411cb14f8880cea8348da339b9d434a5ec7050000006a47304402201d69fddb269b53aa742ff6437a45adb4ca5c59f666c9b4eabc4a0c7a6e6f4c0f022015a747b7a6d9371a4020f5b396dcd094b0f36af3fc82e95091da856181912dfa012102c9a8d5b2f768afe30ee772d185e7a61f751be05649a79508b38a2be8824adec3ffffffff020065cd1d000000001976a914ca983c2da690de3cdc693ca013d93e569810c52c88ac00b07098e60000001976a9141630d812e219e6bcbe494eb96f7a7900c216ad5d88ac00000000"}, {"edaf445288d8e65cf7963bc8047c90f53681acaadc5ccfc5ecc67aedbd73cddb", "010000000164a3990893c012b20287d43d1071ac26f4b93648ff4213db6da6979beed6b7dc010000006b48304502210086ac11d4a8146b4176a72059960690c72a9776468cd671fd07c064b51f24961d02205bcf008d6995014f3cfd79100ee9beab5688c88cca15c5cea38b769563785d900121036530415a7b3b9c5976f26a63a57d119ab39491762121723c773399a2531a1bd7ffffffff020065cd1d000000001976a91477263ab93a49b1d3eb5887187704cdb82e1c60ce88ac006aad74e60000001976a914e5616848352c328c9f61b167eb1b0fde39b5cb6788ac00000000"}, {"81a1f0f8242d5e71e65ff9e8ec51e8e85d641b607d7f691c1770d4f25918ebd7", "010000000141c217dfea3a1d8d6a06e9d3daf75b292581f652256d73a7891e5dc9c7ee3cca000000006a47304402205cce451228f98fece9645052546b82c2b2d425a4889b03999001fababfc7f4690220583b2189faef07d6b0191c788301cfab1b3f47ffe2c403d632b92c6dde27e14f012102d26e423c9da9ff4a7bf6b756b2dafb75cca34fbd34f64c4c3b77c37179c5bba2ffffffff0100ca9a3b000000001976a914dc40fbbc8caa1f7617d275aec9a3a14ce8d8652188ac00000000"} }; }
CryptowalletSi/Cryptowallet.si
core/src/test/java/com/coinomi/core/wallet/WalletPocketHDTest.java
45,934
package com.crownpay.core.wallet; import com.crownpay.core.coins.BitcoinMain; import com.crownpay.core.coins.CoinType; import com.crownpay.core.coins.DogecoinTest; import com.crownpay.core.coins.NuBitsMain; import com.crownpay.core.coins.Value; import com.crownpay.core.coins.VpncoinMain; import com.crownpay.core.exceptions.AddressMalformedException; import com.crownpay.core.exceptions.Bip44KeyLookAheadExceededException; import com.crownpay.core.exceptions.KeyIsEncryptedException; import com.crownpay.core.exceptions.MissingPrivateKeyException; import com.crownpay.core.network.AddressStatus; import com.crownpay.core.network.BlockHeader; import com.crownpay.core.network.ServerClient.HistoryTx; import com.crownpay.core.network.ServerClient.UnspentTx; import com.crownpay.core.network.interfaces.ConnectionEventListener; import com.crownpay.core.network.interfaces.TransactionEventListener; import com.crownpay.core.protos.Protos; import com.crownpay.core.wallet.families.bitcoin.BitAddress; import com.crownpay.core.wallet.families.bitcoin.BitBlockchainConnection; import com.crownpay.core.wallet.families.bitcoin.BitSendRequest; import com.crownpay.core.wallet.families.bitcoin.BitTransaction; import com.crownpay.core.wallet.families.bitcoin.BitTransactionEventListener; import com.crownpay.core.wallet.families.bitcoin.OutPointOutput; import com.crownpay.core.wallet.families.bitcoin.TrimmedOutPoint; import com.google.common.collect.ImmutableList; import org.bitcoinj.core.ChildMessage; import org.bitcoinj.core.Coin; import org.bitcoinj.core.ECKey; import org.bitcoinj.core.Sha256Hash; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.TransactionConfidence.Source; import org.bitcoinj.core.TransactionInput; import org.bitcoinj.core.TransactionOutput; import org.bitcoinj.core.Utils; import org.bitcoinj.crypto.DeterministicHierarchy; import org.bitcoinj.crypto.DeterministicKey; import org.bitcoinj.crypto.HDKeyDerivation; import org.bitcoinj.crypto.KeyCrypter; import org.bitcoinj.crypto.KeyCrypterScrypt; import org.bitcoinj.store.UnreadableWalletException; import org.bitcoinj.utils.BriefLogFormatter; import org.bitcoinj.wallet.DeterministicSeed; import org.bitcoinj.wallet.KeyChain; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.spongycastle.crypto.params.KeyParameter; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.crownpay.core.Preconditions.checkNotNull; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; /** * @author John L. Jegutanis */ public class WalletPocketHDTest { static final CoinType BTC = BitcoinMain.get(); static final CoinType DOGE = DogecoinTest.get(); static final CoinType NBT = NuBitsMain.get(); static final CoinType VPN = VpncoinMain.get(); static final List<String> MNEMONIC = ImmutableList.of("citizen", "fever", "scale", "nurse", "brief", "round", "ski", "fiction", "car", "fitness", "pluck", "act"); static final byte[] AES_KEY_BYTES = {0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7}; static final long AMOUNT_TO_SEND = 2700000000L; static final String MESSAGE = "test"; static final String MESSAGE_UNICODE = "δοκιμή испытание 测试"; static final String EXPECTED_BITCOIN_SIG = "IMBbIFDDuUwomYlvSjwWytqP/CXYym2yOKbJUx8Y+ujzZKBwoCFMr73GUxpr1Ird/DvnNZcsQLphvx18ftqN54o="; static final String EXPECTED_BITCOIN_SIG_UNICODE = "IGGZEOBsVny5dozTOfc2/3UuvmZGdDI4XK/03HIk34PILd2oXbnq+87GINT3lumeXcgSO2NkGzUFcQ1SCSVI3Hk="; static final String EXPECTED_NUBITS_SIG = "IMuzNZTZIjZjLicyDFGzqFl21vqNBGW1N5m4qHBRqbTvLBbkQeGjraeLmZEt7mRH4MSMPLFXW2T3Maz+HYx1tEc="; static final String EXPECTED_NUBITS_SIG_UNICODE = "Hx7xkBbboXrp96dbQrJFzm2unTGwLstjbWlKa1/N1E4LJqbwJAJR1qIvwXm6LHQFnLOzwoQA45zYNjwUEPMc8sg="; DeterministicSeed seed = new DeterministicSeed(MNEMONIC, null, "", 0); DeterministicKey masterKey = HDKeyDerivation.createMasterPrivateKey(checkNotNull(seed.getSeedBytes())); DeterministicHierarchy hierarchy = new DeterministicHierarchy(masterKey); DeterministicKey rootKey = hierarchy.get(DOGE.getBip44Path(0), false, true); KeyParameter aesKey = new KeyParameter(AES_KEY_BYTES); KeyCrypter crypter = new KeyCrypterScrypt(); WalletPocketHD pocket; @Before public void setup() { BriefLogFormatter.init(); pocket = new WalletPocketHD(rootKey, DOGE, null, null); pocket.keys.setLookaheadSize(20); } @Test public void testId() throws Exception { assertEquals("8747886e9a77fe2a1588df3168b867648434d6d339b0b448793ae1db8f283f41", pocket.getId()); } @Test public void testSingleAddressWallet() throws Exception { ECKey key = pocket.keys.getCurrentUnusedKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); BitWalletSingleKey bitWalletSingleKey = new BitWalletSingleKey(DOGE, key); bitWalletSingleKey.onConnection(getBlockchainConnection(DOGE)); assertEquals(DOGE.value("10"), bitWalletSingleKey.getBalance()); } @Test public void xpubWallet() { String xpub = "xpub67tVq9TLPPoaHVSiYu8mqahm3eztTPUts6JUftNq3pZF1PJwjknrTqQhjc2qRGd6vS8wANu7mLnqkiUzFZ1xZsAZoUMi8o6icMhzGCAhcSW"; DeterministicKey key = DeterministicKey.deserializeB58(null, xpub); WalletPocketHD account = new WalletPocketHD(key, BTC, null, null); assertEquals("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", account.getReceiveAddress().toString()); account = new WalletPocketHD(key, NBT, null, null); assertEquals("BNvJUwg3BgkbQk5br1CxvHxdcDp1EC3saE", account.getReceiveAddress().toString()); } @Test public void xpubWalletSerialized() throws Exception { WalletPocketHD account = new WalletPocketHD(rootKey, BTC, null, null); Protos.WalletPocket proto = account.toProtobuf(); WalletPocketHD newAccount = new WalletPocketProtobufSerializer().readWallet(proto, null); assertEquals(account.getPublicKeySerialized(), newAccount.getPublicKeySerialized()); } @Test public void signMessage() throws AddressMalformedException, MissingPrivateKeyException, KeyIsEncryptedException { WalletPocketHD pocketHD = new WalletPocketHD(rootKey, BTC, null, null); pocketHD.getReceiveAddress(); // Generate the first key SignedMessage signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE); pocketHD.signMessage(signedMessage, null); assertEquals(EXPECTED_BITCOIN_SIG, signedMessage.getSignature()); signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE_UNICODE); pocketHD.signMessage(signedMessage, null); assertEquals(EXPECTED_BITCOIN_SIG_UNICODE, signedMessage.getSignature()); pocketHD = new WalletPocketHD(rootKey, NBT, null, null); pocketHD.getReceiveAddress(); // Generate the first key signedMessage = new SignedMessage("BNvJUwg3BgkbQk5br1CxvHxdcDp1EC3saE", MESSAGE); pocketHD.signMessage(signedMessage, null); assertEquals(EXPECTED_NUBITS_SIG, signedMessage.getSignature()); signedMessage = new SignedMessage("BNvJUwg3BgkbQk5br1CxvHxdcDp1EC3saE", MESSAGE_UNICODE); pocketHD.signMessage(signedMessage, null); assertEquals(EXPECTED_NUBITS_SIG_UNICODE, signedMessage.getSignature()); } @Test public void signMessageEncrypted() throws AddressMalformedException, MissingPrivateKeyException, KeyIsEncryptedException { WalletPocketHD pocketHD = new WalletPocketHD(rootKey, BTC, null, null); pocketHD.getReceiveAddress(); // Generate the first key pocketHD.encrypt(crypter, aesKey); SignedMessage signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE); pocketHD.signMessage(signedMessage, aesKey); assertEquals(EXPECTED_BITCOIN_SIG, signedMessage.getSignature()); signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE_UNICODE); pocketHD.signMessage(signedMessage, aesKey); assertEquals(EXPECTED_BITCOIN_SIG_UNICODE, signedMessage.getSignature()); } @Test public void signMessageEncryptedFailed() throws AddressMalformedException, MissingPrivateKeyException, KeyIsEncryptedException { WalletPocketHD pocketHD = new WalletPocketHD(rootKey, BTC, null, null); pocketHD.getReceiveAddress(); // Generate the first key pocketHD.encrypt(crypter, aesKey); SignedMessage signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE); pocketHD.signMessage(signedMessage, null); assertEquals(SignedMessage.Status.KeyIsEncrypted, signedMessage.status); } @Test public void watchingAddresses() { List<AbstractAddress> watchingAddresses = pocket.getAddressesToWatch(); assertEquals(40, watchingAddresses.size()); // 20 + 20 lookahead size for (int i = 0; i < addresses.size(); i++) { assertEquals(addresses.get(i), watchingAddresses.get(i).toString()); } } @Test public void issuedKeys() throws Bip44KeyLookAheadExceededException { List<BitAddress> issuedAddresses = new ArrayList<>(); assertEquals(0, pocket.getIssuedReceiveAddresses().size()); assertEquals(0, pocket.keys.getNumIssuedExternalKeys()); issuedAddresses.add(0, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS)); BitAddress freshAddress = pocket.getFreshReceiveAddress(); assertEquals(freshAddress, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS)); assertEquals(1, pocket.getIssuedReceiveAddresses().size()); assertEquals(1, pocket.keys.getNumIssuedExternalKeys()); assertEquals(issuedAddresses, pocket.getIssuedReceiveAddresses()); issuedAddresses.add(0, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS)); freshAddress = pocket.getFreshReceiveAddress(); assertEquals(freshAddress, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS)); assertEquals(2, pocket.getIssuedReceiveAddresses().size()); assertEquals(2, pocket.keys.getNumIssuedExternalKeys()); assertEquals(issuedAddresses, pocket.getIssuedReceiveAddresses()); } @Test public void issuedKeysLimit() throws Exception { assertTrue(pocket.canCreateFreshReceiveAddress()); try { for (int i = 0; i < 100; i++) { pocket.getFreshReceiveAddress(); } } catch (Bip44KeyLookAheadExceededException e) { assertFalse(pocket.canCreateFreshReceiveAddress()); // We haven't used any key so the total must be 20 - 1 (the unused key) assertEquals(19, pocket.getNumberIssuedReceiveAddresses()); assertEquals(19, pocket.getIssuedReceiveAddresses().size()); } pocket.onConnection(getBlockchainConnection(DOGE)); assertTrue(pocket.canCreateFreshReceiveAddress()); try { for (int i = 0; i < 100; i++) { pocket.getFreshReceiveAddress(); } } catch (Bip44KeyLookAheadExceededException e) { // try { // pocket.getFreshReceiveAddress(); // } catch (Bip44KeyLookAheadExceededException e1) { /* ignore */ } assertFalse(pocket.canCreateFreshReceiveAddress()); // We used 18, so the total must be (20-1)+18=37 assertEquals(37, pocket.getNumberIssuedReceiveAddresses()); assertEquals(37, pocket.getIssuedReceiveAddresses().size()); } } @Test public void issuedKeysLimit2() throws Exception { assertTrue(pocket.canCreateFreshReceiveAddress()); try { for (int i = 0; i < 100; i++) { pocket.getFreshReceiveAddress(); } } catch (Bip44KeyLookAheadExceededException e) { assertFalse(pocket.canCreateFreshReceiveAddress()); // We haven't used any key so the total must be 20 - 1 (the unused key) assertEquals(19, pocket.getNumberIssuedReceiveAddresses()); assertEquals(19, pocket.getIssuedReceiveAddresses().size()); } } @Test public void usedAddresses() throws Exception { assertEquals(0, pocket.getUsedAddresses().size()); pocket.onConnection(getBlockchainConnection(DOGE)); // Receive and change addresses assertEquals(13, pocket.getUsedAddresses().size()); } private Sha256Hash send(Value value, WalletPocketHD w1, WalletPocketHD w2) throws Exception { assertEquals(w1.getCoinType(), w2.getCoinType()); CoinType type = w1.getCoinType(); BitSendRequest req = w1.sendCoinsOffline(w2.getReceiveAddress(), value); req.feePerTxSize = type.value("0.01"); w1.completeAndSignTx(req); byte[] txBytes = req.tx.bitcoinSerialize(); w1.addNewTransactionIfNeeded(new BitTransaction(type, txBytes)); w2.addNewTransactionIfNeeded(new BitTransaction(type, txBytes)); return req.tx.getHash(); } @Test public void testSendingAndBalances() throws Exception { DeterministicHierarchy h = new DeterministicHierarchy(masterKey); WalletPocketHD account1 = new WalletPocketHD(h.get(BTC.getBip44Path(0), false, true), BTC, null, null); WalletPocketHD account2 = new WalletPocketHD(h.get(BTC.getBip44Path(1), false, true), BTC, null, null); WalletPocketHD account3 = new WalletPocketHD(h.get(BTC.getBip44Path(2), false, true), BTC, null, null); Transaction tx = new Transaction(BTC); tx.addOutput(BTC.oneCoin().toCoin(), account1.getReceiveAddress()); tx.getConfidence().setSource(Source.SELF); account1.addNewTransactionIfNeeded(tx); assertEquals(BTC.value("1"), account1.getBalance()); assertEquals(BTC.value("0"), account2.getBalance()); assertEquals(BTC.value("0"), account3.getBalance()); Sha256Hash txId = send(BTC.value("0.05"), account1, account2); assertEquals(BTC.value("0.94"), account1.getBalance()); assertEquals(BTC.value("0"), account2.getBalance()); assertEquals(BTC.value("0"), account3.getBalance()); setTrustedTransaction(account1, txId); setTrustedTransaction(account2, txId); assertEquals(BTC.value("0.94"), account1.getBalance()); assertEquals(BTC.value("0.05"), account2.getBalance()); txId = send(BTC.value("0.07"), account1, account3); setTrustedTransaction(account1, txId); setTrustedTransaction(account3, txId); assertEquals(BTC.value("0.86"), account1.getBalance()); assertEquals(BTC.value("0.05"), account2.getBalance()); assertEquals(BTC.value("0.07"), account3.getBalance()); txId = send(BTC.value("0.03"), account2, account3); setTrustedTransaction(account2, txId); setTrustedTransaction(account3, txId); assertEquals(BTC.value("0.86"), account1.getBalance()); assertEquals(BTC.value("0.01"), account2.getBalance()); assertEquals(BTC.value("0.1"), account3.getBalance()); } private void setTrustedTransaction(WalletPocketHD account, Sha256Hash txId) { BitTransaction tx = checkNotNull(account.getTransaction(txId)); tx.setSource(Source.SELF); } @Test public void testLoading() throws Exception { assertFalse(pocket.isLoading()); pocket.onConnection(getBlockchainConnection(DOGE)); // TODO add fine grained control to the blockchain connection in order to test the loading status assertFalse(pocket.isLoading()); } @Test public void fillTransactions() throws Exception { pocket.onConnection(getBlockchainConnection(DOGE)); checkUnspentOutputs(getDummyUtxoSet(), pocket); assertEquals(11000000000L, pocket.getBalance().value); // Issued keys assertEquals(18, pocket.keys.getNumIssuedExternalKeys()); assertEquals(9, pocket.keys.getNumIssuedInternalKeys()); // No addresses left to subscribe List<AbstractAddress> addressesToWatch = pocket.getAddressesToWatch(); assertEquals(0, addressesToWatch.size()); // 18 external issued + 20 lookahead + 9 external issued + 20 lookahead assertEquals(67, pocket.addressesStatus.size()); assertEquals(67, pocket.addressesSubscribed.size()); BitAddress receiveAddr = pocket.getReceiveAddress(); // This key is not issued assertEquals(18, pocket.keys.getNumIssuedExternalKeys()); assertEquals(67, pocket.addressesStatus.size()); assertEquals(67, pocket.addressesSubscribed.size()); DeterministicKey key = pocket.keys.findKeyFromPubHash(receiveAddr.getHash160()); assertNotNull(key); // 18 here is the key index, not issued keys count assertEquals(18, key.getChildNumber().num()); assertEquals(11000000000L, pocket.getBalance().value); } @Test public void serializeTransactionsBtc() throws Exception, Bip44KeyLookAheadExceededException { WalletPocketHD account = new WalletPocketHD(rootKey, BTC, null, null); Transaction tx = new Transaction(BTC); tx.addOutput(BTC.oneCoin().toCoin(), account.getReceiveAddress()); account.addNewTransactionIfNeeded(tx); testWalletSerializationForCoin(account); } @Test public void serializeTransactionsNbt() throws Exception, Bip44KeyLookAheadExceededException { WalletPocketHD account = new WalletPocketHD(rootKey, NBT, null, null); Transaction tx = new Transaction(NBT); tx.addOutput(NBT.oneCoin().toCoin(), account.getReceiveAddress()); account.addNewTransactionIfNeeded(tx); testWalletSerializationForCoin(account); } @Test public void serializeTransactionsVpn() throws Exception, Bip44KeyLookAheadExceededException { WalletPocketHD account = new WalletPocketHD(rootKey, VPN, null, null); // Test tx with null extra bytes Transaction tx = new Transaction(VPN); tx.setTime(0x99999999); tx.addOutput(VPN.oneCoin().toCoin(), account.getFreshReceiveAddress()); account.addNewTransactionIfNeeded(tx); WalletPocketHD newAccount = testWalletSerializationForCoin(account); Transaction newTx = newAccount.getRawTransaction(tx.getHash()); assertNotNull(newTx); assertNotNull(newTx.getExtraBytes()); assertEquals(0, newTx.getExtraBytes().length); // Test tx with empty extra bytes tx = new Transaction(VPN); tx.setTime(0x99999999); tx.setExtraBytes(new byte[0]); tx.addOutput(VPN.oneCoin().toCoin(), account.getFreshReceiveAddress()); account.addNewTransactionIfNeeded(tx); newAccount = testWalletSerializationForCoin(account); newTx = newAccount.getRawTransaction(tx.getHash()); assertNotNull(newTx); assertNotNull(newTx.getExtraBytes()); assertEquals(0, newTx.getExtraBytes().length); // Test tx with extra bytes tx = new Transaction(VPN); tx.setTime(0x99999999); byte[] bytes = {0x1, 0x2, 0x3}; tx.setExtraBytes(bytes); tx.addOutput(VPN.oneCoin().toCoin(), account.getFreshReceiveAddress()); account.addNewTransactionIfNeeded(tx); newAccount = testWalletSerializationForCoin(account); newTx = newAccount.getRawTransaction(tx.getHash()); assertNotNull(newTx); assertArrayEquals(bytes, newTx.getExtraBytes()); } private WalletPocketHD testWalletSerializationForCoin(WalletPocketHD account) throws UnreadableWalletException { Protos.WalletPocket proto = account.toProtobuf(); WalletPocketHD newAccount = new WalletPocketProtobufSerializer().readWallet(proto, null); assertEquals(account.getBalance().value, newAccount.getBalance().value); Map<Sha256Hash, BitTransaction> transactions = account.getTransactions(); Map<Sha256Hash, BitTransaction> newTransactions = newAccount.getTransactions(); for (Sha256Hash txId : transactions.keySet()) { assertTrue(newTransactions.containsKey(txId)); assertEquals(transactions.get(txId), newTransactions.get(txId)); } return newAccount; } @Test public void serializeUnencryptedNormal() throws Exception { pocket.onConnection(getBlockchainConnection(DOGE)); Protos.WalletPocket walletPocketProto = pocket.toProtobuf(); System.out.println(walletPocketProto.toString()); WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(walletPocketProto, null); assertEquals(pocket.getBalance().value, newPocket.getBalance().value); assertEquals(DOGE.value(11000000000l), newPocket.getBalance()); Map<TrimmedOutPoint, OutPointOutput> expectedUtxoSet = getDummyUtxoSet(); checkUnspentOutputs(expectedUtxoSet, pocket); checkUnspentOutputs(expectedUtxoSet, newPocket); assertEquals(pocket.getCoinType(), newPocket.getCoinType()); assertEquals(pocket.getDescriptionOrCoinName(), newPocket.getDescriptionOrCoinName()); assertEquals(pocket.keys.toProtobuf().toString(), newPocket.keys.toProtobuf().toString()); assertEquals(pocket.getLastBlockSeenHash(), newPocket.getLastBlockSeenHash()); assertEquals(pocket.getLastBlockSeenHeight(), newPocket.getLastBlockSeenHeight()); assertEquals(pocket.getLastBlockSeenTimeSecs(), newPocket.getLastBlockSeenTimeSecs()); for (BitTransaction tx : pocket.getTransactions().values()) { assertEquals(tx, newPocket.getTransaction(tx.getHash())); BitTransaction txNew = checkNotNull(newPocket.getTransaction(tx.getHash())); assertInputsEquals(tx.getInputs(), txNew.getInputs()); assertOutputsEquals(tx.getOutputs(false), txNew.getOutputs(false)); } for (AddressStatus status : pocket.getAllAddressStatus()) { if (status.getStatus() == null) continue; assertEquals(status, newPocket.getAddressStatus(status.getAddress())); } // Issued keys assertEquals(18, newPocket.keys.getNumIssuedExternalKeys()); assertEquals(9, newPocket.keys.getNumIssuedInternalKeys()); newPocket.onConnection(getBlockchainConnection(DOGE)); // No addresses left to subscribe List<AbstractAddress> addressesToWatch = newPocket.getAddressesToWatch(); assertEquals(0, addressesToWatch.size()); // 18 external issued + 20 lookahead + 9 external issued + 20 lookahead assertEquals(67, newPocket.addressesStatus.size()); assertEquals(67, newPocket.addressesSubscribed.size()); } private void assertInputsEquals(List<TransactionInput> expected, List<TransactionInput> actual) { assertEquals(expected.size(), actual.size()); for (int i = 0; i < expected.size(); i++) { assertArrayEquals(expected.get(i).bitcoinSerialize(), actual.get(i).bitcoinSerialize()); } } private void assertOutputsEquals(List<TransactionOutput> expected, List<TransactionOutput> actual) { assertEquals(expected.size(), actual.size()); for (int i = 0; i < expected.size(); i++) { assertArrayEquals(expected.get(i).bitcoinSerialize(), actual.get(i).bitcoinSerialize()); } } @Test public void serializeUnencryptedEmpty() throws Exception { pocket.maybeInitializeAllKeys(); Protos.WalletPocket walletPocketProto = pocket.toProtobuf(); WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(walletPocketProto, null); assertEquals(walletPocketProto.toString(), newPocket.toProtobuf().toString()); // Issued keys assertEquals(0, newPocket.keys.getNumIssuedExternalKeys()); assertEquals(0, newPocket.keys.getNumIssuedInternalKeys()); // 20 lookahead + 20 lookahead assertEquals(40, newPocket.keys.getActiveKeys().size()); } @Test public void serializeEncryptedEmpty() throws Exception { pocket.maybeInitializeAllKeys(); pocket.encrypt(crypter, aesKey); Protos.WalletPocket walletPocketProto = pocket.toProtobuf(); WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(walletPocketProto, crypter); assertEquals(walletPocketProto.toString(), newPocket.toProtobuf().toString()); pocket.decrypt(aesKey); // One is encrypted, so they should not match assertNotEquals(pocket.toProtobuf().toString(), newPocket.toProtobuf().toString()); newPocket.decrypt(aesKey); assertEquals(pocket.toProtobuf().toString(), newPocket.toProtobuf().toString()); } @Test public void serializeEncryptedNormal() throws Exception { pocket.maybeInitializeAllKeys(); pocket.encrypt(crypter, aesKey); pocket.onConnection(getBlockchainConnection(DOGE)); assertEquals(DOGE.value(11000000000l), pocket.getBalance()); assertAllKeysEncrypted(pocket); WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(pocket.toProtobuf(), crypter); assertEquals(DOGE.value(11000000000l), newPocket.getBalance()); Map<TrimmedOutPoint, OutPointOutput> expectedUtxoSet = getDummyUtxoSet(); checkUnspentOutputs(expectedUtxoSet, pocket); checkUnspentOutputs(expectedUtxoSet, newPocket); assertAllKeysEncrypted(newPocket); pocket.decrypt(aesKey); newPocket.decrypt(aesKey); assertAllKeysDecrypted(pocket); assertAllKeysDecrypted(newPocket); } private void checkUnspentOutputs(Map<TrimmedOutPoint, OutPointOutput> expectedUtxoSet, WalletPocketHD pocket) { Map<TrimmedOutPoint, OutPointOutput> pocketUtxoSet = pocket.getUnspentOutputs(false); for (OutPointOutput utxo : expectedUtxoSet.values()) { assertEquals(utxo, pocketUtxoSet.get(utxo.getOutPoint())); } } private void assertAllKeysDecrypted(WalletPocketHD pocket) { List<ECKey> keys = pocket.keys.getKeys(false); for (ECKey k : keys) { DeterministicKey key = (DeterministicKey) k; assertFalse(key.isEncrypted()); } } private void assertAllKeysEncrypted(WalletPocketHD pocket) { List<ECKey> keys = pocket.keys.getKeys(false); for (ECKey k : keys) { DeterministicKey key = (DeterministicKey) k; assertTrue(key.isEncrypted()); } } @Test public void createDustTransactionFee() throws Exception { pocket.onConnection(getBlockchainConnection(DOGE)); BitAddress toAddr = BitAddress.from(DOGE, "nZB8PHkfgJvuCJqchSexmfY3ABXa2aE1vp"); Value softDust = DOGE.getSoftDustLimit(); assertNotNull(softDust); // Send a soft dust BitSendRequest sendRequest = pocket.sendCoinsOffline(toAddr, softDust.subtract(DOGE.value(1))); pocket.completeTransaction(sendRequest); assertEquals(DOGE.getFeeValue().multiply(2), sendRequest.tx.getFee()); } @Test public void createTransactionAndBroadcast() throws Exception { pocket.onConnection(getBlockchainConnection(DOGE)); BitAddress toAddr = BitAddress.from(DOGE, "nZB8PHkfgJvuCJqchSexmfY3ABXa2aE1vp"); Value orgBalance = pocket.getBalance(); BitSendRequest sendRequest = pocket.sendCoinsOffline(toAddr, DOGE.value(AMOUNT_TO_SEND)); sendRequest.shuffleOutputs = false; sendRequest.feePerTxSize = DOGE.value(0); pocket.completeTransaction(sendRequest); // FIXME, mock does not work here // pocket.broadcastTx(tx); pocket.addNewTransactionIfNeeded(sendRequest.tx); assertEquals(orgBalance.subtract(AMOUNT_TO_SEND), pocket.getBalance()); } // Util methods //////////////////////////////////////////////////////////////////////////////////////////////// public class MessageComparator implements Comparator<ChildMessage> { @Override public int compare(ChildMessage o1, ChildMessage o2) { String s1 = Utils.HEX.encode(o1.bitcoinSerialize()); String s2 = Utils.HEX.encode(o2.bitcoinSerialize()); return s1.compareTo(s2); } } HashMap<AbstractAddress, AddressStatus> getDummyStatuses() throws AddressMalformedException { HashMap<AbstractAddress, AddressStatus> status = new HashMap<>(40); for (int i = 0; i < addresses.size(); i++) { AbstractAddress address = DOGE.newAddress(addresses.get(i)); status.put(address, new AddressStatus(address, statuses[i])); } return status; } private HashMap<AbstractAddress, ArrayList<HistoryTx>> getDummyHistoryTXs() throws AddressMalformedException, JSONException { HashMap<AbstractAddress, ArrayList<HistoryTx>> htxs = new HashMap<>(40); for (int i = 0; i < statuses.length; i++) { JSONArray jsonArray = new JSONArray(history[i]); ArrayList<HistoryTx> list = new ArrayList<>(); for (int j = 0; j < jsonArray.length(); j++) { list.add(new HistoryTx(jsonArray.getJSONObject(j))); } htxs.put(DOGE.newAddress(addresses.get(i)), list); } return htxs; } private HashMap<AbstractAddress, ArrayList<UnspentTx>> getDummyUnspentTXs() throws AddressMalformedException, JSONException { HashMap<AbstractAddress, ArrayList<UnspentTx>> utxs = new HashMap<>(40); for (int i = 0; i < statuses.length; i++) { JSONArray jsonArray = new JSONArray(unspent[i]); ArrayList<UnspentTx> list = new ArrayList<>(); for (int j = 0; j < jsonArray.length(); j++) { list.add(new UnspentTx(jsonArray.getJSONObject(j))); } utxs.put(DOGE.newAddress(addresses.get(i)), list); } return utxs; } private Map<TrimmedOutPoint, OutPointOutput> getDummyUtxoSet() throws AddressMalformedException, JSONException { final HashMap<TrimmedOutPoint, OutPointOutput> unspentOutputs = new HashMap<>(); for (int i = 0; i < statuses.length; i++) { BitAddress address = (BitAddress) DOGE.newAddress(addresses.get(i)); JSONArray utxoArray = new JSONArray(unspent[i]); for (int j = 0; j < utxoArray.length(); j++) { JSONObject utxoObject = utxoArray.getJSONObject(j); //"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 11, \"value\": 500000000, \"height\": 160267}]", TrimmedOutPoint outPoint = new TrimmedOutPoint(DOGE, utxoObject.getInt("tx_pos"), new Sha256Hash(utxoObject.getString("tx_hash"))); TransactionOutput output = new TransactionOutput(DOGE, null, Coin.valueOf(utxoObject.getLong("value")), address); OutPointOutput utxo = new OutPointOutput(outPoint, output, false); unspentOutputs.put(outPoint, utxo); } } return unspentOutputs; } private HashMap<Sha256Hash, byte[]> getDummyRawTXs() throws AddressMalformedException, JSONException { HashMap<Sha256Hash, byte[]> rawTxs = new HashMap<>(); for (String[] tx : txs) { rawTxs.put(new Sha256Hash(tx[0]), Utils.HEX.decode(tx[1])); } return rawTxs; } class MockBlockchainConnection implements BitBlockchainConnection { final HashMap<AbstractAddress, AddressStatus> statuses; final HashMap<AbstractAddress, ArrayList<HistoryTx>> historyTxs; final HashMap<AbstractAddress, ArrayList<UnspentTx>> unspentTxs; final HashMap<Sha256Hash, byte[]> rawTxs; private CoinType coinType; MockBlockchainConnection(CoinType coinType) throws Exception { this.coinType = coinType; statuses = getDummyStatuses(); historyTxs = getDummyHistoryTXs(); unspentTxs = getDummyUnspentTXs(); rawTxs = getDummyRawTXs(); } @Override public void getBlock(int height, TransactionEventListener<BitTransaction> listener) { } @Override public void subscribeToBlockchain(TransactionEventListener<BitTransaction> listener) { listener.onNewBlock(new BlockHeader(coinType, blockTimestamp, blockHeight)); } @Override public void subscribeToAddresses(List<AbstractAddress> addresses, TransactionEventListener<BitTransaction> listener) { for (AbstractAddress a : addresses) { AddressStatus status = statuses.get(a); if (status == null) { status = new AddressStatus(a, null); } listener.onAddressStatusUpdate(status); } } @Override public void getHistoryTx(AddressStatus status, TransactionEventListener<BitTransaction> listener) { List<HistoryTx> htx = historyTxs.get(status.getAddress()); if (htx == null) { htx = ImmutableList.of(); } listener.onTransactionHistory(status, htx); } @Override public void getUnspentTx(AddressStatus status, BitTransactionEventListener listener) { List<UnspentTx> utx = unspentTxs.get(status.getAddress()); if (utx == null) { utx = ImmutableList.of(); } listener.onUnspentTransactionUpdate(status, utx); } @Override public void getTransaction(Sha256Hash txHash, TransactionEventListener<BitTransaction> listener) { BitTransaction tx = new BitTransaction(coinType, rawTxs.get(txHash)); listener.onTransactionUpdate(tx); } @Override public void broadcastTx(BitTransaction tx, TransactionEventListener<BitTransaction> listener) { // List<AddressStatus> newStatuses = new ArrayList<AddressStatus>(); // Random rand = new Random(); // byte[] randBytes = new byte[32]; // // Get spent outputs and modify statuses // for (TransactionInput txi : tx.getInputs()) { // UnspentTx unspentTx = new UnspentTx( // txi.getOutpoint(), txi.getValue().value, 0); // // for (Map.Entry<Address, ArrayList<UnspentTx>> entry : utxs.entrySet()) { // if (entry.getValue().remove(unspentTx)) { // rand.nextBytes(randBytes); // AddressStatus newStatus = new AddressStatus(entry.getKey(), Utils.HEX.encode(randBytes)); // statuses.put(entry.getKey(), newStatus); // newStatuses.add(newStatus); // } // } // } // // for (TransactionOutput txo : tx.getOutputs()) { // if (txo.getAddressFromP2PKHScript(coinType) != null) { // Address address = txo.getAddressFromP2PKHScript(coinType); // if (addresses.contains(address.toString())) { // AddressStatus newStatus = new AddressStatus(address, tx.getHashAsString()); // statuses.put(address, newStatus); // newStatuses.add(newStatus); // if (!utxs.containsKey(address)) { // utxs.put(address, new ArrayList<UnspentTx>()); // } // ArrayList<UnspentTx> unspentTxs = utxs.get(address); // unspentTxs.add(new UnspentTx(txo.getOutPointFor(), // txo.getValue().value, 0)); // if (!historyTxs.containsKey(address)) { // historyTxs.put(address, new ArrayList<HistoryTx>()); // } // ArrayList<HistoryTx> historyTxes = historyTxs.get(address); // historyTxes.add(new HistoryTx(txo.getOutPointFor(), 0)); // } // } // } // // rawTxs.put(tx.getHash(), tx.bitcoinSerialize()); // // for (AddressStatus newStatus : newStatuses) { // listener.onAddressStatusUpdate(newStatus); // } } @Override public boolean broadcastTxSync(BitTransaction tx) { return false; } @Override public void ping(String versionString) {} @Override public void addEventListener(ConnectionEventListener listener) { } @Override public void resetConnection() { } @Override public void stopAsync() { } @Override public boolean isActivelyConnected() { return false; } @Override public void startAsync() { } } private MockBlockchainConnection getBlockchainConnection(CoinType coinType) throws Exception { return new MockBlockchainConnection(coinType); } // Mock data long blockTimestamp = 1411000000l; int blockHeight = 200000; List<String> addresses = ImmutableList.of( "nnfP8VuPfZXhNtMDzvX1bKurzcV1k7HNrQ", "nf4AUKiaGdx4GTbbh222KvtuCbAuvbcdE2", "npGkmbWtdWybFNSZQXUK6zZxbEocMtrTzz", "nVaN45bbs6AUc1EUpP71hHGBGb2qciNrJc", "nrdHFZP1AfdKBrjsSQmwFm8R2i2mzMef75", "niGZgfbhFYn6tJqksmC8CnzSRL1GHNsu7e", "nh6w8yu1zoKYoT837ffkVmuPjTaP69Pc5E", "nbyMgmEghsL9tpk7XfdH9gLGudh6Lrbbuf", "naX9akzYuWY1gKbcZo3t36aBKc1gqbzgSs", "nqcPVTGeAfCowELB2D5PdVF3FWFjFtkkFf", "nd4vVvPTpp2LfcsMPsmG3Dh7MFAsqRHp4g", "nVK4Uz5Sf56ygrr6RiwXcRvH8AuUVbjjHi", "nbipkRwT1NCSXZSrm8uAAEgQAA2s2NWMkG", "nZU6QAMAdCQcVDxEmL7GEY6ykFm8m6u6am", "nbFqayssM5s7hLjLFwf2d95JXKRWBk2pBH", "nacZfcNgVi47hamLscWdUGQhUQGGpSdgq8", "niiMT7ZYeFnaLPYtqQFBBX1sP3dT5JtcEw", "ns6GyTaniLWaiYrvAf5tk4D8tWrbcCLGyj", "nhdwQfptLTzLJGbLF3vvtqyBaqPMPecDmE", "neMUAGeTzwxLbSkXMsdmWf1fTKS1UsJjXY", "nXsAMeXxtpx8jaxnU3Xv9ZQ6ZcRcD1xYhR", "ns35rKnnWf6xP3KSj5WPkMCVVaADGi6Ndk", "nk4wcXYBEWs5HkhNLsuaQJoAjJHoK6SQmG", "npsJQWu8fsALoTPum8D4j8FDkyeusk8fU8", "nZNhZo4Vz3DnwQGPL3SJTZgUw2Kh4g9oay", "nnxDTYB8WMHMgLnCY2tuaEtysvdhRnWehZ", "nb2iaDXG1EqkcE47H87WQFkQNkeVK66Z21", "nWHAkpn2DB3DJRsbiK3vpbigoa3M2uVuF8", "nViKdC7Gm6TMmCuWTBwVE9i4rJhyfwbfqg", "nZQV5BifbGPzaxTrB4efgHruWH5rufemqP", "nVvZaLvnkCVAzpLYPoHeqU4w9zJ5yrZgUn", "nrMp6pRCk98WYWkCWq9Pqthz9HbpQu8BT3", "nnA3aYsLqysKT6gAu1dr4EKm586cmKiRxS", "nVfcVgMY7DL6nqoSxwJy7B7hKXirQwj6ic", "ni4oAzi6nCVuEdjoHyVMVKWb1DqTd3qY3H", "nnpf3gx442yomniRJPMGPapgjHrraPZXxJ", "nkuFnF8wUmHFkMycaFMvyjBoiMeR5KBKGd", "nXKccwjaUyrQkLrdqKT6aq6cDiFgBBVgNz", "nZMSNsXSAL7i1YD6KP5FrhATuZ2CWvnxqR", "nUEkQ3LjH9m4ScbP6NGtnAdnnUsdtWv99Q" ); String[] statuses = { "fe7c109d8bd90551a406cf0b3499117db04bc9c4f48e1df27ac1cf3ddcb3d464", "8a53babd831c6c3a857e20190e884efe75a005bdd7cd273c4f27ab1b8ec81c2d", "86bc2f0cf0112fd59c9aadfe5c887062c21d7a873db260dff68dcfe4417fe212", "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, null, null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, null, null, null, null, null, null, null, null, null }; String[] unspent = { "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 0, \"value\": 500000000, \"height\": 160267}, {\"tx_hash\": \"89a72ba4732505ce9b09c30668db985952701252ce0adbd7c43336396697d6ae\", \"tx_pos\": 0, \"value\": 500000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 1, \"value\": 1000000000, \"height\": 160267}, {\"tx_hash\": \"edaf445288d8e65cf7963bc8047c90f53681acaadc5ccfc5ecc67aedbd73cddb\", \"tx_pos\": 0, \"value\": 500000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 2, \"value\": 500000000, \"height\": 160267}, {\"tx_hash\": \"81a1f0f8242d5e71e65ff9e8ec51e8e85d641b607d7f691c1770d4f25918ebd7\", \"tx_pos\": 0, \"value\": 1000000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 3, \"value\": 500000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 4, \"value\": 1000000000, \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 11, \"value\": 500000000, \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 12, \"value\": 1000000000, \"height\": 160267}]", "[]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 13, \"value\": 500000000, \"height\": 160267}]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 6, \"value\": 500000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 7, \"value\": 1000000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 8, \"value\": 500000000, \"height\": 160267}]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 9, \"value\": 500000000, \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 10, \"value\": 1000000000, \"height\": 160267}]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]" }; String[] history = { "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}, {\"tx_hash\": \"89a72ba4732505ce9b09c30668db985952701252ce0adbd7c43336396697d6ae\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}, {\"tx_hash\": \"edaf445288d8e65cf7963bc8047c90f53681acaadc5ccfc5ecc67aedbd73cddb\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}, {\"tx_hash\": \"81a1f0f8242d5e71e65ff9e8ec51e8e85d641b607d7f691c1770d4f25918ebd7\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]" }; String[][] txs = { {"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f", "0100000001b8778dff640ccb144346d9db48201639b2707a0cc59e19672d2dd76cc6d1a5a6010000006b48304502210098d2e5b8a6c72442430bc09f2f4bcb56612c5b9e5eee821d65b412d099bb723402204f7f008ac052e5d7be0ab5b0c85ea5e627d725a521bd9e9b193d1fdf81c317a0012102d26e423c9da9ff4a7bf6b756b2dafb75cca34fbd34f64c4c3b77c37179c5bba2ffffffff0e0065cd1d000000001976a914ca983c2da690de3cdc693ca013d93e569810c52c88ac00ca9a3b000000001976a91477263ab93a49b1d3eb5887187704cdb82e1c60ce88ac0065cd1d000000001976a914dc40fbbc8caa1f7617d275aec9a3a14ce8d8652188ac0065cd1d000000001976a9140f2b1e5b376e22c5d1e635233eb90cf50ad9095188ac00ca9a3b000000001976a914f612ffd50b6a69df5e34ee0c5b529dfaaedca03d88ac00f633bce60000001976a914937258e3a8c463ec07e78ce62326c488170ad25e88ac0065cd1d000000001976a9142848ad5ff4cc32df3649646017c47bc04e8d211788ac00ca9a3b000000001976a914fa937737a6df2b8a5e39cce8b0bdd9510683023a88ac0065cd1d000000001976a914ae248a5d710143b6b309aaab9ce17059536e2aa388ac0065cd1d000000001976a91438d6eb11eca405be497a7183c50e437851425e0088ac00ca9a3b000000001976a91410ac6b2704146b50a1dd8f6df70736856ebf8b3488ac0065cd1d000000001976a914456816dccb3a4f33ae2dbd3ba623997075d5c73d88ac00ca9a3b000000001976a91452957c44e5bee9a60402a739fc8959c2850ea98488ac0065cd1d000000001976a914fb2dffa402d05f74335d137e21e41d8920c745fb88ac00000000"}, {"89a72ba4732505ce9b09c30668db985952701252ce0adbd7c43336396697d6ae", "01000000011a656d67706db286d1e6fad57eb4f411cb14f8880cea8348da339b9d434a5ec7050000006a47304402201d69fddb269b53aa742ff6437a45adb4ca5c59f666c9b4eabc4a0c7a6e6f4c0f022015a747b7a6d9371a4020f5b396dcd094b0f36af3fc82e95091da856181912dfa012102c9a8d5b2f768afe30ee772d185e7a61f751be05649a79508b38a2be8824adec3ffffffff020065cd1d000000001976a914ca983c2da690de3cdc693ca013d93e569810c52c88ac00b07098e60000001976a9141630d812e219e6bcbe494eb96f7a7900c216ad5d88ac00000000"}, {"edaf445288d8e65cf7963bc8047c90f53681acaadc5ccfc5ecc67aedbd73cddb", "010000000164a3990893c012b20287d43d1071ac26f4b93648ff4213db6da6979beed6b7dc010000006b48304502210086ac11d4a8146b4176a72059960690c72a9776468cd671fd07c064b51f24961d02205bcf008d6995014f3cfd79100ee9beab5688c88cca15c5cea38b769563785d900121036530415a7b3b9c5976f26a63a57d119ab39491762121723c773399a2531a1bd7ffffffff020065cd1d000000001976a91477263ab93a49b1d3eb5887187704cdb82e1c60ce88ac006aad74e60000001976a914e5616848352c328c9f61b167eb1b0fde39b5cb6788ac00000000"}, {"81a1f0f8242d5e71e65ff9e8ec51e8e85d641b607d7f691c1770d4f25918ebd7", "010000000141c217dfea3a1d8d6a06e9d3daf75b292581f652256d73a7891e5dc9c7ee3cca000000006a47304402205cce451228f98fece9645052546b82c2b2d425a4889b03999001fababfc7f4690220583b2189faef07d6b0191c788301cfab1b3f47ffe2c403d632b92c6dde27e14f012102d26e423c9da9ff4a7bf6b756b2dafb75cca34fbd34f64c4c3b77c37179c5bba2ffffffff0100ca9a3b000000001976a914dc40fbbc8caa1f7617d275aec9a3a14ce8d8652188ac00000000"} }; }
Crowndev/crownwallet-android
core/src/test/java/com/coinomi/core/wallet/WalletPocketHDTest.java
45,935
package com.mfcoin.core.wallet; import com.mfcoin.core.coins.BitcoinMain; import com.mfcoin.core.coins.CoinType; import com.mfcoin.core.coins.DogecoinTest; import com.mfcoin.core.coins.NuBitsMain; import com.mfcoin.core.coins.Value; import com.mfcoin.core.coins.VpncoinMain; import com.mfcoin.core.exceptions.AddressMalformedException; import com.mfcoin.core.exceptions.Bip44KeyLookAheadExceededException; import com.mfcoin.core.exceptions.KeyIsEncryptedException; import com.mfcoin.core.exceptions.MissingPrivateKeyException; import com.mfcoin.core.network.AddressStatus; import com.mfcoin.core.network.BlockHeader; import com.mfcoin.core.network.ServerClient.HistoryTx; import com.mfcoin.core.network.ServerClient.UnspentTx; import com.mfcoin.core.network.interfaces.ConnectionEventListener; import com.mfcoin.core.network.interfaces.TransactionEventListener; import com.mfcoin.core.protos.Protos; import com.mfcoin.core.wallet.families.bitcoin.BitAddress; import com.mfcoin.core.wallet.families.bitcoin.BitBlockchainConnection; import com.mfcoin.core.wallet.families.bitcoin.BitSendRequest; import com.mfcoin.core.wallet.families.bitcoin.BitTransaction; import com.mfcoin.core.wallet.families.bitcoin.BitTransactionEventListener; import com.mfcoin.core.wallet.families.bitcoin.OutPointOutput; import com.mfcoin.core.wallet.families.bitcoin.TrimmedOutPoint; import com.google.common.collect.ImmutableList; import org.bitcoinj.core.ChildMessage; import org.bitcoinj.core.Coin; import org.bitcoinj.core.ECKey; import org.bitcoinj.core.Sha256Hash; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.TransactionConfidence.Source; import org.bitcoinj.core.TransactionInput; import org.bitcoinj.core.TransactionOutput; import org.bitcoinj.core.Utils; import org.bitcoinj.crypto.DeterministicHierarchy; import org.bitcoinj.crypto.DeterministicKey; import org.bitcoinj.crypto.HDKeyDerivation; import org.bitcoinj.crypto.KeyCrypter; import org.bitcoinj.crypto.KeyCrypterScrypt; import org.bitcoinj.store.UnreadableWalletException; import org.bitcoinj.utils.BriefLogFormatter; import org.bitcoinj.wallet.DeterministicSeed; import org.bitcoinj.wallet.KeyChain; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.spongycastle.crypto.params.KeyParameter; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.mfcoin.core.Preconditions.checkNotNull; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; /** * @author John L. Jegutanis */ public class WalletPocketHDTest { static final CoinType BTC = BitcoinMain.get(); static final CoinType DOGE = DogecoinTest.get(); static final CoinType NBT = NuBitsMain.get(); static final CoinType VPN = VpncoinMain.get(); static final List<String> MNEMONIC = ImmutableList.of("citizen", "fever", "scale", "nurse", "brief", "round", "ski", "fiction", "car", "fitness", "pluck", "act"); static final byte[] AES_KEY_BYTES = {0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7}; static final long AMOUNT_TO_SEND = 2700000000L; static final String MESSAGE = "test"; static final String MESSAGE_UNICODE = "δοκιμή испытание 测试"; static final String EXPECTED_BITCOIN_SIG = "IMBbIFDDuUwomYlvSjwWytqP/CXYym2yOKbJUx8Y+ujzZKBwoCFMr73GUxpr1Ird/DvnNZcsQLphvx18ftqN54o="; static final String EXPECTED_BITCOIN_SIG_UNICODE = "IGGZEOBsVny5dozTOfc2/3UuvmZGdDI4XK/03HIk34PILd2oXbnq+87GINT3lumeXcgSO2NkGzUFcQ1SCSVI3Hk="; static final String EXPECTED_NUBITS_SIG = "IMuzNZTZIjZjLicyDFGzqFl21vqNBGW1N5m4qHBRqbTvLBbkQeGjraeLmZEt7mRH4MSMPLFXW2T3Maz+HYx1tEc="; static final String EXPECTED_NUBITS_SIG_UNICODE = "Hx7xkBbboXrp96dbQrJFzm2unTGwLstjbWlKa1/N1E4LJqbwJAJR1qIvwXm6LHQFnLOzwoQA45zYNjwUEPMc8sg="; DeterministicSeed seed = new DeterministicSeed(MNEMONIC, null, "", 0); DeterministicKey masterKey = HDKeyDerivation.createMasterPrivateKey(checkNotNull(seed.getSeedBytes())); DeterministicHierarchy hierarchy = new DeterministicHierarchy(masterKey); DeterministicKey rootKey = hierarchy.get(DOGE.getBip44Path(0), false, true); KeyParameter aesKey = new KeyParameter(AES_KEY_BYTES); KeyCrypter crypter = new KeyCrypterScrypt(); WalletPocketHD pocket; @Before public void setup() { BriefLogFormatter.init(); pocket = new WalletPocketHD(rootKey, DOGE, null, null); pocket.keys.setLookaheadSize(20); } @Test public void testId() throws Exception { assertEquals("8747886e9a77fe2a1588df3168b867648434d6d339b0b448793ae1db8f283f41", pocket.getId()); } @Test public void testSingleAddressWallet() throws Exception { ECKey key = pocket.keys.getCurrentUnusedKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); BitWalletSingleKey bitWalletSingleKey = new BitWalletSingleKey(DOGE, key); bitWalletSingleKey.onConnection(getBlockchainConnection(DOGE)); assertEquals(DOGE.value("10"), bitWalletSingleKey.getBalance()); } @Test public void xpubWallet() { String xpub = "xpub67tVq9TLPPoaHVSiYu8mqahm3eztTPUts6JUftNq3pZF1PJwjknrTqQhjc2qRGd6vS8wANu7mLnqkiUzFZ1xZsAZoUMi8o6icMhzGCAhcSW"; DeterministicKey key = DeterministicKey.deserializeB58(null, xpub); WalletPocketHD account = new WalletPocketHD(key, BTC, null, null); assertEquals("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", account.getReceiveAddress().toString()); account = new WalletPocketHD(key, NBT, null, null); assertEquals("BNvJUwg3BgkbQk5br1CxvHxdcDp1EC3saE", account.getReceiveAddress().toString()); } @Test public void xpubWalletSerialized() throws Exception { WalletPocketHD account = new WalletPocketHD(rootKey, BTC, null, null); Protos.WalletPocket proto = account.toProtobuf(); WalletPocketHD newAccount = new WalletPocketProtobufSerializer().readWallet(proto, null); assertEquals(account.getPublicKeySerialized(), newAccount.getPublicKeySerialized()); } @Test public void signMessage() throws AddressMalformedException, MissingPrivateKeyException, KeyIsEncryptedException { WalletPocketHD pocketHD = new WalletPocketHD(rootKey, BTC, null, null); pocketHD.getReceiveAddress(); // Generate the first key SignedMessage signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE); pocketHD.signMessage(signedMessage, null); assertEquals(EXPECTED_BITCOIN_SIG, signedMessage.getSignature()); signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE_UNICODE); pocketHD.signMessage(signedMessage, null); assertEquals(EXPECTED_BITCOIN_SIG_UNICODE, signedMessage.getSignature()); pocketHD = new WalletPocketHD(rootKey, NBT, null, null); pocketHD.getReceiveAddress(); // Generate the first key signedMessage = new SignedMessage("BNvJUwg3BgkbQk5br1CxvHxdcDp1EC3saE", MESSAGE); pocketHD.signMessage(signedMessage, null); assertEquals(EXPECTED_NUBITS_SIG, signedMessage.getSignature()); signedMessage = new SignedMessage("BNvJUwg3BgkbQk5br1CxvHxdcDp1EC3saE", MESSAGE_UNICODE); pocketHD.signMessage(signedMessage, null); assertEquals(EXPECTED_NUBITS_SIG_UNICODE, signedMessage.getSignature()); } @Test public void signMessageEncrypted() throws AddressMalformedException, MissingPrivateKeyException, KeyIsEncryptedException { WalletPocketHD pocketHD = new WalletPocketHD(rootKey, BTC, null, null); pocketHD.getReceiveAddress(); // Generate the first key pocketHD.encrypt(crypter, aesKey); SignedMessage signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE); pocketHD.signMessage(signedMessage, aesKey); assertEquals(EXPECTED_BITCOIN_SIG, signedMessage.getSignature()); signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE_UNICODE); pocketHD.signMessage(signedMessage, aesKey); assertEquals(EXPECTED_BITCOIN_SIG_UNICODE, signedMessage.getSignature()); } @Test public void signMessageEncryptedFailed() throws AddressMalformedException, MissingPrivateKeyException, KeyIsEncryptedException { WalletPocketHD pocketHD = new WalletPocketHD(rootKey, BTC, null, null); pocketHD.getReceiveAddress(); // Generate the first key pocketHD.encrypt(crypter, aesKey); SignedMessage signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE); pocketHD.signMessage(signedMessage, null); assertEquals(SignedMessage.Status.KeyIsEncrypted, signedMessage.status); } @Test public void watchingAddresses() { List<AbstractAddress> watchingAddresses = pocket.getAddressesToWatch(); assertEquals(40, watchingAddresses.size()); // 20 + 20 lookahead size for (int i = 0; i < addresses.size(); i++) { assertEquals(addresses.get(i), watchingAddresses.get(i).toString()); } } @Test public void issuedKeys() throws Bip44KeyLookAheadExceededException { List<BitAddress> issuedAddresses = new ArrayList<>(); assertEquals(0, pocket.getIssuedReceiveAddresses().size()); assertEquals(0, pocket.keys.getNumIssuedExternalKeys()); issuedAddresses.add(0, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS)); BitAddress freshAddress = pocket.getFreshReceiveAddress(); assertEquals(freshAddress, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS)); assertEquals(1, pocket.getIssuedReceiveAddresses().size()); assertEquals(1, pocket.keys.getNumIssuedExternalKeys()); assertEquals(issuedAddresses, pocket.getIssuedReceiveAddresses()); issuedAddresses.add(0, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS)); freshAddress = pocket.getFreshReceiveAddress(); assertEquals(freshAddress, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS)); assertEquals(2, pocket.getIssuedReceiveAddresses().size()); assertEquals(2, pocket.keys.getNumIssuedExternalKeys()); assertEquals(issuedAddresses, pocket.getIssuedReceiveAddresses()); } @Test public void issuedKeysLimit() throws Exception { assertTrue(pocket.canCreateFreshReceiveAddress()); try { for (int i = 0; i < 100; i++) { pocket.getFreshReceiveAddress(); } } catch (Bip44KeyLookAheadExceededException e) { assertFalse(pocket.canCreateFreshReceiveAddress()); // We haven't used any key so the total must be 20 - 1 (the unused key) assertEquals(19, pocket.getNumberIssuedReceiveAddresses()); assertEquals(19, pocket.getIssuedReceiveAddresses().size()); } pocket.onConnection(getBlockchainConnection(DOGE)); assertTrue(pocket.canCreateFreshReceiveAddress()); try { for (int i = 0; i < 100; i++) { pocket.getFreshReceiveAddress(); } } catch (Bip44KeyLookAheadExceededException e) { // try { // pocket.getFreshReceiveAddress(); // } catch (Bip44KeyLookAheadExceededException e1) { /* ignore */ } assertFalse(pocket.canCreateFreshReceiveAddress()); // We used 18, so the total must be (20-1)+18=37 assertEquals(37, pocket.getNumberIssuedReceiveAddresses()); assertEquals(37, pocket.getIssuedReceiveAddresses().size()); } } @Test public void issuedKeysLimit2() throws Exception { assertTrue(pocket.canCreateFreshReceiveAddress()); try { for (int i = 0; i < 100; i++) { pocket.getFreshReceiveAddress(); } } catch (Bip44KeyLookAheadExceededException e) { assertFalse(pocket.canCreateFreshReceiveAddress()); // We haven't used any key so the total must be 20 - 1 (the unused key) assertEquals(19, pocket.getNumberIssuedReceiveAddresses()); assertEquals(19, pocket.getIssuedReceiveAddresses().size()); } } @Test public void usedAddresses() throws Exception { assertEquals(0, pocket.getUsedAddresses().size()); pocket.onConnection(getBlockchainConnection(DOGE)); // Receive and change addresses assertEquals(13, pocket.getUsedAddresses().size()); } private Sha256Hash send(Value value, WalletPocketHD w1, WalletPocketHD w2) throws Exception { assertEquals(w1.getCoinType(), w2.getCoinType()); CoinType type = w1.getCoinType(); BitSendRequest req = w1.sendCoinsOffline(w2.getReceiveAddress(), value); req.feePerTxSize = type.value("0.01"); w1.completeAndSignTx(req); byte[] txBytes = req.tx.bitcoinSerialize(); w1.addNewTransactionIfNeeded(new BitTransaction(type, txBytes)); w2.addNewTransactionIfNeeded(new BitTransaction(type, txBytes)); return req.tx.getHash(); } @Test public void testSendingAndBalances() throws Exception { DeterministicHierarchy h = new DeterministicHierarchy(masterKey); WalletPocketHD account1 = new WalletPocketHD(h.get(BTC.getBip44Path(0), false, true), BTC, null, null); WalletPocketHD account2 = new WalletPocketHD(h.get(BTC.getBip44Path(1), false, true), BTC, null, null); WalletPocketHD account3 = new WalletPocketHD(h.get(BTC.getBip44Path(2), false, true), BTC, null, null); Transaction tx = new Transaction(BTC); tx.addOutput(BTC.oneCoin().toCoin(), account1.getReceiveAddress()); tx.getConfidence().setSource(Source.SELF); account1.addNewTransactionIfNeeded(tx); assertEquals(BTC.value("1"), account1.getBalance()); assertEquals(BTC.value("0"), account2.getBalance()); assertEquals(BTC.value("0"), account3.getBalance()); Sha256Hash txId = send(BTC.value("0.05"), account1, account2); assertEquals(BTC.value("0.94"), account1.getBalance()); assertEquals(BTC.value("0"), account2.getBalance()); assertEquals(BTC.value("0"), account3.getBalance()); setTrustedTransaction(account1, txId); setTrustedTransaction(account2, txId); assertEquals(BTC.value("0.94"), account1.getBalance()); assertEquals(BTC.value("0.05"), account2.getBalance()); txId = send(BTC.value("0.07"), account1, account3); setTrustedTransaction(account1, txId); setTrustedTransaction(account3, txId); assertEquals(BTC.value("0.86"), account1.getBalance()); assertEquals(BTC.value("0.05"), account2.getBalance()); assertEquals(BTC.value("0.07"), account3.getBalance()); txId = send(BTC.value("0.03"), account2, account3); setTrustedTransaction(account2, txId); setTrustedTransaction(account3, txId); assertEquals(BTC.value("0.86"), account1.getBalance()); assertEquals(BTC.value("0.01"), account2.getBalance()); assertEquals(BTC.value("0.1"), account3.getBalance()); } private void setTrustedTransaction(WalletPocketHD account, Sha256Hash txId) { BitTransaction tx = checkNotNull(account.getTransaction(txId)); tx.setSource(Source.SELF); } @Test public void testLoading() throws Exception { assertFalse(pocket.isLoading()); pocket.onConnection(getBlockchainConnection(DOGE)); // TODO add fine grained control to the blockchain connection in order to test the loading status assertFalse(pocket.isLoading()); } @Test public void fillTransactions() throws Exception { pocket.onConnection(getBlockchainConnection(DOGE)); checkUnspentOutputs(getDummyUtxoSet(), pocket); assertEquals(11000000000L, pocket.getBalance().value); // Issued keys assertEquals(18, pocket.keys.getNumIssuedExternalKeys()); assertEquals(9, pocket.keys.getNumIssuedInternalKeys()); // No addresses left to subscribe List<AbstractAddress> addressesToWatch = pocket.getAddressesToWatch(); assertEquals(0, addressesToWatch.size()); // 18 external issued + 20 lookahead + 9 external issued + 20 lookahead assertEquals(67, pocket.addressesStatus.size()); assertEquals(67, pocket.addressesSubscribed.size()); BitAddress receiveAddr = pocket.getReceiveAddress(); // This key is not issued assertEquals(18, pocket.keys.getNumIssuedExternalKeys()); assertEquals(67, pocket.addressesStatus.size()); assertEquals(67, pocket.addressesSubscribed.size()); DeterministicKey key = pocket.keys.findKeyFromPubHash(receiveAddr.getHash160()); assertNotNull(key); // 18 here is the key index, not issued keys count assertEquals(18, key.getChildNumber().num()); assertEquals(11000000000L, pocket.getBalance().value); } @Test public void serializeTransactionsBtc() throws Exception, Bip44KeyLookAheadExceededException { WalletPocketHD account = new WalletPocketHD(rootKey, BTC, null, null); Transaction tx = new Transaction(BTC); tx.addOutput(BTC.oneCoin().toCoin(), account.getReceiveAddress()); account.addNewTransactionIfNeeded(tx); testWalletSerializationForCoin(account); } @Test public void serializeTransactionsNbt() throws Exception, Bip44KeyLookAheadExceededException { WalletPocketHD account = new WalletPocketHD(rootKey, NBT, null, null); Transaction tx = new Transaction(NBT); tx.addOutput(NBT.oneCoin().toCoin(), account.getReceiveAddress()); account.addNewTransactionIfNeeded(tx); testWalletSerializationForCoin(account); } @Test public void serializeTransactionsVpn() throws Exception, Bip44KeyLookAheadExceededException { WalletPocketHD account = new WalletPocketHD(rootKey, VPN, null, null); // Test tx with null extra bytes Transaction tx = new Transaction(VPN); tx.setTime(0x99999999); tx.addOutput(VPN.oneCoin().toCoin(), account.getFreshReceiveAddress()); account.addNewTransactionIfNeeded(tx); WalletPocketHD newAccount = testWalletSerializationForCoin(account); Transaction newTx = newAccount.getRawTransaction(tx.getHash()); assertNotNull(newTx); assertNotNull(newTx.getExtraBytes()); assertEquals(0, newTx.getExtraBytes().length); // Test tx with empty extra bytes tx = new Transaction(VPN); tx.setTime(0x99999999); tx.setExtraBytes(new byte[0]); tx.addOutput(VPN.oneCoin().toCoin(), account.getFreshReceiveAddress()); account.addNewTransactionIfNeeded(tx); newAccount = testWalletSerializationForCoin(account); newTx = newAccount.getRawTransaction(tx.getHash()); assertNotNull(newTx); assertNotNull(newTx.getExtraBytes()); assertEquals(0, newTx.getExtraBytes().length); // Test tx with extra bytes tx = new Transaction(VPN); tx.setTime(0x99999999); byte[] bytes = {0x1, 0x2, 0x3}; tx.setExtraBytes(bytes); tx.addOutput(VPN.oneCoin().toCoin(), account.getFreshReceiveAddress()); account.addNewTransactionIfNeeded(tx); newAccount = testWalletSerializationForCoin(account); newTx = newAccount.getRawTransaction(tx.getHash()); assertNotNull(newTx); assertArrayEquals(bytes, newTx.getExtraBytes()); } private WalletPocketHD testWalletSerializationForCoin(WalletPocketHD account) throws UnreadableWalletException { Protos.WalletPocket proto = account.toProtobuf(); WalletPocketHD newAccount = new WalletPocketProtobufSerializer().readWallet(proto, null); assertEquals(account.getBalance().value, newAccount.getBalance().value); Map<Sha256Hash, BitTransaction> transactions = account.getTransactions(); Map<Sha256Hash, BitTransaction> newTransactions = newAccount.getTransactions(); for (Sha256Hash txId : transactions.keySet()) { assertTrue(newTransactions.containsKey(txId)); assertEquals(transactions.get(txId), newTransactions.get(txId)); } return newAccount; } @Test public void serializeUnencryptedNormal() throws Exception { pocket.onConnection(getBlockchainConnection(DOGE)); Protos.WalletPocket walletPocketProto = pocket.toProtobuf(); System.out.println(walletPocketProto.toString()); WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(walletPocketProto, null); assertEquals(pocket.getBalance().value, newPocket.getBalance().value); assertEquals(DOGE.value(11000000000l), newPocket.getBalance()); Map<TrimmedOutPoint, OutPointOutput> expectedUtxoSet = getDummyUtxoSet(); checkUnspentOutputs(expectedUtxoSet, pocket); checkUnspentOutputs(expectedUtxoSet, newPocket); assertEquals(pocket.getCoinType(), newPocket.getCoinType()); assertEquals(pocket.getDescriptionOrCoinName(), newPocket.getDescriptionOrCoinName()); assertEquals(pocket.keys.toProtobuf().toString(), newPocket.keys.toProtobuf().toString()); assertEquals(pocket.getLastBlockSeenHash(), newPocket.getLastBlockSeenHash()); assertEquals(pocket.getLastBlockSeenHeight(), newPocket.getLastBlockSeenHeight()); assertEquals(pocket.getLastBlockSeenTimeSecs(), newPocket.getLastBlockSeenTimeSecs()); for (BitTransaction tx : pocket.getTransactions().values()) { assertEquals(tx, newPocket.getTransaction(tx.getHash())); BitTransaction txNew = checkNotNull(newPocket.getTransaction(tx.getHash())); assertInputsEquals(tx.getInputs(), txNew.getInputs()); assertOutputsEquals(tx.getOutputs(false), txNew.getOutputs(false)); } for (AddressStatus status : pocket.getAllAddressStatus()) { if (status.getStatus() == null) continue; assertEquals(status, newPocket.getAddressStatus(status.getAddress())); } // Issued keys assertEquals(18, newPocket.keys.getNumIssuedExternalKeys()); assertEquals(9, newPocket.keys.getNumIssuedInternalKeys()); newPocket.onConnection(getBlockchainConnection(DOGE)); // No addresses left to subscribe List<AbstractAddress> addressesToWatch = newPocket.getAddressesToWatch(); assertEquals(0, addressesToWatch.size()); // 18 external issued + 20 lookahead + 9 external issued + 20 lookahead assertEquals(67, newPocket.addressesStatus.size()); assertEquals(67, newPocket.addressesSubscribed.size()); } private void assertInputsEquals(List<TransactionInput> expected, List<TransactionInput> actual) { assertEquals(expected.size(), actual.size()); for (int i = 0; i < expected.size(); i++) { assertArrayEquals(expected.get(i).bitcoinSerialize(), actual.get(i).bitcoinSerialize()); } } private void assertOutputsEquals(List<TransactionOutput> expected, List<TransactionOutput> actual) { assertEquals(expected.size(), actual.size()); for (int i = 0; i < expected.size(); i++) { assertArrayEquals(expected.get(i).bitcoinSerialize(), actual.get(i).bitcoinSerialize()); } } @Test public void serializeUnencryptedEmpty() throws Exception { pocket.maybeInitializeAllKeys(); Protos.WalletPocket walletPocketProto = pocket.toProtobuf(); WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(walletPocketProto, null); assertEquals(walletPocketProto.toString(), newPocket.toProtobuf().toString()); // Issued keys assertEquals(0, newPocket.keys.getNumIssuedExternalKeys()); assertEquals(0, newPocket.keys.getNumIssuedInternalKeys()); // 20 lookahead + 20 lookahead assertEquals(40, newPocket.keys.getActiveKeys().size()); } @Test public void serializeEncryptedEmpty() throws Exception { pocket.maybeInitializeAllKeys(); pocket.encrypt(crypter, aesKey); Protos.WalletPocket walletPocketProto = pocket.toProtobuf(); WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(walletPocketProto, crypter); assertEquals(walletPocketProto.toString(), newPocket.toProtobuf().toString()); pocket.decrypt(aesKey); // One is encrypted, so they should not match assertNotEquals(pocket.toProtobuf().toString(), newPocket.toProtobuf().toString()); newPocket.decrypt(aesKey); assertEquals(pocket.toProtobuf().toString(), newPocket.toProtobuf().toString()); } @Test public void serializeEncryptedNormal() throws Exception { pocket.maybeInitializeAllKeys(); pocket.encrypt(crypter, aesKey); pocket.onConnection(getBlockchainConnection(DOGE)); assertEquals(DOGE.value(11000000000l), pocket.getBalance()); assertAllKeysEncrypted(pocket); WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(pocket.toProtobuf(), crypter); assertEquals(DOGE.value(11000000000l), newPocket.getBalance()); Map<TrimmedOutPoint, OutPointOutput> expectedUtxoSet = getDummyUtxoSet(); checkUnspentOutputs(expectedUtxoSet, pocket); checkUnspentOutputs(expectedUtxoSet, newPocket); assertAllKeysEncrypted(newPocket); pocket.decrypt(aesKey); newPocket.decrypt(aesKey); assertAllKeysDecrypted(pocket); assertAllKeysDecrypted(newPocket); } private void checkUnspentOutputs(Map<TrimmedOutPoint, OutPointOutput> expectedUtxoSet, WalletPocketHD pocket) { Map<TrimmedOutPoint, OutPointOutput> pocketUtxoSet = pocket.getUnspentOutputs(false); for (OutPointOutput utxo : expectedUtxoSet.values()) { assertEquals(utxo, pocketUtxoSet.get(utxo.getOutPoint())); } } private void assertAllKeysDecrypted(WalletPocketHD pocket) { List<ECKey> keys = pocket.keys.getKeys(false); for (ECKey k : keys) { DeterministicKey key = (DeterministicKey) k; assertFalse(key.isEncrypted()); } } private void assertAllKeysEncrypted(WalletPocketHD pocket) { List<ECKey> keys = pocket.keys.getKeys(false); for (ECKey k : keys) { DeterministicKey key = (DeterministicKey) k; assertTrue(key.isEncrypted()); } } @Test public void createDustTransactionFee() throws Exception { pocket.onConnection(getBlockchainConnection(DOGE)); BitAddress toAddr = BitAddress.from(DOGE, "nZB8PHkfgJvuCJqchSexmfY3ABXa2aE1vp"); Value softDust = DOGE.getSoftDustLimit(); assertNotNull(softDust); // Send a soft dust BitSendRequest sendRequest = pocket.sendCoinsOffline(toAddr, softDust.subtract(DOGE.value(1))); pocket.completeTransaction(sendRequest); assertEquals(DOGE.getFeeValue().multiply(2), sendRequest.tx.getFee()); } @Test public void createTransactionAndBroadcast() throws Exception { pocket.onConnection(getBlockchainConnection(DOGE)); BitAddress toAddr = BitAddress.from(DOGE, "nZB8PHkfgJvuCJqchSexmfY3ABXa2aE1vp"); Value orgBalance = pocket.getBalance(); BitSendRequest sendRequest = pocket.sendCoinsOffline(toAddr, DOGE.value(AMOUNT_TO_SEND)); sendRequest.shuffleOutputs = false; sendRequest.feePerTxSize = DOGE.value(0); pocket.completeTransaction(sendRequest); // FIXME, mock does not work here // pocket.broadcastTx(tx); pocket.addNewTransactionIfNeeded(sendRequest.tx); assertEquals(orgBalance.subtract(AMOUNT_TO_SEND), pocket.getBalance()); } // Util methods //////////////////////////////////////////////////////////////////////////////////////////////// public class MessageComparator implements Comparator<ChildMessage> { @Override public int compare(ChildMessage o1, ChildMessage o2) { String s1 = Utils.HEX.encode(o1.bitcoinSerialize()); String s2 = Utils.HEX.encode(o2.bitcoinSerialize()); return s1.compareTo(s2); } } HashMap<AbstractAddress, AddressStatus> getDummyStatuses() throws AddressMalformedException { HashMap<AbstractAddress, AddressStatus> status = new HashMap<>(40); for (int i = 0; i < addresses.size(); i++) { AbstractAddress address = DOGE.newAddress(addresses.get(i)); status.put(address, new AddressStatus(address, statuses[i])); } return status; } private HashMap<AbstractAddress, ArrayList<HistoryTx>> getDummyHistoryTXs() throws AddressMalformedException, JSONException { HashMap<AbstractAddress, ArrayList<HistoryTx>> htxs = new HashMap<>(40); for (int i = 0; i < statuses.length; i++) { JSONArray jsonArray = new JSONArray(history[i]); ArrayList<HistoryTx> list = new ArrayList<>(); for (int j = 0; j < jsonArray.length(); j++) { list.add(new HistoryTx(jsonArray.getJSONObject(j))); } htxs.put(DOGE.newAddress(addresses.get(i)), list); } return htxs; } private HashMap<AbstractAddress, ArrayList<UnspentTx>> getDummyUnspentTXs() throws AddressMalformedException, JSONException { HashMap<AbstractAddress, ArrayList<UnspentTx>> utxs = new HashMap<>(40); for (int i = 0; i < statuses.length; i++) { JSONArray jsonArray = new JSONArray(unspent[i]); ArrayList<UnspentTx> list = new ArrayList<>(); for (int j = 0; j < jsonArray.length(); j++) { list.add(new UnspentTx(jsonArray.getJSONObject(j))); } utxs.put(DOGE.newAddress(addresses.get(i)), list); } return utxs; } private Map<TrimmedOutPoint, OutPointOutput> getDummyUtxoSet() throws AddressMalformedException, JSONException { final HashMap<TrimmedOutPoint, OutPointOutput> unspentOutputs = new HashMap<>(); for (int i = 0; i < statuses.length; i++) { BitAddress address = (BitAddress) DOGE.newAddress(addresses.get(i)); JSONArray utxoArray = new JSONArray(unspent[i]); for (int j = 0; j < utxoArray.length(); j++) { JSONObject utxoObject = utxoArray.getJSONObject(j); //"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 11, \"value\": 500000000, \"height\": 160267}]", TrimmedOutPoint outPoint = new TrimmedOutPoint(DOGE, utxoObject.getInt("tx_pos"), new Sha256Hash(utxoObject.getString("tx_hash"))); TransactionOutput output = new TransactionOutput(DOGE, null, Coin.valueOf(utxoObject.getLong("value")), address); OutPointOutput utxo = new OutPointOutput(outPoint, output, false); unspentOutputs.put(outPoint, utxo); } } return unspentOutputs; } private HashMap<Sha256Hash, byte[]> getDummyRawTXs() throws AddressMalformedException, JSONException { HashMap<Sha256Hash, byte[]> rawTxs = new HashMap<>(); for (String[] tx : txs) { rawTxs.put(new Sha256Hash(tx[0]), Utils.HEX.decode(tx[1])); } return rawTxs; } class MockBlockchainConnection implements BitBlockchainConnection { final HashMap<AbstractAddress, AddressStatus> statuses; final HashMap<AbstractAddress, ArrayList<HistoryTx>> historyTxs; final HashMap<AbstractAddress, ArrayList<UnspentTx>> unspentTxs; final HashMap<Sha256Hash, byte[]> rawTxs; private CoinType coinType; MockBlockchainConnection(CoinType coinType) throws Exception { this.coinType = coinType; statuses = getDummyStatuses(); historyTxs = getDummyHistoryTXs(); unspentTxs = getDummyUnspentTXs(); rawTxs = getDummyRawTXs(); } @Override public void getBlock(int height, TransactionEventListener<BitTransaction> listener) { } @Override public void subscribeToBlockchain(TransactionEventListener<BitTransaction> listener) { listener.onNewBlock(new BlockHeader(coinType, blockTimestamp, blockHeight)); } @Override public void subscribeToAddresses(List<AbstractAddress> addresses, TransactionEventListener<BitTransaction> listener) { for (AbstractAddress a : addresses) { AddressStatus status = statuses.get(a); if (status == null) { status = new AddressStatus(a, null); } listener.onAddressStatusUpdate(status); } } @Override public void getHistoryTx(AddressStatus status, TransactionEventListener<BitTransaction> listener) { List<HistoryTx> htx = historyTxs.get(status.getAddress()); if (htx == null) { htx = ImmutableList.of(); } listener.onTransactionHistory(status, htx); } @Override public void getUnspentTx(AddressStatus status, BitTransactionEventListener listener) { List<UnspentTx> utx = unspentTxs.get(status.getAddress()); if (utx == null) { utx = ImmutableList.of(); } listener.onUnspentTransactionUpdate(status, utx); } @Override public void getTransaction(Sha256Hash txHash, TransactionEventListener<BitTransaction> listener) { BitTransaction tx = new BitTransaction(coinType, rawTxs.get(txHash)); listener.onTransactionUpdate(tx); } @Override public void broadcastTx(BitTransaction tx, TransactionEventListener<BitTransaction> listener) { // List<AddressStatus> newStatuses = new ArrayList<AddressStatus>(); // Random rand = new Random(); // byte[] randBytes = new byte[32]; // // Get spent outputs and modify statuses // for (TransactionInput txi : tx.getInputs()) { // UnspentTx unspentTx = new UnspentTx( // txi.getOutpoint(), txi.getValue().value, 0); // // for (Map.Entry<Address, ArrayList<UnspentTx>> entry : utxs.entrySet()) { // if (entry.getValue().remove(unspentTx)) { // rand.nextBytes(randBytes); // AddressStatus newStatus = new AddressStatus(entry.getKey(), Utils.HEX.encode(randBytes)); // statuses.put(entry.getKey(), newStatus); // newStatuses.add(newStatus); // } // } // } // // for (TransactionOutput txo : tx.getOutputs()) { // if (txo.getAddressFromP2PKHScript(coinType) != null) { // Address address = txo.getAddressFromP2PKHScript(coinType); // if (addresses.contains(address.toString())) { // AddressStatus newStatus = new AddressStatus(address, tx.getHashAsString()); // statuses.put(address, newStatus); // newStatuses.add(newStatus); // if (!utxs.containsKey(address)) { // utxs.put(address, new ArrayList<UnspentTx>()); // } // ArrayList<UnspentTx> unspentTxs = utxs.get(address); // unspentTxs.add(new UnspentTx(txo.getOutPointFor(), // txo.getValue().value, 0)); // if (!historyTxs.containsKey(address)) { // historyTxs.put(address, new ArrayList<HistoryTx>()); // } // ArrayList<HistoryTx> historyTxes = historyTxs.get(address); // historyTxes.add(new HistoryTx(txo.getOutPointFor(), 0)); // } // } // } // // rawTxs.put(tx.getHash(), tx.bitcoinSerialize()); // // for (AddressStatus newStatus : newStatuses) { // listener.onAddressStatusUpdate(newStatus); // } } @Override public boolean broadcastTxSync(BitTransaction tx) { return false; } @Override public void ping(String versionString) {} @Override public void addEventListener(ConnectionEventListener listener) { } @Override public void resetConnection() { } @Override public void stopAsync() { } @Override public boolean isActivelyConnected() { return false; } @Override public void startAsync() { } } private MockBlockchainConnection getBlockchainConnection(CoinType coinType) throws Exception { return new MockBlockchainConnection(coinType); } // Mock data long blockTimestamp = 1411000000l; int blockHeight = 200000; List<String> addresses = ImmutableList.of( "nnfP8VuPfZXhNtMDzvX1bKurzcV1k7HNrQ", "nf4AUKiaGdx4GTbbh222KvtuCbAuvbcdE2", "npGkmbWtdWybFNSZQXUK6zZxbEocMtrTzz", "nVaN45bbs6AUc1EUpP71hHGBGb2qciNrJc", "nrdHFZP1AfdKBrjsSQmwFm8R2i2mzMef75", "niGZgfbhFYn6tJqksmC8CnzSRL1GHNsu7e", "nh6w8yu1zoKYoT837ffkVmuPjTaP69Pc5E", "nbyMgmEghsL9tpk7XfdH9gLGudh6Lrbbuf", "naX9akzYuWY1gKbcZo3t36aBKc1gqbzgSs", "nqcPVTGeAfCowELB2D5PdVF3FWFjFtkkFf", "nd4vVvPTpp2LfcsMPsmG3Dh7MFAsqRHp4g", "nVK4Uz5Sf56ygrr6RiwXcRvH8AuUVbjjHi", "nbipkRwT1NCSXZSrm8uAAEgQAA2s2NWMkG", "nZU6QAMAdCQcVDxEmL7GEY6ykFm8m6u6am", "nbFqayssM5s7hLjLFwf2d95JXKRWBk2pBH", "nacZfcNgVi47hamLscWdUGQhUQGGpSdgq8", "niiMT7ZYeFnaLPYtqQFBBX1sP3dT5JtcEw", "ns6GyTaniLWaiYrvAf5tk4D8tWrbcCLGyj", "nhdwQfptLTzLJGbLF3vvtqyBaqPMPecDmE", "neMUAGeTzwxLbSkXMsdmWf1fTKS1UsJjXY", "nXsAMeXxtpx8jaxnU3Xv9ZQ6ZcRcD1xYhR", "ns35rKnnWf6xP3KSj5WPkMCVVaADGi6Ndk", "nk4wcXYBEWs5HkhNLsuaQJoAjJHoK6SQmG", "npsJQWu8fsALoTPum8D4j8FDkyeusk8fU8", "nZNhZo4Vz3DnwQGPL3SJTZgUw2Kh4g9oay", "nnxDTYB8WMHMgLnCY2tuaEtysvdhRnWehZ", "nb2iaDXG1EqkcE47H87WQFkQNkeVK66Z21", "nWHAkpn2DB3DJRsbiK3vpbigoa3M2uVuF8", "nViKdC7Gm6TMmCuWTBwVE9i4rJhyfwbfqg", "nZQV5BifbGPzaxTrB4efgHruWH5rufemqP", "nVvZaLvnkCVAzpLYPoHeqU4w9zJ5yrZgUn", "nrMp6pRCk98WYWkCWq9Pqthz9HbpQu8BT3", "nnA3aYsLqysKT6gAu1dr4EKm586cmKiRxS", "nVfcVgMY7DL6nqoSxwJy7B7hKXirQwj6ic", "ni4oAzi6nCVuEdjoHyVMVKWb1DqTd3qY3H", "nnpf3gx442yomniRJPMGPapgjHrraPZXxJ", "nkuFnF8wUmHFkMycaFMvyjBoiMeR5KBKGd", "nXKccwjaUyrQkLrdqKT6aq6cDiFgBBVgNz", "nZMSNsXSAL7i1YD6KP5FrhATuZ2CWvnxqR", "nUEkQ3LjH9m4ScbP6NGtnAdnnUsdtWv99Q" ); String[] statuses = { "fe7c109d8bd90551a406cf0b3499117db04bc9c4f48e1df27ac1cf3ddcb3d464", "8a53babd831c6c3a857e20190e884efe75a005bdd7cd273c4f27ab1b8ec81c2d", "86bc2f0cf0112fd59c9aadfe5c887062c21d7a873db260dff68dcfe4417fe212", "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, null, null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, null, null, null, null, null, null, null, null, null }; String[] unspent = { "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 0, \"value\": 500000000, \"height\": 160267}, {\"tx_hash\": \"89a72ba4732505ce9b09c30668db985952701252ce0adbd7c43336396697d6ae\", \"tx_pos\": 0, \"value\": 500000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 1, \"value\": 1000000000, \"height\": 160267}, {\"tx_hash\": \"edaf445288d8e65cf7963bc8047c90f53681acaadc5ccfc5ecc67aedbd73cddb\", \"tx_pos\": 0, \"value\": 500000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 2, \"value\": 500000000, \"height\": 160267}, {\"tx_hash\": \"81a1f0f8242d5e71e65ff9e8ec51e8e85d641b607d7f691c1770d4f25918ebd7\", \"tx_pos\": 0, \"value\": 1000000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 3, \"value\": 500000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 4, \"value\": 1000000000, \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 11, \"value\": 500000000, \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 12, \"value\": 1000000000, \"height\": 160267}]", "[]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 13, \"value\": 500000000, \"height\": 160267}]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 6, \"value\": 500000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 7, \"value\": 1000000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 8, \"value\": 500000000, \"height\": 160267}]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 9, \"value\": 500000000, \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 10, \"value\": 1000000000, \"height\": 160267}]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]" }; String[] history = { "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}, {\"tx_hash\": \"89a72ba4732505ce9b09c30668db985952701252ce0adbd7c43336396697d6ae\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}, {\"tx_hash\": \"edaf445288d8e65cf7963bc8047c90f53681acaadc5ccfc5ecc67aedbd73cddb\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}, {\"tx_hash\": \"81a1f0f8242d5e71e65ff9e8ec51e8e85d641b607d7f691c1770d4f25918ebd7\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]" }; String[][] txs = { {"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f", "0100000001b8778dff640ccb144346d9db48201639b2707a0cc59e19672d2dd76cc6d1a5a6010000006b48304502210098d2e5b8a6c72442430bc09f2f4bcb56612c5b9e5eee821d65b412d099bb723402204f7f008ac052e5d7be0ab5b0c85ea5e627d725a521bd9e9b193d1fdf81c317a0012102d26e423c9da9ff4a7bf6b756b2dafb75cca34fbd34f64c4c3b77c37179c5bba2ffffffff0e0065cd1d000000001976a914ca983c2da690de3cdc693ca013d93e569810c52c88ac00ca9a3b000000001976a91477263ab93a49b1d3eb5887187704cdb82e1c60ce88ac0065cd1d000000001976a914dc40fbbc8caa1f7617d275aec9a3a14ce8d8652188ac0065cd1d000000001976a9140f2b1e5b376e22c5d1e635233eb90cf50ad9095188ac00ca9a3b000000001976a914f612ffd50b6a69df5e34ee0c5b529dfaaedca03d88ac00f633bce60000001976a914937258e3a8c463ec07e78ce62326c488170ad25e88ac0065cd1d000000001976a9142848ad5ff4cc32df3649646017c47bc04e8d211788ac00ca9a3b000000001976a914fa937737a6df2b8a5e39cce8b0bdd9510683023a88ac0065cd1d000000001976a914ae248a5d710143b6b309aaab9ce17059536e2aa388ac0065cd1d000000001976a91438d6eb11eca405be497a7183c50e437851425e0088ac00ca9a3b000000001976a91410ac6b2704146b50a1dd8f6df70736856ebf8b3488ac0065cd1d000000001976a914456816dccb3a4f33ae2dbd3ba623997075d5c73d88ac00ca9a3b000000001976a91452957c44e5bee9a60402a739fc8959c2850ea98488ac0065cd1d000000001976a914fb2dffa402d05f74335d137e21e41d8920c745fb88ac00000000"}, {"89a72ba4732505ce9b09c30668db985952701252ce0adbd7c43336396697d6ae", "01000000011a656d67706db286d1e6fad57eb4f411cb14f8880cea8348da339b9d434a5ec7050000006a47304402201d69fddb269b53aa742ff6437a45adb4ca5c59f666c9b4eabc4a0c7a6e6f4c0f022015a747b7a6d9371a4020f5b396dcd094b0f36af3fc82e95091da856181912dfa012102c9a8d5b2f768afe30ee772d185e7a61f751be05649a79508b38a2be8824adec3ffffffff020065cd1d000000001976a914ca983c2da690de3cdc693ca013d93e569810c52c88ac00b07098e60000001976a9141630d812e219e6bcbe494eb96f7a7900c216ad5d88ac00000000"}, {"edaf445288d8e65cf7963bc8047c90f53681acaadc5ccfc5ecc67aedbd73cddb", "010000000164a3990893c012b20287d43d1071ac26f4b93648ff4213db6da6979beed6b7dc010000006b48304502210086ac11d4a8146b4176a72059960690c72a9776468cd671fd07c064b51f24961d02205bcf008d6995014f3cfd79100ee9beab5688c88cca15c5cea38b769563785d900121036530415a7b3b9c5976f26a63a57d119ab39491762121723c773399a2531a1bd7ffffffff020065cd1d000000001976a91477263ab93a49b1d3eb5887187704cdb82e1c60ce88ac006aad74e60000001976a914e5616848352c328c9f61b167eb1b0fde39b5cb6788ac00000000"}, {"81a1f0f8242d5e71e65ff9e8ec51e8e85d641b607d7f691c1770d4f25918ebd7", "010000000141c217dfea3a1d8d6a06e9d3daf75b292581f652256d73a7891e5dc9c7ee3cca000000006a47304402205cce451228f98fece9645052546b82c2b2d425a4889b03999001fababfc7f4690220583b2189faef07d6b0191c788301cfab1b3f47ffe2c403d632b92c6dde27e14f012102d26e423c9da9ff4a7bf6b756b2dafb75cca34fbd34f64c4c3b77c37179c5bba2ffffffff0100ca9a3b000000001976a914dc40fbbc8caa1f7617d275aec9a3a14ce8d8652188ac00000000"} }; }
MFrcoin/android-wallet
core/src/test/java/com/mfcoin/core/wallet/WalletPocketHDTest.java
45,936
package com.mkyong.regex.email; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; public class EmailValidatorUnicodeTest { @ParameterizedTest(name = "#{index} - Run test with email = {0}") @MethodSource("validEmailProvider") void test_email_valid(String email) { assertTrue(EmailValidatorUnicode.isValid(email)); } @ParameterizedTest(name = "#{index} - Run test with email = {0}") @MethodSource("invalidEmailProvider") void test_email_invalid(String email) { assertFalse(EmailValidatorUnicode.isValid(email)); } // Valid email addresses static Stream<String> validEmailProvider() { return Stream.of( "[email protected]", // simple "[email protected]", // .co.uk, 2 tld "[email protected]", // - "[email protected]", // . "[email protected]", // _ "[email protected]", // local-part one letter "[email protected]", // domain contains a hyphen - "[email protected]", // domain contains two hyphens - - "[email protected]", // domain contains . - "[email protected]", // local part contains . - "我買@屋企.香港", // chinese characters "二ノ宮@黒川.日本", // Japanese characters "δοκιμή@παράδειγμα.δοκιμή"); // Greek alphabets } // Invalid email addresses static Stream<String> invalidEmailProvider() { return Stream.of( "hello", // email need at least one @ "hello@[email protected]", // email doesn't allow more than one @ "[email protected]", // local-part can't start with a dot . "[email protected]", // local-part can't end with a dot . "[email protected]", // local part don't allow dot . appear consecutively "[email protected]", // local-part don't allow special characters like !+ "[email protected]", // domain tld min 2 chars "[email protected]", // domain part doesn't allow dot . appear consecutively "[email protected]", // domain part doesn't start with a dot . "[email protected].", // domain part doesn't end with a dot . "[email protected]", // domain part doesn't allow to start with a hyphen - "[email protected]", // domain part doesn't allow to end with a hyphen - "hello@example_example.com", // domain part doesn't allow underscore "1234567890123456789012345678901234567890123456789012345678901234xx@example.com"); // local part is longer than 64 characters } }
nipunarora/core-java
java-regex/src/test/java/com/mkyong/regex/email/EmailValidatorUnicodeTest.java
45,937
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.handler.codec.socks; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.util.CharsetUtil; import org.junit.Test; import java.net.IDN; import java.nio.CharBuffer; import static org.junit.Assert.*; public class SocksCmdRequestTest { @Test public void testConstructorParamsAreNotNull() { try { new SocksCmdRequest(null, SocksAddressType.UNKNOWN, "", 1); } catch (Exception e) { assertTrue(e instanceof NullPointerException); } try { new SocksCmdRequest(SocksCmdType.UNKNOWN, null, "", 1); } catch (Exception e) { assertTrue(e instanceof NullPointerException); } try { new SocksCmdRequest(SocksCmdType.UNKNOWN, SocksAddressType.UNKNOWN, null, 1); } catch (Exception e) { assertTrue(e instanceof NullPointerException); } } @Test public void testIPv4CorrectAddress() { try { new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.IPv4, "54.54.1111.253", 1); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } @Test public void testIPv6CorrectAddress() { try { new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.IPv6, "xxx:xxx:xxx", 1); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } @Test public void testIDNNotExceeds255CharsLimit() { try { new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.DOMAIN, "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" + "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" + "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" + "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή", 1); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } @Test public void testHostNotEncodedForUnknown() { String asciiHost = "xn--e1aybc.xn--p1ai"; short port = 10000; SocksCmdRequest rq = new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.UNKNOWN, asciiHost, port); assertEquals(asciiHost, rq.host()); ByteBuf buffer = Unpooled.buffer(16); rq.encodeAsByteBuf(buffer); buffer.readerIndex(0); assertEquals(SocksProtocolVersion.SOCKS5.byteValue(), buffer.readByte()); assertEquals(SocksCmdType.BIND.byteValue(), buffer.readByte()); assertEquals((byte) 0x00, buffer.readByte()); assertEquals(SocksAddressType.UNKNOWN.byteValue(), buffer.readByte()); assertFalse(buffer.isReadable()); buffer.release(); } @Test public void testIDNEncodeToAsciiForDomain() { String host = "тест.рф"; CharBuffer asciiHost = CharBuffer.wrap(IDN.toASCII(host)); short port = 10000; SocksCmdRequest rq = new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.DOMAIN, host, port); assertEquals(host, rq.host()); ByteBuf buffer = Unpooled.buffer(24); rq.encodeAsByteBuf(buffer); buffer.readerIndex(0); assertEquals(SocksProtocolVersion.SOCKS5.byteValue(), buffer.readByte()); assertEquals(SocksCmdType.BIND.byteValue(), buffer.readByte()); assertEquals((byte) 0x00, buffer.readByte()); assertEquals(SocksAddressType.DOMAIN.byteValue(), buffer.readByte()); assertEquals((byte) asciiHost.length(), buffer.readUnsignedByte()); assertEquals(asciiHost, CharBuffer.wrap(buffer.readCharSequence(asciiHost.length(), CharsetUtil.US_ASCII))); assertEquals(port, buffer.readUnsignedShort()); buffer.release(); } @Test public void testValidPortRange() { try { new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.DOMAIN, "παράδειγμα.δοκιμήπαράδει", 0); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } try { new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.DOMAIN, "παράδειγμα.δοκιμήπαράδει", 65536); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } }
benevans/netty
codec-socks/src/test/java/io/netty/handler/codec/socks/SocksCmdRequestTest.java
45,938
package com.vergepay.core.wallet; import com.vergepay.core.coins.BitcoinMain; import com.vergepay.core.coins.CoinType; import com.vergepay.core.coins.DogecoinTest; import com.vergepay.core.coins.NuBitsMain; import com.vergepay.core.coins.Value; import com.vergepay.core.coins.VpncoinMain; import com.vergepay.core.exceptions.AddressMalformedException; import com.vergepay.core.exceptions.Bip44KeyLookAheadExceededException; import com.vergepay.core.exceptions.KeyIsEncryptedException; import com.vergepay.core.exceptions.MissingPrivateKeyException; import com.vergepay.core.network.AddressStatus; import com.vergepay.core.network.BlockHeader; import com.vergepay.core.network.ServerClient.HistoryTx; import com.vergepay.core.network.ServerClient.UnspentTx; import com.vergepay.core.network.interfaces.ConnectionEventListener; import com.vergepay.core.network.interfaces.TransactionEventListener; import com.vergepay.core.protos.Protos; import com.vergepay.core.wallet.families.bitcoin.BitAddress; import com.vergepay.core.wallet.families.bitcoin.BitBlockchainConnection; import com.vergepay.core.wallet.families.bitcoin.BitSendRequest; import com.vergepay.core.wallet.families.bitcoin.BitTransaction; import com.vergepay.core.wallet.families.bitcoin.BitTransactionEventListener; import com.vergepay.core.wallet.families.bitcoin.OutPointOutput; import com.vergepay.core.wallet.families.bitcoin.TrimmedOutPoint; import com.google.common.collect.ImmutableList; import org.bitcoinj.core.ChildMessage; import org.bitcoinj.core.Coin; import org.bitcoinj.core.ECKey; import org.bitcoinj.core.Sha256Hash; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.TransactionConfidence.Source; import org.bitcoinj.core.TransactionInput; import org.bitcoinj.core.TransactionOutput; import org.bitcoinj.core.Utils; import org.bitcoinj.crypto.DeterministicHierarchy; import org.bitcoinj.crypto.DeterministicKey; import org.bitcoinj.crypto.HDKeyDerivation; import org.bitcoinj.crypto.KeyCrypter; import org.bitcoinj.crypto.KeyCrypterScrypt; import org.bitcoinj.store.UnreadableWalletException; import org.bitcoinj.utils.BriefLogFormatter; import org.bitcoinj.wallet.DeterministicSeed; import org.bitcoinj.wallet.KeyChain; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.spongycastle.crypto.params.KeyParameter; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.vergepay.core.Preconditions.checkNotNull; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; /** * @author John L. Jegutanis */ public class WalletPocketHDTest { static final CoinType BTC = BitcoinMain.get(); static final CoinType DOGE = DogecoinTest.get(); static final CoinType NBT = NuBitsMain.get(); static final CoinType VPN = VpncoinMain.get(); static final List<String> MNEMONIC = ImmutableList.of("citizen", "fever", "scale", "nurse", "brief", "round", "ski", "fiction", "car", "fitness", "pluck", "act"); static final byte[] AES_KEY_BYTES = {0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7}; static final long AMOUNT_TO_SEND = 2700000000L; static final String MESSAGE = "test"; static final String MESSAGE_UNICODE = "δοκιμή испытание 测试"; static final String EXPECTED_BITCOIN_SIG = "IMBbIFDDuUwomYlvSjwWytqP/CXYym2yOKbJUx8Y+ujzZKBwoCFMr73GUxpr1Ird/DvnNZcsQLphvx18ftqN54o="; static final String EXPECTED_BITCOIN_SIG_UNICODE = "IGGZEOBsVny5dozTOfc2/3UuvmZGdDI4XK/03HIk34PILd2oXbnq+87GINT3lumeXcgSO2NkGzUFcQ1SCSVI3Hk="; static final String EXPECTED_NUBITS_SIG = "IMuzNZTZIjZjLicyDFGzqFl21vqNBGW1N5m4qHBRqbTvLBbkQeGjraeLmZEt7mRH4MSMPLFXW2T3Maz+HYx1tEc="; static final String EXPECTED_NUBITS_SIG_UNICODE = "Hx7xkBbboXrp96dbQrJFzm2unTGwLstjbWlKa1/N1E4LJqbwJAJR1qIvwXm6LHQFnLOzwoQA45zYNjwUEPMc8sg="; DeterministicSeed seed = new DeterministicSeed(MNEMONIC, null, "", 0); DeterministicKey masterKey = HDKeyDerivation.createMasterPrivateKey(checkNotNull(seed.getSeedBytes())); DeterministicHierarchy hierarchy = new DeterministicHierarchy(masterKey); DeterministicKey rootKey = hierarchy.get(DOGE.getBip44Path(0), false, true); KeyParameter aesKey = new KeyParameter(AES_KEY_BYTES); KeyCrypter crypter = new KeyCrypterScrypt(); WalletPocketHD pocket; @Before public void setup() { BriefLogFormatter.init(); pocket = new WalletPocketHD(rootKey, DOGE, null, null); pocket.keys.setLookaheadSize(20); } @Test public void testId() throws Exception { assertEquals("8747886e9a77fe2a1588df3168b867648434d6d339b0b448793ae1db8f283f41", pocket.getId()); } @Test public void testSingleAddressWallet() throws Exception { ECKey key = pocket.keys.getCurrentUnusedKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); BitWalletSingleKey bitWalletSingleKey = new BitWalletSingleKey(DOGE, key); bitWalletSingleKey.onConnection(getBlockchainConnection(DOGE)); assertEquals(DOGE.value("10"), bitWalletSingleKey.getBalance()); } @Test public void xpubWallet() { String xpub = "xpub67tVq9TLPPoaHVSiYu8mqahm3eztTPUts6JUftNq3pZF1PJwjknrTqQhjc2qRGd6vS8wANu7mLnqkiUzFZ1xZsAZoUMi8o6icMhzGCAhcSW"; DeterministicKey key = DeterministicKey.deserializeB58(null, xpub); WalletPocketHD account = new WalletPocketHD(key, BTC, null, null); assertEquals("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", account.getReceiveAddress().toString()); account = new WalletPocketHD(key, NBT, null, null); assertEquals("BNvJUwg3BgkbQk5br1CxvHxdcDp1EC3saE", account.getReceiveAddress().toString()); } @Test public void xpubWalletSerialized() throws Exception { WalletPocketHD account = new WalletPocketHD(rootKey, BTC, null, null); Protos.WalletPocket proto = account.toProtobuf(); WalletPocketHD newAccount = new WalletPocketProtobufSerializer().readWallet(proto, null); assertEquals(account.getPublicKeySerialized(), newAccount.getPublicKeySerialized()); } @Test public void signMessage() throws AddressMalformedException, MissingPrivateKeyException, KeyIsEncryptedException { WalletPocketHD pocketHD = new WalletPocketHD(rootKey, BTC, null, null); pocketHD.getReceiveAddress(); // Generate the first key SignedMessage signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE); pocketHD.signMessage(signedMessage, null); assertEquals(EXPECTED_BITCOIN_SIG, signedMessage.getSignature()); signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE_UNICODE); pocketHD.signMessage(signedMessage, null); assertEquals(EXPECTED_BITCOIN_SIG_UNICODE, signedMessage.getSignature()); pocketHD = new WalletPocketHD(rootKey, NBT, null, null); pocketHD.getReceiveAddress(); // Generate the first key signedMessage = new SignedMessage("BNvJUwg3BgkbQk5br1CxvHxdcDp1EC3saE", MESSAGE); pocketHD.signMessage(signedMessage, null); assertEquals(EXPECTED_NUBITS_SIG, signedMessage.getSignature()); signedMessage = new SignedMessage("BNvJUwg3BgkbQk5br1CxvHxdcDp1EC3saE", MESSAGE_UNICODE); pocketHD.signMessage(signedMessage, null); assertEquals(EXPECTED_NUBITS_SIG_UNICODE, signedMessage.getSignature()); } @Test public void signMessageEncrypted() throws AddressMalformedException, MissingPrivateKeyException, KeyIsEncryptedException { WalletPocketHD pocketHD = new WalletPocketHD(rootKey, BTC, null, null); pocketHD.getReceiveAddress(); // Generate the first key pocketHD.encrypt(crypter, aesKey); SignedMessage signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE); pocketHD.signMessage(signedMessage, aesKey); assertEquals(EXPECTED_BITCOIN_SIG, signedMessage.getSignature()); signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE_UNICODE); pocketHD.signMessage(signedMessage, aesKey); assertEquals(EXPECTED_BITCOIN_SIG_UNICODE, signedMessage.getSignature()); } @Test public void signMessageEncryptedFailed() throws AddressMalformedException, MissingPrivateKeyException, KeyIsEncryptedException { WalletPocketHD pocketHD = new WalletPocketHD(rootKey, BTC, null, null); pocketHD.getReceiveAddress(); // Generate the first key pocketHD.encrypt(crypter, aesKey); SignedMessage signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE); pocketHD.signMessage(signedMessage, null); assertEquals(SignedMessage.Status.KeyIsEncrypted, signedMessage.status); } @Test public void watchingAddresses() { List<AbstractAddress> watchingAddresses = pocket.getAddressesToWatch(); assertEquals(40, watchingAddresses.size()); // 20 + 20 lookahead size for (int i = 0; i < addresses.size(); i++) { assertEquals(addresses.get(i), watchingAddresses.get(i).toString()); } } @Test public void issuedKeys() throws Bip44KeyLookAheadExceededException { List<BitAddress> issuedAddresses = new ArrayList<>(); assertEquals(0, pocket.getIssuedReceiveAddresses().size()); assertEquals(0, pocket.keys.getNumIssuedExternalKeys()); issuedAddresses.add(0, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS)); BitAddress freshAddress = pocket.getFreshReceiveAddress(); assertEquals(freshAddress, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS)); assertEquals(1, pocket.getIssuedReceiveAddresses().size()); assertEquals(1, pocket.keys.getNumIssuedExternalKeys()); assertEquals(issuedAddresses, pocket.getIssuedReceiveAddresses()); issuedAddresses.add(0, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS)); freshAddress = pocket.getFreshReceiveAddress(); assertEquals(freshAddress, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS)); assertEquals(2, pocket.getIssuedReceiveAddresses().size()); assertEquals(2, pocket.keys.getNumIssuedExternalKeys()); assertEquals(issuedAddresses, pocket.getIssuedReceiveAddresses()); } @Test public void issuedKeysLimit() throws Exception { assertTrue(pocket.canCreateFreshReceiveAddress()); try { for (int i = 0; i < 100; i++) { pocket.getFreshReceiveAddress(); } } catch (Bip44KeyLookAheadExceededException e) { assertFalse(pocket.canCreateFreshReceiveAddress()); // We haven't used any key so the total must be 20 - 1 (the unused key) assertEquals(19, pocket.getNumberIssuedReceiveAddresses()); assertEquals(19, pocket.getIssuedReceiveAddresses().size()); } pocket.onConnection(getBlockchainConnection(DOGE)); assertTrue(pocket.canCreateFreshReceiveAddress()); try { for (int i = 0; i < 100; i++) { pocket.getFreshReceiveAddress(); } } catch (Bip44KeyLookAheadExceededException e) { // try { // pocket.getFreshReceiveAddress(); // } catch (Bip44KeyLookAheadExceededException e1) { /* ignore */ } assertFalse(pocket.canCreateFreshReceiveAddress()); // We used 18, so the total must be (20-1)+18=37 assertEquals(37, pocket.getNumberIssuedReceiveAddresses()); assertEquals(37, pocket.getIssuedReceiveAddresses().size()); } } @Test public void issuedKeysLimit2() throws Exception { assertTrue(pocket.canCreateFreshReceiveAddress()); try { for (int i = 0; i < 100; i++) { pocket.getFreshReceiveAddress(); } } catch (Bip44KeyLookAheadExceededException e) { assertFalse(pocket.canCreateFreshReceiveAddress()); // We haven't used any key so the total must be 20 - 1 (the unused key) assertEquals(19, pocket.getNumberIssuedReceiveAddresses()); assertEquals(19, pocket.getIssuedReceiveAddresses().size()); } } @Test public void usedAddresses() throws Exception { assertEquals(0, pocket.getUsedAddresses().size()); pocket.onConnection(getBlockchainConnection(DOGE)); // Receive and change addresses assertEquals(13, pocket.getUsedAddresses().size()); } private Sha256Hash send(Value value, WalletPocketHD w1, WalletPocketHD w2) throws Exception { assertEquals(w1.getCoinType(), w2.getCoinType()); CoinType type = w1.getCoinType(); BitSendRequest req = w1.sendCoinsOffline(w2.getReceiveAddress(), value); req.feePerTxSize = type.value("0.01"); w1.completeAndSignTx(req); byte[] txBytes = req.tx.bitcoinSerialize(); w1.addNewTransactionIfNeeded(new BitTransaction(type, txBytes)); w2.addNewTransactionIfNeeded(new BitTransaction(type, txBytes)); return req.tx.getHash(); } @Test public void testSendingAndBalances() throws Exception { DeterministicHierarchy h = new DeterministicHierarchy(masterKey); WalletPocketHD account1 = new WalletPocketHD(h.get(BTC.getBip44Path(0), false, true), BTC, null, null); WalletPocketHD account2 = new WalletPocketHD(h.get(BTC.getBip44Path(1), false, true), BTC, null, null); WalletPocketHD account3 = new WalletPocketHD(h.get(BTC.getBip44Path(2), false, true), BTC, null, null); Transaction tx = new Transaction(BTC); tx.addOutput(BTC.oneCoin().toCoin(), account1.getReceiveAddress()); tx.getConfidence().setSource(Source.SELF); account1.addNewTransactionIfNeeded(tx); assertEquals(BTC.value("1"), account1.getBalance()); assertEquals(BTC.value("0"), account2.getBalance()); assertEquals(BTC.value("0"), account3.getBalance()); Sha256Hash txId = send(BTC.value("0.05"), account1, account2); assertEquals(BTC.value("0.94"), account1.getBalance()); assertEquals(BTC.value("0"), account2.getBalance()); assertEquals(BTC.value("0"), account3.getBalance()); setTrustedTransaction(account1, txId); setTrustedTransaction(account2, txId); assertEquals(BTC.value("0.94"), account1.getBalance()); assertEquals(BTC.value("0.05"), account2.getBalance()); txId = send(BTC.value("0.07"), account1, account3); setTrustedTransaction(account1, txId); setTrustedTransaction(account3, txId); assertEquals(BTC.value("0.86"), account1.getBalance()); assertEquals(BTC.value("0.05"), account2.getBalance()); assertEquals(BTC.value("0.07"), account3.getBalance()); txId = send(BTC.value("0.03"), account2, account3); setTrustedTransaction(account2, txId); setTrustedTransaction(account3, txId); assertEquals(BTC.value("0.86"), account1.getBalance()); assertEquals(BTC.value("0.01"), account2.getBalance()); assertEquals(BTC.value("0.1"), account3.getBalance()); } private void setTrustedTransaction(WalletPocketHD account, Sha256Hash txId) { BitTransaction tx = checkNotNull(account.getTransaction(txId)); tx.setSource(Source.SELF); } @Test public void testLoading() throws Exception { assertFalse(pocket.isLoading()); pocket.onConnection(getBlockchainConnection(DOGE)); // TODO add fine grained control to the blockchain connection in order to test the loading status assertFalse(pocket.isLoading()); } @Test public void fillTransactions() throws Exception { pocket.onConnection(getBlockchainConnection(DOGE)); checkUnspentOutputs(getDummyUtxoSet(), pocket); assertEquals(11000000000L, pocket.getBalance().value); // Issued keys assertEquals(18, pocket.keys.getNumIssuedExternalKeys()); assertEquals(9, pocket.keys.getNumIssuedInternalKeys()); // No addresses left to subscribe List<AbstractAddress> addressesToWatch = pocket.getAddressesToWatch(); assertEquals(0, addressesToWatch.size()); // 18 external issued + 20 lookahead + 9 external issued + 20 lookahead assertEquals(67, pocket.addressesStatus.size()); assertEquals(67, pocket.addressesSubscribed.size()); BitAddress receiveAddr = pocket.getReceiveAddress(); // This key is not issued assertEquals(18, pocket.keys.getNumIssuedExternalKeys()); assertEquals(67, pocket.addressesStatus.size()); assertEquals(67, pocket.addressesSubscribed.size()); DeterministicKey key = pocket.keys.findKeyFromPubHash(receiveAddr.getHash160()); assertNotNull(key); // 18 here is the key index, not issued keys count assertEquals(18, key.getChildNumber().num()); assertEquals(11000000000L, pocket.getBalance().value); } @Test public void serializeTransactionsBtc() throws Exception, Bip44KeyLookAheadExceededException { WalletPocketHD account = new WalletPocketHD(rootKey, BTC, null, null); Transaction tx = new Transaction(BTC); tx.addOutput(BTC.oneCoin().toCoin(), account.getReceiveAddress()); account.addNewTransactionIfNeeded(tx); testWalletSerializationForCoin(account); } @Test public void serializeTransactionsNbt() throws Exception, Bip44KeyLookAheadExceededException { WalletPocketHD account = new WalletPocketHD(rootKey, NBT, null, null); Transaction tx = new Transaction(NBT); tx.addOutput(NBT.oneCoin().toCoin(), account.getReceiveAddress()); account.addNewTransactionIfNeeded(tx); testWalletSerializationForCoin(account); } @Test public void serializeTransactionsVpn() throws Exception, Bip44KeyLookAheadExceededException { WalletPocketHD account = new WalletPocketHD(rootKey, VPN, null, null); // Test tx with null extra bytes Transaction tx = new Transaction(VPN); tx.setTime(0x99999999); tx.addOutput(VPN.oneCoin().toCoin(), account.getFreshReceiveAddress()); account.addNewTransactionIfNeeded(tx); WalletPocketHD newAccount = testWalletSerializationForCoin(account); Transaction newTx = newAccount.getRawTransaction(tx.getHash()); assertNotNull(newTx); assertNotNull(newTx.getExtraBytes()); assertEquals(0, newTx.getExtraBytes().length); // Test tx with empty extra bytes tx = new Transaction(VPN); tx.setTime(0x99999999); tx.setExtraBytes(new byte[0]); tx.addOutput(VPN.oneCoin().toCoin(), account.getFreshReceiveAddress()); account.addNewTransactionIfNeeded(tx); newAccount = testWalletSerializationForCoin(account); newTx = newAccount.getRawTransaction(tx.getHash()); assertNotNull(newTx); assertNotNull(newTx.getExtraBytes()); assertEquals(0, newTx.getExtraBytes().length); // Test tx with extra bytes tx = new Transaction(VPN); tx.setTime(0x99999999); byte[] bytes = {0x1, 0x2, 0x3}; tx.setExtraBytes(bytes); tx.addOutput(VPN.oneCoin().toCoin(), account.getFreshReceiveAddress()); account.addNewTransactionIfNeeded(tx); newAccount = testWalletSerializationForCoin(account); newTx = newAccount.getRawTransaction(tx.getHash()); assertNotNull(newTx); assertArrayEquals(bytes, newTx.getExtraBytes()); } private WalletPocketHD testWalletSerializationForCoin(WalletPocketHD account) throws UnreadableWalletException { Protos.WalletPocket proto = account.toProtobuf(); WalletPocketHD newAccount = new WalletPocketProtobufSerializer().readWallet(proto, null); assertEquals(account.getBalance().value, newAccount.getBalance().value); Map<Sha256Hash, BitTransaction> transactions = account.getTransactions(); Map<Sha256Hash, BitTransaction> newTransactions = newAccount.getTransactions(); for (Sha256Hash txId : transactions.keySet()) { assertTrue(newTransactions.containsKey(txId)); assertEquals(transactions.get(txId), newTransactions.get(txId)); } return newAccount; } @Test public void serializeUnencryptedNormal() throws Exception { pocket.onConnection(getBlockchainConnection(DOGE)); Protos.WalletPocket walletPocketProto = pocket.toProtobuf(); System.out.println(walletPocketProto.toString()); WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(walletPocketProto, null); assertEquals(pocket.getBalance().value, newPocket.getBalance().value); assertEquals(DOGE.value(11000000000l), newPocket.getBalance()); Map<TrimmedOutPoint, OutPointOutput> expectedUtxoSet = getDummyUtxoSet(); checkUnspentOutputs(expectedUtxoSet, pocket); checkUnspentOutputs(expectedUtxoSet, newPocket); assertEquals(pocket.getCoinType(), newPocket.getCoinType()); assertEquals(pocket.getDescriptionOrCoinName(), newPocket.getDescriptionOrCoinName()); assertEquals(pocket.keys.toProtobuf().toString(), newPocket.keys.toProtobuf().toString()); assertEquals(pocket.getLastBlockSeenHash(), newPocket.getLastBlockSeenHash()); assertEquals(pocket.getLastBlockSeenHeight(), newPocket.getLastBlockSeenHeight()); assertEquals(pocket.getLastBlockSeenTimeSecs(), newPocket.getLastBlockSeenTimeSecs()); for (BitTransaction tx : pocket.getTransactions().values()) { assertEquals(tx, newPocket.getTransaction(tx.getHash())); BitTransaction txNew = checkNotNull(newPocket.getTransaction(tx.getHash())); assertInputsEquals(tx.getInputs(), txNew.getInputs()); assertOutputsEquals(tx.getOutputs(false), txNew.getOutputs(false)); } for (AddressStatus status : pocket.getAllAddressStatus()) { if (status.getStatus() == null) continue; assertEquals(status, newPocket.getAddressStatus(status.getAddress())); } // Issued keys assertEquals(18, newPocket.keys.getNumIssuedExternalKeys()); assertEquals(9, newPocket.keys.getNumIssuedInternalKeys()); newPocket.onConnection(getBlockchainConnection(DOGE)); // No addresses left to subscribe List<AbstractAddress> addressesToWatch = newPocket.getAddressesToWatch(); assertEquals(0, addressesToWatch.size()); // 18 external issued + 20 lookahead + 9 external issued + 20 lookahead assertEquals(67, newPocket.addressesStatus.size()); assertEquals(67, newPocket.addressesSubscribed.size()); } private void assertInputsEquals(List<TransactionInput> expected, List<TransactionInput> actual) { assertEquals(expected.size(), actual.size()); for (int i = 0; i < expected.size(); i++) { assertArrayEquals(expected.get(i).bitcoinSerialize(), actual.get(i).bitcoinSerialize()); } } private void assertOutputsEquals(List<TransactionOutput> expected, List<TransactionOutput> actual) { assertEquals(expected.size(), actual.size()); for (int i = 0; i < expected.size(); i++) { assertArrayEquals(expected.get(i).bitcoinSerialize(), actual.get(i).bitcoinSerialize()); } } @Test public void serializeUnencryptedEmpty() throws Exception { pocket.maybeInitializeAllKeys(); Protos.WalletPocket walletPocketProto = pocket.toProtobuf(); WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(walletPocketProto, null); assertEquals(walletPocketProto.toString(), newPocket.toProtobuf().toString()); // Issued keys assertEquals(0, newPocket.keys.getNumIssuedExternalKeys()); assertEquals(0, newPocket.keys.getNumIssuedInternalKeys()); // 20 lookahead + 20 lookahead assertEquals(40, newPocket.keys.getActiveKeys().size()); } @Test public void serializeEncryptedEmpty() throws Exception { pocket.maybeInitializeAllKeys(); pocket.encrypt(crypter, aesKey); Protos.WalletPocket walletPocketProto = pocket.toProtobuf(); WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(walletPocketProto, crypter); assertEquals(walletPocketProto.toString(), newPocket.toProtobuf().toString()); pocket.decrypt(aesKey); // One is encrypted, so they should not match assertNotEquals(pocket.toProtobuf().toString(), newPocket.toProtobuf().toString()); newPocket.decrypt(aesKey); assertEquals(pocket.toProtobuf().toString(), newPocket.toProtobuf().toString()); } @Test public void serializeEncryptedNormal() throws Exception { pocket.maybeInitializeAllKeys(); pocket.encrypt(crypter, aesKey); pocket.onConnection(getBlockchainConnection(DOGE)); assertEquals(DOGE.value(11000000000l), pocket.getBalance()); assertAllKeysEncrypted(pocket); WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(pocket.toProtobuf(), crypter); assertEquals(DOGE.value(11000000000l), newPocket.getBalance()); Map<TrimmedOutPoint, OutPointOutput> expectedUtxoSet = getDummyUtxoSet(); checkUnspentOutputs(expectedUtxoSet, pocket); checkUnspentOutputs(expectedUtxoSet, newPocket); assertAllKeysEncrypted(newPocket); pocket.decrypt(aesKey); newPocket.decrypt(aesKey); assertAllKeysDecrypted(pocket); assertAllKeysDecrypted(newPocket); } private void checkUnspentOutputs(Map<TrimmedOutPoint, OutPointOutput> expectedUtxoSet, WalletPocketHD pocket) { Map<TrimmedOutPoint, OutPointOutput> pocketUtxoSet = pocket.getUnspentOutputs(false); for (OutPointOutput utxo : expectedUtxoSet.values()) { assertEquals(utxo, pocketUtxoSet.get(utxo.getOutPoint())); } } private void assertAllKeysDecrypted(WalletPocketHD pocket) { List<ECKey> keys = pocket.keys.getKeys(false); for (ECKey k : keys) { DeterministicKey key = (DeterministicKey) k; assertFalse(key.isEncrypted()); } } private void assertAllKeysEncrypted(WalletPocketHD pocket) { List<ECKey> keys = pocket.keys.getKeys(false); for (ECKey k : keys) { DeterministicKey key = (DeterministicKey) k; assertTrue(key.isEncrypted()); } } @Test public void createDustTransactionFee() throws Exception { pocket.onConnection(getBlockchainConnection(DOGE)); BitAddress toAddr = BitAddress.from(DOGE, "nZB8PHkfgJvuCJqchSexmfY3ABXa2aE1vp"); Value softDust = DOGE.getSoftDustLimit(); assertNotNull(softDust); // Send a soft dust BitSendRequest sendRequest = pocket.sendCoinsOffline(toAddr, softDust.subtract(DOGE.value(1))); pocket.completeTransaction(sendRequest); assertEquals(DOGE.getFeeValue().multiply(2), sendRequest.tx.getFee()); } @Test public void createTransactionAndBroadcast() throws Exception { pocket.onConnection(getBlockchainConnection(DOGE)); BitAddress toAddr = BitAddress.from(DOGE, "nZB8PHkfgJvuCJqchSexmfY3ABXa2aE1vp"); Value orgBalance = pocket.getBalance(); BitSendRequest sendRequest = pocket.sendCoinsOffline(toAddr, DOGE.value(AMOUNT_TO_SEND)); sendRequest.shuffleOutputs = false; sendRequest.feePerTxSize = DOGE.value(0); pocket.completeTransaction(sendRequest); // FIXME, mock does not work here // pocket.broadcastTx(tx); pocket.addNewTransactionIfNeeded(sendRequest.tx); assertEquals(orgBalance.subtract(AMOUNT_TO_SEND), pocket.getBalance()); } // Util methods //////////////////////////////////////////////////////////////////////////////////////////////// public class MessageComparator implements Comparator<ChildMessage> { @Override public int compare(ChildMessage o1, ChildMessage o2) { String s1 = Utils.HEX.encode(o1.bitcoinSerialize()); String s2 = Utils.HEX.encode(o2.bitcoinSerialize()); return s1.compareTo(s2); } } HashMap<AbstractAddress, AddressStatus> getDummyStatuses() throws AddressMalformedException { HashMap<AbstractAddress, AddressStatus> status = new HashMap<>(40); for (int i = 0; i < addresses.size(); i++) { AbstractAddress address = DOGE.newAddress(addresses.get(i)); status.put(address, new AddressStatus(address, statuses[i])); } return status; } private HashMap<AbstractAddress, ArrayList<HistoryTx>> getDummyHistoryTXs() throws AddressMalformedException, JSONException { HashMap<AbstractAddress, ArrayList<HistoryTx>> htxs = new HashMap<>(40); for (int i = 0; i < statuses.length; i++) { JSONArray jsonArray = new JSONArray(history[i]); ArrayList<HistoryTx> list = new ArrayList<>(); for (int j = 0; j < jsonArray.length(); j++) { list.add(new HistoryTx(jsonArray.getJSONObject(j))); } htxs.put(DOGE.newAddress(addresses.get(i)), list); } return htxs; } private HashMap<AbstractAddress, ArrayList<UnspentTx>> getDummyUnspentTXs() throws AddressMalformedException, JSONException { HashMap<AbstractAddress, ArrayList<UnspentTx>> utxs = new HashMap<>(40); for (int i = 0; i < statuses.length; i++) { JSONArray jsonArray = new JSONArray(unspent[i]); ArrayList<UnspentTx> list = new ArrayList<>(); for (int j = 0; j < jsonArray.length(); j++) { list.add(new UnspentTx(jsonArray.getJSONObject(j))); } utxs.put(DOGE.newAddress(addresses.get(i)), list); } return utxs; } private Map<TrimmedOutPoint, OutPointOutput> getDummyUtxoSet() throws AddressMalformedException, JSONException { final HashMap<TrimmedOutPoint, OutPointOutput> unspentOutputs = new HashMap<>(); for (int i = 0; i < statuses.length; i++) { BitAddress address = (BitAddress) DOGE.newAddress(addresses.get(i)); JSONArray utxoArray = new JSONArray(unspent[i]); for (int j = 0; j < utxoArray.length(); j++) { JSONObject utxoObject = utxoArray.getJSONObject(j); //"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 11, \"value\": 500000000, \"height\": 160267}]", TrimmedOutPoint outPoint = new TrimmedOutPoint(DOGE, utxoObject.getInt("tx_pos"), new Sha256Hash(utxoObject.getString("tx_hash"))); TransactionOutput output = new TransactionOutput(DOGE, null, Coin.valueOf(utxoObject.getLong("value")), address); OutPointOutput utxo = new OutPointOutput(outPoint, output, false); unspentOutputs.put(outPoint, utxo); } } return unspentOutputs; } private HashMap<Sha256Hash, byte[]> getDummyRawTXs() throws AddressMalformedException, JSONException { HashMap<Sha256Hash, byte[]> rawTxs = new HashMap<>(); for (String[] tx : txs) { rawTxs.put(new Sha256Hash(tx[0]), Utils.HEX.decode(tx[1])); } return rawTxs; } class MockBlockchainConnection implements BitBlockchainConnection { final HashMap<AbstractAddress, AddressStatus> statuses; final HashMap<AbstractAddress, ArrayList<HistoryTx>> historyTxs; final HashMap<AbstractAddress, ArrayList<UnspentTx>> unspentTxs; final HashMap<Sha256Hash, byte[]> rawTxs; private CoinType coinType; MockBlockchainConnection(CoinType coinType) throws Exception { this.coinType = coinType; statuses = getDummyStatuses(); historyTxs = getDummyHistoryTXs(); unspentTxs = getDummyUnspentTXs(); rawTxs = getDummyRawTXs(); } @Override public void getBlock(int height, TransactionEventListener<BitTransaction> listener) { } @Override public void subscribeToBlockchain(TransactionEventListener<BitTransaction> listener) { listener.onNewBlock(new BlockHeader(coinType, blockTimestamp, blockHeight)); } @Override public void subscribeToAddresses(List<AbstractAddress> addresses, TransactionEventListener<BitTransaction> listener) { for (AbstractAddress a : addresses) { AddressStatus status = statuses.get(a); if (status == null) { status = new AddressStatus(a, null); } listener.onAddressStatusUpdate(status); } } @Override public void getHistoryTx(AddressStatus status, TransactionEventListener<BitTransaction> listener) { List<HistoryTx> htx = historyTxs.get(status.getAddress()); if (htx == null) { htx = ImmutableList.of(); } listener.onTransactionHistory(status, htx); } @Override public void getUnspentTx(AddressStatus status, BitTransactionEventListener listener) { List<UnspentTx> utx = unspentTxs.get(status.getAddress()); if (utx == null) { utx = ImmutableList.of(); } listener.onUnspentTransactionUpdate(status, utx); } @Override public void getTransaction(Sha256Hash txHash, TransactionEventListener<BitTransaction> listener) { BitTransaction tx = new BitTransaction(coinType, rawTxs.get(txHash)); listener.onTransactionUpdate(tx); } @Override public void broadcastTx(BitTransaction tx, TransactionEventListener<BitTransaction> listener) { // List<AddressStatus> newStatuses = new ArrayList<AddressStatus>(); // Random rand = new Random(); // byte[] randBytes = new byte[32]; // // Get spent outputs and modify statuses // for (TransactionInput txi : tx.getInputs()) { // UnspentTx unspentTx = new UnspentTx( // txi.getOutpoint(), txi.getValue().value, 0); // // for (Map.Entry<Address, ArrayList<UnspentTx>> entry : utxs.entrySet()) { // if (entry.getValue().remove(unspentTx)) { // rand.nextBytes(randBytes); // AddressStatus newStatus = new AddressStatus(entry.getKey(), Utils.HEX.encode(randBytes)); // statuses.put(entry.getKey(), newStatus); // newStatuses.add(newStatus); // } // } // } // // for (TransactionOutput txo : tx.getOutputs()) { // if (txo.getAddressFromP2PKHScript(coinType) != null) { // Address address = txo.getAddressFromP2PKHScript(coinType); // if (addresses.contains(address.toString())) { // AddressStatus newStatus = new AddressStatus(address, tx.getHashAsString()); // statuses.put(address, newStatus); // newStatuses.add(newStatus); // if (!utxs.containsKey(address)) { // utxs.put(address, new ArrayList<UnspentTx>()); // } // ArrayList<UnspentTx> unspentTxs = utxs.get(address); // unspentTxs.add(new UnspentTx(txo.getOutPointFor(), // txo.getValue().value, 0)); // if (!historyTxs.containsKey(address)) { // historyTxs.put(address, new ArrayList<HistoryTx>()); // } // ArrayList<HistoryTx> historyTxes = historyTxs.get(address); // historyTxes.add(new HistoryTx(txo.getOutPointFor(), 0)); // } // } // } // // rawTxs.put(tx.getHash(), tx.bitcoinSerialize()); // // for (AddressStatus newStatus : newStatuses) { // listener.onAddressStatusUpdate(newStatus); // } } @Override public boolean broadcastTxSync(BitTransaction tx) { return false; } @Override public void ping(String versionString) {} @Override public void addEventListener(ConnectionEventListener listener) { } @Override public void resetConnection() { } @Override public void stopAsync() { } @Override public boolean isActivelyConnected() { return false; } @Override public void startAsync() { } } private MockBlockchainConnection getBlockchainConnection(CoinType coinType) throws Exception { return new MockBlockchainConnection(coinType); } // Mock data long blockTimestamp = 1411000000l; int blockHeight = 200000; List<String> addresses = ImmutableList.of( "nnfP8VuPfZXhNtMDzvX1bKurzcV1k7HNrQ", "nf4AUKiaGdx4GTbbh222KvtuCbAuvbcdE2", "npGkmbWtdWybFNSZQXUK6zZxbEocMtrTzz", "nVaN45bbs6AUc1EUpP71hHGBGb2qciNrJc", "nrdHFZP1AfdKBrjsSQmwFm8R2i2mzMef75", "niGZgfbhFYn6tJqksmC8CnzSRL1GHNsu7e", "nh6w8yu1zoKYoT837ffkVmuPjTaP69Pc5E", "nbyMgmEghsL9tpk7XfdH9gLGudh6Lrbbuf", "naX9akzYuWY1gKbcZo3t36aBKc1gqbzgSs", "nqcPVTGeAfCowELB2D5PdVF3FWFjFtkkFf", "nd4vVvPTpp2LfcsMPsmG3Dh7MFAsqRHp4g", "nVK4Uz5Sf56ygrr6RiwXcRvH8AuUVbjjHi", "nbipkRwT1NCSXZSrm8uAAEgQAA2s2NWMkG", "nZU6QAMAdCQcVDxEmL7GEY6ykFm8m6u6am", "nbFqayssM5s7hLjLFwf2d95JXKRWBk2pBH", "nacZfcNgVi47hamLscWdUGQhUQGGpSdgq8", "niiMT7ZYeFnaLPYtqQFBBX1sP3dT5JtcEw", "ns6GyTaniLWaiYrvAf5tk4D8tWrbcCLGyj", "nhdwQfptLTzLJGbLF3vvtqyBaqPMPecDmE", "neMUAGeTzwxLbSkXMsdmWf1fTKS1UsJjXY", "nXsAMeXxtpx8jaxnU3Xv9ZQ6ZcRcD1xYhR", "ns35rKnnWf6xP3KSj5WPkMCVVaADGi6Ndk", "nk4wcXYBEWs5HkhNLsuaQJoAjJHoK6SQmG", "npsJQWu8fsALoTPum8D4j8FDkyeusk8fU8", "nZNhZo4Vz3DnwQGPL3SJTZgUw2Kh4g9oay", "nnxDTYB8WMHMgLnCY2tuaEtysvdhRnWehZ", "nb2iaDXG1EqkcE47H87WQFkQNkeVK66Z21", "nWHAkpn2DB3DJRsbiK3vpbigoa3M2uVuF8", "nViKdC7Gm6TMmCuWTBwVE9i4rJhyfwbfqg", "nZQV5BifbGPzaxTrB4efgHruWH5rufemqP", "nVvZaLvnkCVAzpLYPoHeqU4w9zJ5yrZgUn", "nrMp6pRCk98WYWkCWq9Pqthz9HbpQu8BT3", "nnA3aYsLqysKT6gAu1dr4EKm586cmKiRxS", "nVfcVgMY7DL6nqoSxwJy7B7hKXirQwj6ic", "ni4oAzi6nCVuEdjoHyVMVKWb1DqTd3qY3H", "nnpf3gx442yomniRJPMGPapgjHrraPZXxJ", "nkuFnF8wUmHFkMycaFMvyjBoiMeR5KBKGd", "nXKccwjaUyrQkLrdqKT6aq6cDiFgBBVgNz", "nZMSNsXSAL7i1YD6KP5FrhATuZ2CWvnxqR", "nUEkQ3LjH9m4ScbP6NGtnAdnnUsdtWv99Q" ); String[] statuses = { "fe7c109d8bd90551a406cf0b3499117db04bc9c4f48e1df27ac1cf3ddcb3d464", "8a53babd831c6c3a857e20190e884efe75a005bdd7cd273c4f27ab1b8ec81c2d", "86bc2f0cf0112fd59c9aadfe5c887062c21d7a873db260dff68dcfe4417fe212", "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, null, null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, null, null, null, null, null, null, null, null, null }; String[] unspent = { "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 0, \"value\": 500000000, \"height\": 160267}, {\"tx_hash\": \"89a72ba4732505ce9b09c30668db985952701252ce0adbd7c43336396697d6ae\", \"tx_pos\": 0, \"value\": 500000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 1, \"value\": 1000000000, \"height\": 160267}, {\"tx_hash\": \"edaf445288d8e65cf7963bc8047c90f53681acaadc5ccfc5ecc67aedbd73cddb\", \"tx_pos\": 0, \"value\": 500000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 2, \"value\": 500000000, \"height\": 160267}, {\"tx_hash\": \"81a1f0f8242d5e71e65ff9e8ec51e8e85d641b607d7f691c1770d4f25918ebd7\", \"tx_pos\": 0, \"value\": 1000000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 3, \"value\": 500000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 4, \"value\": 1000000000, \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 11, \"value\": 500000000, \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 12, \"value\": 1000000000, \"height\": 160267}]", "[]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 13, \"value\": 500000000, \"height\": 160267}]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 6, \"value\": 500000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 7, \"value\": 1000000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 8, \"value\": 500000000, \"height\": 160267}]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 9, \"value\": 500000000, \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 10, \"value\": 1000000000, \"height\": 160267}]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]" }; String[] history = { "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}, {\"tx_hash\": \"89a72ba4732505ce9b09c30668db985952701252ce0adbd7c43336396697d6ae\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}, {\"tx_hash\": \"edaf445288d8e65cf7963bc8047c90f53681acaadc5ccfc5ecc67aedbd73cddb\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}, {\"tx_hash\": \"81a1f0f8242d5e71e65ff9e8ec51e8e85d641b607d7f691c1770d4f25918ebd7\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]" }; String[][] txs = { {"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f", "0100000001b8778dff640ccb144346d9db48201639b2707a0cc59e19672d2dd76cc6d1a5a6010000006b48304502210098d2e5b8a6c72442430bc09f2f4bcb56612c5b9e5eee821d65b412d099bb723402204f7f008ac052e5d7be0ab5b0c85ea5e627d725a521bd9e9b193d1fdf81c317a0012102d26e423c9da9ff4a7bf6b756b2dafb75cca34fbd34f64c4c3b77c37179c5bba2ffffffff0e0065cd1d000000001976a914ca983c2da690de3cdc693ca013d93e569810c52c88ac00ca9a3b000000001976a91477263ab93a49b1d3eb5887187704cdb82e1c60ce88ac0065cd1d000000001976a914dc40fbbc8caa1f7617d275aec9a3a14ce8d8652188ac0065cd1d000000001976a9140f2b1e5b376e22c5d1e635233eb90cf50ad9095188ac00ca9a3b000000001976a914f612ffd50b6a69df5e34ee0c5b529dfaaedca03d88ac00f633bce60000001976a914937258e3a8c463ec07e78ce62326c488170ad25e88ac0065cd1d000000001976a9142848ad5ff4cc32df3649646017c47bc04e8d211788ac00ca9a3b000000001976a914fa937737a6df2b8a5e39cce8b0bdd9510683023a88ac0065cd1d000000001976a914ae248a5d710143b6b309aaab9ce17059536e2aa388ac0065cd1d000000001976a91438d6eb11eca405be497a7183c50e437851425e0088ac00ca9a3b000000001976a91410ac6b2704146b50a1dd8f6df70736856ebf8b3488ac0065cd1d000000001976a914456816dccb3a4f33ae2dbd3ba623997075d5c73d88ac00ca9a3b000000001976a91452957c44e5bee9a60402a739fc8959c2850ea98488ac0065cd1d000000001976a914fb2dffa402d05f74335d137e21e41d8920c745fb88ac00000000"}, {"89a72ba4732505ce9b09c30668db985952701252ce0adbd7c43336396697d6ae", "01000000011a656d67706db286d1e6fad57eb4f411cb14f8880cea8348da339b9d434a5ec7050000006a47304402201d69fddb269b53aa742ff6437a45adb4ca5c59f666c9b4eabc4a0c7a6e6f4c0f022015a747b7a6d9371a4020f5b396dcd094b0f36af3fc82e95091da856181912dfa012102c9a8d5b2f768afe30ee772d185e7a61f751be05649a79508b38a2be8824adec3ffffffff020065cd1d000000001976a914ca983c2da690de3cdc693ca013d93e569810c52c88ac00b07098e60000001976a9141630d812e219e6bcbe494eb96f7a7900c216ad5d88ac00000000"}, {"edaf445288d8e65cf7963bc8047c90f53681acaadc5ccfc5ecc67aedbd73cddb", "010000000164a3990893c012b20287d43d1071ac26f4b93648ff4213db6da6979beed6b7dc010000006b48304502210086ac11d4a8146b4176a72059960690c72a9776468cd671fd07c064b51f24961d02205bcf008d6995014f3cfd79100ee9beab5688c88cca15c5cea38b769563785d900121036530415a7b3b9c5976f26a63a57d119ab39491762121723c773399a2531a1bd7ffffffff020065cd1d000000001976a91477263ab93a49b1d3eb5887187704cdb82e1c60ce88ac006aad74e60000001976a914e5616848352c328c9f61b167eb1b0fde39b5cb6788ac00000000"}, {"81a1f0f8242d5e71e65ff9e8ec51e8e85d641b607d7f691c1770d4f25918ebd7", "010000000141c217dfea3a1d8d6a06e9d3daf75b292581f652256d73a7891e5dc9c7ee3cca000000006a47304402205cce451228f98fece9645052546b82c2b2d425a4889b03999001fababfc7f4690220583b2189faef07d6b0191c788301cfab1b3f47ffe2c403d632b92c6dde27e14f012102d26e423c9da9ff4a7bf6b756b2dafb75cca34fbd34f64c4c3b77c37179c5bba2ffffffff0100ca9a3b000000001976a914dc40fbbc8caa1f7617d275aec9a3a14ce8d8652188ac00000000"} }; }
vergecurrency/tordroid
core/src/test/java/com/coinomi/core/wallet/WalletPocketHDTest.java
45,939
package com.coinomi.core.wallet; import com.coinomi.core.coins.BitcoinMain; import com.coinomi.core.coins.CoinType; import com.coinomi.core.coins.DogecoinTest; import com.coinomi.core.coins.NuBitsMain; import com.coinomi.core.coins.VpncoinMain; import com.coinomi.core.network.AddressStatus; import com.coinomi.core.network.ServerClient.HistoryTx; import com.coinomi.core.network.interfaces.BlockchainConnection; import com.coinomi.core.network.interfaces.TransactionEventListener; import com.coinomi.core.protos.Protos; import com.coinomi.core.wallet.exceptions.AddressMalformedException; import com.coinomi.core.wallet.exceptions.Bip44KeyLookAheadExceededException; import com.coinomi.core.wallet.exceptions.KeyIsEncryptedException; import com.coinomi.core.wallet.exceptions.MissingPrivateKeyException; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import org.bitcoinj.core.Address; import org.bitcoinj.core.AddressFormatException; import org.bitcoinj.core.ChildMessage; import org.bitcoinj.core.Coin; import org.bitcoinj.core.ECKey; import org.bitcoinj.core.Sha256Hash; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.Utils; import org.bitcoinj.crypto.DeterministicHierarchy; import org.bitcoinj.crypto.DeterministicKey; import org.bitcoinj.crypto.HDKeyDerivation; import org.bitcoinj.crypto.KeyCrypter; import org.bitcoinj.crypto.KeyCrypterScrypt; import org.bitcoinj.store.UnreadableWalletException; import org.bitcoinj.utils.BriefLogFormatter; import org.bitcoinj.wallet.DeterministicSeed; import org.bitcoinj.wallet.KeyChain; import org.json.JSONArray; import org.json.JSONException; import org.junit.Before; import org.junit.Test; import org.spongycastle.crypto.params.KeyParameter; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Set; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; /** * @author John L. Jegutanis */ public class WalletPocketHDTest { static final CoinType BTC = BitcoinMain.get(); static final CoinType DOGE = DogecoinTest.get(); static final CoinType NBT = NuBitsMain.get(); static final CoinType VPN = VpncoinMain.get(); static final List<String> MNEMONIC = ImmutableList.of("citizen", "fever", "scale", "nurse", "brief", "round", "ski", "fiction", "car", "fitness", "pluck", "act"); static final byte[] AES_KEY_BYTES = {0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7}; static final long AMOUNT_TO_SEND = 2700000000L; static final String MESSAGE = "test"; static final String MESSAGE_UNICODE = "δοκιμή испытание 测试"; static final String EXPECTED_BITCOIN_SIG = "IMBbIFDDuUwomYlvSjwWytqP/CXYym2yOKbJUx8Y+ujzZKBwoCFMr73GUxpr1Ird/DvnNZcsQLphvx18ftqN54o="; static final String EXPECTED_BITCOIN_SIG_UNICODE = "IGGZEOBsVny5dozTOfc2/3UuvmZGdDI4XK/03HIk34PILd2oXbnq+87GINT3lumeXcgSO2NkGzUFcQ1SCSVI3Hk="; static final String EXPECTED_NUBITS_SIG = "IMuzNZTZIjZjLicyDFGzqFl21vqNBGW1N5m4qHBRqbTvLBbkQeGjraeLmZEt7mRH4MSMPLFXW2T3Maz+HYx1tEc="; static final String EXPECTED_NUBITS_SIG_UNICODE = "Hx7xkBbboXrp96dbQrJFzm2unTGwLstjbWlKa1/N1E4LJqbwJAJR1qIvwXm6LHQFnLOzwoQA45zYNjwUEPMc8sg="; DeterministicSeed seed; DeterministicKey masterKey; DeterministicHierarchy hierarchy; DeterministicKey rootKey; WalletPocketHD pocket; KeyParameter aesKey; KeyCrypter crypter; @Before public void setup() { BriefLogFormatter.init(); seed = new DeterministicSeed(MNEMONIC, null, "", 0); masterKey = HDKeyDerivation.createMasterPrivateKey(seed.getSeedBytes()); hierarchy = new DeterministicHierarchy(masterKey); rootKey = hierarchy.get(DOGE.getBip44Path(0), false, true); aesKey = new KeyParameter(AES_KEY_BYTES); crypter = new KeyCrypterScrypt(); pocket = new WalletPocketHD(rootKey, DOGE, null, null); pocket.keys.setLookaheadSize(20); } @Test public void xpubWallet() { String xpub = "xpub67tVq9TLPPoaHVSiYu8mqahm3eztTPUts6JUftNq3pZF1PJwjknrTqQhjc2qRGd6vS8wANu7mLnqkiUzFZ1xZsAZoUMi8o6icMhzGCAhcSW"; DeterministicKey key = DeterministicKey.deserializeB58(null, xpub); WalletPocketHD account = new WalletPocketHD(key, BTC, null, null); assertEquals("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", account.getReceiveAddress().toString()); account = new WalletPocketHD(key, NBT, null, null); assertEquals("BNvJUwg3BgkbQk5br1CxvHxdcDp1EC3saE", account.getReceiveAddress().toString()); } @Test public void xpubWalletSerialized() throws Exception { WalletPocketHD account = new WalletPocketHD(rootKey, BTC, null, null); Protos.WalletPocket proto = account.toProtobuf(); WalletPocketHD newAccount = new WalletPocketProtobufSerializer().readWallet(proto, null); assertEquals(account.getPublicKeySerialized(), newAccount.getPublicKeySerialized()); } @Test public void signMessage() throws AddressMalformedException, MissingPrivateKeyException, KeyIsEncryptedException { WalletPocketHD pocketHD = new WalletPocketHD(rootKey, BTC, null, null); pocketHD.getReceiveAddress(); // Generate the first key SignedMessage signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE); pocketHD.signMessage(signedMessage, null); assertEquals(EXPECTED_BITCOIN_SIG, signedMessage.getSignature()); signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE_UNICODE); pocketHD.signMessage(signedMessage, null); assertEquals(EXPECTED_BITCOIN_SIG_UNICODE, signedMessage.getSignature()); pocketHD = new WalletPocketHD(rootKey, NBT, null, null); pocketHD.getReceiveAddress(); // Generate the first key signedMessage = new SignedMessage("BNvJUwg3BgkbQk5br1CxvHxdcDp1EC3saE", MESSAGE); pocketHD.signMessage(signedMessage, null); assertEquals(EXPECTED_NUBITS_SIG, signedMessage.getSignature()); signedMessage = new SignedMessage("BNvJUwg3BgkbQk5br1CxvHxdcDp1EC3saE", MESSAGE_UNICODE); pocketHD.signMessage(signedMessage, null); assertEquals(EXPECTED_NUBITS_SIG_UNICODE, signedMessage.getSignature()); } @Test public void signMessageEncrypted() throws AddressMalformedException, MissingPrivateKeyException, KeyIsEncryptedException { WalletPocketHD pocketHD = new WalletPocketHD(rootKey, BTC, null, null); pocketHD.getReceiveAddress(); // Generate the first key pocketHD.encrypt(crypter, aesKey); SignedMessage signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE); pocketHD.signMessage(signedMessage, aesKey); assertEquals(EXPECTED_BITCOIN_SIG, signedMessage.getSignature()); signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE_UNICODE); pocketHD.signMessage(signedMessage, aesKey); assertEquals(EXPECTED_BITCOIN_SIG_UNICODE, signedMessage.getSignature()); } @Test public void signMessageEncryptedFailed() throws AddressMalformedException, MissingPrivateKeyException, KeyIsEncryptedException { WalletPocketHD pocketHD = new WalletPocketHD(rootKey, BTC, null, null); pocketHD.getReceiveAddress(); // Generate the first key pocketHD.encrypt(crypter, aesKey); SignedMessage signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE); pocketHD.signMessage(signedMessage, null); assertEquals(SignedMessage.Status.KeyIsEncrypted, signedMessage.status); } @Test public void watchingAddresses() { List<Address> watchingAddresses = pocket.getAddressesToWatch(); assertEquals(40, watchingAddresses.size()); // 20 + 20 lookahead size for (int i = 0; i < addresses.size(); i++) { assertEquals(addresses.get(i), watchingAddresses.get(i).toString()); } } @Test public void issuedKeys() throws Bip44KeyLookAheadExceededException { LinkedList<Address> issuedAddresses = new LinkedList<Address>(); assertEquals(0, pocket.getIssuedReceiveAddresses().size()); assertEquals(0, pocket.keys.getNumIssuedExternalKeys()); issuedAddresses.add(0, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS)); Address freshAddress = pocket.getFreshReceiveAddress(); assertEquals(freshAddress, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS)); assertEquals(1, pocket.getIssuedReceiveAddresses().size()); assertEquals(1, pocket.keys.getNumIssuedExternalKeys()); assertEquals(issuedAddresses, pocket.getIssuedReceiveAddresses()); issuedAddresses.add(0, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS)); freshAddress = pocket.getFreshReceiveAddress(); assertEquals(freshAddress, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS)); assertEquals(2, pocket.getIssuedReceiveAddresses().size()); assertEquals(2, pocket.keys.getNumIssuedExternalKeys()); assertEquals(issuedAddresses, pocket.getIssuedReceiveAddresses()); } @Test public void issuedKeysLimit() throws Exception { assertTrue(pocket.canCreateFreshReceiveAddress()); try { for (int i = 0; i < 100; i++) { pocket.getFreshReceiveAddress(); } } catch (Bip44KeyLookAheadExceededException e) { assertFalse(pocket.canCreateFreshReceiveAddress()); // We haven't used any key so the total must be 20 - 1 (the unused key) assertEquals(19, pocket.getNumberIssuedReceiveAddresses()); assertEquals(19, pocket.getIssuedReceiveAddresses().size()); } pocket.onConnection(getBlockchainConnection(DOGE)); assertTrue(pocket.canCreateFreshReceiveAddress()); try { for (int i = 0; i < 100; i++) { pocket.getFreshReceiveAddress(); } } catch (Bip44KeyLookAheadExceededException e) { try { pocket.getFreshReceiveAddress(); } catch (Bip44KeyLookAheadExceededException e1) { } assertFalse(pocket.canCreateFreshReceiveAddress()); // We used 18, so the total must be (20-1)+18=37 assertEquals(37, pocket.getNumberIssuedReceiveAddresses()); assertEquals(37, pocket.getIssuedReceiveAddresses().size()); } } @Test public void issuedKeysLimit2() throws Exception { assertTrue(pocket.canCreateFreshReceiveAddress()); try { for (int i = 0; i < 100; i++) { pocket.getFreshReceiveAddress(); } } catch (Bip44KeyLookAheadExceededException e) { assertFalse(pocket.canCreateFreshReceiveAddress()); // We haven't used any key so the total must be 20 - 1 (the unused key) assertEquals(19, pocket.getNumberIssuedReceiveAddresses()); assertEquals(19, pocket.getIssuedReceiveAddresses().size()); } } @Test public void usedAddresses() throws Exception { assertEquals(0, pocket.getUsedAddresses().size()); pocket.onConnection(getBlockchainConnection(DOGE)); // Receive and change addresses assertEquals(13, pocket.getUsedAddresses().size()); } private Transaction send(Coin value, WalletPocketHD w1, WalletPocketHD w2) throws Exception { SendRequest req; req = w1.sendCoinsOffline(w2.getReceiveAddress(), value); req.feePerKb = Coin.ZERO; w1.completeAndSignTx(req); byte[] txBytes = req.tx.bitcoinSerialize(); w1.addNewTransactionIfNeeded(new Transaction(w1.getCoinType(), txBytes)); w2.addNewTransactionIfNeeded(new Transaction(w1.getCoinType(), txBytes)); return req.tx; } @Test public void testSendingAndBalances() throws Exception { DeterministicHierarchy h = new DeterministicHierarchy(masterKey); WalletPocketHD account1 = new WalletPocketHD(h.get(BTC.getBip44Path(0), false, true), BTC, null, null); WalletPocketHD account2 = new WalletPocketHD(h.get(BTC.getBip44Path(1), false, true), BTC, null, null); WalletPocketHD account3 = new WalletPocketHD(h.get(BTC.getBip44Path(2), false, true), BTC, null, null); Transaction tx = new Transaction(BTC); tx.addOutput(BTC.oneCoin().toCoin(), account1.getReceiveAddress()); account1.addNewTransactionIfNeeded(tx); assertEquals(BTC.value("1"), account1.getBalance()); assertEquals(BTC.value("0"), account2.getBalance()); assertEquals(BTC.value("0"), account3.getBalance()); send(Coin.CENT.multiply(5), account1, account2); assertEquals(BTC.value("0.95"), account1.getBalance()); assertEquals(BTC.value("0.05"), account2.getBalance()); assertEquals(BTC.value("0"), account3.getBalance()); send(Coin.CENT.multiply(7), account1, account3); assertEquals(BTC.value("0.88"), account1.getBalance()); assertEquals(BTC.value("0.05"), account2.getBalance()); assertEquals(BTC.value("0.07"), account3.getBalance()); send(Coin.CENT.multiply(3), account2, account3); assertEquals(BTC.value("0.88"), account1.getBalance()); assertEquals(BTC.value("0.02"), account2.getBalance()); assertEquals(BTC.value("0.1"), account3.getBalance()); } @Test public void fillTransactions() throws Exception { pocket.onConnection(getBlockchainConnection(DOGE)); // Issued keys assertEquals(18, pocket.keys.getNumIssuedExternalKeys()); assertEquals(9, pocket.keys.getNumIssuedInternalKeys()); // No addresses left to subscribe List<Address> addressesToWatch = pocket.getAddressesToWatch(); assertEquals(0, addressesToWatch.size()); // 18 external issued + 20 lookahead + 9 external issued + 20 lookahead assertEquals(67, pocket.addressesStatus.size()); assertEquals(67, pocket.addressesSubscribed.size()); Address receiveAddr = pocket.getReceiveAddress(); // This key is not issued assertEquals(18, pocket.keys.getNumIssuedExternalKeys()); assertEquals(67, pocket.addressesStatus.size()); assertEquals(67, pocket.addressesSubscribed.size()); DeterministicKey key = pocket.keys.findKeyFromPubHash(receiveAddr.getHash160()); assertNotNull(key); // 18 here is the key index, not issued keys count assertEquals(18, key.getChildNumber().num()); assertEquals(11000000000L, pocket.getBalance().value); // TODO added more tests to insure it uses the "holes" in the keychain } @Test public void serializeTransactionsBtc() throws Exception, Bip44KeyLookAheadExceededException { WalletPocketHD account = new WalletPocketHD(rootKey, BTC, null, null); Transaction tx = new Transaction(BTC); tx.addOutput(BTC.oneCoin().toCoin(), account.getReceiveAddress()); account.addNewTransactionIfNeeded(tx); testWalletSerializationForCoin(account); } @Test public void serializeTransactionsNbt() throws Exception, Bip44KeyLookAheadExceededException { WalletPocketHD account = new WalletPocketHD(rootKey, NBT, null, null); Transaction tx = new Transaction(NBT); tx.addOutput(NBT.oneCoin().toCoin(), account.getReceiveAddress()); account.addNewTransactionIfNeeded(tx); testWalletSerializationForCoin(account); } @Test public void serializeTransactionsVpn() throws Exception, Bip44KeyLookAheadExceededException { WalletPocketHD account = new WalletPocketHD(rootKey, VPN, null, null); // Test tx with null extra bytes Transaction tx = new Transaction(VPN); tx.setTime(0x99999999); tx.addOutput(VPN.oneCoin().toCoin(), account.getFreshReceiveAddress()); account.addNewTransactionIfNeeded(tx); WalletPocketHD newAccount = testWalletSerializationForCoin(account); Transaction newTx = newAccount.getTransaction(tx.getHash()); assertNotNull(newTx.getExtraBytes()); assertEquals(0, newTx.getExtraBytes().length); // Test tx with empty extra bytes tx = new Transaction(VPN); tx.setTime(0x99999999); tx.setExtraBytes(new byte[0]); tx.addOutput(VPN.oneCoin().toCoin(), account.getFreshReceiveAddress()); account.addNewTransactionIfNeeded(tx); newAccount = testWalletSerializationForCoin(account); newTx = newAccount.getTransaction(tx.getHash()); assertNotNull(newTx.getExtraBytes()); assertEquals(0, newTx.getExtraBytes().length); // Test tx with extra bytes tx = new Transaction(VPN); tx.setTime(0x99999999); byte[] bytes = {0x1, 0x2, 0x3}; tx.setExtraBytes(bytes); tx.addOutput(VPN.oneCoin().toCoin(), account.getFreshReceiveAddress()); account.addNewTransactionIfNeeded(tx); newAccount = testWalletSerializationForCoin(account); newTx = newAccount.getTransaction(tx.getHash()); assertArrayEquals(bytes, newTx.getExtraBytes()); } private WalletPocketHD testWalletSerializationForCoin(WalletPocketHD account) throws UnreadableWalletException { Protos.WalletPocket proto = account.toProtobuf(); WalletPocketHD newAccount = new WalletPocketProtobufSerializer().readWallet(proto, null); assertEquals(account.getBalance().value, newAccount.getBalance().value); Set<Transaction> transactions = account.getTransactions(false); Set<Transaction> newTransactions = newAccount.getTransactions(false); for (Transaction tx : transactions) { assertTrue(newTransactions.contains(tx)); } return newAccount; } @Test public void serializeUnencryptedNormal() throws Exception { pocket.onConnection(getBlockchainConnection(DOGE)); Protos.WalletPocket walletPocketProto = pocket.toProtobuf(); WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(walletPocketProto, null); assertEquals(pocket.getBalance().value, newPocket.getBalance().value); assertEquals(pocket.getCoinType(), newPocket.getCoinType()); assertEquals(pocket.getDescription(), newPocket.getDescription()); assertEquals(pocket.keys.toProtobuf().toString(), newPocket.keys.toProtobuf().toString()); assertEquals(pocket.getLastBlockSeenHash(), newPocket.getLastBlockSeenHash()); assertEquals(pocket.getLastBlockSeenHeight(), newPocket.getLastBlockSeenHeight()); assertEquals(pocket.getLastBlockSeenTimeSecs(), newPocket.getLastBlockSeenTimeSecs()); for (Transaction tx : pocket.getTransactions(false)) { assertEquals(tx, newPocket.getTransaction(tx.getHash())); } for (AddressStatus status : pocket.getAllAddressStatus()) { if (status.getStatus() == null) continue; assertEquals(status, newPocket.getAddressStatus(status.getAddress())); } // Issued keys assertEquals(18, newPocket.keys.getNumIssuedExternalKeys()); assertEquals(9, newPocket.keys.getNumIssuedInternalKeys()); newPocket.onConnection(getBlockchainConnection(DOGE)); // No addresses left to subscribe List<Address> addressesToWatch = newPocket.getAddressesToWatch(); assertEquals(0, addressesToWatch.size()); // 18 external issued + 20 lookahead + 9 external issued + 20 lookahead assertEquals(67, newPocket.addressesStatus.size()); assertEquals(67, newPocket.addressesSubscribed.size()); } @Test public void serializeUnencryptedEmpty() throws Exception { pocket.maybeInitializeAllKeys(); Protos.WalletPocket walletPocketProto = pocket.toProtobuf(); WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(walletPocketProto, null); assertEquals(walletPocketProto.toString(), newPocket.toProtobuf().toString()); // Issued keys assertEquals(0, newPocket.keys.getNumIssuedExternalKeys()); assertEquals(0, newPocket.keys.getNumIssuedInternalKeys()); // 20 lookahead + 20 lookahead assertEquals(40, newPocket.keys.getActiveKeys().size()); } @Test public void serializeEncryptedEmpty() throws Exception { pocket.maybeInitializeAllKeys(); pocket.encrypt(crypter, aesKey); Protos.WalletPocket walletPocketProto = pocket.toProtobuf(); WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(walletPocketProto, crypter); assertEquals(walletPocketProto.toString(), newPocket.toProtobuf().toString()); pocket.decrypt(aesKey); // One is encrypted, so they should not match assertNotEquals(pocket.toProtobuf().toString(), newPocket.toProtobuf().toString()); newPocket.decrypt(aesKey); assertEquals(pocket.toProtobuf().toString(), newPocket.toProtobuf().toString()); } @Test public void serializeEncryptedNormal() throws Exception { pocket.maybeInitializeAllKeys(); pocket.encrypt(crypter, aesKey); pocket.onConnection(getBlockchainConnection(DOGE)); assertEquals(DOGE.value(11000000000l), pocket.getBalance()); assertAllKeysEncrypted(pocket); WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(pocket.toProtobuf(), crypter); assertAllKeysEncrypted(newPocket); pocket.decrypt(aesKey); newPocket.decrypt(aesKey); assertAllKeysDecrypted(pocket); assertAllKeysDecrypted(newPocket); } private void assertAllKeysDecrypted(WalletPocketHD pocket) { List<ECKey> keys = pocket.keys.getKeys(false); for (ECKey k : keys) { DeterministicKey key = (DeterministicKey) k; assertFalse(key.isEncrypted()); } } private void assertAllKeysEncrypted(WalletPocketHD pocket) { List<ECKey> keys = pocket.keys.getKeys(false); for (ECKey k : keys) { DeterministicKey key = (DeterministicKey) k; assertTrue(key.isEncrypted()); } } @Test public void createDustTransactionFee() throws Exception { pocket.onConnection(getBlockchainConnection(DOGE)); Address toAddr = new Address(DOGE, "nUEkQ3LjH9m4ScbP6NGtnAdnnUsdtWv99Q"); Coin softDust = DOGE.getSoftDustLimit(); assertNotNull(softDust); // Send a soft dust SendRequest sendRequest = pocket.sendCoinsOffline(toAddr, softDust.subtract(Coin.SATOSHI)); pocket.completeTx(sendRequest); assertEquals(DOGE.getFeePerKb().multiply(2), sendRequest.tx.getFee()); } @Test public void createTransactionAndBroadcast() throws Exception { pocket.onConnection(getBlockchainConnection(DOGE)); Address toAddr = new Address(DOGE, "nUEkQ3LjH9m4ScbP6NGtnAdnnUsdtWv99Q"); long orgBalance = pocket.getBalance().value; SendRequest sendRequest = pocket.sendCoinsOffline(toAddr, Coin.valueOf(AMOUNT_TO_SEND)); sendRequest.shuffleOutputs = false; pocket.completeTx(sendRequest); Transaction tx = sendRequest.tx; assertEquals(expectedTx, Utils.HEX.encode(tx.bitcoinSerialize())); // FIXME, mock does not work here // pocket.broadcastTx(tx); // assertEquals(orgBalance - AMOUNT_TO_SEND, pocket.getBalance().value); } // Util methods //////////////////////////////////////////////////////////////////////////////////////////////// public class MessageComparator implements Comparator<ChildMessage> { @Override public int compare(ChildMessage o1, ChildMessage o2) { String s1 = Utils.HEX.encode(o1.bitcoinSerialize()); String s2 = Utils.HEX.encode(o2.bitcoinSerialize()); return s1.compareTo(s2); } } HashMap<Address, AddressStatus> getDummyStatuses() throws AddressFormatException { HashMap<Address, AddressStatus> status = new HashMap<Address, AddressStatus>(40); for (int i = 0; i < addresses.size(); i++) { Address address = new Address(DOGE, addresses.get(i)); status.put(address, new AddressStatus(address, statuses[i])); } return status; } // private HashMap<Address, ArrayList<UnspentTx>> getDummyUTXs() throws AddressFormatException, JSONException { // HashMap<Address, ArrayList<UnspentTx>> utxs = new HashMap<Address, ArrayList<UnspentTx>>(40); // // for (int i = 0; i < statuses.length; i++) { // List<UnspentTx> utxList = (List<UnspentTx>) UnspentTx.fromArray(new JSONArray(unspent[i])); // utxs.put(new Address(DOGE, addresses.get(i)), Lists.newArrayList(utxList)); // } // // return utxs; // } private HashMap<Address, ArrayList<HistoryTx>> getDummyHistoryTXs() throws AddressFormatException, JSONException { HashMap<Address, ArrayList<HistoryTx>> htxs = new HashMap<Address, ArrayList<HistoryTx>>(40); for (int i = 0; i < statuses.length; i++) { List<HistoryTx> utxList = (List<HistoryTx>) HistoryTx.fromArray(new JSONArray(unspent[i])); htxs.put(new Address(DOGE, addresses.get(i)), Lists.newArrayList(utxList)); } return htxs; } private HashMap<Sha256Hash, byte[]> getDummyRawTXs() throws AddressFormatException, JSONException { HashMap<Sha256Hash, byte[]> rawTxs = new HashMap<Sha256Hash, byte[]>(); for (int i = 0; i < txs.length; i++) { String[] txEntry = txs[i]; rawTxs.put(new Sha256Hash(txs[i][0]), Utils.HEX.decode(txs[i][1])); } return rawTxs; } class MockBlockchainConnection implements BlockchainConnection { final HashMap<Address, AddressStatus> statuses; // final HashMap<Address, ArrayList<UnspentTx>> utxs; final HashMap<Address, ArrayList<HistoryTx>> historyTxs; final HashMap<Sha256Hash, byte[]> rawTxs; private CoinType coinType; MockBlockchainConnection(CoinType coinType) throws Exception { this.coinType = coinType; statuses = getDummyStatuses(); // utxs = getDummyUTXs(); historyTxs = getDummyHistoryTXs(); rawTxs = getDummyRawTXs(); } @Override public void subscribeToBlockchain(TransactionEventListener listener) { } @Override public void subscribeToAddresses(List<Address> addresses, TransactionEventListener listener) { for (Address a : addresses) { AddressStatus status = statuses.get(a); if (status == null) { status = new AddressStatus(a, null); } listener.onAddressStatusUpdate(status); } } // @Override // public void getUnspentTx(AddressStatus status, TransactionEventListener listener) { // List<UnspentTx> utx = utxs.get(status.getAddress()); // if (status == null) { // utx = ImmutableList.of(); // } // listener.onUnspentTransactionUpdate(status, utx); // } @Override public void getHistoryTx(AddressStatus status, TransactionEventListener listener) { List<HistoryTx> htx = historyTxs.get(status.getAddress()); if (status == null) { htx = ImmutableList.of(); } listener.onTransactionHistory(status, htx); } @Override public void getTransaction(Sha256Hash txHash, TransactionEventListener listener) { Transaction tx = new Transaction(coinType, rawTxs.get(txHash)); listener.onTransactionUpdate(tx); } @Override public void broadcastTx(Transaction tx, TransactionEventListener listener) { // List<AddressStatus> newStatuses = new ArrayList<AddressStatus>(); // Random rand = new Random(); // byte[] randBytes = new byte[32]; // // Get spent outputs and modify statuses // for (TransactionInput txi : tx.getInputs()) { // UnspentTx unspentTx = new UnspentTx( // txi.getOutpoint(), txi.getValue().value, 0); // // for (Map.Entry<Address, ArrayList<UnspentTx>> entry : utxs.entrySet()) { // if (entry.getValue().remove(unspentTx)) { // rand.nextBytes(randBytes); // AddressStatus newStatus = new AddressStatus(entry.getKey(), Utils.HEX.encode(randBytes)); // statuses.put(entry.getKey(), newStatus); // newStatuses.add(newStatus); // } // } // } // // for (TransactionOutput txo : tx.getOutputs()) { // if (txo.getAddressFromP2PKHScript(coinType) != null) { // Address address = txo.getAddressFromP2PKHScript(coinType); // if (addresses.contains(address.toString())) { // AddressStatus newStatus = new AddressStatus(address, tx.getHashAsString()); // statuses.put(address, newStatus); // newStatuses.add(newStatus); // if (!utxs.containsKey(address)) { // utxs.put(address, new ArrayList<UnspentTx>()); // } // ArrayList<UnspentTx> unspentTxs = utxs.get(address); // unspentTxs.add(new UnspentTx(txo.getOutPointFor(), // txo.getValue().value, 0)); // if (!historyTxs.containsKey(address)) { // historyTxs.put(address, new ArrayList<HistoryTx>()); // } // ArrayList<HistoryTx> historyTxes = historyTxs.get(address); // historyTxes.add(new HistoryTx(txo.getOutPointFor(), 0)); // } // } // } // // rawTxs.put(tx.getHash(), tx.bitcoinSerialize()); // // for (AddressStatus newStatus : newStatuses) { // listener.onAddressStatusUpdate(newStatus); // } } @Override public boolean broadcastTxSync(Transaction tx) { return false; } @Override public void ping() {} } private MockBlockchainConnection getBlockchainConnection(CoinType coinType) throws Exception { return new MockBlockchainConnection(coinType); } // Mock data List<String> addresses = ImmutableList.of( "nnfP8VuPfZXhNtMDzvX1bKurzcV1k7HNrQ", "nf4AUKiaGdx4GTbbh222KvtuCbAuvbcdE2", "npGkmbWtdWybFNSZQXUK6zZxbEocMtrTzz", "nVaN45bbs6AUc1EUpP71hHGBGb2qciNrJc", "nrdHFZP1AfdKBrjsSQmwFm8R2i2mzMef75", "niGZgfbhFYn6tJqksmC8CnzSRL1GHNsu7e", "nh6w8yu1zoKYoT837ffkVmuPjTaP69Pc5E", "nbyMgmEghsL9tpk7XfdH9gLGudh6Lrbbuf", "naX9akzYuWY1gKbcZo3t36aBKc1gqbzgSs", "nqcPVTGeAfCowELB2D5PdVF3FWFjFtkkFf", "nd4vVvPTpp2LfcsMPsmG3Dh7MFAsqRHp4g", "nVK4Uz5Sf56ygrr6RiwXcRvH8AuUVbjjHi", "nbipkRwT1NCSXZSrm8uAAEgQAA2s2NWMkG", "nZU6QAMAdCQcVDxEmL7GEY6ykFm8m6u6am", "nbFqayssM5s7hLjLFwf2d95JXKRWBk2pBH", "nacZfcNgVi47hamLscWdUGQhUQGGpSdgq8", "niiMT7ZYeFnaLPYtqQFBBX1sP3dT5JtcEw", "ns6GyTaniLWaiYrvAf5tk4D8tWrbcCLGyj", "nhdwQfptLTzLJGbLF3vvtqyBaqPMPecDmE", "neMUAGeTzwxLbSkXMsdmWf1fTKS1UsJjXY", "nXsAMeXxtpx8jaxnU3Xv9ZQ6ZcRcD1xYhR", "ns35rKnnWf6xP3KSj5WPkMCVVaADGi6Ndk", "nk4wcXYBEWs5HkhNLsuaQJoAjJHoK6SQmG", "npsJQWu8fsALoTPum8D4j8FDkyeusk8fU8", "nZNhZo4Vz3DnwQGPL3SJTZgUw2Kh4g9oay", "nnxDTYB8WMHMgLnCY2tuaEtysvdhRnWehZ", "nb2iaDXG1EqkcE47H87WQFkQNkeVK66Z21", "nWHAkpn2DB3DJRsbiK3vpbigoa3M2uVuF8", "nViKdC7Gm6TMmCuWTBwVE9i4rJhyfwbfqg", "nZQV5BifbGPzaxTrB4efgHruWH5rufemqP", "nVvZaLvnkCVAzpLYPoHeqU4w9zJ5yrZgUn", "nrMp6pRCk98WYWkCWq9Pqthz9HbpQu8BT3", "nnA3aYsLqysKT6gAu1dr4EKm586cmKiRxS", "nVfcVgMY7DL6nqoSxwJy7B7hKXirQwj6ic", "ni4oAzi6nCVuEdjoHyVMVKWb1DqTd3qY3H", "nnpf3gx442yomniRJPMGPapgjHrraPZXxJ", "nkuFnF8wUmHFkMycaFMvyjBoiMeR5KBKGd", "nXKccwjaUyrQkLrdqKT6aq6cDiFgBBVgNz", "nZMSNsXSAL7i1YD6KP5FrhATuZ2CWvnxqR", "nUEkQ3LjH9m4ScbP6NGtnAdnnUsdtWv99Q" ); String[] statuses = { "fe7c109d8bd90551a406cf0b3499117db04bc9c4f48e1df27ac1cf3ddcb3d464", "8a53babd831c6c3a857e20190e884efe75a005bdd7cd273c4f27ab1b8ec81c2d", "86bc2f0cf0112fd59c9aadfe5c887062c21d7a873db260dff68dcfe4417fe212", "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, null, null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, null, null, null, null, null, null, null, null, null }; String[] unspent = { "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 0, \"value\": 500000000, \"height\": 160267}, {\"tx_hash\": \"89a72ba4732505ce9b09c30668db985952701252ce0adbd7c43336396697d6ae\", \"tx_pos\": 0, \"value\": 500000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 1, \"value\": 1000000000, \"height\": 160267}, {\"tx_hash\": \"edaf445288d8e65cf7963bc8047c90f53681acaadc5ccfc5ecc67aedbd73cddb\", \"tx_pos\": 0, \"value\": 500000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 2, \"value\": 500000000, \"height\": 160267}, {\"tx_hash\": \"81a1f0f8242d5e71e65ff9e8ec51e8e85d641b607d7f691c1770d4f25918ebd7\", \"tx_pos\": 0, \"value\": 1000000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 3, \"value\": 500000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 4, \"value\": 1000000000, \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 11, \"value\": 500000000, \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 12, \"value\": 1000000000, \"height\": 160267}]", "[]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 13, \"value\": 500000000, \"height\": 160267}]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 6, \"value\": 500000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 7, \"value\": 1000000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 8, \"value\": 500000000, \"height\": 160267}]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 9, \"value\": 500000000, \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 10, \"value\": 1000000000, \"height\": 160267}]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]" }; String[] history = { "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}, {\"tx_hash\": \"89a72ba4732505ce9b09c30668db985952701252ce0adbd7c43336396697d6ae\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}, {\"tx_hash\": \"edaf445288d8e65cf7963bc8047c90f53681acaadc5ccfc5ecc67aedbd73cddb\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}, {\"tx_hash\": \"81a1f0f8242d5e71e65ff9e8ec51e8e85d641b607d7f691c1770d4f25918ebd7\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]" }; String[][] txs = { {"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f", "0100000001b8778dff640ccb144346d9db48201639b2707a0cc59e19672d2dd76cc6d1a5a6010000006b48304502210098d2e5b8a6c72442430bc09f2f4bcb56612c5b9e5eee821d65b412d099bb723402204f7f008ac052e5d7be0ab5b0c85ea5e627d725a521bd9e9b193d1fdf81c317a0012102d26e423c9da9ff4a7bf6b756b2dafb75cca34fbd34f64c4c3b77c37179c5bba2ffffffff0e0065cd1d000000001976a914ca983c2da690de3cdc693ca013d93e569810c52c88ac00ca9a3b000000001976a91477263ab93a49b1d3eb5887187704cdb82e1c60ce88ac0065cd1d000000001976a914dc40fbbc8caa1f7617d275aec9a3a14ce8d8652188ac0065cd1d000000001976a9140f2b1e5b376e22c5d1e635233eb90cf50ad9095188ac00ca9a3b000000001976a914f612ffd50b6a69df5e34ee0c5b529dfaaedca03d88ac00f633bce60000001976a914937258e3a8c463ec07e78ce62326c488170ad25e88ac0065cd1d000000001976a9142848ad5ff4cc32df3649646017c47bc04e8d211788ac00ca9a3b000000001976a914fa937737a6df2b8a5e39cce8b0bdd9510683023a88ac0065cd1d000000001976a914ae248a5d710143b6b309aaab9ce17059536e2aa388ac0065cd1d000000001976a91438d6eb11eca405be497a7183c50e437851425e0088ac00ca9a3b000000001976a91410ac6b2704146b50a1dd8f6df70736856ebf8b3488ac0065cd1d000000001976a914456816dccb3a4f33ae2dbd3ba623997075d5c73d88ac00ca9a3b000000001976a91452957c44e5bee9a60402a739fc8959c2850ea98488ac0065cd1d000000001976a914fb2dffa402d05f74335d137e21e41d8920c745fb88ac00000000"}, {"89a72ba4732505ce9b09c30668db985952701252ce0adbd7c43336396697d6ae", "01000000011a656d67706db286d1e6fad57eb4f411cb14f8880cea8348da339b9d434a5ec7050000006a47304402201d69fddb269b53aa742ff6437a45adb4ca5c59f666c9b4eabc4a0c7a6e6f4c0f022015a747b7a6d9371a4020f5b396dcd094b0f36af3fc82e95091da856181912dfa012102c9a8d5b2f768afe30ee772d185e7a61f751be05649a79508b38a2be8824adec3ffffffff020065cd1d000000001976a914ca983c2da690de3cdc693ca013d93e569810c52c88ac00b07098e60000001976a9141630d812e219e6bcbe494eb96f7a7900c216ad5d88ac00000000"}, {"edaf445288d8e65cf7963bc8047c90f53681acaadc5ccfc5ecc67aedbd73cddb", "010000000164a3990893c012b20287d43d1071ac26f4b93648ff4213db6da6979beed6b7dc010000006b48304502210086ac11d4a8146b4176a72059960690c72a9776468cd671fd07c064b51f24961d02205bcf008d6995014f3cfd79100ee9beab5688c88cca15c5cea38b769563785d900121036530415a7b3b9c5976f26a63a57d119ab39491762121723c773399a2531a1bd7ffffffff020065cd1d000000001976a91477263ab93a49b1d3eb5887187704cdb82e1c60ce88ac006aad74e60000001976a914e5616848352c328c9f61b167eb1b0fde39b5cb6788ac00000000"}, {"81a1f0f8242d5e71e65ff9e8ec51e8e85d641b607d7f691c1770d4f25918ebd7", "010000000141c217dfea3a1d8d6a06e9d3daf75b292581f652256d73a7891e5dc9c7ee3cca000000006a47304402205cce451228f98fece9645052546b82c2b2d425a4889b03999001fababfc7f4690220583b2189faef07d6b0191c788301cfab1b3f47ffe2c403d632b92c6dde27e14f012102d26e423c9da9ff4a7bf6b756b2dafb75cca34fbd34f64c4c3b77c37179c5bba2ffffffff0100ca9a3b000000001976a914dc40fbbc8caa1f7617d275aec9a3a14ce8d8652188ac00000000"} }; String expectedTx = "01000000039f79b1953195fe490a8036b9b1c735cb0c7efb1474700bd6e2778a3e27da74ef040000006b483045022100ec1ede06eb8ef3e0e7afead274c86cd505f7f88d0077db86aee4f38b11b304150220329ade48f5881ad923c7acc98004c84982fb2440cbac7778e30c95da254f2f9a012103c956c491833b8f1ebfde275cd7d5660824c53efe215f9956356b85f6c86031ffffffffff9f79b1953195fe490a8036b9b1c735cb0c7efb1474700bd6e2778a3e27da74ef010000006a47304402207700077df150a7796f950784eeb0d7e38e7e144cba051cab01002ca4d23167ed02204e460a31805e014b0f312202e5d7c35da62b4a2f209c8b16cdc977a9a8f7128b0121033daee143740ae505dd588be89f659b34ba30f587bcebece11d72ec7a115bc41bffffffffd7eb1859f2d470171c697f7d601b645de8e851ece8f95fe6715e2d24f8f0a181000000006a4730440220710c679f4e4024d8df8c5178106cb50db232b793c49327f5c73a70c8f4c2a17e0220693410baf65a82aad63bf961bf1d2687cf085f8560bf38e14b9efabd9663554d01210392ed3b840c8474f8b6b57e71d9a60fbf75adea6fc68d8985330e8d782b80621fffffffff0200bbeea0000000001976a914007d5355731b44e274eb495a26f4c33a734ee3eb88ac00c2eb0b000000001976a914392d52419e94e237f0d5817de1c9e21d09b515a688ac00000000"; }
c-bit/cbit-android
core/src/test/java/com/coinomi/core/wallet/WalletPocketHDTest.java
45,940
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.handler.codec.socks; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.util.CharsetUtil; import org.junit.Test; import java.net.IDN; import java.nio.CharBuffer; import static org.junit.Assert.*; public class SocksCmdRequestTest { @Test public void testConstructorParamsAreNotNull() { try { new SocksCmdRequest(null, SocksAddressType.UNKNOWN, "", 1); } catch (Exception e) { assertTrue(e instanceof NullPointerException); } try { new SocksCmdRequest(SocksCmdType.UNKNOWN, null, "", 1); } catch (Exception e) { assertTrue(e instanceof NullPointerException); } try { new SocksCmdRequest(SocksCmdType.UNKNOWN, SocksAddressType.UNKNOWN, null, 1); } catch (Exception e) { assertTrue(e instanceof NullPointerException); } } @Test public void testIPv4CorrectAddress() { try { new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.IPv4, "54.54.1111.253", 1); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } @Test public void testIPv6CorrectAddress() { try { new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.IPv6, "xxx:xxx:xxx", 1); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } @Test public void testIDNNotExceeds255CharsLimit() { try { new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.DOMAIN, "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" + "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" + "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" + "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή", 1); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } @Test public void testHostNotEncodedForUnknown() { String asciiHost = "xn--e1aybc.xn--p1ai"; short port = 10000; SocksCmdRequest rq = new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.UNKNOWN, asciiHost, port); assertEquals(asciiHost, rq.host()); ByteBuf buffer = Unpooled.buffer(16); rq.encodeAsByteBuf(buffer); buffer.readerIndex(0); assertEquals(SocksProtocolVersion.SOCKS5.byteValue(), buffer.readByte()); assertEquals(SocksCmdType.BIND.byteValue(), buffer.readByte()); assertEquals((byte) 0x00, buffer.readByte()); assertEquals(SocksAddressType.UNKNOWN.byteValue(), buffer.readByte()); assertFalse(buffer.isReadable()); buffer.release(); } @Test public void testIDNEncodeToAsciiForDomain() { String host = "тест.рф"; CharBuffer asciiHost = CharBuffer.wrap(IDN.toASCII(host)); short port = 10000; SocksCmdRequest rq = new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.DOMAIN, host, port); assertEquals(host, rq.host()); ByteBuf buffer = Unpooled.buffer(24); rq.encodeAsByteBuf(buffer); buffer.readerIndex(0); assertEquals(SocksProtocolVersion.SOCKS5.byteValue(), buffer.readByte()); assertEquals(SocksCmdType.BIND.byteValue(), buffer.readByte()); assertEquals((byte) 0x00, buffer.readByte()); assertEquals(SocksAddressType.DOMAIN.byteValue(), buffer.readByte()); assertEquals((byte) asciiHost.length(), buffer.readUnsignedByte()); assertEquals(asciiHost, CharBuffer.wrap(buffer.readCharSequence(asciiHost.length(), CharsetUtil.US_ASCII))); assertEquals(port, buffer.readUnsignedShort()); buffer.release(); } @Test public void testValidPortRange() { try { new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.DOMAIN, "παράδειγμα.δοκιμήπαράδει", 0); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } try { new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.DOMAIN, "παράδειγμα.δοκιμήπαράδει", 65536); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } }
fedorovr/netty
codec-socks/src/test/java/io/netty/handler/codec/socks/SocksCmdRequestTest.java
45,941
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.handler.codec.socks; import org.junit.Test; import static org.junit.Assert.assertTrue; public class SocksAuthRequestTest { @Test public void testConstructorParamsAreNotNull() { try { new SocksAuthRequest(null, ""); } catch (Exception e) { assertTrue(e instanceof NullPointerException); } try { new SocksAuthRequest("", null); } catch (Exception e) { assertTrue(e instanceof NullPointerException); } } @Test public void testUsernameOrPasswordIsNotAscii() { try { new SocksAuthRequest("παράδειγμα.δοκιμή", "password"); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } try { new SocksAuthRequest("username", "παράδειγμα.δοκιμή"); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } @Test public void testUsernameOrPasswordLengthIsLessThan255Chars() { try { new SocksAuthRequest( "passwordpasswordpasswordpasswordpasswordpasswordpassword" + "passwordpasswordpasswordpasswordpasswordpasswordpassword" + "passwordpasswordpasswordpasswordpasswordpasswordpassword" + "passwordpasswordpasswordpasswordpasswordpasswordpassword" + "passwordpasswordpasswordpasswordpasswordpasswordpassword" + "passwordpasswordpasswordpasswordpasswordpasswordpassword" + "passwordpasswordpasswordpasswordpasswordpasswordpassword" + "passwordpasswordpasswordpasswordpasswordpasswordpassword", "password"); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } try { new SocksAuthRequest("password", "passwordpasswordpasswordpasswordpasswordpasswordpassword" + "passwordpasswordpasswordpasswordpasswordpasswordpassword" + "passwordpasswordpasswordpasswordpasswordpasswordpassword" + "passwordpasswordpasswordpasswordpasswordpasswordpassword" + "passwordpasswordpasswordpasswordpasswordpasswordpassword" + "passwordpasswordpasswordpasswordpasswordpasswordpassword" + "passwordpasswordpasswordpasswordpasswordpasswordpassword" + "passwordpasswordpasswordpasswordpasswordpasswordpassword"); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } }
benevans/netty
codec-socks/src/test/java/io/netty/handler/codec/socks/SocksAuthRequestTest.java
45,942
package com.huawei.zxing.resultdispatch; import java.util.regex.Matcher; import java.util.regex.Pattern; public class QRCodeMatcher { private static final Pattern WEB_URL = Pattern.compile("(?:(?:((http|https|rtsp)):\\/\\/(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?(?:(?:(?:[a-zA-Z0-9 -퟿豈-﷏ﷰ-￯][a-zA-Z0-9 -퟿豈-﷏ﷰ-￯\\-]{0,64}\\.)+(?:(?:aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(?:biz|b[abdefghijmnorstvwyz])|(?:cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(?:edu|e[cegrstu])|f[ijkmor]|(?:gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(?:info|int|i[delmnoqrst])|(?:jobs|j[emop])|k[eghimnprwyz]|l[abcikrstuvy]|(?:mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])|(?:name|net|n[acefgilopruz])|(?:org|om)|(?:pro|p[aefghklmnrstwy])|qa|r[eosuw]|s[abcdeghijklmnortuvyz]|(?:tel|travel|t[cdfghjklmnoprtvwz])|u[agksyz]|v[aceginu]|w[fs]|(?:δοκιμή|испытание|рф|срб|טעסט|آزمایشی|إختبار|الاردن|الجزائر|السعودية|المغرب|امارات|بھارت|تونس|سورية|فلسطين|قطر|مصر|परीक्षा|भारत|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|பரிட்சை|భారత్|ලංකා|ไทย|テスト|中国|中國|台湾|台灣|新加坡|测试|測試|香港|테스트|한국|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)|y[et]|z[amw]))|(?:(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])))(?:\\:\\d{1,5})?)(?:\\/(?:(?:[a-zA-Z0-9 -퟿豈-﷏ﷰ-￯\\;\\/\\?\\:\\@\\&\\=\\#\\~\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))*)?(?:\\b|$)"); private static final Pattern WEB_URL_QQ = Pattern.compile("(http:\\/\\/mobile.qq.com|mobile.qq:\\/\\/)"); private static final Pattern WEB_URL_WEIBO = Pattern.compile("(http:\\/\\/weibo.cn|weibo:\\/\\/)"); private static final Pattern WECHAT = Pattern.compile("(http:\\/\\/weixin.qq.com|weixin:\\/\\/)"); public static QRCodeType match(String paramString) { String str1 = paramString.trim(); String str2 = str1.toLowerCase(); QRCodeType localQRCodeType = QRCodeType.TEXT; Matcher localMatcher1 = WECHAT.matcher(str2); if (localMatcher1.find() && localMatcher1.start() == 0) { return QRCodeType.WECHAT; } Matcher localMatcher2 = WEB_URL_QQ.matcher(str2); if (localMatcher2.find() && localMatcher2.start() == 0) { return QRCodeType.WEB_URL_QQ; } Matcher localMatcher3 = WEB_URL_WEIBO.matcher(str2); if (localMatcher3.find() && localMatcher3.start() == 0) { return QRCodeType.WEB_URL_WEIBO; } if (str2.contains("hicloud.com")) { return QRCodeType.MARKET; } if (!WEB_URL.matcher(str2).matches()) { return localQRCodeType; } if (str1.endsWith(".apk")) { return QRCodeType.WEB_URL_APK; } if (str1.startsWith("http://qm.qq.com")) { return QRCodeType.WEB_URL_QQ; } return QRCodeType.WEB_URL; } }
dstmath/HWFramework
P9-8.0/src/main/java/com/huawei/zxing/resultdispatch/QRCodeMatcher.java
45,943
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.handler.codec.socksx.v5; import org.junit.Test; import static org.junit.Assert.*; public class DefaultSocks5CommandRequestTest { @Test public void testConstructorParamsAreNotNull() { try { new DefaultSocks5CommandRequest(null, Socks5AddressType.DOMAIN, "", 1); } catch (Exception e) { assertTrue(e instanceof NullPointerException); } try { new DefaultSocks5CommandRequest(Socks5CommandType.CONNECT, null, "", 1); } catch (Exception e) { assertTrue(e instanceof NullPointerException); } try { new DefaultSocks5CommandRequest(Socks5CommandType.CONNECT, Socks5AddressType.DOMAIN, null, 1); } catch (Exception e) { assertTrue(e instanceof NullPointerException); } } @Test public void testIPv4CorrectAddress() { try { new DefaultSocks5CommandRequest(Socks5CommandType.BIND, Socks5AddressType.IPv4, "54.54.1111.253", 1); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } @Test public void testIPv6CorrectAddress() { try { new DefaultSocks5CommandRequest(Socks5CommandType.BIND, Socks5AddressType.IPv6, "xxx:xxx:xxx", 1); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } @Test public void testIDNNotExceeds255CharsLimit() { try { new DefaultSocks5CommandRequest(Socks5CommandType.BIND, Socks5AddressType.DOMAIN, "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" + "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" + "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" + "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή", 1); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } @Test public void testValidPortRange() { try { new DefaultSocks5CommandRequest(Socks5CommandType.BIND, Socks5AddressType.DOMAIN, "παράδειγμα.δοκιμήπαράδει", 0); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } try { new DefaultSocks5CommandRequest(Socks5CommandType.BIND, Socks5AddressType.DOMAIN, "παράδειγμα.δοκιμήπαράδει", 65536); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } }
casidiablo/netty
codec-socks/src/test/java/io/netty/handler/codec/socksx/v5/DefaultSocks5CommandRequestTest.java
45,944
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.jboss.netty.handler.codec.socks; import org.junit.Test; import static org.junit.Assert.assertTrue; public class SocksCmdRequestTest { @Test public void testConstructorParamsAreNotNull(){ try { new SocksCmdRequest(null, SocksMessage.AddressType.UNKNOWN, "", 0); } catch (Exception e){ assertTrue(e instanceof NullPointerException); } try { new SocksCmdRequest(SocksMessage.CmdType.UNKNOWN, null, "", 0); } catch (Exception e){ assertTrue(e instanceof NullPointerException); } try { new SocksCmdRequest(SocksMessage.CmdType.UNKNOWN, SocksMessage.AddressType.UNKNOWN, null, 0); } catch (Exception e){ assertTrue(e instanceof NullPointerException); } } @Test public void testIPv4CorrectAddress(){ try { new SocksCmdRequest(SocksMessage.CmdType.BIND, SocksMessage.AddressType.IPv4, "54.54.1111.253", 0); } catch (Exception e){ assertTrue(e instanceof IllegalArgumentException); } } @Test public void testIPv6CorrectAddress(){ try { new SocksCmdRequest(SocksMessage.CmdType.BIND, SocksMessage.AddressType.IPv6, "xxx:xxx:xxx", 0); } catch (Exception e){ assertTrue(e instanceof IllegalArgumentException); } } @Test public void testIDNNotExceeds255CharsLimit(){ try { new SocksCmdRequest(SocksMessage.CmdType.BIND, SocksMessage.AddressType.DOMAIN, "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" + "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" + "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" + "παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή", 0); } catch (Exception e){ assertTrue(e instanceof IllegalArgumentException); } } @Test public void testValidPortRange(){ try { new SocksCmdRequest(SocksMessage.CmdType.BIND, SocksMessage.AddressType.DOMAIN, "παράδειγμα.δοκιμήπαράδει", -1); } catch (Exception e){ assertTrue(e instanceof IllegalArgumentException); } try { new SocksCmdRequest(SocksMessage.CmdType.BIND, SocksMessage.AddressType.DOMAIN, "παράδειγμα.δοκιμήπαράδει", 65536); } catch (Exception e){ assertTrue(e instanceof IllegalArgumentException); } } }
MifengbushiMifeng/netty-learning
netty-3.7/src/test/java/org/jboss/netty/handler/codec/socks/SocksCmdRequestTest.java
45,945
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.jboss.netty.handler.codec.socks; import org.junit.Test; import static org.junit.Assert.assertTrue; public class SocksAuthRequestTest { @Test public void testConstructorParamsAreNotNull() { try { new SocksAuthRequest(null, ""); } catch (Exception e) { assertTrue(e instanceof NullPointerException); } try { new SocksAuthRequest("", null); } catch (Exception e) { assertTrue(e instanceof NullPointerException); } } @Test public void testUsernameOrPasswordIsNotAscii() { try { new SocksAuthRequest("παράδειγμα.δοκιμή", "password"); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } try { new SocksAuthRequest("username", "παράδειγμα.δοκιμή"); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } @Test public void testUsernameOrPasswordLengthIsLessThan255Chars() { try { new SocksAuthRequest( "passwordpasswordpasswordpasswordpasswordpasswordpassword" + "passwordpasswordpasswordpasswordpasswordpasswordpassword" + "passwordpasswordpasswordpasswordpasswordpasswordpassword" + "passwordpasswordpasswordpasswordpasswordpasswordpassword" + "passwordpasswordpasswordpasswordpasswordpasswordpassword" + "passwordpasswordpasswordpasswordpasswordpasswordpassword" + "passwordpasswordpasswordpasswordpasswordpasswordpassword" + "passwordpasswordpasswordpasswordpasswordpasswordpassword", "password"); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } try { new SocksAuthRequest("password", "passwordpasswordpasswordpasswordpasswordpasswordpassword" + "passwordpasswordpasswordpasswordpasswordpasswordpassword" + "passwordpasswordpasswordpasswordpasswordpasswordpassword" + "passwordpasswordpasswordpasswordpasswordpasswordpassword" + "passwordpasswordpasswordpasswordpasswordpasswordpassword" + "passwordpasswordpasswordpasswordpasswordpasswordpassword" + "passwordpasswordpasswordpasswordpasswordpasswordpassword" + "passwordpasswordpasswordpasswordpasswordpasswordpassword"); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } }
MifengbushiMifeng/netty-learning
netty-3.7/src/test/java/org/jboss/netty/handler/codec/socks/SocksAuthRequestTest.java
45,946
package com.onix.core.wallet; import com.onix.core.coins.BitcoinMain; import com.onix.core.coins.CoinType; import com.onix.core.coins.DogecoinTest; import com.onix.core.coins.NuBitsMain; import com.onix.core.coins.VpncoinMain; import com.onix.core.network.AddressStatus; import com.onix.core.network.ServerClient.HistoryTx; import com.onix.core.network.interfaces.BlockchainConnection; import com.onix.core.network.interfaces.TransactionEventListener; import com.onix.core.protos.Protos; import com.onix.core.wallet.exceptions.AddressMalformedException; import com.onix.core.wallet.exceptions.Bip44KeyLookAheadExceededException; import com.onix.core.wallet.exceptions.KeyIsEncryptedException; import com.onix.core.wallet.exceptions.MissingPrivateKeyException; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import org.bitcoinj.core.Address; import org.bitcoinj.core.AddressFormatException; import org.bitcoinj.core.ChildMessage; import org.bitcoinj.core.Coin; import org.bitcoinj.core.ECKey; import org.bitcoinj.core.Sha256Hash; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.Utils; import org.bitcoinj.crypto.DeterministicHierarchy; import org.bitcoinj.crypto.DeterministicKey; import org.bitcoinj.crypto.HDKeyDerivation; import org.bitcoinj.crypto.KeyCrypter; import org.bitcoinj.crypto.KeyCrypterScrypt; import org.bitcoinj.store.UnreadableWalletException; import org.bitcoinj.utils.BriefLogFormatter; import org.bitcoinj.wallet.DeterministicSeed; import org.bitcoinj.wallet.KeyChain; import org.json.JSONArray; import org.json.JSONException; import org.junit.Before; import org.junit.Test; import org.spongycastle.crypto.params.KeyParameter; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Set; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; /** * @author John L. Jegutanis */ public class WalletPocketHDTest { static final CoinType BTC = BitcoinMain.get(); static final CoinType DOGE = DogecoinTest.get(); static final CoinType NBT = NuBitsMain.get(); static final CoinType VPN = VpncoinMain.get(); static final List<String> MNEMONIC = ImmutableList.of("citizen", "fever", "scale", "nurse", "brief", "round", "ski", "fiction", "car", "fitness", "pluck", "act"); static final byte[] AES_KEY_BYTES = {0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7}; static final long AMOUNT_TO_SEND = 2700000000L; static final String MESSAGE = "test"; static final String MESSAGE_UNICODE = "δοκιμή испытание 测试"; static final String EXPECTED_BITCOIN_SIG = "IMBbIFDDuUwomYlvSjwWytqP/CXYym2yOKbJUx8Y+ujzZKBwoCFMr73GUxpr1Ird/DvnNZcsQLphvx18ftqN54o="; static final String EXPECTED_BITCOIN_SIG_UNICODE = "IGGZEOBsVny5dozTOfc2/3UuvmZGdDI4XK/03HIk34PILd2oXbnq+87GINT3lumeXcgSO2NkGzUFcQ1SCSVI3Hk="; static final String EXPECTED_NUBITS_SIG = "IMuzNZTZIjZjLicyDFGzqFl21vqNBGW1N5m4qHBRqbTvLBbkQeGjraeLmZEt7mRH4MSMPLFXW2T3Maz+HYx1tEc="; static final String EXPECTED_NUBITS_SIG_UNICODE = "Hx7xkBbboXrp96dbQrJFzm2unTGwLstjbWlKa1/N1E4LJqbwJAJR1qIvwXm6LHQFnLOzwoQA45zYNjwUEPMc8sg="; DeterministicSeed seed; DeterministicKey masterKey; DeterministicHierarchy hierarchy; DeterministicKey rootKey; WalletPocketHD pocket; KeyParameter aesKey; KeyCrypter crypter; @Before public void setup() { BriefLogFormatter.init(); seed = new DeterministicSeed(MNEMONIC, null, "", 0); masterKey = HDKeyDerivation.createMasterPrivateKey(seed.getSeedBytes()); hierarchy = new DeterministicHierarchy(masterKey); rootKey = hierarchy.get(DOGE.getBip44Path(0), false, true); aesKey = new KeyParameter(AES_KEY_BYTES); crypter = new KeyCrypterScrypt(); pocket = new WalletPocketHD(rootKey, DOGE, null, null); pocket.keys.setLookaheadSize(20); } @Test public void xpubWallet() { String xpub = "xpub67tVq9TLPPoaHVSiYu8mqahm3eztTPUts6JUftNq3pZF1PJwjknrTqQhjc2qRGd6vS8wANu7mLnqkiUzFZ1xZsAZoUMi8o6icMhzGCAhcSW"; DeterministicKey key = DeterministicKey.deserializeB58(null, xpub); WalletPocketHD account = new WalletPocketHD(key, BTC, null, null); assertEquals("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", account.getReceiveAddress().toString()); account = new WalletPocketHD(key, NBT, null, null); assertEquals("BNvJUwg3BgkbQk5br1CxvHxdcDp1EC3saE", account.getReceiveAddress().toString()); } @Test public void xpubWalletSerialized() throws Exception { WalletPocketHD account = new WalletPocketHD(rootKey, BTC, null, null); Protos.WalletPocket proto = account.toProtobuf(); WalletPocketHD newAccount = new WalletPocketProtobufSerializer().readWallet(proto, null); assertEquals(account.getPublicKeySerialized(), newAccount.getPublicKeySerialized()); } @Test public void signMessage() throws AddressMalformedException, MissingPrivateKeyException, KeyIsEncryptedException { WalletPocketHD pocketHD = new WalletPocketHD(rootKey, BTC, null, null); pocketHD.getReceiveAddress(); // Generate the first key SignedMessage signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE); pocketHD.signMessage(signedMessage, null); assertEquals(EXPECTED_BITCOIN_SIG, signedMessage.getSignature()); signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE_UNICODE); pocketHD.signMessage(signedMessage, null); assertEquals(EXPECTED_BITCOIN_SIG_UNICODE, signedMessage.getSignature()); pocketHD = new WalletPocketHD(rootKey, NBT, null, null); pocketHD.getReceiveAddress(); // Generate the first key signedMessage = new SignedMessage("BNvJUwg3BgkbQk5br1CxvHxdcDp1EC3saE", MESSAGE); pocketHD.signMessage(signedMessage, null); assertEquals(EXPECTED_NUBITS_SIG, signedMessage.getSignature()); signedMessage = new SignedMessage("BNvJUwg3BgkbQk5br1CxvHxdcDp1EC3saE", MESSAGE_UNICODE); pocketHD.signMessage(signedMessage, null); assertEquals(EXPECTED_NUBITS_SIG_UNICODE, signedMessage.getSignature()); } @Test public void signMessageEncrypted() throws AddressMalformedException, MissingPrivateKeyException, KeyIsEncryptedException { WalletPocketHD pocketHD = new WalletPocketHD(rootKey, BTC, null, null); pocketHD.getReceiveAddress(); // Generate the first key pocketHD.encrypt(crypter, aesKey); SignedMessage signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE); pocketHD.signMessage(signedMessage, aesKey); assertEquals(EXPECTED_BITCOIN_SIG, signedMessage.getSignature()); signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE_UNICODE); pocketHD.signMessage(signedMessage, aesKey); assertEquals(EXPECTED_BITCOIN_SIG_UNICODE, signedMessage.getSignature()); } @Test public void signMessageEncryptedFailed() throws AddressMalformedException, MissingPrivateKeyException, KeyIsEncryptedException { WalletPocketHD pocketHD = new WalletPocketHD(rootKey, BTC, null, null); pocketHD.getReceiveAddress(); // Generate the first key pocketHD.encrypt(crypter, aesKey); SignedMessage signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE); pocketHD.signMessage(signedMessage, null); assertEquals(SignedMessage.Status.KeyIsEncrypted, signedMessage.status); } @Test public void watchingAddresses() { List<Address> watchingAddresses = pocket.getAddressesToWatch(); assertEquals(40, watchingAddresses.size()); // 20 + 20 lookahead size for (int i = 0; i < addresses.size(); i++) { assertEquals(addresses.get(i), watchingAddresses.get(i).toString()); } } @Test public void issuedKeys() throws Bip44KeyLookAheadExceededException { LinkedList<Address> issuedAddresses = new LinkedList<Address>(); assertEquals(0, pocket.getIssuedReceiveAddresses().size()); assertEquals(0, pocket.keys.getNumIssuedExternalKeys()); issuedAddresses.add(0, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS)); Address freshAddress = pocket.getFreshReceiveAddress(); assertEquals(freshAddress, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS)); assertEquals(1, pocket.getIssuedReceiveAddresses().size()); assertEquals(1, pocket.keys.getNumIssuedExternalKeys()); assertEquals(issuedAddresses, pocket.getIssuedReceiveAddresses()); issuedAddresses.add(0, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS)); freshAddress = pocket.getFreshReceiveAddress(); assertEquals(freshAddress, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS)); assertEquals(2, pocket.getIssuedReceiveAddresses().size()); assertEquals(2, pocket.keys.getNumIssuedExternalKeys()); assertEquals(issuedAddresses, pocket.getIssuedReceiveAddresses()); } @Test public void issuedKeysLimit() throws Exception { assertTrue(pocket.canCreateFreshReceiveAddress()); try { for (int i = 0; i < 100; i++) { pocket.getFreshReceiveAddress(); } } catch (Bip44KeyLookAheadExceededException e) { assertFalse(pocket.canCreateFreshReceiveAddress()); // We haven't used any key so the total must be 20 - 1 (the unused key) assertEquals(19, pocket.getNumberIssuedReceiveAddresses()); assertEquals(19, pocket.getIssuedReceiveAddresses().size()); } pocket.onConnection(getBlockchainConnection(DOGE)); assertTrue(pocket.canCreateFreshReceiveAddress()); try { for (int i = 0; i < 100; i++) { pocket.getFreshReceiveAddress(); } } catch (Bip44KeyLookAheadExceededException e) { try { pocket.getFreshReceiveAddress(); } catch (Bip44KeyLookAheadExceededException e1) { } assertFalse(pocket.canCreateFreshReceiveAddress()); // We used 18, so the total must be (20-1)+18=37 assertEquals(37, pocket.getNumberIssuedReceiveAddresses()); assertEquals(37, pocket.getIssuedReceiveAddresses().size()); } } @Test public void issuedKeysLimit2() throws Exception { assertTrue(pocket.canCreateFreshReceiveAddress()); try { for (int i = 0; i < 100; i++) { pocket.getFreshReceiveAddress(); } } catch (Bip44KeyLookAheadExceededException e) { assertFalse(pocket.canCreateFreshReceiveAddress()); // We haven't used any key so the total must be 20 - 1 (the unused key) assertEquals(19, pocket.getNumberIssuedReceiveAddresses()); assertEquals(19, pocket.getIssuedReceiveAddresses().size()); } } @Test public void usedAddresses() throws Exception { assertEquals(0, pocket.getUsedAddresses().size()); pocket.onConnection(getBlockchainConnection(DOGE)); // Receive and change addresses assertEquals(13, pocket.getUsedAddresses().size()); } private Transaction send(Coin value, WalletPocketHD w1, WalletPocketHD w2) throws Exception { SendRequest req; req = w1.sendCoinsOffline(w2.getReceiveAddress(), value); req.feePerKb = Coin.ZERO; w1.completeAndSignTx(req); byte[] txBytes = req.tx.bitcoinSerialize(); w1.addNewTransactionIfNeeded(new Transaction(w1.getCoinType(), txBytes)); w2.addNewTransactionIfNeeded(new Transaction(w1.getCoinType(), txBytes)); return req.tx; } @Test public void testSendingAndBalances() throws Exception { DeterministicHierarchy h = new DeterministicHierarchy(masterKey); WalletPocketHD account1 = new WalletPocketHD(h.get(BTC.getBip44Path(0), false, true), BTC, null, null); WalletPocketHD account2 = new WalletPocketHD(h.get(BTC.getBip44Path(1), false, true), BTC, null, null); WalletPocketHD account3 = new WalletPocketHD(h.get(BTC.getBip44Path(2), false, true), BTC, null, null); Transaction tx = new Transaction(BTC); tx.addOutput(BTC.oneCoin().toCoin(), account1.getReceiveAddress()); account1.addNewTransactionIfNeeded(tx); assertEquals(BTC.value("1"), account1.getBalance()); assertEquals(BTC.value("0"), account2.getBalance()); assertEquals(BTC.value("0"), account3.getBalance()); send(Coin.CENT.multiply(5), account1, account2); assertEquals(BTC.value("0.95"), account1.getBalance()); assertEquals(BTC.value("0.05"), account2.getBalance()); assertEquals(BTC.value("0"), account3.getBalance()); send(Coin.CENT.multiply(7), account1, account3); assertEquals(BTC.value("0.88"), account1.getBalance()); assertEquals(BTC.value("0.05"), account2.getBalance()); assertEquals(BTC.value("0.07"), account3.getBalance()); send(Coin.CENT.multiply(3), account2, account3); assertEquals(BTC.value("0.88"), account1.getBalance()); assertEquals(BTC.value("0.02"), account2.getBalance()); assertEquals(BTC.value("0.1"), account3.getBalance()); } @Test public void fillTransactions() throws Exception { pocket.onConnection(getBlockchainConnection(DOGE)); // Issued keys assertEquals(18, pocket.keys.getNumIssuedExternalKeys()); assertEquals(9, pocket.keys.getNumIssuedInternalKeys()); // No addresses left to subscribe List<Address> addressesToWatch = pocket.getAddressesToWatch(); assertEquals(0, addressesToWatch.size()); // 18 external issued + 20 lookahead + 9 external issued + 20 lookahead assertEquals(67, pocket.addressesStatus.size()); assertEquals(67, pocket.addressesSubscribed.size()); Address receiveAddr = pocket.getReceiveAddress(); // This key is not issued assertEquals(18, pocket.keys.getNumIssuedExternalKeys()); assertEquals(67, pocket.addressesStatus.size()); assertEquals(67, pocket.addressesSubscribed.size()); DeterministicKey key = pocket.keys.findKeyFromPubHash(receiveAddr.getHash160()); assertNotNull(key); // 18 here is the key index, not issued keys count assertEquals(18, key.getChildNumber().num()); assertEquals(11000000000L, pocket.getBalance().value); // TODO added more tests to insure it uses the "holes" in the keychain } @Test public void serializeTransactionsBtc() throws Exception, Bip44KeyLookAheadExceededException { WalletPocketHD account = new WalletPocketHD(rootKey, BTC, null, null); Transaction tx = new Transaction(BTC); tx.addOutput(BTC.oneCoin().toCoin(), account.getReceiveAddress()); account.addNewTransactionIfNeeded(tx); testWalletSerializationForCoin(account); } @Test public void serializeTransactionsNbt() throws Exception, Bip44KeyLookAheadExceededException { WalletPocketHD account = new WalletPocketHD(rootKey, NBT, null, null); Transaction tx = new Transaction(NBT); tx.addOutput(NBT.oneCoin().toCoin(), account.getReceiveAddress()); account.addNewTransactionIfNeeded(tx); testWalletSerializationForCoin(account); } @Test public void serializeTransactionsVpn() throws Exception, Bip44KeyLookAheadExceededException { WalletPocketHD account = new WalletPocketHD(rootKey, VPN, null, null); // Test tx with null extra bytes Transaction tx = new Transaction(VPN); tx.setTime(0x99999999); tx.addOutput(VPN.oneCoin().toCoin(), account.getFreshReceiveAddress()); account.addNewTransactionIfNeeded(tx); WalletPocketHD newAccount = testWalletSerializationForCoin(account); Transaction newTx = newAccount.getTransaction(tx.getHash()); assertNotNull(newTx.getExtraBytes()); assertEquals(0, newTx.getExtraBytes().length); // Test tx with empty extra bytes tx = new Transaction(VPN); tx.setTime(0x99999999); tx.setExtraBytes(new byte[0]); tx.addOutput(VPN.oneCoin().toCoin(), account.getFreshReceiveAddress()); account.addNewTransactionIfNeeded(tx); newAccount = testWalletSerializationForCoin(account); newTx = newAccount.getTransaction(tx.getHash()); assertNotNull(newTx.getExtraBytes()); assertEquals(0, newTx.getExtraBytes().length); // Test tx with extra bytes tx = new Transaction(VPN); tx.setTime(0x99999999); byte[] bytes = {0x1, 0x2, 0x3}; tx.setExtraBytes(bytes); tx.addOutput(VPN.oneCoin().toCoin(), account.getFreshReceiveAddress()); account.addNewTransactionIfNeeded(tx); newAccount = testWalletSerializationForCoin(account); newTx = newAccount.getTransaction(tx.getHash()); assertArrayEquals(bytes, newTx.getExtraBytes()); } private WalletPocketHD testWalletSerializationForCoin(WalletPocketHD account) throws UnreadableWalletException { Protos.WalletPocket proto = account.toProtobuf(); WalletPocketHD newAccount = new WalletPocketProtobufSerializer().readWallet(proto, null); assertEquals(account.getBalance().value, newAccount.getBalance().value); Set<Transaction> transactions = account.getTransactions(false); Set<Transaction> newTransactions = newAccount.getTransactions(false); for (Transaction tx : transactions) { assertTrue(newTransactions.contains(tx)); } return newAccount; } @Test public void serializeUnencryptedNormal() throws Exception { pocket.onConnection(getBlockchainConnection(DOGE)); Protos.WalletPocket walletPocketProto = pocket.toProtobuf(); WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(walletPocketProto, null); assertEquals(pocket.getBalance().value, newPocket.getBalance().value); assertEquals(pocket.getCoinType(), newPocket.getCoinType()); assertEquals(pocket.getDescription(), newPocket.getDescription()); assertEquals(pocket.keys.toProtobuf().toString(), newPocket.keys.toProtobuf().toString()); assertEquals(pocket.getLastBlockSeenHash(), newPocket.getLastBlockSeenHash()); assertEquals(pocket.getLastBlockSeenHeight(), newPocket.getLastBlockSeenHeight()); assertEquals(pocket.getLastBlockSeenTimeSecs(), newPocket.getLastBlockSeenTimeSecs()); for (Transaction tx : pocket.getTransactions(false)) { assertEquals(tx, newPocket.getTransaction(tx.getHash())); } for (AddressStatus status : pocket.getAllAddressStatus()) { if (status.getStatus() == null) continue; assertEquals(status, newPocket.getAddressStatus(status.getAddress())); } // Issued keys assertEquals(18, newPocket.keys.getNumIssuedExternalKeys()); assertEquals(9, newPocket.keys.getNumIssuedInternalKeys()); newPocket.onConnection(getBlockchainConnection(DOGE)); // No addresses left to subscribe List<Address> addressesToWatch = newPocket.getAddressesToWatch(); assertEquals(0, addressesToWatch.size()); // 18 external issued + 20 lookahead + 9 external issued + 20 lookahead assertEquals(67, newPocket.addressesStatus.size()); assertEquals(67, newPocket.addressesSubscribed.size()); } @Test public void serializeUnencryptedEmpty() throws Exception { pocket.maybeInitializeAllKeys(); Protos.WalletPocket walletPocketProto = pocket.toProtobuf(); WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(walletPocketProto, null); assertEquals(walletPocketProto.toString(), newPocket.toProtobuf().toString()); // Issued keys assertEquals(0, newPocket.keys.getNumIssuedExternalKeys()); assertEquals(0, newPocket.keys.getNumIssuedInternalKeys()); // 20 lookahead + 20 lookahead assertEquals(40, newPocket.keys.getActiveKeys().size()); } @Test public void serializeEncryptedEmpty() throws Exception { pocket.maybeInitializeAllKeys(); pocket.encrypt(crypter, aesKey); Protos.WalletPocket walletPocketProto = pocket.toProtobuf(); WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(walletPocketProto, crypter); assertEquals(walletPocketProto.toString(), newPocket.toProtobuf().toString()); pocket.decrypt(aesKey); // One is encrypted, so they should not match assertNotEquals(pocket.toProtobuf().toString(), newPocket.toProtobuf().toString()); newPocket.decrypt(aesKey); assertEquals(pocket.toProtobuf().toString(), newPocket.toProtobuf().toString()); } @Test public void serializeEncryptedNormal() throws Exception { pocket.maybeInitializeAllKeys(); pocket.encrypt(crypter, aesKey); pocket.onConnection(getBlockchainConnection(DOGE)); assertEquals(DOGE.value(11000000000l), pocket.getBalance()); assertAllKeysEncrypted(pocket); WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(pocket.toProtobuf(), crypter); assertAllKeysEncrypted(newPocket); pocket.decrypt(aesKey); newPocket.decrypt(aesKey); assertAllKeysDecrypted(pocket); assertAllKeysDecrypted(newPocket); } private void assertAllKeysDecrypted(WalletPocketHD pocket) { List<ECKey> keys = pocket.keys.getKeys(false); for (ECKey k : keys) { DeterministicKey key = (DeterministicKey) k; assertFalse(key.isEncrypted()); } } private void assertAllKeysEncrypted(WalletPocketHD pocket) { List<ECKey> keys = pocket.keys.getKeys(false); for (ECKey k : keys) { DeterministicKey key = (DeterministicKey) k; assertTrue(key.isEncrypted()); } } @Test public void createDustTransactionFee() throws Exception { pocket.onConnection(getBlockchainConnection(DOGE)); Address toAddr = new Address(DOGE, "nUEkQ3LjH9m4ScbP6NGtnAdnnUsdtWv99Q"); Coin softDust = DOGE.getSoftDustLimit(); assertNotNull(softDust); // Send a soft dust SendRequest sendRequest = pocket.sendCoinsOffline(toAddr, softDust.subtract(Coin.SATOSHI)); pocket.completeTx(sendRequest); assertEquals(DOGE.getFeePerKb().multiply(2), sendRequest.tx.getFee()); } @Test public void createTransactionAndBroadcast() throws Exception { pocket.onConnection(getBlockchainConnection(DOGE)); Address toAddr = new Address(DOGE, "nUEkQ3LjH9m4ScbP6NGtnAdnnUsdtWv99Q"); long orgBalance = pocket.getBalance().value; SendRequest sendRequest = pocket.sendCoinsOffline(toAddr, Coin.valueOf(AMOUNT_TO_SEND)); sendRequest.shuffleOutputs = false; pocket.completeTx(sendRequest); Transaction tx = sendRequest.tx; assertEquals(expectedTx, Utils.HEX.encode(tx.bitcoinSerialize())); // FIXME, mock does not work here // pocket.broadcastTx(tx); // assertEquals(orgBalance - AMOUNT_TO_SEND, pocket.getBalance().value); } // Util methods //////////////////////////////////////////////////////////////////////////////////////////////// public class MessageComparator implements Comparator<ChildMessage> { @Override public int compare(ChildMessage o1, ChildMessage o2) { String s1 = Utils.HEX.encode(o1.bitcoinSerialize()); String s2 = Utils.HEX.encode(o2.bitcoinSerialize()); return s1.compareTo(s2); } } HashMap<Address, AddressStatus> getDummyStatuses() throws AddressFormatException { HashMap<Address, AddressStatus> status = new HashMap<Address, AddressStatus>(40); for (int i = 0; i < addresses.size(); i++) { Address address = new Address(DOGE, addresses.get(i)); status.put(address, new AddressStatus(address, statuses[i])); } return status; } // private HashMap<Address, ArrayList<UnspentTx>> getDummyUTXs() throws AddressFormatException, JSONException { // HashMap<Address, ArrayList<UnspentTx>> utxs = new HashMap<Address, ArrayList<UnspentTx>>(40); // // for (int i = 0; i < statuses.length; i++) { // List<UnspentTx> utxList = (List<UnspentTx>) UnspentTx.fromArray(new JSONArray(unspent[i])); // utxs.put(new Address(DOGE, addresses.get(i)), Lists.newArrayList(utxList)); // } // // return utxs; // } private HashMap<Address, ArrayList<HistoryTx>> getDummyHistoryTXs() throws AddressFormatException, JSONException { HashMap<Address, ArrayList<HistoryTx>> htxs = new HashMap<Address, ArrayList<HistoryTx>>(40); for (int i = 0; i < statuses.length; i++) { List<HistoryTx> utxList = (List<HistoryTx>) HistoryTx.fromArray(new JSONArray(unspent[i])); htxs.put(new Address(DOGE, addresses.get(i)), Lists.newArrayList(utxList)); } return htxs; } private HashMap<Sha256Hash, byte[]> getDummyRawTXs() throws AddressFormatException, JSONException { HashMap<Sha256Hash, byte[]> rawTxs = new HashMap<Sha256Hash, byte[]>(); for (int i = 0; i < txs.length; i++) { String[] txEntry = txs[i]; rawTxs.put(new Sha256Hash(txs[i][0]), Utils.HEX.decode(txs[i][1])); } return rawTxs; } class MockBlockchainConnection implements BlockchainConnection { final HashMap<Address, AddressStatus> statuses; // final HashMap<Address, ArrayList<UnspentTx>> utxs; final HashMap<Address, ArrayList<HistoryTx>> historyTxs; final HashMap<Sha256Hash, byte[]> rawTxs; private CoinType coinType; MockBlockchainConnection(CoinType coinType) throws Exception { this.coinType = coinType; statuses = getDummyStatuses(); // utxs = getDummyUTXs(); historyTxs = getDummyHistoryTXs(); rawTxs = getDummyRawTXs(); } @Override public void subscribeToBlockchain(TransactionEventListener listener) { } @Override public void subscribeToAddresses(List<Address> addresses, TransactionEventListener listener) { for (Address a : addresses) { AddressStatus status = statuses.get(a); if (status == null) { status = new AddressStatus(a, null); } listener.onAddressStatusUpdate(status); } } // @Override // public void getUnspentTx(AddressStatus status, TransactionEventListener listener) { // List<UnspentTx> utx = utxs.get(status.getAddress()); // if (status == null) { // utx = ImmutableList.of(); // } // listener.onUnspentTransactionUpdate(status, utx); // } @Override public void getHistoryTx(AddressStatus status, TransactionEventListener listener) { List<HistoryTx> htx = historyTxs.get(status.getAddress()); if (status == null) { htx = ImmutableList.of(); } listener.onTransactionHistory(status, htx); } @Override public void getTransaction(Sha256Hash txHash, TransactionEventListener listener) { Transaction tx = new Transaction(coinType, rawTxs.get(txHash)); listener.onTransactionUpdate(tx); } @Override public void broadcastTx(Transaction tx, TransactionEventListener listener) { // List<AddressStatus> newStatuses = new ArrayList<AddressStatus>(); // Random rand = new Random(); // byte[] randBytes = new byte[32]; // // Get spent outputs and modify statuses // for (TransactionInput txi : tx.getInputs()) { // UnspentTx unspentTx = new UnspentTx( // txi.getOutpoint(), txi.getValue().value, 0); // // for (Map.Entry<Address, ArrayList<UnspentTx>> entry : utxs.entrySet()) { // if (entry.getValue().remove(unspentTx)) { // rand.nextBytes(randBytes); // AddressStatus newStatus = new AddressStatus(entry.getKey(), Utils.HEX.encode(randBytes)); // statuses.put(entry.getKey(), newStatus); // newStatuses.add(newStatus); // } // } // } // // for (TransactionOutput txo : tx.getOutputs()) { // if (txo.getAddressFromP2PKHScript(coinType) != null) { // Address address = txo.getAddressFromP2PKHScript(coinType); // if (addresses.contains(address.toString())) { // AddressStatus newStatus = new AddressStatus(address, tx.getHashAsString()); // statuses.put(address, newStatus); // newStatuses.add(newStatus); // if (!utxs.containsKey(address)) { // utxs.put(address, new ArrayList<UnspentTx>()); // } // ArrayList<UnspentTx> unspentTxs = utxs.get(address); // unspentTxs.add(new UnspentTx(txo.getOutPointFor(), // txo.getValue().value, 0)); // if (!historyTxs.containsKey(address)) { // historyTxs.put(address, new ArrayList<HistoryTx>()); // } // ArrayList<HistoryTx> historyTxes = historyTxs.get(address); // historyTxes.add(new HistoryTx(txo.getOutPointFor(), 0)); // } // } // } // // rawTxs.put(tx.getHash(), tx.bitcoinSerialize()); // // for (AddressStatus newStatus : newStatuses) { // listener.onAddressStatusUpdate(newStatus); // } } @Override public boolean broadcastTxSync(Transaction tx) { return false; } @Override public void ping() {} } private MockBlockchainConnection getBlockchainConnection(CoinType coinType) throws Exception { return new MockBlockchainConnection(coinType); } // Mock data List<String> addresses = ImmutableList.of( "nnfP8VuPfZXhNtMDzvX1bKurzcV1k7HNrQ", "nf4AUKiaGdx4GTbbh222KvtuCbAuvbcdE2", "npGkmbWtdWybFNSZQXUK6zZxbEocMtrTzz", "nVaN45bbs6AUc1EUpP71hHGBGb2qciNrJc", "nrdHFZP1AfdKBrjsSQmwFm8R2i2mzMef75", "niGZgfbhFYn6tJqksmC8CnzSRL1GHNsu7e", "nh6w8yu1zoKYoT837ffkVmuPjTaP69Pc5E", "nbyMgmEghsL9tpk7XfdH9gLGudh6Lrbbuf", "naX9akzYuWY1gKbcZo3t36aBKc1gqbzgSs", "nqcPVTGeAfCowELB2D5PdVF3FWFjFtkkFf", "nd4vVvPTpp2LfcsMPsmG3Dh7MFAsqRHp4g", "nVK4Uz5Sf56ygrr6RiwXcRvH8AuUVbjjHi", "nbipkRwT1NCSXZSrm8uAAEgQAA2s2NWMkG", "nZU6QAMAdCQcVDxEmL7GEY6ykFm8m6u6am", "nbFqayssM5s7hLjLFwf2d95JXKRWBk2pBH", "nacZfcNgVi47hamLscWdUGQhUQGGpSdgq8", "niiMT7ZYeFnaLPYtqQFBBX1sP3dT5JtcEw", "ns6GyTaniLWaiYrvAf5tk4D8tWrbcCLGyj", "nhdwQfptLTzLJGbLF3vvtqyBaqPMPecDmE", "neMUAGeTzwxLbSkXMsdmWf1fTKS1UsJjXY", "nXsAMeXxtpx8jaxnU3Xv9ZQ6ZcRcD1xYhR", "ns35rKnnWf6xP3KSj5WPkMCVVaADGi6Ndk", "nk4wcXYBEWs5HkhNLsuaQJoAjJHoK6SQmG", "npsJQWu8fsALoTPum8D4j8FDkyeusk8fU8", "nZNhZo4Vz3DnwQGPL3SJTZgUw2Kh4g9oay", "nnxDTYB8WMHMgLnCY2tuaEtysvdhRnWehZ", "nb2iaDXG1EqkcE47H87WQFkQNkeVK66Z21", "nWHAkpn2DB3DJRsbiK3vpbigoa3M2uVuF8", "nViKdC7Gm6TMmCuWTBwVE9i4rJhyfwbfqg", "nZQV5BifbGPzaxTrB4efgHruWH5rufemqP", "nVvZaLvnkCVAzpLYPoHeqU4w9zJ5yrZgUn", "nrMp6pRCk98WYWkCWq9Pqthz9HbpQu8BT3", "nnA3aYsLqysKT6gAu1dr4EKm586cmKiRxS", "nVfcVgMY7DL6nqoSxwJy7B7hKXirQwj6ic", "ni4oAzi6nCVuEdjoHyVMVKWb1DqTd3qY3H", "nnpf3gx442yomniRJPMGPapgjHrraPZXxJ", "nkuFnF8wUmHFkMycaFMvyjBoiMeR5KBKGd", "nXKccwjaUyrQkLrdqKT6aq6cDiFgBBVgNz", "nZMSNsXSAL7i1YD6KP5FrhATuZ2CWvnxqR", "nUEkQ3LjH9m4ScbP6NGtnAdnnUsdtWv99Q" ); String[] statuses = { "fe7c109d8bd90551a406cf0b3499117db04bc9c4f48e1df27ac1cf3ddcb3d464", "8a53babd831c6c3a857e20190e884efe75a005bdd7cd273c4f27ab1b8ec81c2d", "86bc2f0cf0112fd59c9aadfe5c887062c21d7a873db260dff68dcfe4417fe212", "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, null, null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, null, null, null, null, null, null, null, null, null }; String[] unspent = { "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 0, \"value\": 500000000, \"height\": 160267}, {\"tx_hash\": \"89a72ba4732505ce9b09c30668db985952701252ce0adbd7c43336396697d6ae\", \"tx_pos\": 0, \"value\": 500000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 1, \"value\": 1000000000, \"height\": 160267}, {\"tx_hash\": \"edaf445288d8e65cf7963bc8047c90f53681acaadc5ccfc5ecc67aedbd73cddb\", \"tx_pos\": 0, \"value\": 500000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 2, \"value\": 500000000, \"height\": 160267}, {\"tx_hash\": \"81a1f0f8242d5e71e65ff9e8ec51e8e85d641b607d7f691c1770d4f25918ebd7\", \"tx_pos\": 0, \"value\": 1000000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 3, \"value\": 500000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 4, \"value\": 1000000000, \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 11, \"value\": 500000000, \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 12, \"value\": 1000000000, \"height\": 160267}]", "[]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 13, \"value\": 500000000, \"height\": 160267}]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 6, \"value\": 500000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 7, \"value\": 1000000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 8, \"value\": 500000000, \"height\": 160267}]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 9, \"value\": 500000000, \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 10, \"value\": 1000000000, \"height\": 160267}]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]" }; String[] history = { "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}, {\"tx_hash\": \"89a72ba4732505ce9b09c30668db985952701252ce0adbd7c43336396697d6ae\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}, {\"tx_hash\": \"edaf445288d8e65cf7963bc8047c90f53681acaadc5ccfc5ecc67aedbd73cddb\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}, {\"tx_hash\": \"81a1f0f8242d5e71e65ff9e8ec51e8e85d641b607d7f691c1770d4f25918ebd7\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]" }; String[][] txs = { {"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f", "0100000001b8778dff640ccb144346d9db48201639b2707a0cc59e19672d2dd76cc6d1a5a6010000006b48304502210098d2e5b8a6c72442430bc09f2f4bcb56612c5b9e5eee821d65b412d099bb723402204f7f008ac052e5d7be0ab5b0c85ea5e627d725a521bd9e9b193d1fdf81c317a0012102d26e423c9da9ff4a7bf6b756b2dafb75cca34fbd34f64c4c3b77c37179c5bba2ffffffff0e0065cd1d000000001976a914ca983c2da690de3cdc693ca013d93e569810c52c88ac00ca9a3b000000001976a91477263ab93a49b1d3eb5887187704cdb82e1c60ce88ac0065cd1d000000001976a914dc40fbbc8caa1f7617d275aec9a3a14ce8d8652188ac0065cd1d000000001976a9140f2b1e5b376e22c5d1e635233eb90cf50ad9095188ac00ca9a3b000000001976a914f612ffd50b6a69df5e34ee0c5b529dfaaedca03d88ac00f633bce60000001976a914937258e3a8c463ec07e78ce62326c488170ad25e88ac0065cd1d000000001976a9142848ad5ff4cc32df3649646017c47bc04e8d211788ac00ca9a3b000000001976a914fa937737a6df2b8a5e39cce8b0bdd9510683023a88ac0065cd1d000000001976a914ae248a5d710143b6b309aaab9ce17059536e2aa388ac0065cd1d000000001976a91438d6eb11eca405be497a7183c50e437851425e0088ac00ca9a3b000000001976a91410ac6b2704146b50a1dd8f6df70736856ebf8b3488ac0065cd1d000000001976a914456816dccb3a4f33ae2dbd3ba623997075d5c73d88ac00ca9a3b000000001976a91452957c44e5bee9a60402a739fc8959c2850ea98488ac0065cd1d000000001976a914fb2dffa402d05f74335d137e21e41d8920c745fb88ac00000000"}, {"89a72ba4732505ce9b09c30668db985952701252ce0adbd7c43336396697d6ae", "01000000011a656d67706db286d1e6fad57eb4f411cb14f8880cea8348da339b9d434a5ec7050000006a47304402201d69fddb269b53aa742ff6437a45adb4ca5c59f666c9b4eabc4a0c7a6e6f4c0f022015a747b7a6d9371a4020f5b396dcd094b0f36af3fc82e95091da856181912dfa012102c9a8d5b2f768afe30ee772d185e7a61f751be05649a79508b38a2be8824adec3ffffffff020065cd1d000000001976a914ca983c2da690de3cdc693ca013d93e569810c52c88ac00b07098e60000001976a9141630d812e219e6bcbe494eb96f7a7900c216ad5d88ac00000000"}, {"edaf445288d8e65cf7963bc8047c90f53681acaadc5ccfc5ecc67aedbd73cddb", "010000000164a3990893c012b20287d43d1071ac26f4b93648ff4213db6da6979beed6b7dc010000006b48304502210086ac11d4a8146b4176a72059960690c72a9776468cd671fd07c064b51f24961d02205bcf008d6995014f3cfd79100ee9beab5688c88cca15c5cea38b769563785d900121036530415a7b3b9c5976f26a63a57d119ab39491762121723c773399a2531a1bd7ffffffff020065cd1d000000001976a91477263ab93a49b1d3eb5887187704cdb82e1c60ce88ac006aad74e60000001976a914e5616848352c328c9f61b167eb1b0fde39b5cb6788ac00000000"}, {"81a1f0f8242d5e71e65ff9e8ec51e8e85d641b607d7f691c1770d4f25918ebd7", "010000000141c217dfea3a1d8d6a06e9d3daf75b292581f652256d73a7891e5dc9c7ee3cca000000006a47304402205cce451228f98fece9645052546b82c2b2d425a4889b03999001fababfc7f4690220583b2189faef07d6b0191c788301cfab1b3f47ffe2c403d632b92c6dde27e14f012102d26e423c9da9ff4a7bf6b756b2dafb75cca34fbd34f64c4c3b77c37179c5bba2ffffffff0100ca9a3b000000001976a914dc40fbbc8caa1f7617d275aec9a3a14ce8d8652188ac00000000"} }; String expectedTx = "01000000039f79b1953195fe490a8036b9b1c735cb0c7efb1474700bd6e2778a3e27da74ef040000006b483045022100ec1ede06eb8ef3e0e7afead274c86cd505f7f88d0077db86aee4f38b11b304150220329ade48f5881ad923c7acc98004c84982fb2440cbac7778e30c95da254f2f9a012103c956c491833b8f1ebfde275cd7d5660824c53efe215f9956356b85f6c86031ffffffffff9f79b1953195fe490a8036b9b1c735cb0c7efb1474700bd6e2778a3e27da74ef010000006a47304402207700077df150a7796f950784eeb0d7e38e7e144cba051cab01002ca4d23167ed02204e460a31805e014b0f312202e5d7c35da62b4a2f209c8b16cdc977a9a8f7128b0121033daee143740ae505dd588be89f659b34ba30f587bcebece11d72ec7a115bc41bffffffffd7eb1859f2d470171c697f7d601b645de8e851ece8f95fe6715e2d24f8f0a181000000006a4730440220710c679f4e4024d8df8c5178106cb50db232b793c49327f5c73a70c8f4c2a17e0220693410baf65a82aad63bf961bf1d2687cf085f8560bf38e14b9efabd9663554d01210392ed3b840c8474f8b6b57e71d9a60fbf75adea6fc68d8985330e8d782b80621fffffffff0200bbeea0000000001976a914007d5355731b44e274eb495a26f4c33a734ee3eb88ac00c2eb0b000000001976a914392d52419e94e237f0d5817de1c9e21d09b515a688ac00000000"; }
onix-project/wallet-android
core/src/test/java/com/onix/core/wallet/WalletPocketHDTest.java
45,947
package com.fillerino.core.wallet; import com.fillerino.core.coins.BitcoinMain; import com.fillerino.core.coins.CoinType; import com.fillerino.core.coins.DogecoinTest; import com.fillerino.core.coins.NuBitsMain; import com.fillerino.core.coins.Value; import com.fillerino.core.coins.VpncoinMain; import com.fillerino.core.exceptions.AddressMalformedException; import com.fillerino.core.exceptions.Bip44KeyLookAheadExceededException; import com.fillerino.core.exceptions.KeyIsEncryptedException; import com.fillerino.core.exceptions.MissingPrivateKeyException; import com.fillerino.core.network.AddressStatus; import com.fillerino.core.network.BlockHeader; import com.fillerino.core.network.interfaces.ConnectionEventListener; import com.fillerino.core.network.interfaces.TransactionEventListener; import com.fillerino.core.protos.Protos; import com.fillerino.core.wallet.families.bitcoin.BitAddress; import com.fillerino.core.wallet.families.bitcoin.BitBlockchainConnection; import com.fillerino.core.wallet.families.bitcoin.BitSendRequest; import com.fillerino.core.wallet.families.bitcoin.BitTransaction; import com.fillerino.core.wallet.families.bitcoin.BitTransactionEventListener; import com.fillerino.core.wallet.families.bitcoin.OutPointOutput; import com.fillerino.core.wallet.families.bitcoin.TrimmedOutPoint; import com.fillerino.core.Preconditions; import com.fillerino.core.network.ServerClient; import com.google.common.collect.ImmutableList; import org.bitcoinj.core.ChildMessage; import org.bitcoinj.core.Coin; import org.bitcoinj.core.ECKey; import org.bitcoinj.core.Sha256Hash; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.TransactionConfidence.Source; import org.bitcoinj.core.TransactionInput; import org.bitcoinj.core.TransactionOutput; import org.bitcoinj.core.Utils; import org.bitcoinj.crypto.DeterministicHierarchy; import org.bitcoinj.crypto.DeterministicKey; import org.bitcoinj.crypto.HDKeyDerivation; import org.bitcoinj.crypto.KeyCrypter; import org.bitcoinj.crypto.KeyCrypterScrypt; import org.bitcoinj.store.UnreadableWalletException; import org.bitcoinj.utils.BriefLogFormatter; import org.bitcoinj.wallet.DeterministicSeed; import org.bitcoinj.wallet.KeyChain; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.spongycastle.crypto.params.KeyParameter; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.fillerino.core.Preconditions.checkNotNull; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; /** * @author John L. Jegutanis */ public class WalletPocketHDTest { static final CoinType BTC = BitcoinMain.get(); static final CoinType DOGE = DogecoinTest.get(); static final CoinType NBT = NuBitsMain.get(); static final CoinType VPN = VpncoinMain.get(); static final List<String> MNEMONIC = ImmutableList.of("citizen", "fever", "scale", "nurse", "brief", "round", "ski", "fiction", "car", "fitness", "pluck", "act"); static final byte[] AES_KEY_BYTES = {0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7}; static final long AMOUNT_TO_SEND = 2700000000L; static final String MESSAGE = "test"; static final String MESSAGE_UNICODE = "δοκιμή испытание 测试"; static final String EXPECTED_BITCOIN_SIG = "IMBbIFDDuUwomYlvSjwWytqP/CXYym2yOKbJUx8Y+ujzZKBwoCFMr73GUxpr1Ird/DvnNZcsQLphvx18ftqN54o="; static final String EXPECTED_BITCOIN_SIG_UNICODE = "IGGZEOBsVny5dozTOfc2/3UuvmZGdDI4XK/03HIk34PILd2oXbnq+87GINT3lumeXcgSO2NkGzUFcQ1SCSVI3Hk="; static final String EXPECTED_NUBITS_SIG = "IMuzNZTZIjZjLicyDFGzqFl21vqNBGW1N5m4qHBRqbTvLBbkQeGjraeLmZEt7mRH4MSMPLFXW2T3Maz+HYx1tEc="; static final String EXPECTED_NUBITS_SIG_UNICODE = "Hx7xkBbboXrp96dbQrJFzm2unTGwLstjbWlKa1/N1E4LJqbwJAJR1qIvwXm6LHQFnLOzwoQA45zYNjwUEPMc8sg="; DeterministicSeed seed = new DeterministicSeed(MNEMONIC, null, "", 0); DeterministicKey masterKey = HDKeyDerivation.createMasterPrivateKey(Preconditions.checkNotNull(seed.getSeedBytes())); DeterministicHierarchy hierarchy = new DeterministicHierarchy(masterKey); DeterministicKey rootKey = hierarchy.get(DOGE.getBip44Path(0), false, true); KeyParameter aesKey = new KeyParameter(AES_KEY_BYTES); KeyCrypter crypter = new KeyCrypterScrypt(); WalletPocketHD pocket; @Before public void setup() { BriefLogFormatter.init(); pocket = new WalletPocketHD(rootKey, DOGE, null, null); pocket.keys.setLookaheadSize(20); } @Test public void testId() throws Exception { assertEquals("8747886e9a77fe2a1588df3168b867648434d6d339b0b448793ae1db8f283f41", pocket.getId()); } @Test public void testSingleAddressWallet() throws Exception { ECKey key = pocket.keys.getCurrentUnusedKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); BitWalletSingleKey bitWalletSingleKey = new BitWalletSingleKey(DOGE, key); bitWalletSingleKey.onConnection(getBlockchainConnection(DOGE)); assertEquals(DOGE.value("10"), bitWalletSingleKey.getBalance()); } @Test public void xpubWallet() { String xpub = "xpub67tVq9TLPPoaHVSiYu8mqahm3eztTPUts6JUftNq3pZF1PJwjknrTqQhjc2qRGd6vS8wANu7mLnqkiUzFZ1xZsAZoUMi8o6icMhzGCAhcSW"; DeterministicKey key = DeterministicKey.deserializeB58(null, xpub); WalletPocketHD account = new WalletPocketHD(key, BTC, null, null); assertEquals("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", account.getReceiveAddress().toString()); account = new WalletPocketHD(key, NBT, null, null); assertEquals("BNvJUwg3BgkbQk5br1CxvHxdcDp1EC3saE", account.getReceiveAddress().toString()); } @Test public void xpubWalletSerialized() throws Exception { WalletPocketHD account = new WalletPocketHD(rootKey, BTC, null, null); Protos.WalletPocket proto = account.toProtobuf(); WalletPocketHD newAccount = new WalletPocketProtobufSerializer().readWallet(proto, null); assertEquals(account.getPublicKeySerialized(), newAccount.getPublicKeySerialized()); } @Test public void signMessage() throws AddressMalformedException, MissingPrivateKeyException, KeyIsEncryptedException { WalletPocketHD pocketHD = new WalletPocketHD(rootKey, BTC, null, null); pocketHD.getReceiveAddress(); // Generate the first key SignedMessage signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE); pocketHD.signMessage(signedMessage, null); assertEquals(EXPECTED_BITCOIN_SIG, signedMessage.getSignature()); signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE_UNICODE); pocketHD.signMessage(signedMessage, null); assertEquals(EXPECTED_BITCOIN_SIG_UNICODE, signedMessage.getSignature()); pocketHD = new WalletPocketHD(rootKey, NBT, null, null); pocketHD.getReceiveAddress(); // Generate the first key signedMessage = new SignedMessage("BNvJUwg3BgkbQk5br1CxvHxdcDp1EC3saE", MESSAGE); pocketHD.signMessage(signedMessage, null); assertEquals(EXPECTED_NUBITS_SIG, signedMessage.getSignature()); signedMessage = new SignedMessage("BNvJUwg3BgkbQk5br1CxvHxdcDp1EC3saE", MESSAGE_UNICODE); pocketHD.signMessage(signedMessage, null); assertEquals(EXPECTED_NUBITS_SIG_UNICODE, signedMessage.getSignature()); } @Test public void signMessageEncrypted() throws AddressMalformedException, MissingPrivateKeyException, KeyIsEncryptedException { WalletPocketHD pocketHD = new WalletPocketHD(rootKey, BTC, null, null); pocketHD.getReceiveAddress(); // Generate the first key pocketHD.encrypt(crypter, aesKey); SignedMessage signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE); pocketHD.signMessage(signedMessage, aesKey); assertEquals(EXPECTED_BITCOIN_SIG, signedMessage.getSignature()); signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE_UNICODE); pocketHD.signMessage(signedMessage, aesKey); assertEquals(EXPECTED_BITCOIN_SIG_UNICODE, signedMessage.getSignature()); } @Test public void signMessageEncryptedFailed() throws AddressMalformedException, MissingPrivateKeyException, KeyIsEncryptedException { WalletPocketHD pocketHD = new WalletPocketHD(rootKey, BTC, null, null); pocketHD.getReceiveAddress(); // Generate the first key pocketHD.encrypt(crypter, aesKey); SignedMessage signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE); pocketHD.signMessage(signedMessage, null); assertEquals(SignedMessage.Status.KeyIsEncrypted, signedMessage.status); } @Test public void watchingAddresses() { List<AbstractAddress> watchingAddresses = pocket.getAddressesToWatch(); assertEquals(40, watchingAddresses.size()); // 20 + 20 lookahead size for (int i = 0; i < addresses.size(); i++) { assertEquals(addresses.get(i), watchingAddresses.get(i).toString()); } } @Test public void issuedKeys() throws Bip44KeyLookAheadExceededException { List<BitAddress> issuedAddresses = new ArrayList<>(); assertEquals(0, pocket.getIssuedReceiveAddresses().size()); assertEquals(0, pocket.keys.getNumIssuedExternalKeys()); issuedAddresses.add(0, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS)); BitAddress freshAddress = pocket.getFreshReceiveAddress(); assertEquals(freshAddress, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS)); assertEquals(1, pocket.getIssuedReceiveAddresses().size()); assertEquals(1, pocket.keys.getNumIssuedExternalKeys()); assertEquals(issuedAddresses, pocket.getIssuedReceiveAddresses()); issuedAddresses.add(0, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS)); freshAddress = pocket.getFreshReceiveAddress(); assertEquals(freshAddress, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS)); assertEquals(2, pocket.getIssuedReceiveAddresses().size()); assertEquals(2, pocket.keys.getNumIssuedExternalKeys()); assertEquals(issuedAddresses, pocket.getIssuedReceiveAddresses()); } @Test public void issuedKeysLimit() throws Exception { assertTrue(pocket.canCreateFreshReceiveAddress()); try { for (int i = 0; i < 100; i++) { pocket.getFreshReceiveAddress(); } } catch (Bip44KeyLookAheadExceededException e) { assertFalse(pocket.canCreateFreshReceiveAddress()); // We haven't used any key so the total must be 20 - 1 (the unused key) assertEquals(19, pocket.getNumberIssuedReceiveAddresses()); assertEquals(19, pocket.getIssuedReceiveAddresses().size()); } pocket.onConnection(getBlockchainConnection(DOGE)); assertTrue(pocket.canCreateFreshReceiveAddress()); try { for (int i = 0; i < 100; i++) { pocket.getFreshReceiveAddress(); } } catch (Bip44KeyLookAheadExceededException e) { // try { // pocket.getFreshReceiveAddress(); // } catch (Bip44KeyLookAheadExceededException e1) { /* ignore */ } assertFalse(pocket.canCreateFreshReceiveAddress()); // We used 18, so the total must be (20-1)+18=37 assertEquals(37, pocket.getNumberIssuedReceiveAddresses()); assertEquals(37, pocket.getIssuedReceiveAddresses().size()); } } @Test public void issuedKeysLimit2() throws Exception { assertTrue(pocket.canCreateFreshReceiveAddress()); try { for (int i = 0; i < 100; i++) { pocket.getFreshReceiveAddress(); } } catch (Bip44KeyLookAheadExceededException e) { assertFalse(pocket.canCreateFreshReceiveAddress()); // We haven't used any key so the total must be 20 - 1 (the unused key) assertEquals(19, pocket.getNumberIssuedReceiveAddresses()); assertEquals(19, pocket.getIssuedReceiveAddresses().size()); } } @Test public void usedAddresses() throws Exception { assertEquals(0, pocket.getUsedAddresses().size()); pocket.onConnection(getBlockchainConnection(DOGE)); // Receive and change addresses assertEquals(13, pocket.getUsedAddresses().size()); } private Sha256Hash send(Value value, WalletPocketHD w1, WalletPocketHD w2) throws Exception { Assert.assertEquals(w1.getCoinType(), w2.getCoinType()); CoinType type = w1.getCoinType(); BitSendRequest req = w1.sendCoinsOffline(w2.getReceiveAddress(), value); req.feePerTxSize = type.value("0.01"); w1.completeAndSignTx(req); byte[] txBytes = req.tx.bitcoinSerialize(); w1.addNewTransactionIfNeeded(new BitTransaction(type, txBytes)); w2.addNewTransactionIfNeeded(new BitTransaction(type, txBytes)); return req.tx.getHash(); } @Test public void testSendingAndBalances() throws Exception { DeterministicHierarchy h = new DeterministicHierarchy(masterKey); WalletPocketHD account1 = new WalletPocketHD(h.get(BTC.getBip44Path(0), false, true), BTC, null, null); WalletPocketHD account2 = new WalletPocketHD(h.get(BTC.getBip44Path(1), false, true), BTC, null, null); WalletPocketHD account3 = new WalletPocketHD(h.get(BTC.getBip44Path(2), false, true), BTC, null, null); Transaction tx = new Transaction(BTC); tx.addOutput(BTC.oneCoin().toCoin(), account1.getReceiveAddress()); tx.getConfidence().setSource(Source.SELF); account1.addNewTransactionIfNeeded(tx); assertEquals(BTC.value("1"), account1.getBalance()); assertEquals(BTC.value("0"), account2.getBalance()); assertEquals(BTC.value("0"), account3.getBalance()); Sha256Hash txId = send(BTC.value("0.05"), account1, account2); assertEquals(BTC.value("0.94"), account1.getBalance()); assertEquals(BTC.value("0"), account2.getBalance()); assertEquals(BTC.value("0"), account3.getBalance()); setTrustedTransaction(account1, txId); setTrustedTransaction(account2, txId); assertEquals(BTC.value("0.94"), account1.getBalance()); assertEquals(BTC.value("0.05"), account2.getBalance()); txId = send(BTC.value("0.07"), account1, account3); setTrustedTransaction(account1, txId); setTrustedTransaction(account3, txId); assertEquals(BTC.value("0.86"), account1.getBalance()); assertEquals(BTC.value("0.05"), account2.getBalance()); assertEquals(BTC.value("0.07"), account3.getBalance()); txId = send(BTC.value("0.03"), account2, account3); setTrustedTransaction(account2, txId); setTrustedTransaction(account3, txId); assertEquals(BTC.value("0.86"), account1.getBalance()); assertEquals(BTC.value("0.01"), account2.getBalance()); assertEquals(BTC.value("0.1"), account3.getBalance()); } private void setTrustedTransaction(WalletPocketHD account, Sha256Hash txId) { BitTransaction tx = Preconditions.checkNotNull(account.getTransaction(txId)); tx.setSource(Source.SELF); } @Test public void testLoading() throws Exception { assertFalse(pocket.isLoading()); pocket.onConnection(getBlockchainConnection(DOGE)); // TODO add fine grained control to the blockchain connection in order to test the loading status assertFalse(pocket.isLoading()); } @Test public void fillTransactions() throws Exception { pocket.onConnection(getBlockchainConnection(DOGE)); checkUnspentOutputs(getDummyUtxoSet(), pocket); assertEquals(11000000000L, pocket.getBalance().value); // Issued keys assertEquals(18, pocket.keys.getNumIssuedExternalKeys()); assertEquals(9, pocket.keys.getNumIssuedInternalKeys()); // No addresses left to subscribe List<AbstractAddress> addressesToWatch = pocket.getAddressesToWatch(); assertEquals(0, addressesToWatch.size()); // 18 external issued + 20 lookahead + 9 external issued + 20 lookahead assertEquals(67, pocket.addressesStatus.size()); assertEquals(67, pocket.addressesSubscribed.size()); BitAddress receiveAddr = pocket.getReceiveAddress(); // This key is not issued assertEquals(18, pocket.keys.getNumIssuedExternalKeys()); assertEquals(67, pocket.addressesStatus.size()); assertEquals(67, pocket.addressesSubscribed.size()); DeterministicKey key = pocket.keys.findKeyFromPubHash(receiveAddr.getHash160()); assertNotNull(key); // 18 here is the key index, not issued keys count assertEquals(18, key.getChildNumber().num()); assertEquals(11000000000L, pocket.getBalance().value); } @Test public void serializeTransactionsBtc() throws Exception, Bip44KeyLookAheadExceededException { WalletPocketHD account = new WalletPocketHD(rootKey, BTC, null, null); Transaction tx = new Transaction(BTC); tx.addOutput(BTC.oneCoin().toCoin(), account.getReceiveAddress()); account.addNewTransactionIfNeeded(tx); testWalletSerializationForCoin(account); } @Test public void serializeTransactionsNbt() throws Exception, Bip44KeyLookAheadExceededException { WalletPocketHD account = new WalletPocketHD(rootKey, NBT, null, null); Transaction tx = new Transaction(NBT); tx.addOutput(NBT.oneCoin().toCoin(), account.getReceiveAddress()); account.addNewTransactionIfNeeded(tx); testWalletSerializationForCoin(account); } @Test public void serializeTransactionsVpn() throws Exception, Bip44KeyLookAheadExceededException { WalletPocketHD account = new WalletPocketHD(rootKey, VPN, null, null); // Test tx with null extra bytes Transaction tx = new Transaction(VPN); tx.setTime(0x99999999); tx.addOutput(VPN.oneCoin().toCoin(), account.getFreshReceiveAddress()); account.addNewTransactionIfNeeded(tx); WalletPocketHD newAccount = testWalletSerializationForCoin(account); Transaction newTx = newAccount.getRawTransaction(tx.getHash()); assertNotNull(newTx); assertNotNull(newTx.getExtraBytes()); assertEquals(0, newTx.getExtraBytes().length); // Test tx with empty extra bytes tx = new Transaction(VPN); tx.setTime(0x99999999); tx.setExtraBytes(new byte[0]); tx.addOutput(VPN.oneCoin().toCoin(), account.getFreshReceiveAddress()); account.addNewTransactionIfNeeded(tx); newAccount = testWalletSerializationForCoin(account); newTx = newAccount.getRawTransaction(tx.getHash()); assertNotNull(newTx); assertNotNull(newTx.getExtraBytes()); assertEquals(0, newTx.getExtraBytes().length); // Test tx with extra bytes tx = new Transaction(VPN); tx.setTime(0x99999999); byte[] bytes = {0x1, 0x2, 0x3}; tx.setExtraBytes(bytes); tx.addOutput(VPN.oneCoin().toCoin(), account.getFreshReceiveAddress()); account.addNewTransactionIfNeeded(tx); newAccount = testWalletSerializationForCoin(account); newTx = newAccount.getRawTransaction(tx.getHash()); assertNotNull(newTx); assertArrayEquals(bytes, newTx.getExtraBytes()); } private WalletPocketHD testWalletSerializationForCoin(WalletPocketHD account) throws UnreadableWalletException { Protos.WalletPocket proto = account.toProtobuf(); WalletPocketHD newAccount = new WalletPocketProtobufSerializer().readWallet(proto, null); assertEquals(account.getBalance().value, newAccount.getBalance().value); Map<Sha256Hash, BitTransaction> transactions = account.getTransactions(); Map<Sha256Hash, BitTransaction> newTransactions = newAccount.getTransactions(); for (Sha256Hash txId : transactions.keySet()) { assertTrue(newTransactions.containsKey(txId)); assertEquals(transactions.get(txId), newTransactions.get(txId)); } return newAccount; } @Test public void serializeUnencryptedNormal() throws Exception { pocket.onConnection(getBlockchainConnection(DOGE)); Protos.WalletPocket walletPocketProto = pocket.toProtobuf(); System.out.println(walletPocketProto.toString()); WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(walletPocketProto, null); assertEquals(pocket.getBalance().value, newPocket.getBalance().value); assertEquals(DOGE.value(11000000000l), newPocket.getBalance()); Map<TrimmedOutPoint, OutPointOutput> expectedUtxoSet = getDummyUtxoSet(); checkUnspentOutputs(expectedUtxoSet, pocket); checkUnspentOutputs(expectedUtxoSet, newPocket); Assert.assertEquals(pocket.getCoinType(), newPocket.getCoinType()); assertEquals(pocket.getDescriptionOrCoinName(), newPocket.getDescriptionOrCoinName()); assertEquals(pocket.keys.toProtobuf().toString(), newPocket.keys.toProtobuf().toString()); assertEquals(pocket.getLastBlockSeenHash(), newPocket.getLastBlockSeenHash()); assertEquals(pocket.getLastBlockSeenHeight(), newPocket.getLastBlockSeenHeight()); assertEquals(pocket.getLastBlockSeenTimeSecs(), newPocket.getLastBlockSeenTimeSecs()); for (BitTransaction tx : pocket.getTransactions().values()) { Assert.assertEquals(tx, newPocket.getTransaction(tx.getHash())); BitTransaction txNew = Preconditions.checkNotNull(newPocket.getTransaction(tx.getHash())); assertInputsEquals(tx.getInputs(), txNew.getInputs()); assertOutputsEquals(tx.getOutputs(false), txNew.getOutputs(false)); } for (AddressStatus status : pocket.getAllAddressStatus()) { if (status.getStatus() == null) continue; Assert.assertEquals(status, newPocket.getAddressStatus(status.getAddress())); } // Issued keys assertEquals(18, newPocket.keys.getNumIssuedExternalKeys()); assertEquals(9, newPocket.keys.getNumIssuedInternalKeys()); newPocket.onConnection(getBlockchainConnection(DOGE)); // No addresses left to subscribe List<AbstractAddress> addressesToWatch = newPocket.getAddressesToWatch(); assertEquals(0, addressesToWatch.size()); // 18 external issued + 20 lookahead + 9 external issued + 20 lookahead assertEquals(67, newPocket.addressesStatus.size()); assertEquals(67, newPocket.addressesSubscribed.size()); } private void assertInputsEquals(List<TransactionInput> expected, List<TransactionInput> actual) { assertEquals(expected.size(), actual.size()); for (int i = 0; i < expected.size(); i++) { assertArrayEquals(expected.get(i).bitcoinSerialize(), actual.get(i).bitcoinSerialize()); } } private void assertOutputsEquals(List<TransactionOutput> expected, List<TransactionOutput> actual) { assertEquals(expected.size(), actual.size()); for (int i = 0; i < expected.size(); i++) { assertArrayEquals(expected.get(i).bitcoinSerialize(), actual.get(i).bitcoinSerialize()); } } @Test public void serializeUnencryptedEmpty() throws Exception { pocket.maybeInitializeAllKeys(); Protos.WalletPocket walletPocketProto = pocket.toProtobuf(); WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(walletPocketProto, null); Assert.assertEquals(walletPocketProto.toString(), newPocket.toProtobuf().toString()); // Issued keys assertEquals(0, newPocket.keys.getNumIssuedExternalKeys()); assertEquals(0, newPocket.keys.getNumIssuedInternalKeys()); // 20 lookahead + 20 lookahead assertEquals(40, newPocket.keys.getActiveKeys().size()); } @Test public void serializeEncryptedEmpty() throws Exception { pocket.maybeInitializeAllKeys(); pocket.encrypt(crypter, aesKey); Protos.WalletPocket walletPocketProto = pocket.toProtobuf(); WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(walletPocketProto, crypter); Assert.assertEquals(walletPocketProto.toString(), newPocket.toProtobuf().toString()); pocket.decrypt(aesKey); // One is encrypted, so they should not match Assert.assertNotEquals(pocket.toProtobuf().toString(), newPocket.toProtobuf().toString()); newPocket.decrypt(aesKey); Assert.assertEquals(pocket.toProtobuf().toString(), newPocket.toProtobuf().toString()); } @Test public void serializeEncryptedNormal() throws Exception { pocket.maybeInitializeAllKeys(); pocket.encrypt(crypter, aesKey); pocket.onConnection(getBlockchainConnection(DOGE)); assertEquals(DOGE.value(11000000000l), pocket.getBalance()); assertAllKeysEncrypted(pocket); WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(pocket.toProtobuf(), crypter); assertEquals(DOGE.value(11000000000l), newPocket.getBalance()); Map<TrimmedOutPoint, OutPointOutput> expectedUtxoSet = getDummyUtxoSet(); checkUnspentOutputs(expectedUtxoSet, pocket); checkUnspentOutputs(expectedUtxoSet, newPocket); assertAllKeysEncrypted(newPocket); pocket.decrypt(aesKey); newPocket.decrypt(aesKey); assertAllKeysDecrypted(pocket); assertAllKeysDecrypted(newPocket); } private void checkUnspentOutputs(Map<TrimmedOutPoint, OutPointOutput> expectedUtxoSet, WalletPocketHD pocket) { Map<TrimmedOutPoint, OutPointOutput> pocketUtxoSet = pocket.getUnspentOutputs(false); for (OutPointOutput utxo : expectedUtxoSet.values()) { assertEquals(utxo, pocketUtxoSet.get(utxo.getOutPoint())); } } private void assertAllKeysDecrypted(WalletPocketHD pocket) { List<ECKey> keys = pocket.keys.getKeys(false); for (ECKey k : keys) { DeterministicKey key = (DeterministicKey) k; assertFalse(key.isEncrypted()); } } private void assertAllKeysEncrypted(WalletPocketHD pocket) { List<ECKey> keys = pocket.keys.getKeys(false); for (ECKey k : keys) { DeterministicKey key = (DeterministicKey) k; assertTrue(key.isEncrypted()); } } @Test public void createDustTransactionFee() throws Exception { pocket.onConnection(getBlockchainConnection(DOGE)); BitAddress toAddr = BitAddress.from(DOGE, "nZB8PHkfgJvuCJqchSexmfY3ABXa2aE1vp"); Value softDust = DOGE.getSoftDustLimit(); assertNotNull(softDust); // Send a soft dust BitSendRequest sendRequest = pocket.sendCoinsOffline(toAddr, softDust.subtract(DOGE.value(1))); pocket.completeTransaction(sendRequest); assertEquals(DOGE.getFeeValue().multiply(2), sendRequest.tx.getFee()); } @Test public void createTransactionAndBroadcast() throws Exception { pocket.onConnection(getBlockchainConnection(DOGE)); BitAddress toAddr = BitAddress.from(DOGE, "nZB8PHkfgJvuCJqchSexmfY3ABXa2aE1vp"); Value orgBalance = pocket.getBalance(); BitSendRequest sendRequest = pocket.sendCoinsOffline(toAddr, DOGE.value(AMOUNT_TO_SEND)); sendRequest.shuffleOutputs = false; sendRequest.feePerTxSize = DOGE.value(0); pocket.completeTransaction(sendRequest); // FIXME, mock does not work here // pocket.broadcastTx(tx); pocket.addNewTransactionIfNeeded(sendRequest.tx); assertEquals(orgBalance.subtract(AMOUNT_TO_SEND), pocket.getBalance()); } // Util methods //////////////////////////////////////////////////////////////////////////////////////////////// public class MessageComparator implements Comparator<ChildMessage> { @Override public int compare(ChildMessage o1, ChildMessage o2) { String s1 = Utils.HEX.encode(o1.bitcoinSerialize()); String s2 = Utils.HEX.encode(o2.bitcoinSerialize()); return s1.compareTo(s2); } } HashMap<AbstractAddress, AddressStatus> getDummyStatuses() throws AddressMalformedException { HashMap<AbstractAddress, AddressStatus> status = new HashMap<>(40); for (int i = 0; i < addresses.size(); i++) { AbstractAddress address = DOGE.newAddress(addresses.get(i)); status.put(address, new AddressStatus(address, statuses[i])); } return status; } private HashMap<AbstractAddress, ArrayList<ServerClient.HistoryTx>> getDummyHistoryTXs() throws AddressMalformedException, JSONException { HashMap<AbstractAddress, ArrayList<ServerClient.HistoryTx>> htxs = new HashMap<>(40); for (int i = 0; i < statuses.length; i++) { JSONArray jsonArray = new JSONArray(history[i]); ArrayList<ServerClient.HistoryTx> list = new ArrayList<>(); for (int j = 0; j < jsonArray.length(); j++) { list.add(new ServerClient.HistoryTx(jsonArray.getJSONObject(j))); } htxs.put(DOGE.newAddress(addresses.get(i)), list); } return htxs; } private HashMap<AbstractAddress, ArrayList<ServerClient.UnspentTx>> getDummyUnspentTXs() throws AddressMalformedException, JSONException { HashMap<AbstractAddress, ArrayList<ServerClient.UnspentTx>> utxs = new HashMap<>(40); for (int i = 0; i < statuses.length; i++) { JSONArray jsonArray = new JSONArray(unspent[i]); ArrayList<ServerClient.UnspentTx> list = new ArrayList<>(); for (int j = 0; j < jsonArray.length(); j++) { list.add(new ServerClient.UnspentTx(jsonArray.getJSONObject(j))); } utxs.put(DOGE.newAddress(addresses.get(i)), list); } return utxs; } private Map<TrimmedOutPoint, OutPointOutput> getDummyUtxoSet() throws AddressMalformedException, JSONException { final HashMap<TrimmedOutPoint, OutPointOutput> unspentOutputs = new HashMap<>(); for (int i = 0; i < statuses.length; i++) { BitAddress address = (BitAddress) DOGE.newAddress(addresses.get(i)); JSONArray utxoArray = new JSONArray(unspent[i]); for (int j = 0; j < utxoArray.length(); j++) { JSONObject utxoObject = utxoArray.getJSONObject(j); //"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 11, \"value\": 500000000, \"height\": 160267}]", TrimmedOutPoint outPoint = new TrimmedOutPoint(DOGE, utxoObject.getInt("tx_pos"), new Sha256Hash(utxoObject.getString("tx_hash"))); TransactionOutput output = new TransactionOutput(DOGE, null, Coin.valueOf(utxoObject.getLong("value")), address); OutPointOutput utxo = new OutPointOutput(outPoint, output, false); unspentOutputs.put(outPoint, utxo); } } return unspentOutputs; } private HashMap<Sha256Hash, byte[]> getDummyRawTXs() throws AddressMalformedException, JSONException { HashMap<Sha256Hash, byte[]> rawTxs = new HashMap<>(); for (String[] tx : txs) { rawTxs.put(new Sha256Hash(tx[0]), Utils.HEX.decode(tx[1])); } return rawTxs; } class MockBlockchainConnection implements BitBlockchainConnection { final HashMap<AbstractAddress, AddressStatus> statuses; final HashMap<AbstractAddress, ArrayList<ServerClient.HistoryTx>> historyTxs; final HashMap<AbstractAddress, ArrayList<ServerClient.UnspentTx>> unspentTxs; final HashMap<Sha256Hash, byte[]> rawTxs; private CoinType coinType; MockBlockchainConnection(CoinType coinType) throws Exception { this.coinType = coinType; statuses = getDummyStatuses(); historyTxs = getDummyHistoryTXs(); unspentTxs = getDummyUnspentTXs(); rawTxs = getDummyRawTXs(); } @Override public void getBlock(int height, TransactionEventListener<BitTransaction> listener) { } @Override public void subscribeToBlockchain(TransactionEventListener<BitTransaction> listener) { listener.onNewBlock(new BlockHeader(coinType, blockTimestamp, blockHeight)); } @Override public void subscribeToAddresses(List<AbstractAddress> addresses, TransactionEventListener<BitTransaction> listener) { for (AbstractAddress a : addresses) { AddressStatus status = statuses.get(a); if (status == null) { status = new AddressStatus(a, null); } listener.onAddressStatusUpdate(status); } } @Override public void getHistoryTx(AddressStatus status, TransactionEventListener<BitTransaction> listener) { List<ServerClient.HistoryTx> htx = historyTxs.get(status.getAddress()); if (htx == null) { htx = ImmutableList.of(); } listener.onTransactionHistory(status, htx); } @Override public void getUnspentTx(AddressStatus status, BitTransactionEventListener listener) { List<ServerClient.UnspentTx> utx = unspentTxs.get(status.getAddress()); if (utx == null) { utx = ImmutableList.of(); } listener.onUnspentTransactionUpdate(status, utx); } @Override public void getTransaction(Sha256Hash txHash, TransactionEventListener<BitTransaction> listener) { BitTransaction tx = new BitTransaction(coinType, rawTxs.get(txHash)); listener.onTransactionUpdate(tx); } @Override public void broadcastTx(BitTransaction tx, TransactionEventListener<BitTransaction> listener) { // List<AddressStatus> newStatuses = new ArrayList<AddressStatus>(); // Random rand = new Random(); // byte[] randBytes = new byte[32]; // // Get spent outputs and modify statuses // for (TransactionInput txi : tx.getInputs()) { // UnspentTx unspentTx = new UnspentTx( // txi.getOutpoint(), txi.getValue().value, 0); // // for (Map.Entry<Address, ArrayList<UnspentTx>> entry : utxs.entrySet()) { // if (entry.getValue().remove(unspentTx)) { // rand.nextBytes(randBytes); // AddressStatus newStatus = new AddressStatus(entry.getKey(), Utils.HEX.encode(randBytes)); // statuses.put(entry.getKey(), newStatus); // newStatuses.add(newStatus); // } // } // } // // for (TransactionOutput txo : tx.getOutputs()) { // if (txo.getAddressFromP2PKHScript(coinType) != null) { // Address address = txo.getAddressFromP2PKHScript(coinType); // if (addresses.contains(address.toString())) { // AddressStatus newStatus = new AddressStatus(address, tx.getHashAsString()); // statuses.put(address, newStatus); // newStatuses.add(newStatus); // if (!utxs.containsKey(address)) { // utxs.put(address, new ArrayList<UnspentTx>()); // } // ArrayList<UnspentTx> unspentTxs = utxs.get(address); // unspentTxs.add(new UnspentTx(txo.getOutPointFor(), // txo.getValue().value, 0)); // if (!historyTxs.containsKey(address)) { // historyTxs.put(address, new ArrayList<HistoryTx>()); // } // ArrayList<HistoryTx> historyTxes = historyTxs.get(address); // historyTxes.add(new HistoryTx(txo.getOutPointFor(), 0)); // } // } // } // // rawTxs.put(tx.getHash(), tx.bitcoinSerialize()); // // for (AddressStatus newStatus : newStatuses) { // listener.onAddressStatusUpdate(newStatus); // } } @Override public boolean broadcastTxSync(BitTransaction tx) { return false; } @Override public void ping(String versionString) {} @Override public void addEventListener(ConnectionEventListener listener) { } @Override public void resetConnection() { } @Override public void stopAsync() { } @Override public boolean isActivelyConnected() { return false; } @Override public void startAsync() { } } private MockBlockchainConnection getBlockchainConnection(CoinType coinType) throws Exception { return new MockBlockchainConnection(coinType); } // Mock data long blockTimestamp = 1411000000l; int blockHeight = 200000; List<String> addresses = ImmutableList.of( "nnfP8VuPfZXhNtMDzvX1bKurzcV1k7HNrQ", "nf4AUKiaGdx4GTbbh222KvtuCbAuvbcdE2", "npGkmbWtdWybFNSZQXUK6zZxbEocMtrTzz", "nVaN45bbs6AUc1EUpP71hHGBGb2qciNrJc", "nrdHFZP1AfdKBrjsSQmwFm8R2i2mzMef75", "niGZgfbhFYn6tJqksmC8CnzSRL1GHNsu7e", "nh6w8yu1zoKYoT837ffkVmuPjTaP69Pc5E", "nbyMgmEghsL9tpk7XfdH9gLGudh6Lrbbuf", "naX9akzYuWY1gKbcZo3t36aBKc1gqbzgSs", "nqcPVTGeAfCowELB2D5PdVF3FWFjFtkkFf", "nd4vVvPTpp2LfcsMPsmG3Dh7MFAsqRHp4g", "nVK4Uz5Sf56ygrr6RiwXcRvH8AuUVbjjHi", "nbipkRwT1NCSXZSrm8uAAEgQAA2s2NWMkG", "nZU6QAMAdCQcVDxEmL7GEY6ykFm8m6u6am", "nbFqayssM5s7hLjLFwf2d95JXKRWBk2pBH", "nacZfcNgVi47hamLscWdUGQhUQGGpSdgq8", "niiMT7ZYeFnaLPYtqQFBBX1sP3dT5JtcEw", "ns6GyTaniLWaiYrvAf5tk4D8tWrbcCLGyj", "nhdwQfptLTzLJGbLF3vvtqyBaqPMPecDmE", "neMUAGeTzwxLbSkXMsdmWf1fTKS1UsJjXY", "nXsAMeXxtpx8jaxnU3Xv9ZQ6ZcRcD1xYhR", "ns35rKnnWf6xP3KSj5WPkMCVVaADGi6Ndk", "nk4wcXYBEWs5HkhNLsuaQJoAjJHoK6SQmG", "npsJQWu8fsALoTPum8D4j8FDkyeusk8fU8", "nZNhZo4Vz3DnwQGPL3SJTZgUw2Kh4g9oay", "nnxDTYB8WMHMgLnCY2tuaEtysvdhRnWehZ", "nb2iaDXG1EqkcE47H87WQFkQNkeVK66Z21", "nWHAkpn2DB3DJRsbiK3vpbigoa3M2uVuF8", "nViKdC7Gm6TMmCuWTBwVE9i4rJhyfwbfqg", "nZQV5BifbGPzaxTrB4efgHruWH5rufemqP", "nVvZaLvnkCVAzpLYPoHeqU4w9zJ5yrZgUn", "nrMp6pRCk98WYWkCWq9Pqthz9HbpQu8BT3", "nnA3aYsLqysKT6gAu1dr4EKm586cmKiRxS", "nVfcVgMY7DL6nqoSxwJy7B7hKXirQwj6ic", "ni4oAzi6nCVuEdjoHyVMVKWb1DqTd3qY3H", "nnpf3gx442yomniRJPMGPapgjHrraPZXxJ", "nkuFnF8wUmHFkMycaFMvyjBoiMeR5KBKGd", "nXKccwjaUyrQkLrdqKT6aq6cDiFgBBVgNz", "nZMSNsXSAL7i1YD6KP5FrhATuZ2CWvnxqR", "nUEkQ3LjH9m4ScbP6NGtnAdnnUsdtWv99Q" ); String[] statuses = { "fe7c109d8bd90551a406cf0b3499117db04bc9c4f48e1df27ac1cf3ddcb3d464", "8a53babd831c6c3a857e20190e884efe75a005bdd7cd273c4f27ab1b8ec81c2d", "86bc2f0cf0112fd59c9aadfe5c887062c21d7a873db260dff68dcfe4417fe212", "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, null, null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, null, "64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9", null, null, null, null, null, null, null, null, null, null, null }; String[] unspent = { "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 0, \"value\": 500000000, \"height\": 160267}, {\"tx_hash\": \"89a72ba4732505ce9b09c30668db985952701252ce0adbd7c43336396697d6ae\", \"tx_pos\": 0, \"value\": 500000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 1, \"value\": 1000000000, \"height\": 160267}, {\"tx_hash\": \"edaf445288d8e65cf7963bc8047c90f53681acaadc5ccfc5ecc67aedbd73cddb\", \"tx_pos\": 0, \"value\": 500000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 2, \"value\": 500000000, \"height\": 160267}, {\"tx_hash\": \"81a1f0f8242d5e71e65ff9e8ec51e8e85d641b607d7f691c1770d4f25918ebd7\", \"tx_pos\": 0, \"value\": 1000000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 3, \"value\": 500000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 4, \"value\": 1000000000, \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 11, \"value\": 500000000, \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 12, \"value\": 1000000000, \"height\": 160267}]", "[]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 13, \"value\": 500000000, \"height\": 160267}]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 6, \"value\": 500000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 7, \"value\": 1000000000, \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 8, \"value\": 500000000, \"height\": 160267}]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 9, \"value\": 500000000, \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 10, \"value\": 1000000000, \"height\": 160267}]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]" }; String[] history = { "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}, {\"tx_hash\": \"89a72ba4732505ce9b09c30668db985952701252ce0adbd7c43336396697d6ae\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}, {\"tx_hash\": \"edaf445288d8e65cf7963bc8047c90f53681acaadc5ccfc5ecc67aedbd73cddb\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}, {\"tx_hash\": \"81a1f0f8242d5e71e65ff9e8ec51e8e85d641b607d7f691c1770d4f25918ebd7\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[]", "[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]", "[]" }; String[][] txs = { {"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f", "0100000001b8778dff640ccb144346d9db48201639b2707a0cc59e19672d2dd76cc6d1a5a6010000006b48304502210098d2e5b8a6c72442430bc09f2f4bcb56612c5b9e5eee821d65b412d099bb723402204f7f008ac052e5d7be0ab5b0c85ea5e627d725a521bd9e9b193d1fdf81c317a0012102d26e423c9da9ff4a7bf6b756b2dafb75cca34fbd34f64c4c3b77c37179c5bba2ffffffff0e0065cd1d000000001976a914ca983c2da690de3cdc693ca013d93e569810c52c88ac00ca9a3b000000001976a91477263ab93a49b1d3eb5887187704cdb82e1c60ce88ac0065cd1d000000001976a914dc40fbbc8caa1f7617d275aec9a3a14ce8d8652188ac0065cd1d000000001976a9140f2b1e5b376e22c5d1e635233eb90cf50ad9095188ac00ca9a3b000000001976a914f612ffd50b6a69df5e34ee0c5b529dfaaedca03d88ac00f633bce60000001976a914937258e3a8c463ec07e78ce62326c488170ad25e88ac0065cd1d000000001976a9142848ad5ff4cc32df3649646017c47bc04e8d211788ac00ca9a3b000000001976a914fa937737a6df2b8a5e39cce8b0bdd9510683023a88ac0065cd1d000000001976a914ae248a5d710143b6b309aaab9ce17059536e2aa388ac0065cd1d000000001976a91438d6eb11eca405be497a7183c50e437851425e0088ac00ca9a3b000000001976a91410ac6b2704146b50a1dd8f6df70736856ebf8b3488ac0065cd1d000000001976a914456816dccb3a4f33ae2dbd3ba623997075d5c73d88ac00ca9a3b000000001976a91452957c44e5bee9a60402a739fc8959c2850ea98488ac0065cd1d000000001976a914fb2dffa402d05f74335d137e21e41d8920c745fb88ac00000000"}, {"89a72ba4732505ce9b09c30668db985952701252ce0adbd7c43336396697d6ae", "01000000011a656d67706db286d1e6fad57eb4f411cb14f8880cea8348da339b9d434a5ec7050000006a47304402201d69fddb269b53aa742ff6437a45adb4ca5c59f666c9b4eabc4a0c7a6e6f4c0f022015a747b7a6d9371a4020f5b396dcd094b0f36af3fc82e95091da856181912dfa012102c9a8d5b2f768afe30ee772d185e7a61f751be05649a79508b38a2be8824adec3ffffffff020065cd1d000000001976a914ca983c2da690de3cdc693ca013d93e569810c52c88ac00b07098e60000001976a9141630d812e219e6bcbe494eb96f7a7900c216ad5d88ac00000000"}, {"edaf445288d8e65cf7963bc8047c90f53681acaadc5ccfc5ecc67aedbd73cddb", "010000000164a3990893c012b20287d43d1071ac26f4b93648ff4213db6da6979beed6b7dc010000006b48304502210086ac11d4a8146b4176a72059960690c72a9776468cd671fd07c064b51f24961d02205bcf008d6995014f3cfd79100ee9beab5688c88cca15c5cea38b769563785d900121036530415a7b3b9c5976f26a63a57d119ab39491762121723c773399a2531a1bd7ffffffff020065cd1d000000001976a91477263ab93a49b1d3eb5887187704cdb82e1c60ce88ac006aad74e60000001976a914e5616848352c328c9f61b167eb1b0fde39b5cb6788ac00000000"}, {"81a1f0f8242d5e71e65ff9e8ec51e8e85d641b607d7f691c1770d4f25918ebd7", "010000000141c217dfea3a1d8d6a06e9d3daf75b292581f652256d73a7891e5dc9c7ee3cca000000006a47304402205cce451228f98fece9645052546b82c2b2d425a4889b03999001fababfc7f4690220583b2189faef07d6b0191c788301cfab1b3f47ffe2c403d632b92c6dde27e14f012102d26e423c9da9ff4a7bf6b756b2dafb75cca34fbd34f64c4c3b77c37179c5bba2ffffffff0100ca9a3b000000001976a914dc40fbbc8caa1f7617d275aec9a3a14ce8d8652188ac00000000"} }; }
filipnyquist/lbry-android
core/src/test/java/com/fillerino/core/wallet/WalletPocketHDTest.java
45,965
/* * TextTokenizerTest.java * * This source file is part of the FoundationDB open source project * * Copyright 2015-2018 Apple Inc. and the FoundationDB project authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.apple.foundationdb.record.provider.common.text; import com.google.common.collect.ImmutableSet; import org.junit.jupiter.api.Test; import javax.annotation.Nonnull; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Function; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; /** * Tests for {@link TextTokenizer}. */ public class TextTokenizerTest { private TextTokenizer defaultTokenizer = DefaultTextTokenizer.instance(); private TextTokenizer prefixTokenizer = PrefixTextTokenizer.instance(); private TextTokenizer uniqueLimitTokenizer = UniqueTokenLimitTextTokenizer.instance(); private List<String> tokenList(@Nonnull TextTokenizer tokenizer, @Nonnull String text, int version) { return tokenizer.tokenizeToList(text, version, TextTokenizer.TokenizerMode.INDEX); } // Reconstruct the original token list from the mapping from token to offset private List<String> reconstitutedTokenList(@Nonnull TextTokenizer tokenizer, @Nonnull String text, int version) { Map<String, List<Integer>> map = tokenizer.tokenizeToMap(text, version, TextTokenizer.TokenizerMode.INDEX); int maxOffset = 0; for (List<Integer> offsetList : map.values()) { maxOffset = Math.max(maxOffset, offsetList.get(offsetList.size() - 1)); } String[] tokenArr = new String[maxOffset + 1]; Arrays.fill(tokenArr, ""); for (Map.Entry<String, List<Integer>> entry : map.entrySet()) { for (int offset : entry.getValue()) { tokenArr[offset] = entry.getKey(); } } return Arrays.asList(tokenArr); } private static final List<List<String>> EXPECTED_DEFAULT_SAMPLE_TOKENS = Arrays.asList( Arrays.asList("the", "angstrom", "unit", "a", "was", "named", "after", "anders", "angstrom"), Arrays.asList("according", "to", "the", "encyclopædia", "æthelred", "the", "unræd", "was", "king", "from", "966", "to", "1016"), // note that æ is together Arrays.asList("hello", "there"), Arrays.asList("苹果园区"), // Note that this is making no effort to break apart CJK sequences Arrays.asList("蘋果園區"), Arrays.asList("text", "tokenization", "and", "normalization", "is"), // the emojis were removed! Arrays.asList("who", "started", "the", "fire"), Arrays.asList("apres", "deux", "napoleons", "france", "a", "recu", "un", "thiers"), Arrays.asList("die", "nationalmannschaft", "hat", "die", "weltmeisterschaft", "gewonnen", "horte", "ich", "wahrend", "ich", "die", "friedrichstraße", "hinunterlief"), // note that ß is still linked and that compound words are kept Arrays.asList("ολοι", "οι", "ανθρωποι", "ειναι", "θνητοι", "ο", "σωκρατης", "ειναι", "ανθρωπος", "ο", "σωκρατης", "ειναι", "θνητος"), // note the lack of stress marks and that final sigmas are still final for some reason Arrays.asList("나는", "한국어를", "못해"), // hard to tell from here, but the Hangul here is encoded in Jamo Arrays.asList("נון"), // note the lack of dagesh but final nun remains final Arrays.asList("english", "used", "to", "have", "multiple", "versions", "of", "the", "letter", "s"), // note that older s's have been modernized Arrays.asList("two", "households", "both", "alike", "in", "dignity", "in", "fair", "verona", "where", "we", "lay", "our", "scene", "from", "ancient", "grudge", "break", "to", "new", "mutiny", "where", "civil", "blood", "makes", "civil", "hands", "unclean", "from", "forth", "the", "fatal", "loins", "of", "these", "two", "foes", "a", "pair", "of", "star-cross", "d", "lovers", "take", "their", "life", "whose", "misadventur", "d", "piteous", "overthrows", "doth", "with", "their", "death", "bury", "their", "parents", "strife", "the", "fearful", "passage", "of", "their", "death-mark", "d", "love", "and", "the", "continuance", "of", "their", "parents", "rage", "which", "but", "their", "children", "s", "end", "nought", "could", "remove", "is", "now", "the", "two", "hours", "traffic", "of", "our", "stage", "the", "which", "if", "you", "with", "patient", "ears", "attend", "what", "here", "shall", "miss", "our", "toil", "shall", "strive", "to", "mend"), Arrays.asList("актер", "посетил", "многие", "достопримечательности", "москвы"), // note the lack of stress marks Arrays.asList("లద", "అద", "అరధలనదన"), // note that combining vowels have (perhaps erroneously) been removed Arrays.asList("การสะกดการนตไทยมความซบซอนมาก"), // note that no attempt was made to break the words apart Arrays.asList("https", "www.example.com", "fake-path", "1932e32ab3efc0014228eadc28219da2", "hm"), // note that this UUID is still in tact Arrays.asList("א", "שפראך", "איז", "א", "דיאלעקט", "מיט", "אן", "ארמיי", "און", "פלאט") // removing niqqud is arguably wrong for Yiddish, but it is correct for Hebrew (as are removing harakat from Arabic) ); private static final List<List<String>> EXPECTED_PREFIX_V0_SAMPLE_TOKENS = Arrays.asList( Arrays.asList("the", "ang", "uni", "a", "was", "nam", "aft", "and", "ang"), Arrays.asList("acc", "to", "the", "enc", "æth", "the", "unr", "was", "kin", "fro", "966", "to", "101"), Arrays.asList("hel", "the"), Arrays.asList("苹果园"), Arrays.asList("蘋果園"), Arrays.asList("tex", "tok", "and", "nor", "is"), Arrays.asList("who", "sta", "the", "fir"), Arrays.asList("apr", "deu", "nap", "fra", "a", "rec", "un", "thi"), Arrays.asList("die", "nat", "hat", "die", "wel", "gew", "hor", "ich", "wah", "ich", "die", "fri", "hin"), Arrays.asList("ολο", "οι", "ανθ", "ειν", "θνη", "ο", "σωκ", "ειν", "ανθ", "ο", "σωκ", "ειν", "θνη"), Arrays.asList("나ᄂ", "한", "못"), Arrays.asList("נון"), Arrays.asList("eng", "use", "to", "hav", "mul", "ver", "of", "the", "let", "s"), Arrays.asList("two", "hou", "bot", "ali", "in", "dig", "in", "fai", "ver", "whe", "we", "lay", "our", "sce", "fro", "anc", "gru", "bre", "to", "new", "mut", "whe", "civ", "blo", "mak", "civ", "han", "unc", "fro", "for", "the", "fat", "loi", "of", "the", "two", "foe", "a", "pai", "of", "sta", "d", "lov", "tak", "the", "lif", "who", "mis", "d", "pit", "ove", "dot", "wit", "the", "dea", "bur", "the", "par", "str", "the", "fea", "pas", "of", "the", "dea", "d", "lov", "and", "the", "con", "of", "the", "par", "rag", "whi", "but", "the", "chi", "s", "end", "nou", "cou", "rem", "is", "now", "the", "two", "hou", "tra", "of", "our", "sta", "the", "whi", "if", "you", "wit", "pat", "ear", "att", "wha", "her", "sha", "mis", "our", "toi", "sha", "str", "to", "men"), Arrays.asList("акт", "пос", "мно", "дос", "мос"), Arrays.asList("లద", "అద", "అరధ"), Arrays.asList("การ"), Arrays.asList("htt", "www", "fak", "193", "hm"), Arrays.asList("א", "שפר", "איז", "א", "דיא", "מיט", "אן", "ארמ", "און", "פלא") ); private static final List<List<String>> EXPECTED_PREFIX_V1_SAMPLE_TOKENS = Arrays.asList( Arrays.asList("the", "angs", "unit", "a", "was", "name", "afte", "ande", "angs"), Arrays.asList("acco", "to", "the", "ency", "æthe", "the", "unræ", "was", "king", "from", "966", "to", "1016"), Arrays.asList("hell", "ther"), Arrays.asList("苹果园区"), Arrays.asList("蘋果園區"), Arrays.asList("text", "toke", "and", "norm", "is"), Arrays.asList("who", "star", "the", "fire"), Arrays.asList("apre", "deux", "napo", "fran", "a", "recu", "un", "thie"), Arrays.asList("die", "nati", "hat", "die", "welt", "gewo", "hort", "ich", "wahr", "ich", "die", "frie", "hinu"), Arrays.asList("ολοι", "οι", "ανθρ", "εινα", "θνητ", "ο", "σωκρ", "εινα", "ανθρ", "ο", "σωκρ", "εινα", "θνητ"), Arrays.asList("나느", "한ᄀ", "못ᄒ"), Arrays.asList("נון"), Arrays.asList("engl", "used", "to", "have", "mult", "vers", "of", "the", "lett", "s"), Arrays.asList("two", "hous", "both", "alik", "in", "dign", "in", "fair", "vero", "wher", "we", "lay", "our", "scen", "from", "anci", "grud", "brea", "to", "new", "muti", "wher", "civi", "bloo", "make", "civi", "hand", "uncl", "from", "fort", "the", "fata", "loin", "of", "thes", "two", "foes", "a", "pair", "of", "star", "d", "love", "take", "thei", "life", "whos", "misa", "d", "pite", "over", "doth", "with", "thei", "deat", "bury", "thei", "pare", "stri", "the", "fear", "pass", "of", "thei", "deat", "d", "love", "and", "the", "cont", "of", "thei", "pare", "rage", "whic", "but", "thei", "chil", "s", "end", "noug", "coul", "remo", "is", "now", "the", "two", "hour", "traf", "of", "our", "stag", "the", "whic", "if", "you", "with", "pati", "ears", "atte", "what", "here", "shal", "miss", "our", "toil", "shal", "stri", "to", "mend"), Arrays.asList("акте", "посе", "мног", "дост", "моск"), Arrays.asList("లద", "అద", "అరధల"), Arrays.asList("การส"), Arrays.asList("http", "www.", "fake", "1932", "hm"), Arrays.asList("א", "שפרא", "איז", "א", "דיאל", "מיט", "אן", "ארמי", "און", "פלאט") ); private static final List<List<String>> EXPECTED_FILTERED_SAMPLE_TOKENS = Arrays.asList( Arrays.asList("", "angstrom", "unit", "", "was", "named", "after", "anders", "angstrom"), Arrays.asList("according", "to", "", "encyclopædia", "æthelred", "", "unræd", "was", "king", "from", "966", "to", "1016"), Arrays.asList("hello", "there"), Arrays.asList("苹果园区"), Arrays.asList("蘋果園區"), Arrays.asList("text", "tokenization", "", "normalization", "is"), Arrays.asList("who", "started", "", "fire"), Arrays.asList("apres", "deux", "napoleons", "france", "", "recu", "un", "thiers"), Arrays.asList("die", "nationalmannschaft", "hat", "die", "weltmeisterschaft", "gewonnen", "horte", "ich", "wahrend", "ich", "die", "friedrichstraße", "hinunterlief"), Arrays.asList("ολοι", "οι", "ανθρωποι", "ειναι", "θνητοι", "ο", "σωκρατης", "ειναι", "ανθρωπος", "ο", "σωκρατης", "ειναι", "θνητος"), Arrays.asList("나는", "한국어를", "못해"), Arrays.asList("נון"), Arrays.asList("english", "used", "to", "have", "multiple", "versions", "", "", "letter", "s"), Arrays.asList("two", "households", "both", "alike", "", "dignity", "", "fair", "verona", "where", "we", "lay", "our", "scene", "from", "ancient", "grudge", "break", "to", "new", "mutiny", "where", "civil", "blood", "makes", "civil", "hands", "unclean", "from", "forth", "", "fatal", "loins", "", "these", "two", "foes", "", "pair", "", "star-cross", "d", "lovers", "take", "their", "life", "whose", "misadventur", "d", "piteous", "overthrows", "doth", "with", "their", "death", "bury", "their", "parents", "strife", "", "fearful", "passage", "", "their", "death-mark", "d", "love", "", "", "continuance", "", "their", "parents", "rage", "which", "but", "their", "children", "s", "end", "nought", "could", "remove", "is", "now", "", "two", "hours", "traffic", "", "our", "stage", "", "which", "if", "you", "with", "patient", "ears", "attend", "what", "here", "shall", "miss", "our", "toil", "shall", "strive", "to", "mend"), Arrays.asList("актер", "посетил", "многие", "достопримечательности", "москвы"), Arrays.asList("లద", "అద", "అరధలనదన"), Arrays.asList("การสะกดการนตไทยมความซบซอนมาก"), Arrays.asList("https", "www.example.com", "fake-path", "1932e32ab3efc0014228eadc28219da2", "hm"), Arrays.asList("א", "שפראך", "איז", "א", "דיאלעקט", "מיט", "אן", "ארמיי", "און", "פלאט") ); private static final List<List<String>> EXPECTED_RECONSTITUTED_UNIQUE_LIMIT_SAMPLE_TOKENS = Arrays.asList( Arrays.asList("the", "angstrom", "unit", "a", "was"), Arrays.asList("according", "to", "the", "encyclopædia", "æthelred", "the"), Arrays.asList("hello", "there"), Arrays.asList("苹果园区"), Arrays.asList("蘋果園區"), Arrays.asList("text", "tokenization", "and", "normalization", "is"), Arrays.asList("who", "started", "the", "fire"), Arrays.asList("apres", "deux", "napoleons", "france", "a"), Arrays.asList("die", "nationalmannschaft", "hat", "die", "weltmeisterschaft", "gewonnen"), Arrays.asList("ολοι", "οι", "ανθρωποι", "ειναι", "θνητοι"), Arrays.asList("나는", "한국어를", "못해"), Arrays.asList("נון"), Arrays.asList("english", "used", "to", "have", "multiple"), Arrays.asList("two", "households", "both", "alike", "in"), Arrays.asList("актер", "посетил", "многие", "достопримечательности", "москвы"), Arrays.asList("లద", "అద", "అరధలనదన"), Arrays.asList("การสะกดการนตไทยมความซบซอนมาก"), Arrays.asList("https", "www.example.com", "fake-path", "1932e32ab3efc0014228eadc28219da2", "hm"), Arrays.asList("א", "שפראך", "איז", "א", "דיאלעקט", "מיט") ); public void testTokenization(@Nonnull Function<String, List<String>> tokenizationFunction, @Nonnull List<List<String>> tokenLists) { boolean missing = false; for (int i = 0; i < TextSamples.ALL.size(); i++) { final String text = TextSamples.ALL.get(i); List<String> tokens = tokenizationFunction.apply(text); if (i < tokenLists.size()) { List<String> expected = tokenLists.get(i); assertEquals(expected, tokens); } else { System.out.println("string: " + text); System.out.println("tokens: Arrays.asList(\"" + String.join("\", \"", tokens) + "\")"); missing = true; } } assertFalse(missing); } public void compatibility(@Nonnull TextTokenizer tokenizer, int version, @Nonnull List<List<String>> tokenLists) { testTokenization(text -> tokenList(tokenizer, text, version), tokenLists); } public void reconstituted(@Nonnull TextTokenizer tokenizer, int version, @Nonnull List<List<String>> tokenLists) { testTokenization(text -> reconstitutedTokenList(tokenizer, text, version), tokenLists); } @Test public void defaultTokenizer() { compatibility(defaultTokenizer, defaultTokenizer.getMinVersion(), EXPECTED_DEFAULT_SAMPLE_TOKENS); reconstituted(defaultTokenizer, defaultTokenizer.getMinVersion(), EXPECTED_DEFAULT_SAMPLE_TOKENS); } @Test public void prefixV0() { compatibility(prefixTokenizer, TextTokenizer.GLOBAL_MIN_VERSION, EXPECTED_PREFIX_V0_SAMPLE_TOKENS); reconstituted(prefixTokenizer, TextTokenizer.GLOBAL_MIN_VERSION, EXPECTED_PREFIX_V0_SAMPLE_TOKENS); } @Test public void prefixV1() { compatibility(prefixTokenizer, TextTokenizer.GLOBAL_MIN_VERSION + 1, EXPECTED_PREFIX_V1_SAMPLE_TOKENS); reconstituted(prefixTokenizer, TextTokenizer.GLOBAL_MIN_VERSION + 1, EXPECTED_PREFIX_V1_SAMPLE_TOKENS); } @Test public void filtering() { final Set<String> stopWords = ImmutableSet.of("the", "of", "in", "and", "a", "an", "some"); TextTokenizer filteringTokenizer = FilteringTextTokenizer.create( "filter_common", new DefaultTextTokenizerFactory(), (token, version) -> !stopWords.contains(token.toString()) ).getTokenizer(); compatibility(filteringTokenizer, defaultTokenizer.getMinVersion(), EXPECTED_FILTERED_SAMPLE_TOKENS); reconstituted(filteringTokenizer, defaultTokenizer.getMinVersion(), EXPECTED_FILTERED_SAMPLE_TOKENS); } @Test public void uniqueTokenLimitCompatibility() { compatibility(uniqueLimitTokenizer, TextTokenizer.GLOBAL_MIN_VERSION, EXPECTED_DEFAULT_SAMPLE_TOKENS); reconstituted(uniqueLimitTokenizer, TextTokenizer.GLOBAL_MIN_VERSION, EXPECTED_RECONSTITUTED_UNIQUE_LIMIT_SAMPLE_TOKENS); } }
FoundationDB/fdb-record-layer
fdb-record-layer-core/src/test/java/com/apple/foundationdb/record/provider/common/text/TextTokenizerTest.java
45,971
package oeg.utils.rdf; //APACHE CLI import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.ObjectOutputStream; import java.io.OutputStreamWriter; import java.net.URLDecoder; import java.net.URLEncoder; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import ldc.Main; import oeg.utils.strings.ExternalSort; import org.apache.log4j.Logger; /** * Class with the methods for the fast transformation of a .NT file into a * .NQUAD file. This operation is made in a stream process that does not require * much memory. * * @author Victor */ public class NT2NQ { static final Logger logger = Logger.getLogger(NT2NQ.class); /** * Limpia los saltos de linea de todos dumps de todos los datasets */ /* public static void limpiarSaltoLinea() { for (ConditionalDataset cd : ConditionalDatasets.datasets) { logger.info("Limpiando " + cd.name); String f = cd.getDatasetDump().getFileName(); replaceInStreamFile(f, f, "", ""); } }*/ /** * Replaces a string in file1 by another producing file2 * It can handle large files, as it is done in a stream. * @param sfile1 File name1 * @param sfile2 File name2 * @param cad1 * @param cad2 */ public static int replaceInStreamFile(String sfile1, String sfile2, String cad1, String cad2) { boolean same = false; int count = 0; if (sfile1.equals(sfile2)) { same = true; sfile2 = sfile1 + "TMP"; } try { BufferedReader br = new BufferedReader(new FileReader(sfile1)); FileOutputStream fos = new FileOutputStream(new File(sfile2)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos)); String line; while ((line = br.readLine()) != null) { count++; if (count % 1000000 == 0) { System.out.println("Lineas cargadas: " + count); } line = line.replace(cad1, cad2); char separador = 10; //0a bw.write(line + separador); } bw.close(); fos.close(); br.close(); if (same) { File f1 = new File(sfile1); f1.delete(); File f2 = new File(sfile2); f2.renameTo(new File(sfile1)); } } catch (Exception e) { e.printStackTrace(); } return count; } public static void cortar(String sfile1, String sfile2, int lineas) { if (sfile1.equals(sfile2)) { return; } try { BufferedReader br = new BufferedReader(new FileReader(sfile1)); FileOutputStream fos = new FileOutputStream(new File(sfile2)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos)); String line; int count = 0; while ((line = br.readLine()) != null) { count++; if (count > lineas) { break; } if (count % 1000000 == 0) { System.out.println("Lineas cargadas: " + count); } bw.write(line + "\n"); } bw.close(); fos.close(); br.close(); } catch (Exception e) { e.printStackTrace(); } } public static void unicodizar(String sfile1, String sfile2) { if (sfile1.equals(sfile2)) { return; } try { BufferedReader br = new BufferedReader(new FileReader(sfile1)); FileOutputStream fos = new FileOutputStream(new File(sfile2)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos)); String line; int count = 0; while ((line = br.readLine()) != null) { count++; if (count % 1000000 == 0) { System.out.println("Lineas cargadas: " + count); } try { line = URLDecoder.decode(line, "UTF-8"); } catch (Exception e) { } bw.write(line + "\n"); } bw.close(); fos.close(); br.close(); } catch (Exception e) { e.printStackTrace(); } } public static String ultraFastAccess(String nquadsfile, String indexFile, String search) { String res = ""; Map<String, Integer> mapaOffset = new HashMap<String, Integer>(); try { String line = ""; BufferedReader br = new BufferedReader(new FileReader(indexFile)); System.out.println("Cargando diccionario"); int i = 0; while ((line = br.readLine()) != null) { ///potencialmente, 100M de lineas int ind = line.lastIndexOf(" "); String s1 = line.substring(0, ind); String s2 = line.substring(ind + 1, line.length()); if (s2.isEmpty()) { break; } int indice = Integer.parseInt(s2); mapaOffset.put(s1, indice); } br.close(); System.out.println("Diccionario cargado"); Integer k = mapaOffset.get(search); String search2 = URLEncoder.encode(search, "UTF-8"); search2 = search2.replace("oeg-iate%3A", "http://salonica.dia.fi.upm.es/iate/resource/"); search2 = "<" + search2 + ">"; System.out.println("Descodificado: " + search2); BufferedReader br2 = new BufferedReader(new FileReader(nquadsfile)); br2.skip(k); while ((line = br2.readLine()) != null) { ///potencialmente, 100M de lineas System.out.println(line); if (line.startsWith(search2)) { res += line + "\n"; } else { break; } } // System.out.println("Encontrado aqui: " + k); } catch (Exception e) { e.printStackTrace(); } System.out.println("--\nres\n--"); return res; } /** * Indexa volcando el mapa en stream */ public static void indexarSujetosStream(String nquadsFile, String indexFile) { int separator = 1; try { BufferedReader br = new BufferedReader(new FileReader(nquadsFile)); FileOutputStream fos = new FileOutputStream(new File(indexFile)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos)); int i = -1; String line = null; String lasts = ""; int ini = 0; int contador = 0; int inicontador = 0; while ((line = br.readLine()) != null) { ///potencialmente, 100M de lineas contador += line.length() + separator; i++; if (i % 1000000 == 0) { System.out.println("Millones de lineas cargadas: " + i / 1000000); } String s = NQuad.getSubject(line); //rapido if (s.equals(lasts)) { continue; } if (i == 0) { lasts = s; continue; } // List<Integer> li = new ArrayList(); // li.add(ini); // li.add(i - 1); // String abreviado = lasts.replace("http://salonica.dia.fi.upm.es/geo/resource/", "local:"); String abreviado = lasts.replace("http://salonica.dia.fi.upm.es/iate/resource/", "oeg-iate:"); try { abreviado = URLDecoder.decode(abreviado, "UTF-8"); } catch (Exception e) { } // bw.write(abreviado+" "+ini+" "+(i-1)+"\n"); bw.write(abreviado + " " + inicontador + "\n"); lasts = s; ini = i; inicontador = contador - line.length() - separator; } bw.close(); fos.close(); br.close(); } catch (Exception e) { logger.warn(e.getMessage()); } } public static void ordenar(String filename) { ExternalSort.ordenar(filename); } /** * Indexa volcando el mapa a saco */ public static void indexarSujetos(String nquadsFile, String indexFile) { Map<String, List<Integer>> map = new HashMap(); try { BufferedReader br = new BufferedReader(new FileReader(nquadsFile)); int i = -1; String line = null; String lasts = ""; int ini = 0; while ((line = br.readLine()) != null) { ///potencialmente, 100M de lineas i++; if (i % 100000 == 0) { System.out.println("Lineas cargadas: " + i); } String s = NQuad.getSubject(line); //rapido if (s.equals(lasts)) { continue; } if (i == 0) { lasts = s; continue; } List<Integer> li = new ArrayList(); li.add(ini); li.add(i - 1); map.put(lasts, li); lasts = s; ini = i; } } catch (Exception e) { logger.warn(e.getMessage()); } try { FileOutputStream fos = new FileOutputStream(indexFile); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(map); oos.close(); fos.close(); } catch (Exception e) { logger.warn(e.getMessage()); } } public static void nt2nq(String sfile1, String sfile2, String grafo) { try { BufferedReader br = new BufferedReader(new FileReader(sfile1)); FileOutputStream fos = new FileOutputStream(new File(sfile2)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos)); String line; int count = 0; DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); System.out.println(dateFormat.format(new Date())); while ((line = br.readLine()) != null) { count++; int lastin = line.lastIndexOf("."); if (lastin == -1) { continue; } line = line.substring(0, lastin) + grafo; bw.write(line); bw.newLine(); if (count % 100000 == 0) { System.out.println("Lineas procesadas:" + count); } } bw.close(); fos.close(); br.close(); } catch (Exception e) { System.err.println("Error. " + e.getMessage()); } } /** * Test class */ public static void main(String[] args) { String sfile1 = "E:\\data\\iate\\iate.nt"; String sfile2 = "E:\\data\\iate\\iate.nq"; String grafo = "<http://localhost/datasets/default> ."; Main.standardInit(); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); System.out.println(dateFormat.format(new Date())); // ordenar("E:\\data\\ldconditional\\iate\\data.nq"); // indexarSujetosStream("E:\\data\\ldconditional\\iate\\data.nq", "E:\\data\\ldconditional\\iate\\indexsujetos2.idx"); // rebasear("E:\\data\\ldconditional\\iate\\data.nq", "E:\\data\\ldconditional\\iate\\data-salonica.nq", "http://tbx2rdf.lider-project.eu/data/iate", "http://salonica.dia.fi.upm.es/iate/resource"); // unicodizar("E:\\data\\ldconditional\\iate\\data.nq", "E:\\data\\ldconditional\\iate\\datau.nq"); // cortar("E:\\data\\ldconditional\\iate\\data.nq", "E:\\data\\ldconditional\\iate\\data2.nq", 10000000); // ultraFastAccess("E:\\data\\ldconditional\\iate\\data.nq", "E:\\data\\ldconditional\\iate\\indexsujetos2.idx", "oeg-iate:\"\"\"πράσινο\"\" κτήριο\"-el" ); // limpiarSaltoLinea(); System.out.println(dateFormat.format(new Date())); } }
oeg-upm/licensius
ldconditional/src/java/oeg/utils/rdf/NT2NQ.java
45,978
package com.elifut.models; import com.google.auto.value.AutoValue; import android.support.annotation.Nullable; import com.squareup.moshi.JsonAdapter; import com.squareup.moshi.Moshi; @AutoValue public abstract class League extends Model { public abstract String name(); @Nullable public abstract String abbrev_name(); public abstract String image(); public static JsonAdapter<League> jsonAdapter(Moshi moshi) { return new AutoValue_League.MoshiJsonAdapter(moshi); } @Override public int describeContents() { return 0; } }
EliFUT/android
app/src/main/java/com/elifut/models/League.java
45,979
package me.chanjar.weixin.channel.constant; import lombok.experimental.UtilityClass; /** * 视频号小店接口地址常量 * * @author <a href="https://github.com/lixize">Zeyes</a> */ @UtilityClass public class WxChannelApiUrlConstants { /** * 获取access_token. */ public static final String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s"; /** * 获取Stable access_token. */ public static final String GET_STABLE_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/stable_token"; /** 基础接口 */ public interface Basics { /** 获取店铺基本信息 */ String GET_SHOP_INFO = "https://api.weixin.qq.com/channels/ec/basics/info/get"; /** 上传图片 */ String IMG_UPLOAD_URL = "https://api.weixin.qq.com/channels/ec/basics/img/upload"; /** 上传资质图片 */ String UPLOAD_QUALIFICATION_FILE = "https://api.weixin.qq.com/channels/ec/basics/qualification/upload"; /** 下载图片 */ String GET_IMG_URL = "https://api.weixin.qq.com/channels/ec/basics/media/get"; /** 获取地址编码 */ String GET_ADDRESS_CODE = "https://api.weixin.qq.com/channels/ec/basics/addresscode/get"; } /** 商品类目相关接口 */ public interface Category { /** 获取所有的类目 */ String LIST_ALL_CATEGORY_URL = "https://api.weixin.qq.com/channels/ec/category/all"; /** 获取类目详情 */ String GET_CATEGORY_DETAIL_URL = "https://api.weixin.qq.com/channels/ec/category/detail"; /** 获取可用的子类目详情 */ String AVAILABLE_CATEGORY_URL = "https://api.weixin.qq.com/channels/ec/category/availablesoncategories/get"; /** 上传类目资质 */ String ADD_CATEGORY_URL = "https://api.weixin.qq.com/channels/ec/category/add"; /** 获取类目审核结果 */ String GET_CATEGORY_AUDIT_URL = "https://api.weixin.qq.com/channels/ec/category/audit/get"; /** 取消类目提审 */ String CANCEL_CATEGORY_AUDIT_URL = "https://api.weixin.qq.com/channels/ec/category/audit/cancel"; /** 获取账号申请通过的类目和资质信息 */ String LIST_PASS_CATEGORY_URL = "https://api.weixin.qq.com/channels/ec/category/list/get"; } /** 品牌资质相关接口 */ public interface Brand { /** 获取品牌库列表 */ String ALL_BRAND_URL = "https://api.weixin.qq.com/channels/ec/brand/all"; /** 新增品牌资质 */ String ADD_BRAND_URL = "https://api.weixin.qq.com/channels/ec/brand/add"; /** 更新品牌资质 */ String UPDATE_BRAND_URL = "https://api.weixin.qq.com/channels/ec/brand/update"; /** 撤回品牌资质审核 */ String CANCEL_BRAND_AUDIT_URL = "https://api.weixin.qq.com/channels/ec/brand/audit/cancel"; /** 删除品牌资质 */ String DELETE_BRAND_URL = "https://api.weixin.qq.com/channels/ec/brand/delete"; /** 获取品牌资质申请详情 */ String GET_BRAND_URL = "https://api.weixin.qq.com/channels/ec/brand/get"; /** 获取品牌资质申请列表 */ String LIST_BRAND_URL = "https://api.weixin.qq.com/channels/ec/brand/list/get"; /** 获取生效中的品牌资质列表 */ String LIST_BRAND_VALID_URL = "https://api.weixin.qq.com/channels/ec/brand/valid/list/get"; } /** 商品操作相关接口 */ public interface Spu { /** 添加商品 */ String SPU_ADD_URL = "https://api.weixin.qq.com/channels/ec/product/add"; /** 删除商品 */ String SPU_DEL_URL = "https://api.weixin.qq.com/channels/ec/product/delete"; /** 获取商品详情 */ String SPU_GET_URL = "https://api.weixin.qq.com/channels/ec/product/get"; /** 获取商品列表 */ String SPU_LIST_URL = "https://api.weixin.qq.com/channels/ec/product/list/get"; /** 更新商品 */ String SPU_UPDATE_URL = "https://api.weixin.qq.com/channels/ec/product/update"; /** 上架商品 */ String SPU_LISTING_URL = "https://api.weixin.qq.com/channels/ec/product/listing"; /** 下架商品 */ String SPU_DELISTING_URL = "https://api.weixin.qq.com/channels/ec/product/delisting"; /** 撤回商品审核 */ String CANCEL_AUDIT_URL = "https://api.weixin.qq.com/channels/ec/product/audit/cancel"; /** 获取实时库存 */ String SPU_GET_STOCK_URL = "https://api.weixin.qq.com/channels/ec/product/stock/get"; /** 更新商品库存 */ String SPU_UPDATE_STOCK_URL = "https://api.weixin.qq.com/channels/ec/product/stock/update"; /** 添加限时抢购任务 */ String ADD_LIMIT_TASK_URL = "https://api.weixin.qq.com/channels/ec/product/limiteddiscounttask/add"; /** 拉取限时抢购任务列表 */ String LIST_LIMIT_TASK_URL = "https://api.weixin.qq.com/channels/ec/product/limiteddiscounttask/list/get"; /** 停止限时抢购任务 */ String STOP_LIMIT_TASK_URL = "https://api.weixin.qq.com/channels/ec/product/limiteddiscounttask/stop"; /** 删除限时抢购任务 */ String DELETE_LIMIT_TASK_URL = "https://api.weixin.qq.com/channels/ec/product/limiteddiscounttask/delete"; } /** 区域仓库 */ public interface Warehouse { /** 添加区域仓库 */ String ADD_WAREHOUSE_URL = "https://api.weixin.qq.com/channels/ec/warehouse/create"; /** 获取区域仓库列表 */ String LIST_WAREHOUSE_URL = "https://api.weixin.qq.com/channels/ec/warehouse/list/get"; /** 获取区域仓库详情 */ String GET_WAREHOUSE_URL = "https://api.weixin.qq.com/channels/ec/warehouse/get"; /** 更新区域仓库详情 */ String UPDATE_WAREHOUSE_URL = "https://api.weixin.qq.com/channels/ec/warehouse/detail/update"; /** 批量增加覆盖区域 */ String ADD_COVER_AREA_URL = "https://api.weixin.qq.com/channels/ec/warehouse/coverlocations/add"; /** 批量删除覆盖区域 */ String DELETE_COVER_AREA_URL = "https://api.weixin.qq.com/channels/ec/warehouse/coverlocations/del"; /** 设置指定地址下的仓的优先级 */ String SET_WAREHOUSE_PRIORITY_URL = "https://api.weixin.qq.com/channels/ec/warehouse/address/prioritysort/set"; /** 获取指定地址下的仓的优先级 */ String GET_WAREHOUSE_PRIORITY_URL = "https://api.weixin.qq.com/channels/ec/warehouse/address/prioritysort/get"; /** 更新区域仓库存 */ String UPDATE_WAREHOUSE_STOCK_URL = "https://api.weixin.qq.com/channels/ec/warehouse/stock/update"; /** 获取区域仓库存 */ String GET_WAREHOUSE_STOCK_URL = "https://api.weixin.qq.com/channels/ec/warehouse/stock/get"; } /** 订单相关接口 */ public interface Order { /** 获取订单列表 */ String ORDER_LIST_URL = "https://api.weixin.qq.com/channels/ec/order/list/get"; /** 获取订单详情 */ String ORDER_GET_URL = "https://api.weixin.qq.com/channels/ec/order/get"; /** 更改订单价格 */ String UPDATE_PRICE_URL = "https://api.weixin.qq.com/channels/ec/order/price/update"; /** 修改订单备注 */ String UPDATE_REMARK_URL = "https://api.weixin.qq.com/channels/ec/order/merchantnotes/update"; /** 更修改订单地址 */ String UPDATE_ADDRESS_URL = "https://api.weixin.qq.com/channels/ec/order/address/update"; /** 修改物流信息 */ String UPDATE_EXPRESS_URL = "https://api.weixin.qq.com/channels/ec/order/deliveryinfo/update"; /** 同意用户修改收货地址申请 */ String ACCEPT_ADDRESS_MODIFY_URL = "https://api.weixin.qq.com/channels/ec/order/addressmodify/accept"; /** 拒绝用户修改收货地址申请 */ String REJECT_ADDRESS_MODIFY_URL = "https://api.weixin.qq.com/channels/ec/order/addressmodify/reject"; /** 订单搜索 */ String ORDER_SEARCH_URL = "https://api.weixin.qq.com/channels/ec/order/search"; } /** 售后相关接口 */ public interface AfterSale { /** 获取售后列表 */ String AFTER_SALE_LIST_URL = "https://api.weixin.qq.com/channels/ec/aftersale/getaftersalelist"; /** 获取售后单 */ String AFTER_SALE_GET_URL = "https://api.weixin.qq.com/channels/ec/aftersale/getaftersaleorder"; /** 同意售后 */ String AFTER_SALE_ACCEPT_URL = "https://api.weixin.qq.com/channels/ec/aftersale/acceptapply"; /** 拒绝售后 */ String AFTER_SALE_REJECT_URL = "https://api.weixin.qq.com/channels/ec/aftersale/rejectapply"; /** 上传退款凭证 */ String AFTER_SALE_UPLOAD_URL = "https://api.weixin.qq.com/channels/ec/aftersale/uploadrefundcertificate"; } /** 纠纷相关接口 */ public interface Complaint { /** 商家补充纠纷单留言 */ String ADD_COMPLAINT_MATERIAL_URL = "https://api.weixin.qq.com/channels/ec/aftersale/addcomplaintmaterial"; /** 商家举证 */ String ADD_COMPLAINT_PROOF_URL = "https://api.weixin.qq.com/channels/ec/aftersale/addcomplaintproof"; /** 获取纠纷单 */ String GET_COMPLAINT_ORDER_URL = "https://api.weixin.qq.com/channels/ec/aftersale/getcomplaintorder"; } /** 物流相关接口 */ public interface Delivery { /** 获取快递公司列表 */ String GET_DELIVERY_COMPANY_URL = "https://api.weixin.qq.com/channels/ec/order/deliverycompanylist/get"; /** 订单发货 */ String DELIVERY_SEND_URL = "https://api.weixin.qq.com/channels/ec/order/delivery/send"; } /** 运费模板相关接口 */ public interface FreightTemplate { /** 获取运费模板列表 */ String LIST_TEMPLATE_URL = "https://api.weixin.qq.com/channels/ec/merchant/getfreighttemplatelist"; /** 查询运费模版 */ String GET_TEMPLATE_URL = "https://api.weixin.qq.com/channels/ec/merchant/getfreighttemplatedetail"; /** 增加运费模版 */ String ADD_TEMPLATE_URL = "https://api.weixin.qq.com/channels/ec/merchant/addfreighttemplate"; /** 更新运费模版 */ String UPDATE_TEMPLATE_URL = "https://api.weixin.qq.com/channels/ec/merchant/updatefreighttemplate"; } /** 地址管理相关接口 */ public interface Address { /** 增加地址 */ String ADD_ADDRESS_URL = "https://api.weixin.qq.com/channels/ec/merchant/address/add"; /** 获取地址列表 */ String LIST_ADDRESS_URL = "https://api.weixin.qq.com/channels/ec/merchant/address/list"; /** 获取地址详情 */ String GET_ADDRESS_URL = "https://api.weixin.qq.com/channels/ec/merchant/address/get"; /** 更新地址 */ String UPDATE_ADDRESS_URL = "https://api.weixin.qq.com/channels/ec/merchant/address/update"; /** 删除地址 */ String DELETE_ADDRESS_URL = "https://api.weixin.qq.com/channels/ec/merchant/address/delete"; } /** 优惠券相关接口 */ public interface Coupon { /** 创建优惠券 */ String CREATE_COUPON_URL = "https://api.weixin.qq.com/channels/ec/coupon/create"; /** 更新优惠券 */ String UPDATE_COUPON_URL = "https://api.weixin.qq.com/channels/ec/coupon/update"; /** 更新优惠券状态 */ String UPDATE_COUPON_STATUS_URL = "https://api.weixin.qq.com/channels/ec/coupon/update_status"; /** 获取优惠券详情 */ String GET_COUPON_URL = "https://api.weixin.qq.com/channels/ec/coupon/get"; /** 获取优惠券ID列表 */ String LIST_COUPON_URL = "https://api.weixin.qq.com/channels/ec/coupon/get_list"; /** 获取用户优惠券ID列表 */ String LIST_USER_COUPON_URL = "https://api.weixin.qq.com/channels/ec/coupon/get_user_coupon_list"; /** 获取用户优惠券详情 */ String GET_USER_COUPON_URL = "https://api.weixin.qq.com/channels/ec/coupon/get_user_coupon"; } /** 分享员相关接口 */ public interface Share { /** 邀请分享员 */ String BIND_SHARER_URL = "https://api.weixin.qq.com/channels/ec/sharer/bind"; /** 获取绑定的分享员 */ String SEARCH_SHARER_URL = "https://api.weixin.qq.com/channels/ec/sharer/search_sharer"; /** 获取绑定的分享员列表 */ String LIST_SHARER_URL = "https://api.weixin.qq.com/channels/ec/sharer/get_sharer_list"; /** 获取分享员订单列表 */ String LIST_SHARER_ORDER_URL = "https://api.weixin.qq.com/channels/ec/sharer/get_sharer_order_list"; /** 解绑分享员 */ String UNBIND_SHARER_URL = "https://api.weixin.qq.com/channels/ec/sharer/unbind"; } /** 资金相关接口 */ public interface Fund { /** 获取账户余额 */ String GET_BALANCE_URL = "https://api.weixin.qq.com/channels/ec/funds/getbalance"; /** 获取结算账户 */ String GET_BANK_ACCOUNT_URL = "https://api.weixin.qq.com/channels/ec/funds/getbankacct"; /** 获取资金流水详情 */ String GET_BALANCE_FLOW_DETAIL_URL = "https://api.weixin.qq.com/channels/ec/league/funds/getfundsflowdetail"; /** 获取资金流水列表 */ String GET_BALANCE_FLOW_LIST_URL = "https://api.weixin.qq.com/channels/ec/league/funds/getfundsflowlist"; /** 获取提现记录 */ String GET_WITHDRAW_DETAIL_URL = "https://api.weixin.qq.com/channels/ec/funds/getwithdrawdetail"; /** 获取提现记录列表 */ String GET_WITHDRAW_LIST_URL = "https://api.weixin.qq.com/channels/ec/funds/getwithdrawlist"; /** 修改结算账户 */ String SET_BANK_ACCOUNT_URL = "https://api.weixin.qq.com/channels/ec/funds/setbankacct"; /** 商户提现 */ String WITHDRAW_URL = "https://api.weixin.qq.com/channels/ec/funds/submitwithdraw"; /** 根据卡号查银行信息 */ String GET_BANK_BY_NUM_URL = "https://api.weixin.qq.com/shop/funds/getbankbynum"; /** 搜索银行列表 */ String GET_BANK_LIST_URL = "https://api.weixin.qq.com/shop/funds/getbanklist"; /** 查询城市列表 */ String GET_CITY_URL = "https://api.weixin.qq.com/shop/funds/getcity"; /** 查询大陆银行省份列表 */ String GET_PROVINCE_URL = "https://api.weixin.qq.com/shop/funds/getprovince"; /** 查询支行列表 */ String GET_SUB_BANK_URL = "https://api.weixin.qq.com/shop/funds/getsubbranch"; /** 获取二维码 */ String GET_QRCODE_URL = "https://api.weixin.qq.com/shop/funds/qrcode/get"; /** 查询扫码状态 */ String CHECK_QRCODE_URL = "https://api.weixin.qq.com/shop/funds/qrcode/check"; } /** 优选联盟相关接口 */ public interface League { /** 添加团长商品到橱窗 */ String ADD_SUPPLIER_GOODS_URL = "https://api.weixin.qq.com/channels/ec/league/headsupplier/window/add"; /** 查询橱窗上团长商品列表 */ String LIST_SUPPLIER_GOODS_URL = "https://api.weixin.qq.com/channels/ec/league/headsupplier/window/getall"; /** 从橱窗移除团长商品 */ String REMOVE_SUPPLIER_GOODS_URL = "https://api.weixin.qq.com/channels/ec/league/headsupplier/window/remove"; /** 查询橱窗上团长商品详情 */ String GET_SUPPLIER_GOODS_URL = "https://api.weixin.qq.com/channels/ec/league/headsupplier/window/getdetail"; /** 获取达人橱窗授权链接 */ String GET_SUPPLIER_AUTH_URL = "https://api.weixin.qq.com/channels/ec/league/headsupplier/windowauth/get"; /** 获取达人橱窗授权状态 */ String GET_SUPPLIER_AUTH_STATUS_URL = "https://api.weixin.qq.com/channels/ec/league/headsupplier/windowauth/status/get"; /** 获取团长账户余额 */ String GET_SUPPLIER_BALANCE_URL = "https://api.weixin.qq.com/channels/ec/league/headsupplier/funds/balance/get"; /** 获取资金流水详情 */ String GET_SUPPLIER_BALANCE_FLOW_DETAIL_URL = "https://api.weixin.qq.com/channels/ec/league/headsupplier/funds/flowdetail/get"; /** 获取资金流水列表 */ String GET_SUPPLIER_BALANCE_FLOW_LIST_URL = "https://api.weixin.qq.com/channels/ec/league/headsupplier/funds/flowlist/get"; /** 获取合作商品详情 */ String GET_SUPPLIER_ITEM_URL = "https://api.weixin.qq.com/channels/ec/league/headsupplier/item/get"; /** 获取合作商品列表 */ String GET_SUPPLIER_ITEM_LIST_URL = "https://api.weixin.qq.com/channels/ec/league/headsupplier/item/list/get"; /** 获取佣金单详情 */ String GET_SUPPLIER_ORDER_URL = "https://api.weixin.qq.com/channels/ec/league/headsupplier/order/get"; /** 获取佣金单列表 */ String GET_SUPPLIER_ORDER_LIST_URL = "https://api.weixin.qq.com/channels/ec/league/headsupplier/order/list/get"; /** 获取合作小店详情 */ String GET_SUPPLIER_SHOP_URL = "https://api.weixin.qq.com/channels/ec/league/headsupplier/shop/get"; /** 获取合作小店列表 */ String GET_SUPPLIER_SHOP_LIST_URL = "https://api.weixin.qq.com/channels/ec/league/headsupplier/shop/list/get"; /** 新增达人 */ String ADD_PROMOTER_URL = "https://api.weixin.qq.com/channels/ec/league/promoter/add"; /** 编辑达人 */ String EDIT_PROMOTER_URL = "https://api.weixin.qq.com/channels/ec/league/promoter/upd"; /** 删除达人 */ String DELETE_PROMOTER_URL = "https://api.weixin.qq.com/channels/ec/league/promoter/delete"; /** 获取达人详情信息 */ String GET_PROMOTER_URL = "https://api.weixin.qq.com/channels/ec/league/promoter/get"; /** 拉取商店达人列表 */ String GET_PROMOTER_LIST_URL = "https://api.weixin.qq.com/channels/ec/league/promoter/list/get"; /** 批量新增联盟商品 */ String BATCH_ADD_LEAGUE_ITEM_URL = "https://api.weixin.qq.com/channels/ec/league/item/batchadd"; /** 更新联盟商品信息 */ String UPDATE_LEAGUE_ITEM_URL = "https://api.weixin.qq.com/channels/ec/league/item/upd"; /** 删除联盟商品 */ String DELETE_LEAGUE_ITEM_URL = "https://api.weixin.qq.com/channels/ec/league/item/delete"; /** 拉取联盟商品详情 */ String GET_LEAGUE_ITEM_URL = "https://api.weixin.qq.com/channels/ec/league/item/get"; /** 拉取联盟商品推广列表 */ String GET_LEAGUE_ITEM_LIST_URL = "https://api.weixin.qq.com/channels/ec/league/item/list/get"; } /** 视频号助手开放接口 */ public interface Assistant { /** 上架商品到橱窗 */ String ADD_WINDOW_PRODUCT_URL = "https://api.weixin.qq.com/channels/ec/window/product/add"; /** 获取橱窗商品详情 */ String GET_WINDOW_PRODUCT_URL = "https://api.weixin.qq.com/channels/ec/window/product/get"; /** 获取已添加到橱窗的商品列表 */ String LIST_WINDOW_PRODUCT_URL = "https://api.weixin.qq.com/channels/ec/window/product/list/get"; /** 下架橱窗商品 */ String OFF_WINDOW_PRODUCT_URL = "https://api.weixin.qq.com/channels/ec/window/product/off"; } /** * 留资组件管理 */ public interface LeadComponent { /** * <a href="https://developers.weixin.qq.com/doc/channels/API/leads/get_leads_info_by_component_id.html">按时间获取留资信息详情</a> */ String GET_LEADS_INFO_BY_COMPONENT_ID = "https://api.weixin.qq.com/channels/leads/get_leads_info_by_component_id"; /** * <a href="https://developers.weixin.qq.com/doc/channels/API/leads/get_leads_info_by_request_id.html">按直播场次获取留资信息详情</a> */ String GET_LEADS_INFO_BY_REQUEST_ID = "https://api.weixin.qq.com/channels/leads/get_leads_info_by_request_id"; /** * <a href="https://developers.weixin.qq.com/doc/channels/API/leads/get_leads_request_id.html">获取留资request_id列表详情</a> */ String GET_LEADS_REQUEST_ID = "https://api.weixin.qq.com/channels/leads/get_leads_request_id"; /** * <a href="https://developers.weixin.qq.com/doc/channels/API/leads/get_leads_component_promote_record.html">获取留资组件直播推广记录信息详情</a> */ String GET_LEADS_COMPONENT_PROMOTE_RECORD = "https://api.weixin.qq.com/channels/leads/get_leads_component_promote_record"; /** * <a href="https://developers.weixin.qq.com/doc/channels/API/leads/get_leads_component_id.html">获取留资组件Id列表详情</a> */ String GET_LEADS_COMPONENT_ID = "https://api.weixin.qq.com/channels/leads/get_leads_component_id"; } /** * 留资服务的直播数据 */ public interface FinderLive { /** * <a href="https://developers.weixin.qq.com/doc/channels/API/live/get_finder_attr_by_appid.html">获取视频号账号信息</a> */ String GET_FINDER_ATTR_BY_APPID = "https://api.weixin.qq.com/channels/finderlive/get_finder_attr_by_appid"; /** * <a href="https://developers.weixin.qq.com/doc/channels/API/live/get_finder_live_data_list.html">获取留资直播间数据详情</a> */ String GET_FINDER_LIVE_DATA_LIST = "https://api.weixin.qq.com/channels/finderlive/get_finder_live_data_list"; /** * <a href="https://developers.weixin.qq.com/doc/channels/API/live/get_finder_live_leads_data.html">获取账号收集的留资数量</a> */ String GET_FINDER_LIVE_LEADS_DATA = "https://api.weixin.qq.com/channels/finderlive/get_finder_live_leads_data"; } /** 会员功能接口 */ public interface Vip { /** 拉取用户详情 */ String VIP_USER_INFO_URL = "https://api.weixin.qq.com/channels/ec/vip/user/info/get"; /** 拉取用户列表 */ String VIP_USER_LIST_URL = "https://api.weixin.qq.com/channels/ec/vip/user/list/get"; /** 获取用户积分 */ String VIP_SCORE_URL = "https://api.weixin.qq.com/channels/ec/vip/user/score/get"; /** 增加用户积分 */ String SCORE_INCREASE_URL = "https://api.weixin.qq.com/channels/ec/vip/user/score/increase"; /** 减少用户积分 */ String SCORE_DECREASE_URL = "https://api.weixin.qq.com/channels/ec/vip/user/score/decrease"; /** 更新用户等级 */ String GRADE_UPDATE_URL = "https://api.weixin.qq.com/channels/ec/vip/user/grade/update"; } }
Wechat-Group/WxJava
weixin-java-channel/src/main/java/me/chanjar/weixin/channel/constant/WxChannelApiUrlConstants.java
45,980
/* * Copyright (c) 2018. Aberic - All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.aberic.fabric.dao.entity; import com.gitee.sunchenbin.mybatis.actable.annotation.Column; import com.gitee.sunchenbin.mybatis.actable.annotation.Table; import com.gitee.sunchenbin.mybatis.actable.constants.MySqlTypeConstant; import lombok.Getter; import lombok.Setter; import lombok.ToString; /** * 作者:Aberic on 2018/6/27 21:12 * 邮箱:[email protected] */ @Setter @Getter @ToString @Table(name = "fns_league") public class League { @Column(name = "id",type = MySqlTypeConstant.INT,length = 9,isKey = true,isAutoIncrement = true) private int id; // required @Column(name = "name",type = MySqlTypeConstant.VARCHAR,length = 256) private String name; // required @Column(name = "date",type = MySqlTypeConstant.VARCHAR,length = 14) private String date; // required private int orgCount; // required }
aberic/fabric-net-server
fabric-edge/src/main/java/cn/aberic/fabric/dao/entity/League.java
45,981
package com.github.javafaker; public class Esports { private final Faker faker; protected Esports(final Faker faker) { this.faker = faker; } public String player() { return faker.resolve("esport.players"); } public String team() { return faker.resolve("esport.teams"); } public String event() { return faker.resolve("esport.events"); } public String league() { return faker.resolve("esport.leagues"); } public String game() { return faker.resolve("esport.games"); } }
DiUS/java-faker
src/main/java/com/github/javafaker/Esports.java
45,982
package net.datafaker.providers.sport; import net.datafaker.providers.base.AbstractProvider; /** * @since 0.9.0 */ public class EnglandFootBall extends AbstractProvider<SportProviders> { protected EnglandFootBall(final SportProviders faker) { super(faker); } public String league() { return resolve("englandfootball.leagues"); } public String team() { return resolve("englandfootball.teams"); } }
datafaker-net/datafaker
src/main/java/net/datafaker/providers/sport/EnglandFootBall.java
45,983
/** * This file is part of Aion-Lightning <aion-lightning.org>. * * Aion-Lightning is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Aion-Lightning is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Aion-Lightning. * If not, see <http://www.gnu.org/licenses/>. */ package com.aionemu.gameserver.model.team2.league; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import com.aionemu.gameserver.model.Race; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.model.team2.GeneralTeam; import com.aionemu.gameserver.model.team2.alliance.PlayerAlliance; import com.aionemu.gameserver.model.team2.alliance.PlayerAllianceMember; import com.aionemu.gameserver.model.team2.common.legacy.LootGroupRules; import com.aionemu.gameserver.network.aion.AionServerPacket; import com.aionemu.gameserver.utils.idfactory.IDFactory; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.Lists; /** * @author ATracer */ public class League extends GeneralTeam<PlayerAlliance, LeagueMember> { private LootGroupRules lootGroupRules = new LootGroupRules(); private static final LeagueMemberComparator MEMBER_COMPARATOR = new LeagueMemberComparator(); public League(LeagueMember leader) { super(IDFactory.getInstance().nextId()); initializeTeam(leader); } protected final void initializeTeam(LeagueMember leader) { setLeader(leader); } @Override public Collection<PlayerAlliance> getOnlineMembers() { return getMembers(); } @Override public void addMember(LeagueMember member) { super.addMember(member); member.getObject().setLeague(this); } @Override public void removeMember(LeagueMember member) { super.removeMember(member); member.getObject().setLeague(null); } @Override public void sendPacket(AionServerPacket packet) { for (PlayerAlliance alliance : getMembers()) { alliance.sendPacket(packet); } } @Override public void sendPacket(AionServerPacket packet, Predicate<PlayerAlliance> predicate) { for (PlayerAlliance alliance : getMembers()) { if (predicate.apply(alliance)) { alliance.sendPacket(packet, Predicates.<Player> alwaysTrue()); } } } @Override public int onlineMembers() { return getMembers().size(); } @Override public Race getRace() { return getLeaderObject().getRace(); } @Override public boolean isFull() { return size() == 8; } public LootGroupRules getLootGroupRules() { return lootGroupRules; } public void setLootGroupRules(LootGroupRules lootGroupRules) { this.lootGroupRules = lootGroupRules; } /** * @return sorted alliances by position */ public Collection<LeagueMember> getSortedMembers() { ArrayList<LeagueMember> newArrayList = Lists.newArrayList(members.values()); Collections.sort(newArrayList, MEMBER_COMPARATOR); return newArrayList; } /** * Search for player member in all alliances * * @return player object */ public Player getPlayerMember(Integer playerObjId) { for (PlayerAlliance member : getMembers()) { PlayerAllianceMember playerMember = member.getMember(playerObjId); if (playerMember != null) { return playerMember.getObject(); } } return null; } static class LeagueMemberComparator implements Comparator<LeagueMember> { @Override public int compare(LeagueMember o1, LeagueMember o2) { return o1.getLeaguePosition() > o2.getLeaguePosition() ? 1 : -1; } } }
EmuZONE/Aion-Lightning-6.0
AL-Game/src/com/aionemu/gameserver/model/team2/league/League.java
45,984
package mage.cards.l; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.costs.common.TapSourceCost; import mage.abilities.costs.mana.ManaCostsImpl; import mage.abilities.effects.common.CopyTargetStackObjectEffect; import mage.abilities.effects.common.DrawCardSourceControllerEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.constants.TargetController; import mage.filter.FilterSpell; import mage.filter.common.FilterInstantOrSorcerySpell; import mage.target.TargetSpell; import mage.target.targetadjustment.XManaValueTargetAdjuster; import java.util.UUID; /** * * @author TheElk801 */ public final class LeagueGuildmage extends CardImpl { private static final FilterSpell filter = new FilterInstantOrSorcerySpell("instant or sorcery spell you control with mana value X"); static { filter.add(TargetController.YOU.getControllerPredicate()); } public LeagueGuildmage(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{U}{R}"); this.subtype.add(SubType.HUMAN); this.subtype.add(SubType.WIZARD); this.power = new MageInt(2); this.toughness = new MageInt(2); // {3}{U}, {T}: Draw a card. Ability ability = new SimpleActivatedAbility( new DrawCardSourceControllerEffect(1), new ManaCostsImpl<>("{3}{U}") ); ability.addCost(new TapSourceCost()); this.addAbility(ability); // {X}{R}, {T}: Copy target instant or sorcery spell you control with converted mana cost X. You may choose new targets for the copy. ability = new SimpleActivatedAbility( new CopyTargetStackObjectEffect(), new ManaCostsImpl<>("{X}{R}") ); ability.addCost(new TapSourceCost()); ability.addTarget(new TargetSpell(filter)); ability.setTargetAdjuster(new XManaValueTargetAdjuster()); this.addAbility(ability); } private LeagueGuildmage(final LeagueGuildmage card) { super(card); } @Override public LeagueGuildmage copy() { return new LeagueGuildmage(this); } }
magefree/mage
Mage.Sets/src/mage/cards/l/LeagueGuildmage.java
45,985
/* * Copyright (C) 2015 joulupunikki [email protected]. * * Disclaimer of Warranties and Limitation of Liability. * * The creators and distributors offer this software as-is and * as-available, and make no representations or warranties of any * kind concerning this software, whether express, implied, statutory, * or other. This includes, without limitation, warranties of title, * merchantability, fitness for a particular purpose, non-infringement, * absence of latent or other defects, accuracy, or the presence or * absence of errors, whether or not known or discoverable. * * To the extent possible, in no event will the creators or distributors * be liable on any legal theory (including, without limitation, * negligence) or otherwise for any direct, special, indirect, * incidental, consequential, punitive, exemplary, or other losses, * costs, expenses, or damages arising out of the use of this software, * even if the creators or distributors have been advised of the * possibility of such losses, costs, expenses, or damages. * * The disclaimer of warranties and limitation of liability provided * above shall be interpreted in a manner that, to the extent possible, * most closely approximates an absolute disclaimer and waiver of * all liability. * */ package ai; import galaxyreader.Structure; import galaxyreader.Unit; import game.Game; import game.Hex; import java.util.LinkedList; import java.util.List; import util.C; import util.Util; /** * League AI base class. * * @author joulupunikki [email protected] */ public class LeagueAI extends AI { private static final long serialVersionUID = 1L; /** * Agora restock interval in years. */ protected static final int RESTOCK_INTERVAL = 2; /** * Agora restock values. */ protected static final int[] AGORA_RESTOCK = { 500, 200, 200, 100, 100, 50, 50, 50, 50, 25, 25, 10, 2 }; @Override protected void findAssets(int faction) { super.clear(); // fix #126 for (Structure s : all_structures) { if (s.type == C.MONASTERY || s.type == C.ALIEN_RUINS || s.type == C.RUINS) { continue; } if (s.owner == faction) { structures.add(s); } else if (planets.get(s.p_idx).spotted[faction]) { enemy_structures.add(s); } } } /** * Restock all League agoras every RESTOCK_INTERVAL years. Excess pods are * silently deleted and replaced with pods of missing resources if * necessary. */ protected void restockAgoras() { System.out.println("Check agora restock ..."); if ((game.getYear() - C.STARTING_YEAR + 1) % RESTOCK_INTERVAL != 0) { System.out.println("... no agora restock"); return; } System.out.println("... restocking"); for (Structure s : structures) { if (s.type != C.AGORA) { continue; } System.out.println(" Agora at " + s.p_idx + "," + s.x + "," + s.y); Hex hex = game.getHexFromPXY(s.p_idx, s.x, s.y); List<Unit> stock = hex.getStack(); boolean[] have = new boolean[C.NR_RESOURCES]; List<Unit> overflow = new LinkedList<>(); for (Unit u : stock) { if (u.type == C.CARGO_UNIT_TYPE) { if (have[u.res_relic]) { overflow.add(u); continue; } have[u.res_relic] = true; int adjust = AGORA_RESTOCK[u.res_relic] - u.amount; game.getResources().adjustPodResources(u, adjust); } } for (Unit u : overflow) { game.deleteUnitNotInCombat(u); } for (int i = 0; i < have.length; i++) { if (!have[i]) { game.createUnitInHex(s.p_idx, s.x, s.y, C.LEAGUE, C.LEAGUE, C.CARGO_UNIT_TYPE, 0, i, AGORA_RESTOCK[i]); } } } } public enum UTypes { PSYCH, CLOSE, DIRECT, INDIRECT, AIR, NESTER, CLOSE_SP, DIRECT_SP, RANGED_SP, CARGO_SP, } public LeagueAI(Game game) { super(game, C.LEAGUE); Util.dP("##### LeagueAI init begin"); Util.dP("##### LeagueAI init end"); } @Override public void doTurn() { findAssets(C.LEAGUE); considerPeaceOffers(); restockAgoras(); //logSuper(C.NEUTRAL, "Start"); // list stacks //findAssets(C.NEUTRAL); // list known enemy cities // attack enemy cities // attack enemy units } }
joulupunikki/Phoenix
src/ai/LeagueAI.java
45,986
package data; import java.awt.Color; /** * This class holds attributes defining rules. * * @author Michel Bartsch */ public abstract class Rules { /** Note all league's rules here to have them available. */ public static final Rules[] LEAGUES = { new SPL() }; /** * Returns the Rules object for the given class. */ public static Rules getLeagueRules(final Class<? extends Rules> c) { for(final Rules r : LEAGUES) { if(c.isInstance(r) && r.getClass().isAssignableFrom(c)) { return r; } } return null; } /** The rules of the league playing. */ public static Rules league = LEAGUES[0]; /** The league's name this rules are for. */ public String leagueName; /** The league's directory name with its teams and icons. */ public String leagueDirectory; /** How many robots are in a team. */ public int teamSize; /** The Java Colors the left and the right team starts with. */ public Color[] teamColor; /** Time in seconds one half is long. */ public int halfTime; }
RoboCup-SPL/GameController
src/data/Rules.java
45,987
/** * Copyright (c) 2010-2024 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.core.library.unit; import java.math.BigInteger; import javax.measure.Unit; import javax.measure.quantity.Area; import javax.measure.quantity.Length; import javax.measure.quantity.Mass; import javax.measure.quantity.Pressure; import javax.measure.quantity.Speed; import javax.measure.quantity.Temperature; import javax.measure.quantity.Volume; import javax.measure.spi.SystemOfUnits; import org.eclipse.jdt.annotation.NonNullByDefault; import org.openhab.core.library.dimension.VolumetricFlowRate; import tech.units.indriya.format.SimpleUnitFormat; import tech.units.indriya.function.AddConverter; import tech.units.indriya.function.MultiplyConverter; import tech.units.indriya.unit.ProductUnit; import tech.units.indriya.unit.TransformedUnit; import tech.units.indriya.unit.Units; /** * Imperial units used for the United States and Liberia. * * @author Henning Treu - Initial contribution */ @NonNullByDefault public final class ImperialUnits extends CustomUnits { public static final String MEASUREMENT_SYSTEM_NAME = "US"; private static final ImperialUnits INSTANCE = new ImperialUnits(); public static final Unit<Mass> POUND = addUnit(new TransformedUnit<>("lb", Units.GRAM, MultiplyConverter.ofRational(BigInteger.valueOf(45359237), BigInteger.valueOf(100000)))); /** Additionally defined units to be used in openHAB **/ public static final Unit<Pressure> INCH_OF_MERCURY = addUnit(new TransformedUnit<>("inHg", Units.PASCAL, MultiplyConverter.ofRational(BigInteger.valueOf(3386388), BigInteger.valueOf(1000)))); public static final Unit<Pressure> POUND_FORCE_SQUARE_INCH = addUnit(new TransformedUnit<>("psi", Units.PASCAL, MultiplyConverter.ofRational(BigInteger.valueOf(6894757), BigInteger.valueOf(1000)))); public static final Unit<Temperature> FAHRENHEIT = addUnit( new TransformedUnit<>("°F", Units.KELVIN, MultiplyConverter .ofRational(BigInteger.valueOf(5), BigInteger.valueOf(9)).concatenate(new AddConverter(459.67)))); public static final Unit<Speed> MILES_PER_HOUR = addUnit(new TransformedUnit<>("mph", Units.KILOMETRE_PER_HOUR, MultiplyConverter.ofRational(BigInteger.valueOf(1609344), BigInteger.valueOf(1000000)))); /** Length **/ public static final Unit<Length> INCH = addUnit(new TransformedUnit<>("in", Units.METRE, MultiplyConverter.ofRational(BigInteger.valueOf(254), BigInteger.valueOf(10000)))); public static final Unit<Length> FOOT = addUnit(new TransformedUnit<>("ft", INCH, MultiplyConverter.of(12.0))); public static final Unit<Length> YARD = addUnit(new TransformedUnit<>("yd", FOOT, MultiplyConverter.of(3.0))); public static final Unit<Length> CHAIN = addUnit(new TransformedUnit<>("ch", YARD, MultiplyConverter.of(22.0))); public static final Unit<Length> FURLONG = addUnit(new TransformedUnit<>("fur", CHAIN, MultiplyConverter.of(10.0))); public static final Unit<Length> MILE = addUnit(new TransformedUnit<>("mi", FURLONG, MultiplyConverter.of(8.0))); public static final Unit<Length> LEAGUE = addUnit(new TransformedUnit<>("lea", MILE, MultiplyConverter.of(3.0))); /** Area **/ public static final Unit<Area> SQUARE_INCH = addUnit(new ProductUnit<>(INCH.multiply(INCH))); public static final Unit<Area> SQUARE_FOOT = addUnit(new ProductUnit<>(FOOT.multiply(FOOT))); /** Volume **/ public static final Unit<Volume> CUBIC_INCH = addUnit(new ProductUnit<>(SQUARE_INCH.multiply(INCH))); public static final Unit<Volume> CUBIC_FOOT = addUnit(new ProductUnit<>(SQUARE_FOOT.multiply(FOOT))); public static final Unit<Volume> GALLON_LIQUID_US = addUnit( new TransformedUnit<>("gal", CUBIC_INCH, MultiplyConverter.of(231.0))); public static final Unit<VolumetricFlowRate> GALLON_PER_MINUTE = addUnit( new ProductUnit<>(GALLON_LIQUID_US.divide(tech.units.indriya.unit.Units.MINUTE))); /* * Add unit symbols for imperial units. */ static { SimpleUnitFormat.getInstance().label(INCH_OF_MERCURY, INCH_OF_MERCURY.getSymbol()); SimpleUnitFormat.getInstance().label(FAHRENHEIT, FAHRENHEIT.getSymbol()); SimpleUnitFormat.getInstance().label(MILES_PER_HOUR, MILES_PER_HOUR.getSymbol()); SimpleUnitFormat.getInstance().label(INCH, INCH.getSymbol()); SimpleUnitFormat.getInstance().label(FOOT, FOOT.getSymbol()); SimpleUnitFormat.getInstance().label(YARD, YARD.getSymbol()); SimpleUnitFormat.getInstance().label(CHAIN, CHAIN.getSymbol()); SimpleUnitFormat.getInstance().label(FURLONG, FURLONG.getSymbol()); SimpleUnitFormat.getInstance().label(MILE, MILE.getSymbol()); SimpleUnitFormat.getInstance().label(LEAGUE, LEAGUE.getSymbol()); SimpleUnitFormat.getInstance().label(GALLON_LIQUID_US, GALLON_LIQUID_US.getSymbol()); SimpleUnitFormat.getInstance().label(GALLON_PER_MINUTE, "gal/min"); SimpleUnitFormat.getInstance().label(POUND_FORCE_SQUARE_INCH, POUND_FORCE_SQUARE_INCH.getSymbol()); } private ImperialUnits() { // avoid external instantiation } /** * Returns the unique instance of this class. * * @return the Units instance. */ public static SystemOfUnits getInstance() { return INSTANCE; } /** * Adds a new unit not mapped to any specified quantity type. * * @param unit the unit being added. * @return <code>unit</code>. */ private static <U extends Unit<?>> U addUnit(U unit) { INSTANCE.units.add(unit); return unit; } @Override public String getName() { return MEASUREMENT_SYSTEM_NAME; } }
openhab/openhab-core
bundles/org.openhab.core/src/main/java/org/openhab/core/library/unit/ImperialUnits.java
45,988
package core.file.xml; public class TeamInfo { private int teamId; private Integer youthTeamId; private String name; private String country; private String league; private int leagueId; private String currencyRate; private boolean primaryTeam; private String countryId; public int getTeamId() { return teamId; } public void setTeamId(int teamId) { this.teamId = teamId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getLeague() { return league; } public void setLeague(String league) { this.league = league; } public int getLeagueId() { return leagueId; } public void setLeagueId(int leagueId) { this.leagueId = leagueId; } public String getCurrencyRate() { return currencyRate; } public void setCurrencyRate(String currencyRate) { this.currencyRate = currencyRate; } public boolean isPrimaryTeam() { return primaryTeam; } public void setPrimaryTeam(boolean primaryTeam) { this.primaryTeam = primaryTeam; } public Integer getYouthTeamId() { return youthTeamId; } public void setYouthTeamId(Integer youthTeamId) { this.youthTeamId = youthTeamId; } public void setCountryId(String countryId) { this.countryId = countryId; } public String getCountryId() { return countryId; } }
ho-dev/HattrickOrganizer
src/main/java/core/file/xml/TeamInfo.java
45,989
package designpattern.mediator; /** * 抽象同事类 * * @author liu yuning * */ public abstract class Colleague { protected Mediator mediator; public Colleague(Mediator mediator) { this.mediator = mediator; } public abstract void sendMsg(String message); public abstract void notifyMsg(String message); } class ConcreteColleague1 extends Colleague { public ConcreteColleague1(Mediator mediator) { super(mediator); } @Override public void sendMsg(String message) { mediator.send(message, this); } @Override public void notifyMsg(String message) { System.out.println("同事1得到消息:" + message); } } class ConcreteColleague2 extends Colleague { public ConcreteColleague2(Mediator mediator) { super(mediator); } @Override public void sendMsg(String message) { mediator.send(message, this); } @Override public void notifyMsg(String message) { System.out.println("同事2得到消息:" + message); } }
echoTheLiar/JavaCodeAcc
src/designpattern/mediator/Colleague.java
45,990
/* * This file is part of LeagueLib. * LeagueLib is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * LeagueLib is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with LeagueLib. If not, see <http://www.gnu.org/licenses/>. */ package com.achimala.leaguelib.connection; import com.achimala.leaguelib.errors.*; import com.achimala.util.Callback; import com.gvaneyck.rtmp.LoLRTMPSClient; import com.gvaneyck.rtmp.TypedObject; import java.io.IOException; public class LeagueAccount { private LeagueServer _server; private String _clientVersion, _username, _password; LoLRTMPSClient _internalClient; /** * Creates a LeagueAccount, which is used to authenticate API calls to the League of Legends RTMP API. */ public LeagueAccount(LeagueServer server, String clientVersion, String username, String password) { _server = server; _clientVersion = clientVersion; _username = username; _password = password; } private void setupClient() throws LeagueException { if(_server == null || _clientVersion == null || _username == null || _password == null || _username.length() <= 0 || _password.length() <= 0) throw new LeagueException(LeagueErrorCode.AUTHENTICATION_ERROR, "Missing credentials"); if(_internalClient == null) _internalClient = new LoLRTMPSClient(_server.getServerCode(), _clientVersion, _username, _password); } /** * Returns true if this account is connected to the League of Legends RTMP server, or false otherwise. */ public boolean isConnected() { return _internalClient != null && _internalClient.isConnected() && _internalClient.isLoggedIn(); } /** * Attempts to connect this account to the League of Legends RTMP server. * Upon failure, throws a LeagueException * Connects synchronously. Upon returning, guarantees account is valid and connected. * If the account is already connected, has no effect. */ public void connect() throws LeagueException { try { if(_internalClient == null) setupClient(); if(_internalClient.isConnected()) { if(_internalClient.isLoggedIn()) return; else _internalClient.login(); } else _internalClient.connectAndLogin(); } catch(IOException e) { throw new LeagueException(LeagueErrorCode.NETWORK_ERROR, e.getMessage()); } } /** * Cleanly disconnects from the League of Legends RTMP server. * No effect if the account is not connected. * You should always remember to call this, because the LoL RTMP service expects a logout message. * Otherwise it will be in an inconsistent state until the heartbeat timeout kicks the user. */ public void close() { if(!isConnected()) return; _internalClient.close(); } /** * Invokes an API call on the RTMP server. * Returns the raw packet data retrieved from the API call. * You should never have to call this method directly; create your accounts and create a LeagueConnection. * Then push your accounts onto the LeagueConnection's account queue. * You can then use LeagueConnection's invoke method or (preferably) use a League service abstraction. */ public TypedObject invoke(String service, String method, Object arguments) throws LeagueException { if(!isConnected()) throw new LeagueException(LeagueErrorCode.RTMP_ERROR, toString() + " is unable to connect to RTMP server"); try { // System.out.println(_username + " performing " + method + " in " + service); return _internalClient.getResult(_internalClient.invoke(service, method, arguments)); } catch(IOException e) { throw new LeagueException(LeagueErrorCode.NETWORK_ERROR, e.getMessage()); } } /** * Same as invoke() but happens in a background thread, asynchronously. Returns immediately. * Suppresses exceptions and calls onError of the provided callback instead. * You shouldn't call this directly, but create a wrapping LeagueConnection and use its invokeWithCallback. */ public void invokeWithCallback(String service, String method, Object arguments, final Callback<TypedObject> callback) { try { // System.out.println(_username + " performing " + method + " in " + service); _internalClient.invokeWithCallback(service, method, arguments, new com.gvaneyck.rtmp.Callback() { public void callback(TypedObject result) { callback.onCompletion(result); } }); } catch(IOException e) { callback.onError(e); } } public void setServer(LeagueServer server) { _server = server; } public void setClientVersion(String clientVersion) { _clientVersion = clientVersion; } public void setUsername(String username) { _username = username; } public void setPassword(String password) { _password = password; } public LeagueServer getServer() { return _server; } public String getClientVersion() { return _clientVersion; } public String getUsername() { return _username; } public String getPassword() { return _password; } public String toString() { return String.format("<LeagueAccount: %s on %s>", _username, _server.getServerCode()); } public boolean equals(Object o) { if(!(o instanceof LeagueAccount)) return false; LeagueAccount other = (LeagueAccount)o; return other.getServer() == _server && other.getUsername().equals(_username) && other.getPassword().equals(_password); } }
mpoon/leaguelib
src/com/achimala/leaguelib/connection/LeagueAccount.java
45,991
package me.chanjar.weixin.channel.bean.league.supplier; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import me.chanjar.weixin.channel.bean.league.ExpressInfo; import me.chanjar.weixin.channel.bean.league.SimpleProductInfo; /** * 商品信息 * * @author <a href="https://github.com/lixize">Zeyes</a> */ @Data @NoArgsConstructor @EqualsAndHashCode(callSuper = true) public class ProductInfo extends SimpleProductInfo { private static final long serialVersionUID = 5352334936089828219L; /** 快递信息 */ @JsonProperty("express_info") private ExpressInfo expressInfo; /** sku信息 */ @JsonProperty("skus") private List<SkuInfo> skus; }
Wechat-Group/WxJava
weixin-java-channel/src/main/java/me/chanjar/weixin/channel/bean/league/supplier/ProductInfo.java
45,992
package com.leosanqing.mediator; import java.awt.*; import java.awt.event.TextEvent; import java.awt.event.TextListener; /** * @Author: leosanqing * @Date: 2019-10-27 10:51 */ public class ColleagueTextField extends TextField implements TextListener, Colleague { private Mediator mediator; @Override public void setMediator(Mediator mediator) { this.mediator = mediator; } public ColleagueTextField(String text, int columns) { super(text, columns); } @Override public void setColleagueEnabled(boolean enabled) { setEnabled(enabled); setBackground(enabled ? Color.white : Color.lightGray); } @Override public void textValueChanged(TextEvent e) { mediator.colleagueChanged(); } }
leosanqing/Java-Notes
designPattern/src/com/leosanqing/mediator/ColleagueTextField.java
45,993
package core.model; public class WorldDetailLeague { private int leagueId; private int countryId; private String countryName; private int activeUsers; public WorldDetailLeague(){ } public WorldDetailLeague(int leagueId, int countryId, String countryName){ this.leagueId = leagueId; this.countryId = countryId; this.countryName = countryName; } public final int getLeagueId() { return leagueId; } public final void setLeagueId(int leagueId) { this.leagueId = leagueId; } public final int getCountryId() { return countryId; } public final void setCountryId(int countryId) { this.countryId = countryId; } public final String getCountryName() { return countryName; } public final void setCountryName(String countryName) { this.countryName = countryName; } public final int getActiveUsers() { return activeUsers; } public final void setActiveUsers(int activeUsers) { this.activeUsers = activeUsers; } @Override public String toString(){ return getCountryName(); } }
grojar/HO
src/main/java/core/model/WorldDetailLeague.java
45,994
package module.nthrf; import core.db.AbstractTable; import core.file.xml.XMLManager; import core.util.HODateTime; import org.w3c.dom.Document; import org.w3c.dom.Element; public class NtTeamDetails extends AbstractTable.Storable { private int hrfId; private int teamId; private String teamName; private String teamNameShort; private int coachId; private String coachName; private int leagueId; private String leagueName; private String homePageUrl; private int xp253=0; private int xp343=0; private int xp352=0; private int xp433=0; private int xp442=0; private int xp451=0; private int xp523=0; private int xp532=0; private int xp541=0; private int xp550=0; private Integer morale; private Integer selfConfidence; private int supportersPopularity; private int ratingScore; private int fanclubSize; private int rank; private HODateTime fetchedDate; private boolean parsingSuccess; public void setTeamName(String teamName) { this.teamName = teamName; } public void setTeamNameShort(String teamNameShort) { this.teamNameShort = teamNameShort; } public void setCoachId(Integer coachId) { if ( coachId!=null )this.coachId = coachId; } public void setCoachName(String coachName) { this.coachName = coachName; } public void setLeagueId(Integer leagueId) { if ( leagueId!=null) this.leagueId = leagueId; } public void setLeagueName(String leagueName) { this.leagueName = leagueName; } public void setHomePageUrl(String homePageUrl) { this.homePageUrl = homePageUrl; } public int getXp253() { return xp253; } public void setXp253(Integer xp253) { if ( xp253 != null )this.xp253 = xp253; } public void setXp343(Integer xp343) { if ( xp343 != null) this.xp343 = xp343; } public void setXp352(Integer xp352) { if (xp352!=null)this.xp352 = xp352; } public void setXp433(Integer xp433) { if ( xp433 != null) this.xp433 = xp433; } public int getXp442() { return xp442; } public void setXp442(Integer xp442) { if ( xp442 != null ) this.xp442 = xp442; } public void setXp451(Integer xp451) { if ( xp451!=null) this.xp451 = xp451; } public void setXp523(Integer xp523) { if ( xp523!= null) this.xp523 = xp523; } public void setXp532(Integer xp532) { if ( xp532!= null) this.xp532 = xp532; } public void setXp541(Integer xp541) { if ( xp541 != null ) this.xp541 = xp541; } public int getXp550() { return xp550; } public void setXp550(Integer xp550) { if ( xp550!= null) this.xp550 = xp550; } public void setMorale(Integer morale) { this.morale = morale; } public void setSelfConfidence(Integer selfConfidence) { this.selfConfidence = selfConfidence; } public void setSupportersPopularity(Integer supportersPopularity) { if ( supportersPopularity!= null) this.supportersPopularity = supportersPopularity; } public void setRatingScore(Integer ratingScore) { if ( ratingScore!= null) this.ratingScore = ratingScore; } public void setFanclubSize(Integer fanclubSize) { if ( fanclubSize!= null) this.fanclubSize = fanclubSize; } public void setRank(Integer rank) { if ( rank!=null) this.rank = rank; } public void setFetchedDate(HODateTime fetchedDate) { this.fetchedDate = fetchedDate; } public int getTeamId() { return teamId; } public void setTeamId(Integer teamId) { if ( teamId != null ) this.teamId = teamId; } public void setHrfId(Integer hrfId) { if ( hrfId!=null) this.hrfId = hrfId; } public String getTeamName() { return teamName; } public long getCoachId() { return coachId; } public String getCoachName() { return coachName; } public int getLeagueId() { return leagueId; } public String getLeagueName() { return leagueName; } public String getHomePageUrl() { return homePageUrl; } public int getXp433() { return xp433; } public int getXp451() { return xp451; } public int getXp352() { return xp352; } public int getXp523() { return this.xp523; } public int getXp532() { return xp532; } public int getXp343() { return xp343; } public int getXp541() { return xp541; } public Integer getMorale() { return morale; } public Integer getSelfConfidence() { return selfConfidence; } public int getSupportersPopularity() { return supportersPopularity; } public int getRatingScore() { return ratingScore; } public int getFanclubSize() { return fanclubSize; } public int getRank() { return rank; } public String getTeamNameShort() { return teamNameShort; } public HODateTime getFetchedDate() { return fetchedDate; } public int getHrfId() { return hrfId; } /** * constructor is used by AbstractTable.load */ public NtTeamDetails(){} public NtTeamDetails(String xmlData) { parseDetails(XMLManager.parseString(xmlData)); } private void parseDetails(Document doc) { if (doc == null) { return; } try { Element root = doc.getDocumentElement(); Element ele = (Element)root.getElementsByTagName("FetchedDate").item(0); fetchedDate = HODateTime.fromHT(XMLManager.getFirstChildNodeValue(ele)); // root Team var teamRoot = (Element) root.getElementsByTagName("Team").item(0); teamId = getInteger(teamRoot, "TeamID", -1); teamName = getString(teamRoot, "TeamName"); teamNameShort = getString(teamRoot, "ShortTeamName"); // root national coach root = (Element) teamRoot.getElementsByTagName("NationalCoach").item(0); coachId = getInteger(root, "NationalCoachUserID"); coachName = getString(root, "NationalCoachLoginname"); // root League root = (Element) teamRoot.getElementsByTagName("League").item(0); leagueId = getInteger(root, "LeagueID", -1); leagueName = getString(root, "LeagueName"); // root HomePage homePageUrl = getString(teamRoot, "HomePage"); // formation XP xp253 = getInteger(teamRoot, "Experience253", 0); xp352 = getInteger(teamRoot, "Experience352",0); xp451 = getInteger(teamRoot, "Experience451",0); xp442 = getInteger(teamRoot, "Experience442",0); xp433 = getInteger(teamRoot, "Experience433",0); xp523 = getInteger(teamRoot, "Experience523",0); xp532 = getInteger(teamRoot, "Experience532",0); xp541 = getInteger(teamRoot, "Experience541",0); xp550 = getInteger(teamRoot, "Experience550",0); // morale etc. morale = getInteger(teamRoot, "Morale"); selfConfidence = getInteger(teamRoot, "SelfConfidence"); supportersPopularity = getInteger(teamRoot, "SupportersPopularity",0); ratingScore = getInteger(teamRoot, "RatingScore",0); fanclubSize = getInteger(teamRoot, "FanClubSize",0); rank = getInteger(teamRoot, "Rank",0); parsingSuccess = true; } catch (Exception e) { parsingSuccess = false; e.printStackTrace(); } } private int getInteger(Element root, String tag, int def) { var ret = getInteger(root, tag); if ( ret != null) return ret; return def; } private String getString(Element root, String tag) { var ele = (Element) root.getElementsByTagName(tag).item(0); return XMLManager.getFirstChildNodeValue(ele); } private Integer getInteger(Element root, String tag) { try { return Integer.parseInt(getString(root, tag)); } catch (NumberFormatException ignored) { //e.printStackTrace(); } return null; } @Override public String toString() { return "NtTeamDetails (from " + fetchedDate + "), parsingSuccess: " + parsingSuccess + "\n\tteam: " + teamName + " (" + teamId + ") - short: " + teamNameShort + "\n\tcoach: " + coachName + " (" + coachId + ")" + "\n\tleague : " + leagueName + " (" + leagueId + ")" + "\n\thomePageUrl: " + homePageUrl + "\n\txp433: " + xp433 + "\txp451: " + xp451 + "\txp352: " + xp352 + "\txp532: " + xp532 + "\txp343: " + xp343 + "\txp541: " + xp541 + "\n\tmorale: " + morale + "\n\tselfConfidence: " + selfConfidence + "\n\tsupportersPopularity: " + supportersPopularity + "\n\tratingScore: " + ratingScore + "\n\tfanclubSize: " + fanclubSize + "\n\trank: " + rank; } }
cmbarbu/HO
src/main/java/module/nthrf/NtTeamDetails.java
45,995
package com.apifan.common.random.constant; /** * 体育竞技赛事类型 * * @author yin */ public enum CompetitionType { //足球 PREMIER_LEAGUE("英超"), LA_LIGA("西甲"), BUNDESLIGA("德甲"), SERIE_A("意甲"), LIGUE_1("法甲"), EREDIVISIE("荷甲"), //篮球 NBA("NBA"), CBA("CBA"); private String name; private CompetitionType(String name) { this.name = name; } public String getName() { return this.name; } }
yindz/common-random
src/main/java/com/apifan/common/random/constant/CompetitionType.java
45,996
/* * This file is part of LeagueLib. * LeagueLib is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * LeagueLib is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with LeagueLib. If not, see <http://www.gnu.org/licenses/>. */ package com.achimala.leaguelib.connection; public enum LeagueServer { NORTH_AMERICA("NA", "North America"), EUROPE_WEST("EUW", "Europe West"), EUROPE_NORDIC_AND_EAST("EUNE", "Europe Nordic & East"), BRAZIL("BR", "Brazil"), KOREA("KR", "Korea"), LATIN_AMERICA_NORTH("LAN", "Latin America North"), LATIN_AMERICA_SOUTH("LAS", "Latin America South"), OCEANIA("OCE", "Oceania"); // Garena servers... // PublicBetaEnvironment private String _serverCode, _publicName; private LeagueServer(String serverCode, String publicName) { _serverCode = serverCode; _publicName = publicName; } public static LeagueServer findServerByCode(String code) { for(LeagueServer server : LeagueServer.values()) if(server.getServerCode().equalsIgnoreCase(code)) return server; return null; } public String getServerCode() { return _serverCode; } public String getPublicName() { return _publicName; } public String toString() { return "<LeagueServer:" + _publicName + " (" + _serverCode + ")>"; } }
worst/leaguelib
src/com/achimala/leaguelib/connection/LeagueServer.java
45,997
package br.padroes.mediator; public abstract class Colleague { protected Mediator mediator; public Colleague(Mediator m) { mediator = m; } public void enviarMensagem(String mensagem) { mediator.enviar(mensagem, this); } public abstract void receberMensagem(String mensagem); }
tgmarinho/Padr-es-de-Projeto
src/br/padroes/mediator/Colleague.java
45,998
/* * Copyright (c) 2010, James Leigh Some rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.callimachusproject.util; import java.security.SecureRandom; import java.util.Random; import org.apache.commons.codec.digest.DigestUtils; /** * Generates a random string of printable characters that can be used as a * password. * * @author James Leigh * */ public class PasswordGenerator { public static void main(String[] args) { System.out.println(PasswordGenerator.generatePassword()); } public static String generatePassword() { return PasswordGenerator.getInstance().nextPassword(); } public static PasswordGenerator getInstance() { return instance; } private static final PasswordGenerator instance = new PasswordGenerator(); private static long byteToLong(byte[] seed) { long hash = 1; for (byte b : seed) { hash = hash * 31 + b; } if (hash == 0) return 1; return hash; } private final Random rnd; public PasswordGenerator() { rnd = new SecureRandom(); } public PasswordGenerator(long seed) { rnd = new Random(seed); } public PasswordGenerator(byte[] seed) { this(byteToLong(DigestUtils.sha256(seed))); } /** * This algorithm selects from a word pool of 1916 words. This gives an * entropy of 11 bits per word. The average word length is 6. The average * entropy of each password generated is 55 bits. * * The entropy of a 8 character password of random [A-Za-z0-9] is 48 bits. * * @return a random pass-phrase */ public String nextPassword() { int length = LENGTH_MIN + rnd.nextInt(LENGTH_MAX - LENGTH_MIN + 1); StringBuilder sb = new StringBuilder(); while (sb.length() < length) { if (sb.length() > 0) { sb.append('-'); } sb.append(WORD_POOL[rnd.nextInt(WORD_POOL.length)]); } return sb.toString(); } private static final int LENGTH_MIN = 25; private static final int LENGTH_MAX = 35; private static final String[] WORD_POOL = { "a", "ability", "able", "about", "above", "academic", "accept", "accepted", "according", "account", "achieved", "achievement", "across", "act", "acting", "action", "actions", "active", "activities", "activity", "actual", "actually", "add", "added", "addition", "additional", "address", "adequate", "administration", "advance", "advantage", "affairs", "afraid", "after", "afternoon", "again", "against", "age", "agencies", "agency", "ago", "agreed", "agreement", "ahead", "aid", "air", "aircraft", "alive", "all", "allow", "allowed", "almost", "alone", "along", "already", "also", "although", "always", "am", "America", "among", "amount", "an", "analysis", "ancient", "and", "animal", "animals", "announced", "annual", "anode", "another", "answer", "answered", "any", "anyone", "anything", "apart", "apartment", "apparent", "apparently", "appeal", "appear", "appearance", "appeared", "appears", "application", "applied", "apply", "approach", "appropriate", "approximately", "April", "are", "area", "areas", "argument", "arm", "armed", "arms", "army", "around", "arrived", "art", "article", "artist", "artists", "arts", "as", "aside", "ask", "asked", "asking", "aspects", "assignment", "assistance", "Associated", "association", "assume", "assumed", "at", "atmosphere", "attack", "attempt", "attention", "attitude", "attorney", "audience", "authority", "available", "average", "avoid", "aware", "away", "baby", "back", "background", "balance", "ball", "bank", "bar", "base", "baseball", "based", "basic", "basis", "battle", "bay", "be", "beach", "bear", "beat", "beautiful", "beauty", "became", "because", "become", "becomes", "becoming", "bed", "been", "before", "began", "begin", "beginning", "begins", "behavior", "behind", "being", "belief", "believe", "believed", "below", "beneath", "benefit", "Berlin", "beside", "besides", "best", "better", "between", "beyond", "Bible", "big", "bill", "billion", "birds", "birth", "bit", "block", "blood", "blue", "board", "boat", "bodies", "body", "book", "books", "born", "Boston", "both", "bottle", "bottom", "bought", "box", "break", "bridge", "brief", "bright", "bring", "Britain", "British", "broad", "broke", "broken", "brother", "brought", "brown", "budget", "build", "building", "buildings", "built", "business", "busy", "but", "buy", "by", "California", "call", "called", "calls", "came", "camp", "campaign", "can", "cannot", "capable", "capacity", "capital", "captain", "car", "care", "career", "careful", "carefully", "carried", "carry", "carrying", "cars", "case", "cases", "cattle", "caught", "cause", "caused", "causes", "cell", "cells", "cent", "center", "central", "century", "certain", "certainly", "chair", "chairman", "chance", "change", "changed", "changes", "Chapter", "character", "characteristic", "charge", "charged", "Charles", "check", "chemical", "Chicago", "chief", "China", "choice", "chosen", "circle", "circumstances", "cities", "citizens", "city", "civil", "claim", "claims", "class", "classes", "Clay", "clean", "clear", "clearly", "close", "closed", "closely", "closer", "clothes", "club", "coast", "coffee", "cold", "collection", "college", "color", "column", "combination", "come", "comes", "coming", "command", "commerce", "commercial", "Commission", "committee", "common", "communication", "community", "companies", "Company", "compared", "competition", "complete", "completed", "completely", "completion", "complex", "components", "concept", "concern", "concerned", "concerning", "conclusion", "condition", "conditions", "conduct", "conducted", "conference", "confidence", "Congo", "Congress", "connection", "consider", "considerable", "considered", "constant", "construction", "contact", "contained", "contemporary", "continue", "continued", "continuing", "contract", "contrast", "control", "cool", "corner", "corporation", "Corps", "cost", "costs", "could", "council", "countries", "country", "county", "couple", "course", "courses", "court", "cover", "covered", "created", "credit", "critical", "cross", "cultural", "culture", "current", "cut", "cutting", "daily", "Dallas", "dance", "danger", "dark", "data", "date", "daughter", "day", "days", "dead", "deal", "death", "December", "decided", "decision", "declared", "deep", "defense", "degree", "demand", "demands", "Democratic", "department", "described", "design", "designed", "desire", "desk", "despite", "detail", "details", "determine", "determined", "develop", "developed", "development", "device", "dictionary", "did", "die", "died", "difference", "differences", "different", "difficult", "difficulty", "dinner", "direct", "directed", "direction", "directly", "director", "discovered", "discussed", "discussion", "distance", "distribution", "District", "divided", "division", "do", "doctor", "does", "dog", "dogs", "doing", "dollars", "domestic", "dominant", "done", "door", "double", "doubt", "down", "Dr", "dramatic", "draw", "drawn", "dream", "dress", "drew", "drink", "drive", "drop", "dropped", "drove", "dry", "due", "during", "dust", "duty", "each", "earlier", "early", "earth", "easily", "east", "easy", "eat", "economic", "economy", "edge", "editor", "education", "educational", "effect", "effective", "effects", "effort", "efforts", "eight", "either", "election", "electric", "electronic", "elements", "else", "emphasis", "employees", "empty", "end", "ended", "ends", "enemy", "energy", "England", "English", "enjoyed", "enough", "enter", "entered", "entire", "entirely", "entitled", "entrance", "equal", "equally", "equipment", "escape", "especially", "essential", "establish", "established", "estimated", "etc", "Europe", "even", "evening", "event", "events", "ever", "every", "everybody", "everyone", "everything", "evidence", "evident", "exactly", "example", "excellent", "except", "exchange", "executive", "exercise", "exist", "existence", "existing", "expect", "expected", "experience", "experiment", "experiments", "explain", "explained", "expressed", "expression", "extended", "extent", "extreme", "eye", "eyes", "face", "faces", "facilities", "fact", "factor", "factors", "facts", "faculty", "failed", "failure", "fair", "fairly", "fall", "familiar", "families", "family", "famous", "far", "farm", "fashion", "fast", "father", "favor", "fear", "features", "federal", "feed", "feel", "feeling", "feelings", "feet", "fell", "fellow", "felt", "few", "field", "fields", "fifteen", "fifty", "fig", "fight", "fighting", "figure", "figures", "file", "filled", "film", "final", "finally", "financial", "find", "finds", " fine", "fingers", "finished", "fire", "firm", "firms", "first", "fiscal", "fit", "five", "fixed", "flat", "floor", "flow", "flowers", "follow", "followed", "following", "follows", "food", "foot", "for", "force", "forced", "forces", "foreign", "forest", "form", "formed", "former", "forms", "formula", "fort", "forth", "forward", "found", "Four", "fourth", "frame", "France", "Frank", "free", "freedom", "frequently", "Fresh", "Friday", "friend", "friendly", "friends", "from", "front", "full", "fully", "function", "fund", "funds", "further", "future", "gain", "game", "games", "garden", "gas", "gave", "general", "generally", "generation", "George", "Germany", "get", "gets", "getting", "give", "given", "gives", "giving", "Glass", "go", "goal", "goes", "going", "gone", "good", "goods", "got", "government", "governments", "governor", "granted", "gray", "great", "greater", "greatest", "greatly", "Green", "grew", "gross", "ground", "grounds", "group", "groups", "grow", "growing", "growth", "guess", "guests", "gun", "had", "hair", "half", "hall", "hand", "hands", "Hanover", "happen", "happened", "happy", "hard", "hardly", "has", "hat", "have", "having", "he", "head", "headed", "headquarters", "health", "hear", "heard", "hearing", "heart", "heat", "heavily", "heavy", "held", "hell", "help", "helped", "hence", "Henry", "her", "here", "herself", "high", "higher", "highest", "highly", "hill", "him", "himself", "his", "historical", "history", "hit", "hold", "holding", "hole", "home", "homes", "honor", "hope", "horse", "horses", "hospital", "hot", "Hotel", "hour", "hours", "house", "houses", "housing", "how", "however", "human", "hundred", "I", "idea", "ideal", "ideas", "if", "image", "imagination", "imagine", "immediate", "immediately", "impact", "importance", "important", "impossible", "improved", "in", "inch", "inches", "include", "included", "including", "income", "increase", "increased", "increases", "increasing", "indeed", "independence", "independent", "index", "India", "indicate", "indicated", "individual", "individuals", "industrial", "industry", "influence", "information", "informed", "initial", "inside", "instance", "instead", "institutions", "intellectual", "intensity", "interest", "interested", "interesting", "interests", "interior", "internal", "international", "into", "involved", "is", "island", "issue", "issues", "it", "items", "its", "itself", "Jack", "James", "jazz", "job", "jobs", "Joe", "John", "join", "joined", "Jones", "Joseph", "Judge", "judgment", "July", "June", "junior", "junior", "Jury", "just", "justice", "keep", "keeping", "Kennedy", "kept", "key", "Khrushchev", "kid", "kind", "king", "kitchen", "knew", "knife", "know", "knowledge", "known", "knows", "la", "labour", "lack", "Lady", "laid", "land", "language", "Laos", "large", "largely", "larger", "last", "late", "later", "latter", "law", "laws", "lay", "lead", "Leader", "leaders", "leadership", "leading", "league", "learn", "learned", "learning", "least", "leave", "leaving", "led", "left", "leg", "legal", "legs", "length", "less", "let", "letter", "letters", "level", "levels", "Lewis", "liberal", "library", "lie", "life", "light", "like", "liked", "likely", "limited", "line", "lines", "lips", "list", "literary", "literature", "little", "live", "lived", "lives", "living", "local", "located", "location", "London", "long", "longer", "Look", "looked", "looking", "looks", "Lord", "lose", "loss", "lost", "lot", "Louis", "loved", "low", "lower", "machine", "machinery", "made", "main", "maintain", "maintenance", "major", "majority", "make", "makes", "making", "management", "manager", "manner", "many", "March", "Mark", "marked", "market", "marriage", "married", "Martin", "Mary", "mass", "master", "material", "materials", "matter", "matters", "maximum", "may", "maybe", "me", "meaning", "means", "meant", "measure", "measured", "medical", "meet", "meeting", "member", "members", "membership", "memory", "mentioned", "Mercer", "merely", "message", "met", "Metal", "method", "methods", "Middle", "might", "Mike", "mile", "miles", "military", "million", "mind", "minds", "mine", "minimum", "Minister", "minor", "minute", "minutes", "Miss", "mission", "model", "modern", "moment", "Monday", "money", "month", "months", "moon", "moral", "more", "moreover", "Morgan", "morning", "most", "mother", "motion", "motor", "mouth", "move", "moved", "movement", "moving", "much", "Music", "musical", "must", "my", "myself", "name", "named", "names", "narrow", "nation", "national", "nations", "natural", "naturally", "nature", "near", "nearly", "necessary", "neck", "need", "needed", "needs", "negro", "negroes", "neighborhood", "neither", "never", "nevertheless", "new", "news", "newspaper", "next", "nice", "night", "nine", "no", "nobody", "none", "nor", "normal", "North", "nose", "not", "note", "noted", "notes", "Nothing", "notice", "novel", "November", "now", "nuclear", "number", "numbers", "object", "objective", "objects", "observed", "obtained", "obvious", "obviously", "occasion", "occurred", "of", "off", "offer", "offered", "office", "officer", "officers", "official", "officials", "often", "Oh", "oil", "on", "once", "one", "ones", "only", "onto", "open", "opened", "opening", "operating", "operation", "operations", "opinion", "opportunity", "opposite", "or", "orchestra", "order", "ordered", "orders", "Ordinary", "organization", "organizations", "organized", "original", "other", "others", "otherwise", "ought", "our", "ourselves", "out", "outside", "over", "own", "page", "paid", "pain", "painting", "pale", "Palmer", "paper", "parents", "Paris", "Park", "Parker", "part", "particular", "particularly", "parties", "parts", "Party", "pass", "passed", "passing", "past", "patient", "pattern", "pay", "peace", "people", "per", "percent", "perfect", "performance", "perhaps", "period", "permit", "permitted", "person", "personal", "personnel", "persons", "phase", "Phil", "philosophy", "physical", "pick", "picked", "picture", "pictures", "piece", "pieces", "place", "placed", "places", "plan", "plane", "planned", "planning", "plans", "plant", "plants", "platform", "play", "played", "playing", "plays", "please", "pleasure", "plenty", "plus", "poems", "poet", "poetry", "point", "pointed", "points", "police", "policies", "policy", "political", "politics", "pool", "popular", "population", "portion", "position", "positive", "possibility", "possible", "possibly", "post", "potential", "power", "powerful", "powers", "practical", "Practice", "prepared", "presence", "present", "presented", "president", "press", "pressure", "pretty", "prevent", "previous", "previously", "price", "prices", "primarily", "primary", "principal", "principle", "principles", "private", "probably", "problem", "problems", "procedure", "procedures", "process", "processes", "produce", "produced", "product", "production", "products", "professional", "professor", "program", "programs", "progress", "project", "projects", "proper", "properties", "property", "proposed", "protection", "proved", "provide", "provided", "Providence", "provides", "providing", "public", "published", "pulled", "pure", "purpose", "purposes", "put", "quality", "question", "questions", "quick", "quickly", "quiet", "quite", "race", "radio", "railroad", "rain", "raised", "ran", "range", "rapidly", "rate", "rates", "rather", "reach", "reached", "reaction", "read", "reading", "ready", "real", "reality", "realize", "realized", "really", "reason", "reasonable", "reasons", "receive", "received", "recent", "recently", "recognize", "recognized", "record", "records", "Red", "reduce", "reduced", "reference", "refused", "regard", "regarded", "region", "regular", "related", "relation", "relations", "relationship", "relatively", "relief", "remain", "remained", "remains", "remember", "remembered", "remove", "removed", "repeated", "replied", "report", "reported", "reports", "represented", "require", "required", "requirements", "requires", "research", "resolution", "resources", "respect", "response", "responsibility", "responsible", "rest", "result", "results", "return", "returned", "review", "revolution", "Rhode", "rich", "Richard", "rifle", "right", "rights", "rise", "rising", "river", "road", "roads", "Robert", "rock", "role", "Roman", "Rome", "roof", "room", "rooms", "rose", "round", "rule", "rules", "run", "running", "runs", "Russia", "safe", "said", "sales", "Sam", "same", "sample", "San", "sat", "Saturday", "save", "saw", "say", "saying", "says", "scale", "scene", "school", "schools", "science", "scientific", "score", "sea", "search", "season", "second", "secret", "secretary", "section", "sections", "security", "see", "seeing", "seek", "seem", "seemed", "seems", "seen", "selected", "Senate", "send", "sense", "sensitive", "sent", "separate", "September", "series", "serious", "serve", "served", "service", "services", "session", "set", "sets", "setting", "settled", "seven", "several", "shall", "shape", "share", "sharp", "she", "shelter", "ship", "shook", "shop", "shore", "short", "shot", "should", "shoulder", "show", "showed", "showing", "shown", "shows", "side", "sides", "sight", "sign", "signal", "significance", "significant", "signs", "similar", "simple", "simply", "since", "single", "Sir", "sit", "site", "sitting", "situation", "six", "size", "sky", "sleep", "slightly", "slow", "slowly", "small", "smaller", "smile", "smiled", "snow", "so", "social", "society", "soft", "solid", "solution", "some", "somebody", "somehow", "someone", "something", "sometimes", "somewhat", "somewhere", "son", "song", "songs", "soon", "sort", "sought", "sound", "source", "sources", "south", "Southern", "Soviet", "space", "speak", "speaking", "special", "specific", "speech", "speed", "spent", "spirit", "spiritual", "spite", "spoke", "spot", "spread", "spring", "square", "St", "staff", "stage", "stand", "standard", "standards", "standing", "stands", "stared", "start", "started", "starting", "State", "stated", "statement", "statements", "states", "station", "stations", "status", "stay", "stayed", "step", "steps", "still", "stock", "Stone", "stood", "stop", "stopped", "store", "stories", "story", "straight", "strange", "street", "streets", "strength", "stress", "strong", "struck", "structure", "struggle", "student", "students", "studied", "studies", "study", "style", "subject", "subjects", "substantial", "success", "successful", "such", "suddenly", "sufficient", "suggested", "summer", "sun", "Sunday", "supply", "support", "suppose", "supposed", "sure", "surface", "surprised", "sweet", "system", "systems", "table", "take", "taken", "takes", "taking", "talk", "talked", "talking", "task", "taste", "tax", "teacher", "teachers", "teaching", "team", "technical", "technique", "techniques", "teeth", "telephone", "tell", "temperature", "ten", "tension", "term", "terms", "test", "tests", "Texas", "text", "than", "that", "the", "their", "them", "theme", "themselves", "then", "theory", "there", "therefore", "these", "they", "thick", "thin", "thing", "things", "think", "thinking", "third", "thirty", "this", "Thomas", "those", "though", "thought", "thousand", "three", "through", "throughout", "thus", "time", "times", "title", "to", "today", "together", "told", "Tom", "tomorrow", "tone", "too", "took", "top", "total", "touch", "toward", "towards", "town", "trade", "tradition", "traditional", "traffic", "train", "training", "travel", "treated", "treatment", "tree", "trees", "trial", "tried", "trip", "trouble", "truck", "true", "truly", "truth", "try", "trying", "Tuesday", "turn", "turned", "turning", "twenty", "twice", "two", "type", "types", "typical", "ultimate", "UN", "uncle", "under", "understand", "understanding", "understood", "union", "unique", "unit", "United", "units", "unity", "universe", "University", "unless", "until", "unusual", "up", "upon", "upper", "US", "use", "used", "useful", "uses", "using", "usual", "usually", "valley", "value", "values", "variety", "various", "vast", "very", "victory", "view", "village", "Virginia", "vision", "visit", "vital", "vocational", "voice", "volume", "vote", "wage", "wait", "waited", "waiting", "walk", "walked", "wall", "walls", "want", "wanted", "wants", "war", "warm", "was", "Washington", "watch", "watched", "watching", "water", "way", "ways", "we", "weapons", "weather", "week", "weeks", "weight", "well", "went", "were", "west", "Western", "what", "whatever", "wheel", "when", "where", "whether", "which", "while", "who", "whole", "whom", "whose", "why", "wide", "wild", "will", "William", "willing", "Wilson", "win", "wind", "window", "wine", "winter", "wish", "with", "within", "without", "won", "wonder", "wondered", "word", "words", "wore", "work", "worked", "workers", "working", "works", "world", "worry", "worth", "would", "write", "Writer", "writers", "writing", "written", "wrong", "wrote", "yards", "year", "years", "Yes", "yesterday", "yet", "York", "you", "young", "your", "yourself", "Youth" }; }
3-Round-Stones/callimachus
src/org/callimachusproject/util/PasswordGenerator.java
45,999
package com.merakianalytics.orianna; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import com.merakianalytics.orianna.datapipeline.transformers.dtodata.AccountTransformer; import com.merakianalytics.orianna.types.core.account.Account; import com.merakianalytics.orianna.types.core.account.Accounts; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonParser.Feature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.TextNode; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.io.CharSource; import com.google.common.io.Files; import com.google.common.io.Resources; import com.merakianalytics.datapipelines.DataPipeline; import com.merakianalytics.orianna.datapipeline.DataDragon; import com.merakianalytics.orianna.datapipeline.GhostLoader; import com.merakianalytics.orianna.datapipeline.ImageDownloader; import com.merakianalytics.orianna.datapipeline.InMemoryCache; import com.merakianalytics.orianna.datapipeline.MerakiAnalyticsCDN; import com.merakianalytics.orianna.datapipeline.PipelineConfiguration; import com.merakianalytics.orianna.datapipeline.PipelineConfiguration.PipelineElementConfiguration; import com.merakianalytics.orianna.datapipeline.PipelineConfiguration.TransformerConfiguration; import com.merakianalytics.orianna.datapipeline.common.expiration.ExpirationPeriod; import com.merakianalytics.orianna.datapipeline.riotapi.RiotAPI; import com.merakianalytics.orianna.datapipeline.transformers.dtodata.ChampionMasteryTransformer; import com.merakianalytics.orianna.datapipeline.transformers.dtodata.ChampionTransformer; import com.merakianalytics.orianna.datapipeline.transformers.dtodata.LeagueTransformer; import com.merakianalytics.orianna.datapipeline.transformers.dtodata.MatchTransformer; import com.merakianalytics.orianna.datapipeline.transformers.dtodata.SpectatorTransformer; import com.merakianalytics.orianna.datapipeline.transformers.dtodata.StaticDataTransformer; import com.merakianalytics.orianna.datapipeline.transformers.dtodata.StatusTransformer; import com.merakianalytics.orianna.datapipeline.transformers.dtodata.SummonerTransformer; import com.merakianalytics.orianna.datapipeline.transformers.dtodata.ThirdPartyCodeTransformer; import com.merakianalytics.orianna.types.common.OriannaException; import com.merakianalytics.orianna.types.common.Platform; import com.merakianalytics.orianna.types.common.Queue; import com.merakianalytics.orianna.types.common.Region; import com.merakianalytics.orianna.types.core.champion.ChampionRotation; import com.merakianalytics.orianna.types.core.champion.ChampionRotations; import com.merakianalytics.orianna.types.core.championmastery.ChampionMasteries; import com.merakianalytics.orianna.types.core.championmastery.ChampionMastery; import com.merakianalytics.orianna.types.core.championmastery.ChampionMasteryScore; import com.merakianalytics.orianna.types.core.championmastery.ChampionMasteryScores; import com.merakianalytics.orianna.types.core.league.League; import com.merakianalytics.orianna.types.core.league.LeaguePositions; import com.merakianalytics.orianna.types.core.league.Leagues; import com.merakianalytics.orianna.types.core.match.Match; import com.merakianalytics.orianna.types.core.match.MatchHistories; import com.merakianalytics.orianna.types.core.match.MatchHistory; import com.merakianalytics.orianna.types.core.match.Matches; import com.merakianalytics.orianna.types.core.match.Timeline; import com.merakianalytics.orianna.types.core.match.Timelines; import com.merakianalytics.orianna.types.core.match.TournamentMatches; import com.merakianalytics.orianna.types.core.spectator.CurrentMatch; import com.merakianalytics.orianna.types.core.spectator.CurrentMatches; import com.merakianalytics.orianna.types.core.spectator.FeaturedMatches; import com.merakianalytics.orianna.types.core.staticdata.Champion; import com.merakianalytics.orianna.types.core.staticdata.Champions; import com.merakianalytics.orianna.types.core.staticdata.Item; import com.merakianalytics.orianna.types.core.staticdata.Items; import com.merakianalytics.orianna.types.core.staticdata.LanguageStrings; import com.merakianalytics.orianna.types.core.staticdata.Languages; import com.merakianalytics.orianna.types.core.staticdata.Map; import com.merakianalytics.orianna.types.core.staticdata.Maps; import com.merakianalytics.orianna.types.core.staticdata.Masteries; import com.merakianalytics.orianna.types.core.staticdata.Mastery; import com.merakianalytics.orianna.types.core.staticdata.Patch; import com.merakianalytics.orianna.types.core.staticdata.Patches; import com.merakianalytics.orianna.types.core.staticdata.ProfileIcon; import com.merakianalytics.orianna.types.core.staticdata.ProfileIcons; import com.merakianalytics.orianna.types.core.staticdata.Realm; import com.merakianalytics.orianna.types.core.staticdata.Realms; import com.merakianalytics.orianna.types.core.staticdata.ReforgedRune; import com.merakianalytics.orianna.types.core.staticdata.ReforgedRunes; import com.merakianalytics.orianna.types.core.staticdata.Rune; import com.merakianalytics.orianna.types.core.staticdata.Runes; import com.merakianalytics.orianna.types.core.staticdata.SummonerSpell; import com.merakianalytics.orianna.types.core.staticdata.SummonerSpells; import com.merakianalytics.orianna.types.core.staticdata.Versions; import com.merakianalytics.orianna.types.core.status.ShardStatus; import com.merakianalytics.orianna.types.core.status.ShardStatuses; import com.merakianalytics.orianna.types.core.summoner.Summoner; import com.merakianalytics.orianna.types.core.summoner.Summoners; import com.merakianalytics.orianna.types.core.thirdpartycode.VerificationString; import com.merakianalytics.orianna.types.core.thirdpartycode.VerificationStrings; public abstract class Orianna { public static class Configuration { private static final ExpirationPeriod DEFAULT_CURRENT_VERSION_EXPIRATION = ExpirationPeriod.create(6L, TimeUnit.HOURS); private static final String DEFAULT_DEFAULT_LOCALE = null; private static final Platform DEFAULT_DEFAULT_PLATFORM = null; private static PipelineConfiguration getDefaultPipeline() { final PipelineConfiguration config = new PipelineConfiguration(); final Set<TransformerConfiguration> transformers = ImmutableSet.of( TransformerConfiguration.defaultConfiguration(AccountTransformer.class), TransformerConfiguration.defaultConfiguration(ChampionMasteryTransformer.class), TransformerConfiguration.defaultConfiguration(ChampionTransformer.class), TransformerConfiguration.defaultConfiguration(LeagueTransformer.class), TransformerConfiguration.defaultConfiguration(MatchTransformer.class), TransformerConfiguration.defaultConfiguration(SpectatorTransformer.class), TransformerConfiguration.defaultConfiguration(StaticDataTransformer.class), TransformerConfiguration.defaultConfiguration(StatusTransformer.class), TransformerConfiguration.defaultConfiguration(SummonerTransformer.class), TransformerConfiguration.defaultConfiguration(ThirdPartyCodeTransformer.class)); config.setTransformers(transformers); final List<PipelineElementConfiguration> elements = ImmutableList.of( PipelineElementConfiguration.defaultConfiguration(InMemoryCache.class), PipelineElementConfiguration.defaultConfiguration(GhostLoader.class), PipelineElementConfiguration.defaultConfiguration(MerakiAnalyticsCDN.class), PipelineElementConfiguration.defaultConfiguration(DataDragon.class), PipelineElementConfiguration.defaultConfiguration(RiotAPI.class), PipelineElementConfiguration.defaultConfiguration(ImageDownloader.class)); config.setElements(elements); return config; } private ExpirationPeriod currentVersionExpiration = DEFAULT_CURRENT_VERSION_EXPIRATION; private String defaultLocale = DEFAULT_DEFAULT_LOCALE; private Platform defaultPlatform = DEFAULT_DEFAULT_PLATFORM; private PipelineConfiguration pipeline = getDefaultPipeline(); /** * @return the currentVersionExpiration */ public ExpirationPeriod getCurrentVersionExpiration() { return currentVersionExpiration; } /** * @return the defaultLocale */ public String getDefaultLocale() { return defaultLocale; } /** * @return the defaultPlatform */ public Platform getDefaultPlatform() { return defaultPlatform; } /** * @return the pipeline */ public PipelineConfiguration getPipeline() { return pipeline; } /** * @param currentVersionExpiration * the currentVersionExpiration to set */ public void setCurrentVersionExpiration(final ExpirationPeriod currentVersionExpiration) { this.currentVersionExpiration = currentVersionExpiration; } /** * @param defaultLocale * the defaultLocale to set */ public void setDefaultLocale(final String defaultLocale) { this.defaultLocale = defaultLocale; } /** * @param defaultPlatform * the defaultPlatform to set */ public void setDefaultPlatform(final Platform defaultPlatform) { this.defaultPlatform = defaultPlatform; } /** * @param pipeline * the pipeline to set */ public void setPipeline(final PipelineConfiguration pipeline) { this.pipeline = pipeline; } } public static class Settings { private final Configuration configuration; private final java.util.Map<Platform, Supplier<String>> currentVersion; private final Object currentVersionLock = new Object(); private Supplier<DataPipeline> pipeline; private Settings(final Configuration config) { pipeline = newPipelineSupplier(); configuration = config; currentVersion = new ConcurrentHashMap<>(); } /** * @param platform * the platform to get the current version for * @return the currentVersion the that platform */ public String getCurrentVersion(final Platform platform) { Supplier<String> version = currentVersion.get(platform); if(version == null) { synchronized(currentVersionLock) { version = currentVersion.get(platform); if(version == null) { version = newVersionSupplier(platform); currentVersion.put(platform, version); } } } return version.get(); } /** * @return the defaultLocale */ public String getDefaultLocale() { return configuration.getDefaultLocale(); } /** * @return the defaultPlatform */ public Platform getDefaultPlatform() { return configuration.getDefaultPlatform(); } /** * @return the pipeline */ public DataPipeline getPipeline() { return pipeline.get(); } private Supplier<DataPipeline> newPipelineSupplier() { return Suppliers.memoize(new Supplier<DataPipeline>() { @Override public DataPipeline get() { return PipelineConfiguration.toPipeline(configuration.getPipeline()); } }); } private Supplier<String> newVersionSupplier(final Platform platform) { Supplier<String> supplier = new Supplier<String>() { @Override public String get() { return Versions.withPlatform(platform).get().getBestMatch(platform.getRealm().getVersion()); } }; if(configuration.getCurrentVersionExpiration().getPeriod() < 0) { supplier = Suppliers.memoize(supplier); } else if(configuration.getCurrentVersionExpiration().getPeriod() > 0) { supplier = Suppliers.memoizeWithExpiration(supplier, configuration.getCurrentVersionExpiration().getPeriod(), configuration.getCurrentVersionExpiration().getUnit()); } return supplier; } private void setDefaultLocale(final String defaultLocale) { configuration.setDefaultLocale(defaultLocale); } private void setDefaultPlatform(final Platform defaultPlatform) { configuration.setDefaultPlatform(defaultPlatform); } private void setRiotAPIKey(final String key) { boolean changed = false; for(final PipelineElementConfiguration element : configuration.getPipeline().getElements()) { if(RiotAPI.class.getCanonicalName().equals(element.getClassName())) { ((ObjectNode)element.getConfig()).set("apiKey", new TextNode(key)); changed = true; break; } } if(changed) { pipeline = newPipelineSupplier(); } } } private static final String CONFIGURATION_PATH_ENVIRONMENT_VARIABLE = "ORIANNA_CONFIGURATION_PATH"; private static final Logger LOGGER = LoggerFactory.getLogger(Orianna.class); private static Settings settings = defaultSettings(); public static League.SelectBuilder.SubBuilder challengerLeagueInQueue(final Queue queue) { return League.challengerInQueue(queue); } public static Leagues.SelectBuilder.SubBuilder challengerLeaguesInQueues(final Iterable<Queue> queues) { return Leagues.challengerInQueues(queues); } public static Leagues.SelectBuilder.SubBuilder challengerLeaguesInQueues(final Queue... queues) { return Leagues.challengerInQueues(queues); } public static ChampionMasteries.Builder championMasteriesForSummoner(final Summoner summoner) { return ChampionMasteries.forSummoner(summoner); } public static ChampionMasteries.ManyBuilder championMasteriesForSummoners(final Iterable<Summoner> summoners) { return ChampionMasteries.forSummoners(summoners); } public static ChampionMasteries.ManyBuilder championMasteriesForSummoners(final Summoner... summoners) { return ChampionMasteries.forSummoners(summoners); } public static ChampionMastery.Builder championMasteryForSummoner(final Summoner summoner) { return ChampionMastery.forSummoner(summoner); } public static ChampionMasteryScore.Builder championMasteryScoreForSummoner(final Summoner summoner) { return ChampionMasteryScore.forSummoner(summoner); } public static ChampionMasteryScores.Builder championMasteryScoresForSummoners(final Iterable<Summoner> summoners) { return ChampionMasteryScores.forSummoners(summoners); } public static ChampionMasteryScores.Builder championMasteryScoresForSummoners(final Summoner... summoners) { return ChampionMasteryScores.forSummoners(summoners); } public static Champion.Builder championNamed(final String name) { return Champion.named(name); } public static ChampionRotations.Builder championRotationsWithPlatforms(final Iterable<Platform> platforms) { return ChampionRotations.withPlatforms(platforms); } public static ChampionRotations.Builder championRotationsWithPlatforms(final Platform... platforms) { return ChampionRotations.withPlatforms(platforms); } public static ChampionRotations.Builder championRotationsWithRegions(final Iterable<Region> regions) { return ChampionRotations.withRegions(regions); } public static ChampionRotations.Builder championRotationsWithRegions(final Region... regions) { return ChampionRotations.withRegions(regions); } public static ChampionRotation.Builder championRotationWithPlatform(final Platform platform) { return ChampionRotation.withPlatform(platform); } public static ChampionRotation.Builder championRotationWithRegion(final Region region) { return ChampionRotation.withRegion(region); } public static Champions.SubsetBuilder championsNamed(final Iterable<String> names) { return Champions.named(names); } public static Champions.SubsetBuilder championsNamed(final String... names) { return Champions.named(names); } public static Champions.SubsetBuilder championsWithIds(final int... ids) { return Champions.withIds(ids); } public static Champions.SubsetBuilder championsWithIds(final Iterable<Integer> ids) { return Champions.withIds(ids); } public static Champions.Builder championsWithIncludedData(final Iterable<String> includedData) { return Champions.withIncludedData(includedData); } public static Champions.Builder championsWithIncludedData(final String... includedData) { return Champions.withIncludedData(includedData); } public static Champions.SubsetBuilder championsWithKeys(final Iterable<String> keys) { return Champions.withKeys(keys); } public static Champions.SubsetBuilder championsWithKeys(final String... keys) { return Champions.withKeys(keys); } public static Champions.Builder championsWithLocale(final String locale) { return Champions.withLocale(locale); } public static Champions.Builder championsWithPlatform(final Platform platform) { return Champions.withPlatform(platform); } public static Champions.Builder championsWithRegion(final Region region) { return Champions.withRegion(region); } public static Champions.Builder championsWithVersion(final String version) { return Champions.withVersion(version); } public static Champion.Builder championWithId(final int id) { return Champion.withId(id); } public static Champion.Builder championWithKey(final String key) { return Champion.withKey(key); } public static CurrentMatches.Builder currentMatchesForSummoners(final Iterable<Summoner> summoners) { return CurrentMatches.forSummoners(summoners); } public static CurrentMatches.Builder currentMatchesForSummoners(final Summoner... summoners) { return CurrentMatches.forSummoners(summoners); } public static CurrentMatch.Builder currentMatchForSummoner(final Summoner summoner) { return CurrentMatch.forSummoner(summoner); } private static Settings defaultSettings() { final String configPath = System.getenv(CONFIGURATION_PATH_ENVIRONMENT_VARIABLE); if(configPath != null && !configPath.isEmpty()) { try { return new Settings(getConfiguration(Files.asCharSource(new File(configPath), Charset.forName("UTF-8")))); } catch(final OriannaException e) { LOGGER.error("Failed to load environment-configured configuration from " + configPath + "! Using default configuration from resources instead.", e); } } try { return new Settings(getConfiguration( Resources.asCharSource(Resources.getResource("com/merakianalytics/orianna/default-orianna-config.json"), Charset.forName("UTF-8")))); } catch(final IllegalArgumentException | OriannaException e) { LOGGER.error("Failed to load default configuration from resources! Using default constuctor instead."); return new Settings(new Configuration()); } } public static FeaturedMatches.Builder featuredMatchesWithPlatform(final Platform platform) { return FeaturedMatches.withPlatform(platform); } public static FeaturedMatches.ManyBuilder featuredMatchesWithPlatforms(final Iterable<Platform> platforms) { return FeaturedMatches.withPlatforms(platforms); } public static FeaturedMatches.ManyBuilder featuredMatchesWithPlatforms(final Platform... platforms) { return FeaturedMatches.withPlatforms(platforms); } public static FeaturedMatches.Builder featuredMatchesWithRegion(final Region region) { return FeaturedMatches.withRegion(region); } public static FeaturedMatches.ManyBuilder featuredMatchesWithRegions(final Iterable<Region> regions) { return FeaturedMatches.withRegions(regions); } public static FeaturedMatches.ManyBuilder featuredMatchesWithRegions(final Region... regions) { return FeaturedMatches.withRegions(regions); } public static Champions getChampions() { return Champions.get(); } private static Configuration getConfiguration(final CharSource configJSON) { final ObjectMapper mapper = new ObjectMapper().enable(Feature.ALLOW_COMMENTS); try { return mapper.readValue(configJSON.read(), Configuration.class); } catch(final IOException e) { LOGGER.error("Failed to load configuration JSON!", e); throw new OriannaException("Failed to load configuration JSON!", e); } } public static FeaturedMatches getFeaturedMatches() { return FeaturedMatches.get(); } public static Items getItems() { return Items.get(); } public static Languages getLanguages() { return Languages.get(); } public static LanguageStrings getLanguageStrings() { return LanguageStrings.get(); } public static Maps getMaps() { return Maps.get(); } public static Masteries getMasteries() { return Masteries.get(); } public static Patch getPatch() { return Patch.get(); } public static Patches getPatches() { return Patches.get(); } public static Patches.SubsetBuilder getPatchesNamed(final Iterable<String> names) { return Patches.named(names); } public static Patches.SubsetBuilder getPatchesNamed(final String... names) { return Patches.named(names); } public static Patches.Builder getPatchesWithPlatform(final Platform platform) { return Patches.withPlatform(platform); } public static Patches.Builder getPatchesWithRegion(final Region region) { return Patches.withRegion(region); } public static Patch.Builder getPatchNamed(final String name) { return Patch.named(name); } public static Patch.Builder getPatchWithPlatform(final Platform platform) { return Patch.withPlatform(platform); } public static Patch.Builder getPatchWithRegion(final Region region) { return Patch.withRegion(region); } public static ProfileIcons getProfileIcons() { return ProfileIcons.get(); } public static ReforgedRunes getReforgedRunes() { return ReforgedRunes.get(); } public static Runes getRunes() { return Runes.get(); } public static Settings getSettings() { return settings; } public static ShardStatus getShardStatus() { return ShardStatus.get(); } public static SummonerSpells getSummonerSpells() { return SummonerSpells.get(); } public static Versions getVersions() { return Versions.get(); } public static League.SelectBuilder.SubBuilder grandmasterLeagueInQueue(final Queue queue) { return League.grandmasterInQueue(queue); } public static Leagues.SelectBuilder.SubBuilder grandmasterLeaguesInQueues(final Iterable<Queue> queues) { return Leagues.grandmasterInQueues(queues); } public static Leagues.SelectBuilder.SubBuilder grandmasterLeaguesInQueues(final Queue... queues) { return Leagues.grandmasterInQueues(queues); } public static Item.Builder itemNamed(final String name) { return Item.named(name); } public static Items.SubsetBuilder itemsNamed(final Iterable<String> names) { return Items.named(names); } public static Items.SubsetBuilder itemsNamed(final String... names) { return Items.named(names); } public static Items.SubsetBuilder itemsWithIds(final int... ids) { return Items.withIds(ids); } public static Items.SubsetBuilder itemsWithIds(final Iterable<Integer> ids) { return Items.withIds(ids); } public static Items.Builder itemsWithIncludedData(final Iterable<String> includedData) { return Items.withIncludedData(includedData); } public static Items.Builder itemsWithIncludedData(final String... includedData) { return Items.withIncludedData(includedData); } public static Items.Builder itemsWithLocale(final String locale) { return Items.withLocale(locale); } public static Items.Builder itemsWithPlatform(final Platform platform) { return Items.withPlatform(platform); } public static Items.Builder itemsWithRegion(final Region region) { return Items.withRegion(region); } public static Items.Builder itemsWithVersion(final String version) { return Items.withVersion(version); } public static Item.Builder itemWithId(final int id) { return Item.withId(id); } public static LanguageStrings.Builder languageStringsWithLocale(final String locale) { return LanguageStrings.withLocale(locale); } public static LanguageStrings.Builder languageStringsWithPlatform(final Platform platform) { return LanguageStrings.withPlatform(platform); } public static LanguageStrings.Builder languageStringsWithRegion(final Region region) { return LanguageStrings.withRegion(region); } public static LanguageStrings.Builder languageStringsWithVersion(final String version) { return LanguageStrings.withVersion(version); } public static Languages.Builder languagesWithPlatform(final Platform platform) { return Languages.withPlatform(platform); } public static Languages.Builder languagesWithRegion(final Region region) { return Languages.withRegion(region); } public static LeaguePositions.Builder leaguePositionsForSummoner(final Summoner summoner) { return LeaguePositions.forSummoner(summoner); } public static LeaguePositions.ManyBuilder leaguePositionsForSummoners(final Iterable<Summoner> summoners) { return LeaguePositions.forSummoners(summoners); } public static LeaguePositions.ManyBuilder leaguePositionsForSummoners(final Summoner... summoners) { return LeaguePositions.forSummoners(summoners); } public static Leagues.Builder leaguesWithIds(final Iterable<String> ids) { return Leagues.withIds(ids); } public static Leagues.Builder leaguesWithIds(final String... ids) { return Leagues.withIds(ids); } public static League.Builder leagueWithId(final String id) { return League.withId(id); } public static void loadConfiguration(final CharSource configJSON) { loadConfiguration(getConfiguration(configJSON)); } public static void loadConfiguration(final Configuration config) { settings = new Settings(config); } public static void loadConfiguration(final File configJSON) { loadConfiguration(Files.asCharSource(configJSON, Charset.forName("UTF-8"))); } public static void loadConfiguration(final String configJSONResourcePath) { loadConfiguration(Resources.asCharSource(Resources.getResource(configJSONResourcePath), Charset.forName("UTF-8"))); } public static Map.Builder mapNamed(final String name) { return Map.named(name); } public static Maps.Builder mapsWithLocale(final String locale) { return Maps.withLocale(locale); } public static Maps.Builder mapsWithPlatform(final Platform platform) { return Maps.withPlatform(platform); } public static Maps.Builder mapsWithRegion(final Region region) { return Maps.withRegion(region); } public static Maps.Builder mapsWithVersion(final String version) { return Maps.withVersion(version); } public static Map.Builder mapWithId(final int id) { return Map.withId(id); } public static Masteries.SubsetBuilder masteriesNamed(final Iterable<String> names) { return Masteries.named(names); } public static Masteries.SubsetBuilder masteriesNamed(final String... names) { return Masteries.named(names); } public static Masteries.SubsetBuilder masteriesWithIds(final int... ids) { return Masteries.withIds(ids); } public static Masteries.SubsetBuilder masteriesWithIds(final Iterable<Integer> ids) { return Masteries.withIds(ids); } public static Masteries.Builder masteriesWithIncludedData(final Iterable<String> includedData) { return Masteries.withIncludedData(includedData); } public static Masteries.Builder masteriesWithIncludedData(final String... includedData) { return Masteries.withIncludedData(includedData); } public static Masteries.Builder masteriesWithLocale(final String locale) { return Masteries.withLocale(locale); } public static Masteries.Builder masteriesWithPlatform(final Platform platform) { return Masteries.withPlatform(platform); } public static Masteries.Builder masteriesWithRegion(final Region region) { return Masteries.withRegion(region); } public static Masteries.Builder masteriesWithVersion(final String version) { return Masteries.withVersion(version); } public static League.SelectBuilder.SubBuilder masterLeagueInQueue(final Queue queue) { return League.masterInQueue(queue); } public static Leagues.SelectBuilder.SubBuilder masterLeaguesInQueues(final Iterable<Queue> queues) { return Leagues.masterInQueues(queues); } public static Leagues.SelectBuilder.SubBuilder masterLeaguesInQueues(final Queue... queues) { return Leagues.masterInQueues(queues); } public static Mastery.Builder masteryNamed(final String name) { return Mastery.named(name); } public static Mastery.Builder masteryWithId(final int id) { return Mastery.withId(id); } public static Matches.Builder matchesWithIds(final Iterable<Long> ids) { return Matches.withIds(ids); } public static Matches.Builder matchesWithIds(final long... ids) { return Matches.withIds(ids); } public static MatchHistories.Builder matchHistoriesForSummoners(final Iterable<Summoner> summoners) { return MatchHistories.forSummoners(summoners); } public static MatchHistories.Builder matchHistoriesForSummoners(final Summoner... summoners) { return MatchHistories.forSummoners(summoners); } public static MatchHistory.Builder matchHistoryForSummoner(final Summoner summoner) { return MatchHistory.forSummoner(summoner); } public static Match.Builder matchWithId(final long id) { return Match.withId(id); } public static ProfileIcons.Builder profileIconsWithLocale(final String locale) { return ProfileIcons.withLocale(locale); } public static ProfileIcons.Builder profileIconsWithPlatform(final Platform platform) { return ProfileIcons.withPlatform(platform); } public static ProfileIcons.Builder profileIconsWithRegion(final Region region) { return ProfileIcons.withRegion(region); } public static ProfileIcons.Builder profileIconsWithVersion(final String version) { return ProfileIcons.withVersion(version); } public static ProfileIcon.Builder profileIconWithId(final int id) { return ProfileIcon.withId(id); } public static Realms.Builder realmsWithPlatforms(final Iterable<Platform> platforms) { return Realms.withPlatforms(platforms); } public static Realms.Builder realmsWithPlatforms(final Platform... platforms) { return Realms.withPlatforms(platforms); } public static Realms.Builder realmsWithRegions(final Iterable<Region> regions) { return Realms.withRegions(regions); } public static Realms.Builder realmsWithRegions(final Region... regions) { return Realms.withRegions(regions); } public static Realm.Builder realmWithPlatform(final Platform platform) { return Realm.withPlatform(platform); } public static Realm.Builder realmWithRegion(final Region region) { return Realm.withRegion(region); } public static ReforgedRune.Builder reforgedRuneNamed(final String name) { return ReforgedRune.named(name); } public static ReforgedRunes.SubsetBuilder reforgedRunesNamed(final Iterable<String> names) { return ReforgedRunes.named(names); } public static ReforgedRunes.SubsetBuilder reforgedRunesNamed(final String... names) { return ReforgedRunes.named(names); } public static ReforgedRunes.SubsetBuilder reforgedRunesWithIds(final int... ids) { return ReforgedRunes.withIds(ids); } public static ReforgedRunes.SubsetBuilder reforgedRunesWithIds(final Iterable<Integer> ids) { return ReforgedRunes.withIds(ids); } public static ReforgedRunes.SubsetBuilder reforgedRunesWithKeys(final Iterable<String> keys) { return ReforgedRunes.withKeys(keys); } public static ReforgedRunes.SubsetBuilder reforgedRunesWithKeys(final String... keys) { return ReforgedRunes.withKeys(keys); } public static ReforgedRunes.Builder reforgedRunesWithLocale(final String locale) { return ReforgedRunes.withLocale(locale); } public static ReforgedRunes.Builder reforgedRunesWithPlatform(final Platform platform) { return ReforgedRunes.withPlatform(platform); } public static ReforgedRunes.Builder reforgedRunesWithRegion(final Region region) { return ReforgedRunes.withRegion(region); } public static ReforgedRunes.Builder reforgedRunesWithVersion(final String version) { return ReforgedRunes.withVersion(version); } public static ReforgedRune.Builder reforgedRuneWithId(final int id) { return ReforgedRune.withId(id); } public static ReforgedRune.Builder reforgedRuneWithKey(final String key) { return ReforgedRune.withKey(key); } public static Rune.Builder runeNamed(final String name) { return Rune.named(name); } public static Runes.SubsetBuilder runesNamed(final Iterable<String> names) { return Runes.named(names); } public static Runes.SubsetBuilder runesNamed(final String... names) { return Runes.named(names); } public static Runes.SubsetBuilder runesWithIds(final int... ids) { return Runes.withIds(ids); } public static Runes.SubsetBuilder runesWithIds(final Iterable<Integer> ids) { return Runes.withIds(ids); } public static Runes.Builder runesWithIncludedData(final Iterable<String> includedData) { return Runes.withIncludedData(includedData); } public static Runes.Builder runesWithIncludedData(final String... includedData) { return Runes.withIncludedData(includedData); } public static Runes.Builder runesWithLocale(final String locale) { return Runes.withLocale(locale); } public static Runes.Builder runesWithPlatform(final Platform platform) { return Runes.withPlatform(platform); } public static Runes.Builder runesWithRegion(final Region region) { return Runes.withRegion(region); } public static Runes.Builder runesWithVersion(final String version) { return Runes.withVersion(version); } public static Rune.Builder runeWithId(final int id) { return Rune.withId(id); } /** * Sets the default locale. The default locale will be used for locale-aware information from the Static Data API like champion names and descriptions. * The default locale starts null, and if it is set to null the default locale for the region/platform the data is from will be used. * * @param defaultLocale * the default locale */ public static void setDefaultLocale(final String defaultLocale) { settings.setDefaultLocale(defaultLocale); } /** * Sets the default platform. If this is not set or is set to null, platforms must be provided for all API queries. * * @param defaultPlatform * the defaultPlatform */ public static void setDefaultPlatform(final Platform defaultPlatform) { settings.setDefaultPlatform(defaultPlatform); } /** * Sets the default region. If this is not set or is set to null, regions must be provided for all API queries. * * @param defaultRegion * the defaultRegion */ public static void setDefaultRegion(final Region defaultRegion) { settings.setDefaultPlatform(defaultRegion.getPlatform()); } /** * Sets the Riot API key if {@link com.merakianalytics.orianna.datapipeline.riotapi.RiotAPI} is being used in the pipeline. * Also forces a full reset of the pipeline. * * @param key * the Riot API key to use */ public static void setRiotAPIKey(final String key) { settings.setRiotAPIKey(key); } public static ShardStatuses.Builder shardStatusesWithPlatforms(final Iterable<Platform> platforms) { return ShardStatuses.withPlatforms(platforms); } public static ShardStatuses.Builder shardStatusesWithPlatforms(final Platform... platforms) { return ShardStatuses.withPlatforms(platforms); } public static ShardStatuses.Builder shardStatusesWithRegions(final Iterable<Region> regions) { return ShardStatuses.withRegions(regions); } public static ShardStatuses.Builder shardStatusesWithRegions(final Region... regions) { return ShardStatuses.withRegions(regions); } public static ShardStatus.Builder shardStatusWithPlatform(final Platform platform) { return ShardStatus.withPlatform(platform); } public static ShardStatus.Builder shardStatusWithRegion(final Region region) { return ShardStatus.withRegion(region); } public static Account.Builder accountWithPuuid(final String puuid) { return Account.withPuuid(puuid); } public static Account.Builder accountWithRiotId(final String gameName, final String tagLine) { return Account.withRiotId(gameName, tagLine); } public static Accounts.Builder accountsWithPuuids(final String... puuids) { return Accounts.withPuuids(puuids); } public static Accounts.Builder accountsWithRiotIds(final List<java.util.Map.Entry<String, String>> riotIds) { return Accounts.withRiotIds(riotIds); } public static Summoner.Builder summonerNamed(final String name) { return Summoner.named(name); } public static Summoners.Builder summonersNamed(final Iterable<String> names) { return Summoners.named(names); } public static Summoners.Builder summonersNamed(final String... names) { return Summoners.named(names); } public static SummonerSpell.Builder summonerSpellNamed(final String name) { return SummonerSpell.named(name); } public static SummonerSpells.SubsetBuilder summonerSpellsNamed(final Iterable<String> names) { return SummonerSpells.named(names); } public static SummonerSpells.SubsetBuilder summonerSpellsNamed(final String... names) { return SummonerSpells.named(names); } public static SummonerSpells.SubsetBuilder summonerSpellsWithIds(final int... ids) { return SummonerSpells.withIds(ids); } public static SummonerSpells.SubsetBuilder summonerSpellsWithIds(final Iterable<Integer> ids) { return SummonerSpells.withIds(ids); } public static SummonerSpells.Builder summonerSpellsWithIncludedData(final Iterable<String> includedData) { return SummonerSpells.withIncludedData(includedData); } public static SummonerSpells.Builder summonerSpellsWithIncludedData(final String... includedData) { return SummonerSpells.withIncludedData(includedData); } public static SummonerSpells.Builder summonerSpellsWithLocale(final String locale) { return SummonerSpells.withLocale(locale); } public static SummonerSpells.Builder summonerSpellsWithPlatform(final Platform platform) { return SummonerSpells.withPlatform(platform); } public static SummonerSpells.Builder summonerSpellsWithRegion(final Region region) { return SummonerSpells.withRegion(region); } public static SummonerSpells.Builder summonerSpellsWithVersion(final String version) { return SummonerSpells.withVersion(version); } public static SummonerSpell.Builder summonerSpellWithId(final int id) { return SummonerSpell.withId(id); } public static Summoners.Builder summonersWithAccountIds(final Iterable<String> accountIds) { return Summoners.withAccountIds(accountIds); } public static Summoners.Builder summonersWithAccountIds(final String... accountIds) { return Summoners.withAccountIds(accountIds); } public static Summoners.Builder summonersWithIds(final Iterable<String> ids) { return Summoners.withIds(ids); } public static Summoners.Builder summonersWithIds(final String... ids) { return Summoners.withIds(ids); } public static Summoners.Builder summonersWithPuuids(final Iterable<String> puuids) { return Summoners.withPuuids(puuids); } public static Summoners.Builder summonersWithPuuids(final String... puuids) { return Summoners.withPuuids(puuids); } public static Summoner.Builder summonerWithAccountId(final String accountId) { return Summoner.withAccountId(accountId); } public static Summoner.Builder summonerWithId(final String id) { return Summoner.withId(id); } public static Summoner.Builder summonerWithPuuid(final String puuid) { return Summoner.withPuuid(puuid); } public static Timelines.Builder timelinesWithIds(final Iterable<Long> ids) { return Timelines.withIds(ids); } public static Timelines.Builder timelinesWithIds(final long... ids) { return Timelines.withIds(ids); } public static Timeline.Builder timelineWithId(final long id) { return Timeline.withId(id); } public static TournamentMatches.Builder tournamentMatchesForTournamentCode(final String tournamentCode) { return TournamentMatches.forTournamentCode(tournamentCode); } public static TournamentMatches.ManyBuilder tournamentMatchesForTournamentCodes(final Iterable<String> tournamentCodes) { return TournamentMatches.forTournamentCodes(tournamentCodes); } public static TournamentMatches.ManyBuilder tournamentMatchesForTournamentCodes(final String... tournamentCodes) { return TournamentMatches.forTournamentCodes(tournamentCodes); } public static VerificationString.Builder verificationStringForSummoner(final Summoner summoner) { return VerificationString.forSummoner(summoner); } public static VerificationStrings.Builder verificationStringsForSummoners(final Iterable<Summoner> summoners) { return VerificationStrings.forSummoners(summoners); } public static VerificationStrings.Builder verificationStringsForSummoners(final Summoner... summoners) { return VerificationStrings.forSummoners(summoners); } public static Versions.Builder versionsWithPlatform(final Platform platform) { return Versions.withPlatform(platform); } public static Versions.ManyBuilder versionsWithPlatforms(final Iterable<Platform> platforms) { return Versions.withPlatforms(platforms); } public static Versions.ManyBuilder versionsWithPlatforms(final Platform... platforms) { return Versions.withPlatforms(platforms); } public static Versions.Builder versionsWithRegion(final Region region) { return Versions.withRegion(region); } public static Versions.ManyBuilder versionsWithRegions(final Iterable<Region> regions) { return Versions.withRegions(regions); } public static Versions.ManyBuilder versionsWithRegions(final Region... regions) { return Versions.withRegions(regions); } }
meraki-analytics/orianna
orianna/src/main/java/com/merakianalytics/orianna/Orianna.java
46,000
package com.pancm.design.mediator; /** * @Title: MediatorTest * @Description: 中介者模式 中介者模式(Mediator Pattern)是用来降低多个对象和类之间的通信复杂性。 * 这种模式提供了一个中介类,该类通常处理不同类之间的通信,并支持松耦合,使代码易于维护。中介者模式属于行为型模式。 * 用一个中介对象来封装一系列的对象交互,中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。 * @Version:1.0.0 * @author pancm * @date 2018年8月8日 */ public class MediatorTest { public static void main(String[] args) { /* * 基本角色 抽象中介者(Mediator): 。定义了同事对象到中介者对象之间的接口。 具体中介者(ConcreteMediator): 实现抽象中介者的方法,它需要知道所有的具体同事类,同时需要从具体的同事类那里接收信息,并且向具体的同事类发送信息。 抽象同事类(Colleague): 定义了中介者对象的接口,它只知道中介者而不知道其他的同事对象。 具体同事类(ConcreteColleague) : 每个具体同事类都只需要知道自己的行为即可,但是他们都需要认识中介者。 * */ JavaQQqun jq = new JavaQQqun(); ZhangSan zs = new ZhangSan("张三", jq); XuWuJing xwj = new XuWuJing("xuwujing", jq); jq.setZs(zs); jq.setXwj(xwj); zs.exchange("大家好!我是张三!"); xwj.exchange("欢迎你!张三!"); /* * 优点: 1、降低了类的复杂度,将一对多转化成了一对一。 2、各个类之间的解耦。 3、符合迪米特原则。 缺点:中介者会庞大,变得复杂难以维护。 */ } } //定义一个中介者 QQ群 interface QQqun { //提供一个交流的方法 void exchange(Person person,String message); } //定义一个抽象同事类 abstract class Person{ protected String name; protected QQqun qun; Person(String name,QQqun qun){ this.name = name; this.qun = qun; } } class ZhangSan extends Person{ ZhangSan(String name, QQqun qun) { super(name, qun); } void exchange(String message){ qun.exchange(this,message); } void talk(String message){ System.out.println(name +"说:" + message); } } class XuWuJing extends Person{ XuWuJing(String name, QQqun qun) { super(name, qun); } void exchange(String message){ qun.exchange(this,message); } void talk(String message){ System.out.println(name +"回应:" + message); } } //定义一个JavaQQ群 class JavaQQqun implements QQqun{ private ZhangSan zs; private XuWuJing xwj; public ZhangSan getZs() { return zs; } public void setZs(ZhangSan zs) { this.zs = zs; } public XuWuJing getXwj() { return xwj; } public void setXwj(XuWuJing xwj) { this.xwj = xwj; } @Override public void exchange(Person person, String message) { if(zs.equals(person)){ zs.talk(message); }else if(xwj.equals(person)){ xwj.talk(message); } } }
xuwujing/java-study
src/main/java/com/pancm/design/mediator/MediatorTest.java
46,001
/* * Copyright (c) 2018. Aberic - All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.aberic.fabric.service.impl; import cn.aberic.fabric.dao.entity.CA; import cn.aberic.fabric.dao.entity.League; import cn.aberic.fabric.dao.entity.Org; import cn.aberic.fabric.dao.entity.Peer; import cn.aberic.fabric.dao.mapper.*; import cn.aberic.fabric.service.CAService; import cn.aberic.fabric.utils.CacheUtil; import cn.aberic.fabric.utils.DateUtil; import cn.aberic.fabric.utils.FabricHelper; import cn.aberic.fabric.utils.MD5Util; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import java.io.IOException; import java.util.List; /** * 作者:Aberic on 2018/7/12 21:11 * 邮箱:[email protected] */ @Slf4j @Service("caService") public class CAServiceImpl implements CAService { @Resource private LeagueMapper leagueMapper; @Resource private OrgMapper orgMapper; @Resource private PeerMapper peerMapper; @Resource private CAMapper caMapper; @Resource private ChannelMapper channelMapper; @Resource private ChaincodeMapper chaincodeMapper; @Override public int add(CA ca, MultipartFile skFile, MultipartFile certificateFile) { if (null == skFile || null == certificateFile) { log.debug("ca cert is null"); return 0; } if (null != caMapper.check(ca)) { log.debug("had the same ca in this peer"); return 0; } ca = resetCa(ca); try { ca.setSk(new String(IOUtils.toByteArray(skFile.getInputStream()))); ca.setCertificate(new String(IOUtils.toByteArray(certificateFile.getInputStream()), "UTF-8")); } catch (IOException e) { e.printStackTrace(); } ca.setDate(DateUtil.getCurrent("yyyy-MM-dd")); CacheUtil.removeHome(); return caMapper.add(ca); } @Override public int update(CA ca, MultipartFile skFile, MultipartFile certificateFile) { FabricHelper.obtain().removeChaincodeManager(channelMapper.list(ca.getPeerId()), chaincodeMapper); CacheUtil.removeHome(); CacheUtil.removeFlagCA(ca.getFlag()); ca = resetCa(ca); if (StringUtils.isEmpty(ca.getCertificate()) || StringUtils.isEmpty(ca.getSk())) { return caMapper.updateWithNoFile(ca); } try { ca.setSk(new String(IOUtils.toByteArray(skFile.getInputStream()))); ca.setCertificate(new String(IOUtils.toByteArray(certificateFile.getInputStream()), "UTF-8")); } catch (IOException e) { e.printStackTrace(); } return caMapper.update(ca); } @Override public List<CA> listAll() { return caMapper.listAll(); } @Override public List<CA> listById(int id) { return caMapper.list(id); } @Override public CA get(int id) { return caMapper.get(id); } @Override public CA getByFlag(String flag) { return caMapper.getByFlag(flag); } @Override public int countById(int id) { return caMapper.count(id); } @Override public int count() { return caMapper.countAll(); } @Override public int delete(int id) { FabricHelper.obtain().removeChaincodeManager(channelMapper.list(caMapper.get(id).getPeerId()), chaincodeMapper); return caMapper.delete(id); } @Override public List<Peer> getFullPeers() { List<Peer> peers = peerMapper.listAll(); for (Peer peer : peers) { Org org = orgMapper.get(peer.getOrgId()); peer.setOrgName(org.getMspId()); League league = leagueMapper.get(org.getLeagueId()); peer.setLeagueName(league.getName()); } return peers; } @Override public List<Peer> getPeersByCA(CA ca) { Org org = orgMapper.get(peerMapper.get(ca.getPeerId()).getOrgId()); List<Peer> peers = peerMapper.list(org.getId()); League league = leagueMapper.get(orgMapper.get(org.getId()).getLeagueId()); for (Peer peer : peers) { peer.setLeagueName(league.getName()); peer.setOrgName(org.getMspId()); } return peers; } @Override public List<CA> listFullCA() { List<CA> cas = caMapper.listAll(); for (CA ca: cas) { Peer peer = peerMapper.get(ca.getPeerId()); Org org = orgMapper.get(peer.getOrgId()); ca.setPeerName(peer.getName()); ca.setOrgName(org.getMspId()); ca.setLeagueName(leagueMapper.get(org.getLeagueId()).getName()); } return cas; } private CA resetCa(CA ca) { Peer peer = peerMapper.get(ca.getPeerId()); Org org = orgMapper.get(peer.getOrgId()); League league = leagueMapper.get(org.getLeagueId()); // ca.setName(String.format("%s-%s", ca.getName(), ca.getPeerId())); ca.setLeagueName(league.getName()); ca.setOrgName(org.getMspId()); ca.setPeerName(peer.getName()); ca.setFlag(MD5Util.md516(league.getName() + org.getMspId() + peer.getName() + ca.getName())); return ca; } }
lipengyu/fabric-net-server
fabric-edge/src/main/java/cn/aberic/fabric/service/impl/CAServiceImpl.java
46,002
package ezvcard.parameter; import java.util.Collection; import ezvcard.property.Related; /* Copyright (c) 2012-2023, Michael Angstadt All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ /** * Represents the TYPE parameter of the {@link Related} property. * <p> * <b>Supported versions:</b> {@code 4.0} * </p> * @author Michael Angstadt */ public class RelatedType extends VCardParameter { private static final VCardParameterCaseClasses<RelatedType> enums = new VCardParameterCaseClasses<>(RelatedType.class); public static final RelatedType ACQUAINTANCE = new RelatedType("acquaintance"); public static final RelatedType AGENT = new RelatedType("agent"); public static final RelatedType CHILD = new RelatedType("child"); public static final RelatedType CO_RESIDENT = new RelatedType("co-resident"); public static final RelatedType CO_WORKER = new RelatedType("co-worker"); public static final RelatedType COLLEAGUE = new RelatedType("colleague"); public static final RelatedType CONTACT = new RelatedType("contact"); public static final RelatedType CRUSH = new RelatedType("crush"); public static final RelatedType DATE = new RelatedType("date"); public static final RelatedType EMERGENCY = new RelatedType("emergency"); public static final RelatedType FRIEND = new RelatedType("friend"); public static final RelatedType KIN = new RelatedType("kin"); public static final RelatedType ME = new RelatedType("me"); public static final RelatedType MET = new RelatedType("met"); public static final RelatedType MUSE = new RelatedType("muse"); public static final RelatedType NEIGHBOR = new RelatedType("neighbor"); public static final RelatedType PARENT = new RelatedType("parent"); public static final RelatedType SIBLING = new RelatedType("sibling"); public static final RelatedType SPOUSE = new RelatedType("spouse"); public static final RelatedType SWEETHEART = new RelatedType("sweetheart"); private RelatedType(String value) { super(value); } /** * Searches for a parameter value that is defined as a static constant in * this class. * @param value the parameter value * @return the object or null if not found */ public static RelatedType find(String value) { return enums.find(value); } /** * Searches for a parameter value and creates one if it cannot be found. All * objects are guaranteed to be unique, so they can be compared with * {@code ==} equality. * @param value the parameter value * @return the object */ public static RelatedType get(String value) { return enums.get(value); } /** * Gets all of the parameter values that are defined as static constants in * this class. * @return the parameter values */ public static Collection<RelatedType> all() { return enums.all(); } }
mangstadt/ez-vcard
src/main/java/ezvcard/parameter/RelatedType.java
46,003
package core.db; import core.HO; import core.constants.TeamConfidence; import core.constants.TeamSpirit; import core.db.backup.BackupDialog; import core.db.user.User; import core.db.user.UserManager; import core.file.hrf.HRF; import core.gui.comp.table.HOTableModel; import core.gui.model.ArenaStatistikTableModel; import core.gui.model.PlayerMatchCBItem; import core.gui.theme.TeamLogoInfo; import core.model.*; import core.model.Tournament.TournamentDetails; import core.model.enums.DBDataSource; import core.model.enums.MatchType; import core.model.match.*; import core.model.misc.Basics; import core.model.misc.Economy; import core.model.misc.Verein; import core.model.player.Player; import core.model.player.Skillup; import core.util.HODateTime; import module.matches.MatchLocation; import module.nthrf.NtTeamDetails; import module.teamAnalyzer.vo.SquadInfo; import module.transfer.TransferType; import module.youth.YouthPlayer; import core.model.series.Liga; import core.model.series.Paarung; import core.training.FuturePlayerTraining; import core.training.TrainingPerWeek; import module.youth.YouthTrainerComment; import core.util.HOLogger; import core.util.ExceptionUtils; import module.ifa.IfaMatch; import module.lineup.substitution.model.Substitution; import module.series.Spielplan; import module.teamAnalyzer.vo.PlayerInfo; import module.transfer.PlayerTransfer; import module.transfer.scout.ScoutEintrag; import module.youth.YouthTraining; import org.jetbrains.annotations.Nullable; import tool.arenasizer.Stadium; import org.hsqldb.error.ErrorCode; import java.io.File; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.*; import java.util.stream.Collectors; /** * The type Db manager. */ public class DBManager { /** database versions */ private static final int DBVersion = 800; // HO 8.0 version /** * Previous db version is used by development versions to ensure that db upgrade will rerun on each * new installed preliminary version */ private static final int previousDBVersion = 701; private static final double DBConfigVersion = 8d; // HO 8.0 version /** 2004-06-14 11:00:00.0 */ public static Timestamp TSIDATE = new Timestamp(1087203600000L); /** singleton */ private static @Nullable DBManager m_clInstance; // ~ Instance fields // ---------------------------------------------------------------------------- /** DB-Adapter */ private @Nullable JDBCAdapter m_clJDBCAdapter; // new JDBCAdapter(); /** all Tables */ private final Hashtable<String, AbstractTable> tables = new Hashtable<>(); /** Erster Start */ private boolean m_bFirstStart; // ~ Constructors // ------------------------------------------------------------------------------- /** * Creates a new instance of DBZugriff */ private DBManager() { m_clJDBCAdapter = new JDBCAdapter(); } // ~ Methods // ------------------------------------------------------------------------------------ /** * Gets version. * * @return the version */ public static int getVersion() { if (HO.isDevelopment()) return previousDBVersion; return DBVersion; } /** * Instance db manager. * * @return the db manager */ // INSTANCE =============================================== public static synchronized DBManager instance() { if (m_clInstance == null) { String errorMsg = null; try { User current_user = UserManager.instance().getCurrentUser(); String dbFolder = current_user.getDbFolder(); File dbfolder = new File(dbFolder); if (!dbfolder.exists()) { File parentFolder = new File(UserManager.instance().getDbParentFolder()); boolean dbDirectoryCreated = false; if (!parentFolder.exists() || parentFolder.canWrite()) { dbDirectoryCreated = dbfolder.mkdirs(); } else { errorMsg = "Could not initialize the database folder."; errorMsg += "No writing rights to the following directory\n" + parentFolder.getAbsolutePath() + "\n"; errorMsg += "You can report this error by opening a new bug ticket on GitHub"; } if (!dbDirectoryCreated) { errorMsg = "Could not create the database folder: " + dbfolder.getAbsolutePath(); } } } catch (Exception e) { errorMsg = "Error encountered during database initialization: \n" + UserManager.instance().getCurrentUser().getDbURL(); e.printStackTrace(); } if (errorMsg != null) { javax.swing.JOptionPane.showMessageDialog(null, errorMsg, "Fatal DB Error", javax.swing.JOptionPane.ERROR_MESSAGE); System.exit(-1); } // Create new instance m_clInstance = new DBManager(); DBUpdater dbUpdater = new DBUpdater(); m_clInstance.initAllTables(); // Try connecting to the DB try { m_clInstance.connect(); // dbUpdater.setDbManager(tempInstance); } catch (Exception e) { String msg = e.getMessage(); boolean recover = true; if ((msg.contains("The database is already in use by another process")) || (e instanceof SQLException && (((SQLException)e).getErrorCode() == ErrorCode.LOCK_FILE_ACQUISITION_FAILURE || ((SQLException)e).getErrorCode() == ErrorCode.LOCK_FILE_ACQUISITION_FAILURE * -1))) { if ((msg.contains("Permission denied")) || msg.contains("system cannot find the path")) { msg = "Could not write to database. Make sure you have write access to the HO directory and its sub-directories.\n" + "If under Windows make sure to stay out of Program Files or similar."; } else { msg = "The database is already in use. You have another HO running\n or the database is still closing. Wait and try again."; } recover = false; } else { msg = "Fatal database error. Exiting HO!\nYou should restore the db-folder from backup or delete that folder."; } javax.swing.JOptionPane .showMessageDialog(null, msg, "Fatal DB Error", javax.swing.JOptionPane.ERROR_MESSAGE); if (recover) { BackupDialog dialog = new BackupDialog(); dialog.setVisible(true); while (dialog.isVisible()) { // wait } } HOLogger.instance().error(DBManager.class, msg); System.exit(-1); } // Does DB already exists? final boolean existsDB = m_clInstance.checkIfDBExists(); // for startup m_clInstance.setFirstStart(!existsDB); // Do we need to create the database from scratch? if (!existsDB) { try { m_clInstance.createAllTables(); } catch (SQLException e) { throw new RuntimeException(e); } UserConfigurationTable configTable = (UserConfigurationTable) m_clInstance.getTable(UserConfigurationTable.TABLENAME); configTable.storeConfigurations(UserParameter.instance()); configTable.storeConfigurations(HOParameter.instance()); } else { // Check if there are any updates on the database to be done. dbUpdater.updateDB(DBVersion); } // tempInstance.updateConfig(); HOLogger.instance().info(DBManager.class, "instance " + UserManager.instance().getCurrentUser().getDbURL() + "; parent folder: " + UserManager.instance().getDbParentFolder()); } return m_clInstance; } private static final HashMap<String,PreparedStatement> preparedStatements = new HashMap<>(); protected PreparedStatement getPreparedStatement(String sql) { PreparedStatement ret = preparedStatements.get(sql); if ( ret == null){ ret = Objects.requireNonNull(m_clJDBCAdapter).createPreparedStatement(sql); preparedStatements.put(sql, ret); } return ret; } public static double getDBConfigVersion() { return DBConfigVersion; } /** This method is called */ public void updateConfig(){ DBConfigUpdater.updateDBConfig(DBConfigVersion); } private void initAllTables() { var adapter = this.m_clJDBCAdapter; tables.put(BasicsTable.TABLENAME, new BasicsTable(adapter)); tables.put(TeamTable.TABLENAME, new TeamTable(adapter)); tables.put(NtTeamTable.TABLENAME, new NtTeamTable(adapter)); tables.put(FaktorenTable.TABLENAME, new FaktorenTable(adapter)); tables.put(HRFTable.TABLENAME, new HRFTable(adapter)); tables.put(StadionTable.TABLENAME, new StadionTable(adapter)); tables.put(VereinTable.TABLENAME, new VereinTable(adapter)); tables.put(LigaTable.TABLENAME, new LigaTable(adapter)); tables.put(SpielerTable.TABLENAME, new SpielerTable(adapter)); tables.put(EconomyTable.TABLENAME, new EconomyTable(adapter)); tables.put(YouthPlayerTable.TABLENAME, new YouthPlayerTable(adapter)); tables.put(YouthScoutCommentTable.TABLENAME, new YouthScoutCommentTable(adapter)); tables.put(YouthTrainingTable.TABLENAME, new YouthTrainingTable(adapter)); tables.put(TeamsLogoTable.TABLENAME, new TeamsLogoTable(adapter)); tables.put(ScoutTable.TABLENAME, new ScoutTable(adapter)); tables.put(UserColumnsTable.TABLENAME, new UserColumnsTable(adapter)); tables.put(SpielerNotizenTable.TABLENAME, new SpielerNotizenTable(adapter)); tables.put(SpielplanTable.TABLENAME, new SpielplanTable(adapter)); tables.put(PaarungTable.TABLENAME, new PaarungTable(adapter)); tables.put(MatchLineupTeamTable.TABLENAME, new MatchLineupTeamTable(adapter)); tables.put(MatchLineupTable.TABLENAME, new MatchLineupTable(adapter)); tables.put(XtraDataTable.TABLENAME, new XtraDataTable(adapter)); tables.put(MatchLineupPlayerTable.TABLENAME,new MatchLineupPlayerTable(adapter)); tables.put(MatchesKurzInfoTable.TABLENAME, new MatchesKurzInfoTable(adapter)); tables.put(MatchDetailsTable.TABLENAME, new MatchDetailsTable(adapter)); tables.put(MatchHighlightsTable.TABLENAME, new MatchHighlightsTable(adapter)); tables.put(TrainingsTable.TABLENAME, new TrainingsTable(adapter)); tables.put(FutureTrainingTable.TABLENAME, new FutureTrainingTable(adapter)); tables.put(UserConfigurationTable.TABLENAME,new UserConfigurationTable(adapter)); tables.put(SpielerSkillupTable.TABLENAME, new SpielerSkillupTable(adapter)); tables.put(StaffTable.TABLENAME, new StaffTable(adapter)); tables.put(MatchSubstitutionTable.TABLENAME, new MatchSubstitutionTable(adapter)); tables.put(TransferTable.TABLENAME, new TransferTable(adapter)); tables.put(TransferTypeTable.TABLENAME, new TransferTypeTable(adapter)); tables.put(ModuleConfigTable.TABLENAME, new ModuleConfigTable(adapter)); tables.put(TAFavoriteTable.TABLENAME, new TAFavoriteTable(adapter)); tables.put(TAPlayerTable.TABLENAME, new TAPlayerTable(adapter)); tables.put(WorldDetailsTable.TABLENAME, new WorldDetailsTable(adapter)); tables.put(IfaMatchTable.TABLENAME, new IfaMatchTable(adapter)); // tables.put(PenaltyTakersTable.TABLENAME, new PenaltyTakersTable(adapter)); tables.put(TournamentDetailsTable.TABLENAME, new TournamentDetailsTable(adapter)); tables.put(FuturePlayerTrainingTable.TABLENAME, new FuturePlayerTrainingTable((adapter))); tables.put(MatchTeamRatingTable.TABLENAME, new MatchTeamRatingTable(adapter)); tables.put(SquadInfoTable.TABLENAME, new SquadInfoTable(adapter)); } /** * Gets table. * * @param tableName the table name * @return the table */ AbstractTable getTable(String tableName) { return tables.get(tableName); } /** * Gets adapter. * * @return the adapter */ // Accessor public JDBCAdapter getAdapter() { return m_clJDBCAdapter; } private void setFirstStart(boolean firststart) { m_bFirstStart = firststart; } /** * Is first start boolean. * * @return the boolean */ public boolean isFirstStart() { return m_bFirstStart; } /** * disconnect from database */ public void disconnect() { if ( m_clJDBCAdapter != null) { m_clJDBCAdapter.disconnect(); m_clJDBCAdapter = null; } m_clInstance = null; } /** * connect to the database */ private void connect() throws Exception { User current_user = UserManager.instance().getCurrentUser(); if (m_clJDBCAdapter != null) { m_clJDBCAdapter.connect(current_user.getDbURL(), current_user.getDbUsername(), current_user.getDbPwd(), UserManager.instance().getDriver()); } } /** * check if tables in DB exists * * @return boolean */ private boolean checkIfDBExists() { if ( m_clJDBCAdapter==null) return false; boolean exists; try { ResultSet rs = m_clJDBCAdapter.executeQuery("SELECT Count(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'PUBLIC'"); assert rs != null; rs.next(); exists = rs.getInt(1) > 0; } catch(SQLException e) { HOLogger.instance().error(getClass(), ExceptionUtils.getStackTrace(e)); exists = false; } return exists; } /** * get the date of the last level increase of given player * * @param skill integer code for the skill * @param spielerId player ID * @return [0] = Time of change [1] = Boolean: false=no skill change found */ public Skillup getLastLevelUp(int skill, int spielerId) { return ((SpielerSkillupTable) getTable(SpielerSkillupTable.TABLENAME)) .getLastLevelUp(skill, spielerId); } /** * liefert das Datum des letzen LevelAufstiegs für den angeforderten Skill * Vector filled with Skillup Objects * * @param skill the skill * @param m_iSpielerID the m i spieler id * @return the all level up */ public List<Skillup> getAllLevelUp(int skill, int m_iSpielerID) { return ((SpielerSkillupTable) getTable(SpielerSkillupTable.TABLENAME)) .getAllLevelUp(skill, m_iSpielerID); } /** * Check skillup. * * @param homodel the homodel */ public void checkSkillup(HOModel homodel) { ((SpielerSkillupTable) getTable(SpielerSkillupTable.TABLENAME)) .importNewSkillup(homodel); } // ------------------------------- SpielerTable // ------------------------------------------------- /** * gibt alle Player zurück, auch ehemalige * * @return the all spieler */ public List<Player> loadAllPlayers() { return ((SpielerTable) getTable(SpielerTable.TABLENAME)) .loadAllPlayers(); } /** * Gibt die letzte Bewertung für den Player zurück // HRF * * @param spielerid the spielerid * @return the letzte bewertung 4 spieler */ public int getLetzteBewertung4Spieler(int spielerid) { return ((SpielerTable) getTable(SpielerTable.TABLENAME)) .getLatestRatingOfPlayer(spielerid); } /** * lädt die Player zum angegeben HRF file ein * * @param hrfID the hrf id * @return the spieler */ public List<Player> getSpieler(int hrfID) { return ((SpielerTable) getTable(SpielerTable.TABLENAME)) .loadPlayers(hrfID); } /** * store youth players * * @param hrfId the hrf id * @param youthPlayers the list of youth players */ public void storeYouthPlayers(int hrfId, List<YouthPlayer> youthPlayers) { var youthplayertable = ((YouthPlayerTable) getTable(YouthPlayerTable.TABLENAME)); youthplayertable.deleteYouthPlayers(hrfId); for ( var youthPlayer : youthPlayers){ youthPlayer.setIsStored(false); storeYouthPlayer(hrfId,youthPlayer); } } /** * store youth players * * @param hrfId the hrf id * @param youthPlayer the youth player */ public void storeYouthPlayer(int hrfId, YouthPlayer youthPlayer) { ((YouthPlayerTable) getTable(YouthPlayerTable.TABLENAME)).storeYouthPlayer(hrfId,youthPlayer); var youthScoutCommentTable = (YouthScoutCommentTable) DBManager.instance().getTable(YouthScoutCommentTable.TABLENAME); youthScoutCommentTable.storeYouthScoutComments(youthPlayer.getId(), youthPlayer.getScoutComments()); } /** * Load youth players list. * * @param hrfID the hrf id * @return the list */ public List<YouthPlayer> loadYouthPlayers(int hrfID) { return ((YouthPlayerTable) getTable(YouthPlayerTable.TABLENAME)) .loadYouthPlayers(hrfID); } /** * Load youth scout comments list. * * @param id the id * @return the list */ public List<YouthPlayer.ScoutComment> loadYouthScoutComments(int id) { return ((YouthScoutCommentTable) getTable(YouthScoutCommentTable.TABLENAME)) .loadYouthScoutComments(id); } /** * Load youth player of match date youth player. * * @param id the id * @param date the date * @return the youth player */ public YouthPlayer loadYouthPlayerOfMatchDate(int id, Timestamp date) { return ((YouthPlayerTable) getTable(YouthPlayerTable.TABLENAME)) .loadYouthPlayerOfMatchDate(id, date); } /** * Gibt einen Player zurück mit den Daten kurz vor dem Timestamp * * @param spielerid the spielerid * @param time the time * @return the spieler at date */ public Player getSpielerAtDate(int spielerid, Timestamp time) { return ((SpielerTable) getTable(SpielerTable.TABLENAME)) .getSpielerNearDate(spielerid, time); } /** * Gibt einen Player zurück aus dem ersten HRF * * @param spielerid the spielerid * @return the spieler first hrf */ public Player loadPlayerFirstHRF(int spielerid) { return loadPlayerFirstHRF(spielerid, null); } public Player loadPlayerFirstHRF(int spielerid, HODateTime after) { if ( after == null){ after = HODateTime.HT_START; } return ((SpielerTable) getTable(SpielerTable.TABLENAME)) .getSpielerFirstHRF(spielerid, after.toDbTimestamp()); } /** * Returns the trainer code for the specified hrf. -99 if error * * @param hrfID HRF for which to load TrainerType * @return int trainer type */ public int getTrainerType(int hrfID) { return ((SpielerTable) getTable(SpielerTable.TABLENAME)) .getTrainerType(hrfID); } /** * store list of Player * * @param player the player */ public void saveSpieler(List<Player> player) { ((SpielerTable) getTable(SpielerTable.TABLENAME)).store(player); } // ------------------------------- LigaTable // ------------------------------------------------- /** * Gibt alle bekannten Ligaids zurück * * @return the integer [ ] */ public Integer[] getAllLigaIDs() { return ((SpielplanTable) getTable(SpielplanTable.TABLENAME)).getAllLigaIDs(); } /** * lädt die Basics zum angegeben HRF file ein * * @param hrfID the hrf id * @return the liga */ public Liga getLiga(int hrfID) { return ((LigaTable) getTable(LigaTable.TABLENAME)).getLiga(hrfID); } /** * speichert die Basdics * * @param hrfId the hrf id * @param liga the liga */ public void saveLiga(int hrfId, Liga liga) { ((LigaTable) getTable(LigaTable.TABLENAME)).saveLiga(hrfId, liga); } // ------------------------------- SpielplanTable // ------------------------------------------------- /** * Gibt eine Ligaid zu einer Seasonid zurück, oder -1, wenn kein Eintrag in * der DB gefunden wurde * * @param seasonid the seasonid * @return the liga id 4 saison id */ public int getLigaID4SaisonID(int seasonid) { return ((SpielplanTable) getTable(SpielplanTable.TABLENAME)) .getLigaID4SaisonID(seasonid); } /** * holt einen Spielplan aus der DB, -1 bei den params holt den zuletzt * gesavten Spielplan * * @param ligaId Id der Liga * @param saison die Saison * @return the spielplan */ public Spielplan getSpielplan(int ligaId, int saison) { var ret = ((SpielplanTable) getTable(SpielplanTable.TABLENAME)).getSpielplan(ligaId, saison); if ( ret != null ){ ret.addFixtures(loadFixtures(ret)); } return ret; } public Spielplan getLatestSpielplan() { var ret = ((SpielplanTable) getTable(SpielplanTable.TABLENAME)).getLatestSpielplan(); if ( ret != null ){ ret.addFixtures(loadFixtures(ret)); } return ret; } /** * speichert einen Spielplan mitsamt Paarungen * * @param plan the plan */ public void storeSpielplan(Spielplan plan) { if ( plan != null){ ((SpielplanTable) getTable(SpielplanTable.TABLENAME)) .storeSpielplan(plan); storePaarung(plan.getMatches(), plan.getLigaId(), plan.getSaison()); } } public void deleteSpielplanTabelle(int saison, int ligaId) { var table = (SpielplanTable)getTable(SpielplanTable.TABLENAME); table.executePreparedDelete(saison, ligaId); } /** * lädt alle Spielpläne aus der DB * * @param withFixtures inklusive der Paarungen ja/nein * @return the spielplan [ ] */ public List<Spielplan> getAllSpielplaene(boolean withFixtures) { var ret = ((SpielplanTable) getTable(SpielplanTable.TABLENAME)) .getAllSpielplaene(); if (withFixtures) { for (Spielplan gameSchedule : ret) { gameSchedule.addFixtures(loadFixtures(gameSchedule)); } } return ret; } // ------------------------------- MatchLineupPlayerTable // ------------------------------------------------- /** * Returns a list of ratings the player has played on [Max, Min, Average, posid] * * @param spielerid the spielerid * @return the alle bewertungen */ public Vector<float[]> getAlleBewertungen(int spielerid) { return ((MatchLineupPlayerTable) getTable(MatchLineupPlayerTable.TABLENAME)) .getAllRatings(spielerid); } /** * Gibt die beste, schlechteste und durchschnittliche Bewertung für den * Player, sowie die Anzahl der Bewertungen zurück // Match * * @param spielerid the spielerid * @return the float [ ] */ public float[] getBewertungen4Player(int spielerid) { return ((MatchLineupPlayerTable) getTable(MatchLineupPlayerTable.TABLENAME)) .getBewertungen4Player(spielerid); } /** * Gibt die beste, schlechteste und durchschnittliche Bewertung für den * Player, sowie die Anzahl der Bewertungen zurück // Match * * @param spielerid Spielerid * @param position Usere positionscodierung mit taktik * @return the float [ ] */ public float[] getBewertungen4PlayerUndPosition(int spielerid, byte position) { return ((MatchLineupPlayerTable) getTable(MatchLineupPlayerTable.TABLENAME)) .getPlayerRatingForPosition(spielerid, position); } /** * Gets match lineup players. * * @param matchID the match id * @param matchType MatchType * @param teamID the team id * @return the match lineup players */ public List<MatchLineupPosition> getMatchLineupPlayers(int matchID, MatchType matchType, int teamID) { return ((MatchLineupPlayerTable) getTable(MatchLineupPlayerTable.TABLENAME)) .getMatchLineupPlayers(matchID, matchType, teamID); } /** * Get match inserts of given Player * * @param objectPlayerID id of the player * @return stored lineup positions of the player */ public List<MatchLineupPosition> getMatchInserts(int objectPlayerID) { return ((MatchLineupPlayerTable) getTable(MatchLineupPlayerTable.TABLENAME)) .getMatchInserts(objectPlayerID); } /** * Get the top or flop players of given lineup position in given matches * * @param position lineup position sector * @param matches list of matches * @param isBest true: the best player is listed first * @return stored lineup positions */ public List<MatchLineupPosition> loadTopFlopRatings(List<Paarung> matches, int position, int count, boolean isBest) { return ((MatchLineupPlayerTable) getTable(MatchLineupPlayerTable.TABLENAME)) .loadTopFlopRatings(matches, position, count, isBest); } // ------------------------------- BasicsTable // ------------------------------------------------- /** * lädt die Basics zum angegeben HRF file ein * * @param hrfID the hrf id * @return the basics */ public Basics getBasics(int hrfID) { return ((BasicsTable) getTable(BasicsTable.TABLENAME)).loadBasics(hrfID); } /** * Returns an HRF before the matchData and after previous TrainingTime * * @param matchTime matchData * @return hrfId hrf id same training */ public int getHrfIDSameTraining(Timestamp matchTime) { return ((BasicsTable) getTable(BasicsTable.TABLENAME)) .getHrfIDSameTraining(matchTime); } /** * speichert die Basdics * * @param hrfId the hrf id * @param basics the basics */ public void saveBasics(int hrfId, core.model.misc.Basics basics) { ((BasicsTable) getTable(BasicsTable.TABLENAME)).saveBasics(hrfId, basics); } /** * Sets faktoren from db. * * @param fo the fo */ // ------------------------------- FaktorenTable // ------------------------------------------------- public void setFaktorenFromDB(FactorObject fo) { ((FaktorenTable) getTable(FaktorenTable.TABLENAME)) .pushFactorsIntoDB(fo); } /** * Gets faktoren from db. */ public void getFaktorenFromDB() { ((FaktorenTable) getTable(FaktorenTable.TABLENAME)).getFaktorenFromDB(); } /** * Gets tournament details from db. * * @param tournamentId the tournament id * @return the tournament details from db */ // Tournament Details public TournamentDetails getTournamentDetailsFromDB(int tournamentId) { TournamentDetails oTournamentDetails; oTournamentDetails = ((TournamentDetailsTable) getTable(TournamentDetailsTable.TABLENAME)).getTournamentDetails(tournamentId); return oTournamentDetails; } /** * Store tournament details into db. * * @param oTournamentDetails the o tournament details */ public void storeTournamentDetailsIntoDB(TournamentDetails oTournamentDetails) { ((TournamentDetailsTable) getTable(TournamentDetailsTable.TABLENAME)).storeTournamentDetails(oTournamentDetails); } // ------------------------------- FinanzenTable // ------------------------------------------------- /** * fetch the Economy table from the DB for the specified HRF ID * * @param hrfID the hrf id * @return the economy */ public Economy getEconomy(int hrfID) { return ((EconomyTable) getTable(EconomyTable.TABLENAME)).getEconomy(hrfID); } /** * store the economy info in the database * * @param hrfId the hrf id * @param economy the economy * @param date the date */ public void saveEconomyInDB(int hrfId, Economy economy, HODateTime date) { ((EconomyTable) getTable(EconomyTable.TABLENAME)).storeEconomyInfoIntoDB(hrfId, economy, date); } // ------------------------------- HRFTable // ------------------------------------------------- /** * Get a list of all HRFs * * @param asc order ascending (descending otherwise) * @return all matching HRFs */ public HRF[] loadAllHRFs( boolean asc) { return ((HRFTable) getTable(HRFTable.TABLENAME)).loadAllHRFs(asc); } /** * get the latest imported hrf * this does not have to be the latest downloaded, if the user imported hrf files in any order from files * @return HRF object */ public HRF getMaxIdHrf() { return ((HRFTable) getTable(HRFTable.TABLENAME)).getMaxHrf(); } /** * get the latest downloaded hrf * @return HRF object */ public HRF getLatestHRF(){ return ((HRFTable) getTable(HRFTable.TABLENAME)).getLatestHrf(); } public HRF loadHRF(int id){ return ((HRFTable) getTable(HRFTable.TABLENAME)).loadHRF(id); } /** * save the HRF info */ public void saveHRF(HRF hrf) { ((HRFTable) getTable(HRFTable.TABLENAME)).saveHRF(hrf); } /** * Gets hrfid 4 date. * * @param time the time * @return the hrfid 4 date */ public int getHRFID4Date(Timestamp time) { return ((HRFTable) getTable(HRFTable.TABLENAME)).getHrfIdNearDate(time); } /** * is there is an HRFFile in the database with the same date? * * @param fetchDate the date * @return The date of the file to which the file was imported or zero if no suitable file is available */ public HRF loadHRFDownloadedAt(Timestamp fetchDate) { return ((HRFTable) getTable(HRFTable.TABLENAME)).loadHRFDownloadedAt(fetchDate); } public HRF loadLatestHRFDownloadedBefore(Timestamp fetchDate){ return ((HRFTable) getTable(HRFTable.TABLENAME)).loadLatestHRFDownloadedBefore(fetchDate); } // ------------------------------- SpielerNotizenTable // ------------------------------------------------- public void storePlayerNotes(Player.Notes notes) { ((SpielerNotizenTable) getTable(SpielerNotizenTable.TABLENAME)).storeNotes(notes); } public Player.Notes loadPlayerNotes(int playerId) { return ((SpielerNotizenTable) getTable(SpielerNotizenTable.TABLENAME)).load(playerId); } // ------------------------------- MatchLineupTable // ------------------------------------------------- /** * Load match lineup match lineup. * * @param iMatchType the source system * @param matchID the match id * @return the match lineup */ public MatchLineup loadMatchLineup(int iMatchType, int matchID) { var ret = ((MatchLineupTable) getTable(MatchLineupTable.TABLENAME)).loadMatchLineup(iMatchType, matchID); if ( ret != null ) { var match = DBManager.instance().loadMatchDetails(iMatchType, matchID); ret.setHomeTeam(DBManager.instance().loadMatchLineupTeam(iMatchType, matchID, match.getHomeTeamId())); ret.setGuestTeam(DBManager.instance().loadMatchLineupTeam(iMatchType, matchID, match.getGuestTeamId())); } return ret; } /** * Is the match already in the database? * * @param iMatchType the source system * @param matchid the matchid * @return the boolean */ public boolean matchLineupIsNotStored(MatchType iMatchType, int matchid) { return !getTable(MatchLineupTable.TABLENAME) .isStored(matchid, iMatchType.getId()); } /** * Is match ifk rating in db boolean. * * @param matchid the matchid * @return the boolean */ public boolean isMatchIFKRatingInDB(int matchid) { return ((MatchDetailsTable) getTable(MatchDetailsTable.TABLENAME)) .isMatchIFKRatingAvailable(matchid); } /** * Has unsure weather forecast boolean. * * @param matchId the match id * @return the boolean */ public boolean hasUnsureWeatherForecast(int matchId){ return ((MatchesKurzInfoTable)getTable(MatchesKurzInfoTable.TABLENAME)).hasUnsureWeatherForecast(matchId); } // ------------------------------- MatchesKurzInfoTable // ------------------------------------------------- /** * Check if match is available * * @param matchid the matchid * @param matchType type of the match * @return the boolean */ public boolean isMatchInDB(int matchid, MatchType matchType) { return ((MatchesKurzInfoTable) getTable(MatchesKurzInfoTable.TABLENAME)) .isMatchInDB(matchid, matchType); } /** * Returns the MatchKurzInfo for the match. Returns null if not found. * * @param matchid The ID for the match * @param matchType type of the match * @return The kurz info object or null */ public MatchKurzInfo getMatchesKurzInfoByMatchID(int matchid, MatchType matchType) { return ((MatchesKurzInfoTable) getTable(MatchesKurzInfoTable.TABLENAME)) .getMatchesKurzInfoByMatchID(matchid, matchType); } /** * Get all matches for the given team from the database. * * @param teamId the teamid or -1 for all matches * @return the match kurz info [ ] */ public List<MatchKurzInfo> getMatchesKurzInfo(int teamId) { return ((MatchesKurzInfoTable) getTable(MatchesKurzInfoTable.TABLENAME)) .getMatchesKurzInfo(teamId); } public List<MatchKurzInfo> getMatchesKurzInfo(String where, Object ... values) { return ((MatchesKurzInfoTable) getTable(MatchesKurzInfoTable.TABLENAME)) .loadMatchesKurzInfo(where, values); } /** * Get last matches kurz info match kurz info. * * @param teamId the team id * @return the match kurz info */ public MatchKurzInfo getLastMatchesKurzInfo(int teamId) { return ((MatchesKurzInfoTable) getTable(MatchesKurzInfoTable.TABLENAME)) .loadLastMatchesKurzInfo(teamId); } public MatchKurzInfo getNextMatchesKurzInfo(int teamId) { return ((MatchesKurzInfoTable) getTable(MatchesKurzInfoTable.TABLENAME)) .loadNextMatchesKurzInfo(teamId); } public MatchKurzInfo getLastMatchWithMatchId(int matchId) { return ((MatchesKurzInfoTable)getTable(MatchesKurzInfoTable.TABLENAME)) .getLastMatchWithMatchId(matchId); } /** * function that fetch info of match played related to the TrainingPerWeek instance * @return MatchKurzInfo[] related to this TrainingPerWeek instance */ public List<MatchKurzInfo> loadOfficialMatchesBetween(int teamId, HODateTime firstMatchDate, HODateTime lastMatchDate) { return ((MatchesKurzInfoTable)getTable(MatchesKurzInfoTable.TABLENAME)).getMatchesKurzInfo(teamId, firstMatchDate.toDbTimestamp(), lastMatchDate.toDbTimestamp(), MatchType.getOfficialMatchTypes()); } /** * function that fetch info of NT match played related to the TrainingPerWeek instance * @return MatchKurzInfo[] related to this TrainingPerWeek instance */ public List<MatchKurzInfo> loadNTMatchesBetween(int teamId,HODateTime firstMatchDate, HODateTime lastMatchDate) { return ((MatchesKurzInfoTable)getTable(MatchesKurzInfoTable.TABLENAME)).getMatchesKurzInfo(teamId, firstMatchDate.toDbTimestamp(), lastMatchDate.toDbTimestamp(), MatchType.getNTMatchType()); } /** * Get all matches with a certain status for the given team from the * database. * * @param teamId the teamid or -1 for all matches * @param matchStatus the match status * @return the match kurz info [ ] */ public List<MatchKurzInfo> getMatchesKurzInfo(final int teamId, final int matchStatus) { return ((MatchesKurzInfoTable) getTable(MatchesKurzInfoTable.TABLENAME)) .getMatchesKurzInfo(teamId, matchStatus); } /** * Gets first upcoming match with team id. * * @param teamId the team id * @return the first upcoming match with team id */ public MatchKurzInfo getFirstUpcomingMatchWithTeamId(final int teamId) { return ((MatchesKurzInfoTable) getTable(MatchesKurzInfoTable.TABLENAME)) .getFirstUpcomingMatchWithTeamId(teamId); } /** * Get played match info array list (own team Only) * * @param iNbGames the nb games * @param bOfficialGamesOnly the b official games only * @return the array list */ public List<MatchKurzInfo> getOwnPlayedMatchInfo(@Nullable Integer iNbGames, boolean bOfficialGamesOnly){ return ((MatchesKurzInfoTable) getTable(MatchesKurzInfoTable.TABLENAME)).getPlayedMatchInfo(iNbGames, bOfficialGamesOnly, true); } /** * Get played match info array list (own team Only) * * @param iNbGames the nb games * @param bOfficialGamesOnly the b official games only * @return the array list */ public List<MatchKurzInfo> getPlayedMatchInfo(@Nullable Integer iNbGames, boolean bOfficialGamesOnly, boolean ownTeam){ return ((MatchesKurzInfoTable) getTable(MatchesKurzInfoTable.TABLENAME)).getPlayedMatchInfo(iNbGames, bOfficialGamesOnly, ownTeam); } /** * Returns an array of {@link MatchKurzInfo} for the team with ID <code>teamId</code>, * and of type <code>matchtyp</code>. * Important: if teamId is -1, <code>matchtype</code> must be set to * <code>MatchesPanel.ALL_MATCHS</code>. * @param teamId The ID of the team, or -1 for all. * @param iMatchType Type of match, as defined in {@link module.matches.MatchesPanel} * @param matchLocation Home, Away, Neutral * * @return MatchKurzInfo[] – Array of match info. */ public List<MatchKurzInfo> getMatchesKurzInfo(int teamId, int iMatchType, MatchLocation matchLocation) { return getMatchesKurzInfo(teamId,iMatchType, matchLocation, HODateTime.HT_START.toDbTimestamp(), true); } /** * Returns an array of {@link MatchKurzInfo} for the team with ID <code>teamId</code>, * and of type <code>matchtyp</code>. * Important: if teamId is -1, <code>matchtype</code> must be set to * <code>MatchesPanel.ALL_MATCHS</code>. * * @param teamId The ID of the team, or -1 for all. * @param iMatchType Type of match, as defined in {@link module.matches.MatchesPanel} * @param matchLocation Home, Away, Neutral * @param from filter match schedule date * @param includeUpcoming if false filter finished matches only * @return MatchKurzInfo[] – Array of match info. */ public List<MatchKurzInfo> getMatchesKurzInfo(int teamId, int iMatchType, MatchLocation matchLocation, Timestamp from, boolean includeUpcoming) { return ((MatchesKurzInfoTable) getTable(MatchesKurzInfoTable.TABLENAME)).getMatchesKurzInfo(teamId, iMatchType, matchLocation, from, includeUpcoming); } /** * Get matches kurz info up coming match kurz info [ ]. * * @param teamId the team id * @return the match kurz info [ ] */ public List<MatchKurzInfo> getMatchesKurzInfoUpComing(int teamId) { return ((MatchesKurzInfoTable) getTable(MatchesKurzInfoTable.TABLENAME)) .getMatchesKurzInfoUpComing(teamId); } /** * Gets matches kurz info. * * @param teamId the team id * @param matchtyp the matchtyp * @param statistic the statistic * @param home the home * @return the matches kurz info */ public MatchKurzInfo getMatchesKurzInfo(int teamId, int matchtyp, int statistic, boolean home) { return ((MatchesKurzInfoTable) getTable(MatchesKurzInfoTable.TABLENAME)) .getMatchesKurzInfo(teamId, matchtyp, statistic, home); } /** * Gets matches kurz info statistics count. * * @param teamId the team id * @param matchtype the matchtype * @param statistic the statistic * @return the matches kurz info statistics count */ public int getMatchesKurzInfoStatisticsCount(int teamId, int matchtype, int statistic) { return MatchesOverviewQuery.getMatchesKurzInfoStatisticsCount(teamId, matchtype, statistic); } /** * speichert die Matches * * @param matches the matches */ public void storeMatchKurzInfos(List<MatchKurzInfo> matches) { ((MatchesKurzInfoTable) getTable(MatchesKurzInfoTable.TABLENAME)) .storeMatchKurzInfos(matches); } // ------------------------------- ScoutTable // ------------------------------------------------- /** * Load player list for insertion into TransferScout * * @return the scout list */ public Vector<ScoutEintrag> getScoutList() { return new Vector<>(((ScoutTable) getTable(ScoutTable.TABLENAME)).getScoutList()); } /** * Save players from TransferScout * * @param list the list */ public void saveScoutList(Vector<ScoutEintrag> list) { ((ScoutTable) getTable(ScoutTable.TABLENAME)).saveScoutList(list); } // ------------------------------- StadionTable // ------------------------------------------------- /** * lädt die Finanzen zum angegeben HRF file ein * * @param hrfID the hrf id * @return the stadion */ public Stadium getStadion(int hrfID) { return ((StadionTable) getTable(StadionTable.TABLENAME)) .getStadion(hrfID); } /** * speichert die Finanzen * * @param hrfId the hrf id * @param stadion the stadion */ public void saveStadion(int hrfId, Stadium stadion) { ((StadionTable) getTable(StadionTable.TABLENAME)).saveStadion(hrfId, stadion); } // ------------------------------- StaffTable // ------------------------------------------------- /** * Fetch a list of staff store din a hrf * * @param hrfId the hrf id * @return A list of StaffMembers belonging to the given hrf */ public List<StaffMember> getStaffByHrfId(int hrfId) { return ((StaffTable) getTable(StaffTable.TABLENAME)).getStaffByHrfId(hrfId); } /** * Stores a list of StaffMembers * * @param hrfId The hrfId * @param list The staff objects */ public void saveStaff(int hrfId, List<StaffMember> list) { ((StaffTable) getTable(StaffTable.TABLENAME)).storeStaff(hrfId, list); } // ------------------------------- MatchSubstitutionTable // ------------------------------------------------- /** * Returns an array with substitution belonging to the match-team. * * @param matchType match type * @param teamId The teamId for the team in question * @param matchId The matchId for the match in question * @return the match substitutions by match team */ public List<Substitution> getMatchSubstitutionsByMatchTeam(int matchId, MatchType matchType, int teamId) { return ((MatchSubstitutionTable) getTable(MatchSubstitutionTable.TABLENAME)) .getMatchSubstitutionsByMatchTeam(matchType.getId(), teamId, matchId); } // /** // * Gibt die Teamstimmung und das Selbstvertrauen für ein HRFID zurück [0] = // * Stimmung [1] = Selbstvertrauen // * // * @param hrfid the hrfid // * @return the string [ ] // */ // public String[] getStimmmungSelbstvertrauen(int hrfid) { // return ((TeamTable) getTable(TeamTable.TABLENAME)) // .getStimmmungSelbstvertrauen(hrfid); // } // // /** // * Gibt die Teamstimmung und das Selbstvertrauen für ein HRFID zurück [0] = // * Stimmung [1] = Selbstvertrauen // * // * @param hrfid the hrfid // * @return the int [ ] // */ // public int[] getStimmmungSelbstvertrauenValues(int hrfid) { // return ((TeamTable) getTable(TeamTable.TABLENAME)) // .getStimmmungSelbstvertrauenValues(hrfid); // } /** * lädt die Basics zum angegeben HRF file ein * * @param hrfID the hrf id * @return the team */ public Team getTeam(int hrfID) { return ((TeamTable) getTable(TeamTable.TABLENAME)).getTeam(hrfID); } /** * speichert das Team * * @param hrfId the hrf id * @param team the team */ public void saveTeam(int hrfId, Team team) { ((TeamTable) getTable(TeamTable.TABLENAME)).saveTeam(hrfId, team); } /** * Gets the content of TrainingsTable as a vector of TrainingPerWeek objects */ public List<TrainingPerWeek> getTrainingList() { return ((TrainingsTable) getTable(TrainingsTable.TABLENAME)) .getTrainingList(); } public List<TrainingPerWeek> getTrainingList(Timestamp fromDate, Timestamp toDate) { return ((TrainingsTable) getTable(TrainingsTable.TABLENAME)) .getTrainingList(fromDate, toDate); } public void saveTraining(TrainingPerWeek training, HODateTime lastTrainingDate) { ((TrainingsTable) getTable(TrainingsTable.TABLENAME)).saveTraining(training, lastTrainingDate); } public void saveTrainings(List<TrainingPerWeek> trainings, HODateTime lastTrainingDate) { ((TrainingsTable) getTable(TrainingsTable.TABLENAME)).saveTrainings(trainings, lastTrainingDate); } // ------------------------------- FutureTrainingTable // ------------------------------------------------- /** * Gets future trainings vector. * * @return the future trainings vector */ public List<TrainingPerWeek> getFutureTrainingsVector() { return ((FutureTrainingTable) getTable(FutureTrainingTable.TABLENAME)).getFutureTrainingsVector(); } /** * Save future training. * * @param training the training */ public void saveFutureTraining(TrainingPerWeek training) { ((FutureTrainingTable) getTable(FutureTrainingTable.TABLENAME)) .storeFutureTraining(training); } public void saveFutureTrainings(List<TrainingPerWeek> trainings) { ((FutureTrainingTable) getTable(FutureTrainingTable.TABLENAME)) .storeFutureTrainings(trainings); } /** * lädt die Basics zum angegeben HRF file ein * * @param hrfID the hrf id * @return the verein */ public Verein getVerein(int hrfID) { return ((VereinTable) getTable(VereinTable.TABLENAME)).loadVerein(hrfID); } /** * speichert das Verein * * @param hrfId the hrf id * @param verein the verein */ public void saveVerein(int hrfId, Verein verein) { ((VereinTable) getTable(VereinTable.TABLENAME)).saveVerein(hrfId, verein); } /** * Gets futur training. * * @param trainingDate the saison * @return the futur training type */ // ------------------------------- FutureTraining // ------------------------------------------------- public TrainingPerWeek getFuturTraining(Timestamp trainingDate) { return ((FutureTrainingTable) getTable(FutureTrainingTable.TABLENAME)).loadFutureTrainings(trainingDate); } // ------------------------------- XtraDataTable // ------------------------------------------------- /** * lädt die Basics zum angegeben HRF file ein * * @param hrfID the hrf id * @return the xtra daten */ public XtraData getXtraDaten(int hrfID) { return ((XtraDataTable) getTable(XtraDataTable.TABLENAME)) .loadXtraData(hrfID); } /** * speichert das Team * * @param hrfId the hrf id * @param xtra the xtra */ public void saveXtraDaten(int hrfId, XtraData xtra) { ((XtraDataTable) getTable(XtraDataTable.TABLENAME)).saveXtraDaten( hrfId, xtra); } // ------------------------------- UserParameterTable // ------------------------------------------------- /** * Lädt die UserParameter direkt in das UserParameter-SingeltonObjekt */ public void loadUserParameter() { UserConfigurationTable table = (UserConfigurationTable) getTable(UserConfigurationTable.TABLENAME); table.loadConfigurations(UserParameter.instance()); table.loadConfigurations(HOParameter.instance()); } /** * Saves the user parameters in the database. */ public void saveUserParameter() { UserConfigurationTable table = (UserConfigurationTable) getTable(UserConfigurationTable.TABLENAME); table.storeConfigurations(UserParameter.instance()); table.storeConfigurations(HOParameter.instance()); } // ------------------------------- PaarungTable // ------------------------------------------------- /** * Gets the fixtures for the given <code>plan</code> from the DB, and add them to that plan. * * @param plan Schedule for which the fixtures are retrieved, and to which they are added. */ protected List<Paarung> loadFixtures(Spielplan plan) { return ((PaarungTable) getTable(PaarungTable.TABLENAME)).loadFixtures( plan.getLigaId(), plan.getSaison()); } /** * Saves the fixtures to an existing game schedule ({@link Spielplan}). * * @param fixtures the fixtures * @param ligaId the liga id * @param saison the saison */ protected void storePaarung(List<Paarung> fixtures, int ligaId, int saison) { ((PaarungTable) getTable(PaarungTable.TABLENAME)).storePaarung(fixtures, ligaId, saison); } public void deletePaarungTabelle(int saison, int ligaId) { var table = getTable(PaarungTable.TABLENAME); table.executePreparedDelete(saison, ligaId); } // ------------------------------- MatchDetailsTable // ------------------------------------------------- /** * Gibt die MatchDetails zu einem Match zurück * * @param iMatchType the sourcesystem * @param matchId the match id * @return the matchdetails */ public Matchdetails loadMatchDetails(int iMatchType, int matchId) { return ((MatchDetailsTable) getTable(MatchDetailsTable.TABLENAME)) .loadMatchDetails(iMatchType, matchId); } /** * Return match statistics (Count,Win,Draw,Loss,Goals) * * @param matchtype the matchtype * @return matches overview row [ ] */ public MatchesOverviewRow[] getMatchesOverviewValues(int matchtype, MatchLocation matchLocation) { return MatchesOverviewQuery.getMatchesOverviewValues(matchtype, matchLocation); } // ------------------------------- MatchHighlightsTable // ------------------------------------------------- /** * Gibt die MatchHighlights zu einem Match zurück * * @param iMatchType the source system * @param matchId the match id * @return the match highlights */ public List<MatchEvent> getMatchHighlights(int iMatchType, int matchId) { return ((MatchHighlightsTable) getTable(MatchHighlightsTable.TABLENAME)) .getMatchHighlights(iMatchType, matchId); } /** * Get chances stat matches highlights stat [ ]. * * @param ownTeam the own team * @param iMatchType the matchtype * @param matchLocation Home, Away, Neutral * @return the matches highlights stat [ ] */ public MatchesHighlightsStat[] getGoalsByActionType(boolean ownTeam, int iMatchType, MatchLocation matchLocation) { return MatchesOverviewQuery.getGoalsByActionType(ownTeam, iMatchType, matchLocation); } /** * Gets transfers. * * @param playerid the playerid * @param allTransfers the all transfers * @return the transfers */ public List<PlayerTransfer> getTransfers(int playerid, boolean allTransfers) { return ((TransferTable) getTable(TransferTable.TABLENAME)) .getTransfers(playerid, allTransfers); } // // /** // * set the attribute player of each transfer // * @param transfers list of transfers // */ // private void setPlayerInfo(List<PlayerTransfer> transfers) { // for (PlayerTransfer transfer : transfers) { // final Player player = getSpielerAtDate(transfer.getPlayerId(), transfer.getDate().toDbTimestamp()); // // if (player != null) { // transfer.setPlayerInfo(player); // } // } // } /** * Gets transfers. * * @param season the season * @param bought the bought * @param sold the sold * @return the transfers */ public List<PlayerTransfer> getTransfers(int season, boolean bought, boolean sold) { return ((TransferTable) getTable(TransferTable.TABLENAME)) .getTransfers(season, bought, sold); } /** * Remove transfer. * * @param transferId the transfer id */ public void removeTransfer(int transferId) { ((TransferTable) getTable(TransferTable.TABLENAME)) .removeTransfer(transferId); } /** * Update player transfers. * * @param transfer PlayerTransfer */ public void storePlayerTransfer(PlayerTransfer transfer) { ((TransferTable) getTable(TransferTable.TABLENAME)) .storeTransfer(transfer); } /** * load one player transfer * @param transferId int * @return PlayerTransfer */ public PlayerTransfer loadPlayerTransfer(int transferId) { return ((TransferTable) getTable(TransferTable.TABLENAME)) .getTransfer(transferId); } /** * Gets transfer type. * * @param playerId the player id * @return the transfer type */ public TransferType getTransferType(int playerId) { return ((TransferTypeTable) getTable(TransferTypeTable.TABLENAME)) .loadTransferType(playerId); } /** * Sets transfer type. * * @param type the type */ public void setTransferType(TransferType type) { ((TransferTypeTable) getTable(TransferTypeTable.TABLENAME)) .storeTransferType(type); } /** * Get all world detail leagues world detail league [ ]. * * @return the world detail league [ ] */ // WorldDetail public List<WorldDetailLeague> getAllWorldDetailLeagues() { return ((WorldDetailsTable) getTable(WorldDetailsTable.TABLENAME)) .getAllWorldDetailLeagues(); } /** * Save world detail leagues. * * @param leagues the leagues */ public void saveWorldDetailLeagues(List<WorldDetailLeague> leagues) { WorldDetailsTable table = (WorldDetailsTable) getTable(WorldDetailsTable.TABLENAME); table.truncateTable(); for (WorldDetailLeague league : leagues) { table.insertWorldDetailsLeague(league); } } // -------------------------------------------------------------------------------- // -------------------------------- Statistik Part // -------------------------------- // -------------------------------------------------------------------------------- /** * Get spieler daten 4 statistik double [ ] [ ]. * * @param spielerId the spieler id * @param anzahlHRF the anzahl hrf * @return the double [ ] [ ] */ public double[][] getSpielerDaten4Statistik(int spielerId, int anzahlHRF) { return StatisticQuery.getSpielerDaten4Statistik(spielerId, anzahlHRF); } /** * Get data for club statistics panel double [ ] [ ]. * * @param nbHRFs the nb hr fs * @return the double [ ] [ ] */ public double[][] getDataForClubStatisticsPanel(int nbHRFs) { return StatisticQuery.getDataForClubStatisticsPanel(nbHRFs); } /** * Get data for finances statistics panel double [ ] [ ]. * * @param nbHRF the nb hrf * @return the double [ ] [ ] */ public double[][] getDataForFinancesStatisticsPanel(int nbHRF) { return StatisticQuery.getDataForFinancesStatisticsPanel(nbHRF); } /** * Gets arena statistik model. * * @param matchtyp the matchtyp * @return the arena statistik model */ public ArenaStatistikTableModel getArenaStatistikModel(int matchtyp) { return StatisticQuery.getArenaStatisticsModel(matchtyp); } /** * Get data for team statistics panel double [ ] [ ]. * * @param anzahlHRF the anzahl hrf * @param group the group * @return the double [ ] [ ] */ public double[][] getDataForTeamStatisticsPanel(int anzahlHRF, String group) { return StatisticQuery.getDataForTeamStatisticsPanel( anzahlHRF, group); } /** * Gets count of played matches. * * @param playerId the player id * @param official the official * @return the count of played matches */ public int getCountOfPlayedMatches(int playerId, boolean official) { var officialWhere = official ? "<8" : ">7"; String sqlStmt = "select count(MATCHESKURZINFO.matchid) as MatchNumber FROM MATCHLINEUPPLAYER " + "INNER JOIN MATCHESKURZINFO ON MATCHESKURZINFO.matchid = MATCHLINEUPPLAYER.matchid " + "where spielerId = "+ playerId + " and ROLEID BETWEEN 100 AND 113 and matchtyp " + officialWhere; assert getAdapter() != null; final ResultSet rs = getAdapter().executeQuery(sqlStmt); if (rs == null) { return 0; } int count = 0; try { while (rs.next()) { count = rs.getInt("MatchNumber"); } } catch (SQLException ignored) { } return count; } /** * Returns a list of PlayerMatchCBItems for given playerID * * @param playerID the player ID */ public Vector<PlayerMatchCBItem> getPlayerMatchCBItems(int playerID) { return getPlayerMatchCBItems(playerID, false); } /** * Returns a list of PlayerMatchCBItems for given playerID * * @param playerID the player ID * @param officialOnly whether or not to select official game only */ public Vector<PlayerMatchCBItem> getPlayerMatchCBItems(int playerID, boolean officialOnly) { if(playerID == -1) return new Vector<>(); final Vector<PlayerMatchCBItem> spielerMatchCBItems = new Vector<>(); String sql = """ SELECT DISTINCT MatchID, MatchDate, Rating, SpielDatum, HeimName, HeimID, GastName, GastID, HoPosCode, MatchTyp FROM MATCHLINEUPPLAYER INNER JOIN MATCHLINEUP ON (MATCHLINEUPPLAYER.MatchID=MATCHLINEUP.MatchID AND MATCHLINEUPPLAYER.MATCHTYP=MATCHLINEUP.MATCHTYP) INNER JOIN MATCHDETAILS ON (MATCHDETAILS.MatchID=MATCHLINEUP.MatchID AND MATCHDETAILS.MATCHTYP=MATCHLINEUP.MATCHTYP) INNER JOIN MATCHESKURZINFO ON (MATCHESKURZINFO.MATCHID=MATCHLINEUP.MatchID AND MATCHESKURZINFO.MATCHTYP=MATCHLINEUP.MATCHTYP) WHERE MATCHLINEUPPLAYER.SpielerID=? AND MATCHLINEUPPLAYER.Rating>0"""; if(officialOnly){ var lMatchTypes = MatchType.fromSourceSystem(Objects.requireNonNull(SourceSystem.valueOf(SourceSystem.HATTRICK.getValue()))); var inValues = lMatchTypes.stream().map(p -> String.valueOf(p.getId())).collect(Collectors.joining(",")); sql += " AND MATCHTYP IN (" + inValues + ")"; } sql += " ORDER BY MATCHDETAILS.SpielDatum DESC"; // Get all data on the player try { final Vector<PlayerMatchCBItem> playerMatchCBItems = new Vector<>(); assert m_clJDBCAdapter != null; final ResultSet rs = m_clJDBCAdapter.executePreparedQuery(DBManager.instance().getPreparedStatement(sql), playerID); PlayerMatchCBItem playerMatchCBItem; assert rs != null; // Get all data on the player while (rs.next()) { playerMatchCBItem = new PlayerMatchCBItem(null, rs.getInt("MatchID"), (int)(rs.getFloat("Rating") * 2), rs.getInt("HoPosCode"), HODateTime.fromDbTimestamp(rs.getTimestamp("MatchDate")), rs.getString("HeimName"), rs.getInt("HeimID"), rs.getString("GastName"), rs.getInt("GastID"), MatchType.getById(rs.getInt("MatchTyp")), null, "", ""); playerMatchCBItems.add(playerMatchCBItem); } Timestamp filter; // Get the player data for the matches for (final PlayerMatchCBItem item : playerMatchCBItems) { filter = item.getMatchdate().toDbTimestamp(); // Player final Player player = getSpielerAtDate(playerID, filter); // Matchdetails final Matchdetails details = loadMatchDetails(item.getMatchType().getMatchTypeId(), item.getMatchID()); // Stimmung und Selbstvertrauen var team = getTeam(getHRFID4Date(filter)); final String[] sTSandConfidences = { TeamSpirit.toString(team.getTeamSpirit()), TeamConfidence.toString(team.getConfidence()) }; //Only if player data has been found, pass it into the return vector if (player != null && details != null) { item.setSpieler(player); item.setMatchdetails(details); item.setTeamSpirit(sTSandConfidences[0]); item.setConfidence(sTSandConfidences[1]); spielerMatchCBItems.add(item); } } } catch (Exception e) { HOLogger.instance().log(getClass(), "DatenbankZugriff.getSpieler4Matches : " + e); } return spielerMatchCBItems; } /** * Delete hrf. * * @param hrfid the hrfid */ public void deleteHRF(int hrfid) { getTable(StadionTable.TABLENAME).executePreparedDelete(hrfid); getTable(HRFTable.TABLENAME).executePreparedDelete(hrfid); getTable(LigaTable.TABLENAME).executePreparedDelete(hrfid); getTable(VereinTable.TABLENAME).executePreparedDelete(hrfid); getTable(TeamTable.TABLENAME).executePreparedDelete(hrfid); getTable(EconomyTable.TABLENAME).executePreparedDelete(hrfid); getTable(BasicsTable.TABLENAME).executePreparedDelete(hrfid); getTable(SpielerTable.TABLENAME).executePreparedDelete(hrfid); getTable(SpielerSkillupTable.TABLENAME).executePreparedDelete(hrfid); getTable(XtraDataTable.TABLENAME).executePreparedDelete(hrfid); getTable(StaffTable.TABLENAME).executePreparedDelete(hrfid); } /** * Deletes all data for the given match * * @param info MatchKurzInfo of the match to delete */ public void deleteMatch(MatchKurzInfo info) { var matchid = info.getMatchID(); var matchType = info.getMatchType().getId(); getTable(MatchDetailsTable.TABLENAME).executePreparedDelete(matchid, matchType); getTable(MatchHighlightsTable.TABLENAME).executePreparedDelete(matchid, matchType); getTable(MatchLineupTable.TABLENAME).executePreparedDelete(matchid, matchType); getTable(MatchLineupTeamTable.TABLENAME).executePreparedDelete(matchid, matchType, info.getHomeTeamID()); getTable(MatchLineupTeamTable.TABLENAME).executePreparedDelete(matchid, matchType, info.getGuestTeamID()); getTable(MatchLineupPlayerTable.TABLENAME).executePreparedDelete(matchid, matchType, info.getHomeTeamID()); getTable(MatchLineupPlayerTable.TABLENAME).executePreparedDelete(matchid, matchType, info.getGuestTeamID()); getTable(MatchesKurzInfoTable.TABLENAME).executePreparedDelete(matchid, matchType); getTable(MatchSubstitutionTable.TABLENAME).executePreparedDelete(matchid, matchType, info.getHomeTeamID()); getTable(MatchSubstitutionTable.TABLENAME).executePreparedDelete(matchid, matchType, info.getGuestTeamID()); } /** * Stores the given match info. If info is missing, or the info are not for * the same match, nothing is stored and false is returned. If the store is * successful, true is returned. * <p> * If status of the info is not FINISHED, nothing is stored, and false is * also returned. * * @param info The MatchKurzInfo for the match * @param details The MatchDetails for the match * @param lineup The MatchLineup for the match * @return true if the match is stored. False if not */ public boolean storeMatch(MatchKurzInfo info, Matchdetails details, MatchLineup lineup) { if ((info == null) || (details == null) || (lineup == null)) { return false; } if ((info.getMatchID() == details.getMatchID()) && (info.getMatchID() == lineup.getMatchID()) && (info.getMatchStatus() == MatchKurzInfo.FINISHED)) { //deleteMatch( info.getMatchID(), info.getMatchType().getId()); var matches = new ArrayList<MatchKurzInfo>(); matches.add(info); ((MatchesKurzInfoTable) getTable(MatchesKurzInfoTable.TABLENAME)) .storeMatchKurzInfos(matches); storeMatchDetails(details); storeMatchLineup(lineup, null); return true; } return false; } /** * Updates the given match in the database. * * @param match the match to update. */ public void updateMatchKurzInfo(MatchKurzInfo match) { ((MatchesKurzInfoTable) getTable(MatchesKurzInfoTable.TABLENAME)) .update(match); } private void createAllTables() throws SQLException { assert m_clJDBCAdapter != null; m_clJDBCAdapter.executeUpdate("SET FILES SPACE TRUE"); Object[] allTables = tables.values().toArray(); for (Object allTable : allTables) { AbstractTable table = (AbstractTable) allTable; HOLogger.instance().info(getClass(),"Create table : " + table.getTableName()); table.createTable(); String[] statements = table.getCreateIndexStatement(); for (String statement : statements) { m_clJDBCAdapter.executeUpdate(statement); } } } /** * Load module configs map. * * @return the map */ public Map<String, Object> loadModuleConfigs() { return ((ModuleConfigTable) getTable(ModuleConfigTable.TABLENAME)) .findAll(); } /** * Save module configs. * * @param values the values */ public void saveModuleConfigs(Map<String, Object> values) { ((ModuleConfigTable) getTable(ModuleConfigTable.TABLENAME)) .saveConfig(values); } /** * Delete module configs key. * * @param key the key */ public void deleteModuleConfigsKey(String key) { ((ModuleConfigTable) getTable(ModuleConfigTable.TABLENAME)) .deleteConfig(key); } /** * Set a single UserParameter in the DB * * @param fieldName the name of the parameter to set * @param value the target value */ void saveUserParameter(String fieldName, int value) { saveUserParameter(fieldName, String.valueOf(value)); } /** * Set a single UserParameter in the DB * * @param fieldName the name of the parameter to set * @param value the target value */ void saveUserParameter(String fieldName, double value) { saveUserParameter(fieldName, String.valueOf(value)); } /** * Set a single UserParameter in the DB * * @param fieldName the name of the parameter to set * @param value the target value */ void saveUserParameter(String fieldName, String value) { ((UserConfigurationTable) getTable(UserConfigurationTable.TABLENAME)) .storeConfiguration(fieldName, value); } /** * Save ho column model. * * @param model the model */ public void saveHOColumnModel(HOTableModel model) { ((UserColumnsTable) getTable(UserColumnsTable.TABLENAME)) .saveModel(model); } /** * Load ho colum model. * * @param model the model */ public void loadHOColumModel(HOTableModel model) { ((UserColumnsTable) getTable(UserColumnsTable.TABLENAME)) .loadModel(model); } /** * Remove ta favorite team. * * @param teamId the team id */ public void removeTAFavoriteTeam(int teamId) { ((TAFavoriteTable) getTable(TAFavoriteTable.TABLENAME)) .removeTeam(teamId); } /** * Add ta favorite team. * * @param team the team */ public void addTAFavoriteTeam(module.teamAnalyzer.vo.Team team) { ((TAFavoriteTable) getTable(TAFavoriteTable.TABLENAME)).addTeam(team); } /** * Is ta favourite boolean. * * @param teamId the team id * @return the boolean */ public boolean isTAFavourite(int teamId) { return ((TAFavoriteTable) getTable(TAFavoriteTable.TABLENAME)) .isTAFavourite(teamId); } /** * Returns all favourite teams * * @return List of Teams Object */ public List<module.teamAnalyzer.vo.Team> getTAFavoriteTeams() { return ((TAFavoriteTable) getTable(TAFavoriteTable.TABLENAME)) .getTAFavoriteTeams(); } /** * Gets ta player info. * * @param playerId the player id * @param week the week * @param season the season * @return the ta player info */ public PlayerInfo getTAPlayerInfo(int playerId, int week, int season) { return ((TAPlayerTable) getTable(TAPlayerTable.TABLENAME)) .getPlayerInfo(playerId, week, season); } /** * Gets ta latest player info. * * @param playerId the player id * @return the ta latest player info */ public PlayerInfo getTALatestPlayerInfo(int playerId) { return ((TAPlayerTable) getTable(TAPlayerTable.TABLENAME)) .getLatestPlayerInfo(playerId); } /** * Update ta player info. * * @param info the info */ public void storeTAPlayerInfo(PlayerInfo info) { ((TAPlayerTable) getTable(TAPlayerTable.TABLENAME)).storePlayer(info); } /** * Is ifa matchin db boolean. * * @param matchId the match id * @return the boolean */ public boolean isIFAMatchinDB(int matchId, int matchType) { return ((IfaMatchTable) getTable(IfaMatchTable.TABLENAME)) .isMatchInDB(matchId, matchType); } /** * Gets last ifa match date. * * @return the last ifa match date */ public Timestamp getLastIFAMatchDate() { return ((IfaMatchTable) getTable(IfaMatchTable.TABLENAME)) .getLastMatchDate(); } /** * Get ifa matches ifa match [ ]. * * @param home the home * @return the ifa match [ ] */ public IfaMatch[] getIFAMatches(boolean home) { return ((IfaMatchTable) getTable(IfaMatchTable.TABLENAME)) .getMatches(home); } /** * Insert ifa match. * * @param match the match */ public void insertIFAMatch(IfaMatch match) { ((IfaMatchTable) getTable(IfaMatchTable.TABLENAME)).insertMatch(match); } /** * Deletes all the content of the IFA match table. */ public void deleteIFAMatches() { ((IfaMatchTable) getTable(IfaMatchTable.TABLENAME)).deleteAllMatches(); } public static Timestamp getTimestamp(ResultSet rs, String columnLabel){ try { var ret = rs.getTimestamp(columnLabel); if (!rs.wasNull()) return ret; } catch (Exception ignored) { } return null; } public static String getString(ResultSet rs, String columnLabel){ try { var ret = rs.getString(columnLabel); if (!rs.wasNull()) return ret; } catch (Exception ignored) { } return ""; } /** * Gets integer. * * @param rs the rs * @param columnLabel the column label * @return the integer */ public static Integer getInteger(ResultSet rs, String columnLabel) { try { var ret = rs.getInt(columnLabel); if (rs.wasNull()) return null; return ret; } catch (Exception ignored) { } return null; } /** * Gets boolean. * * @param rs the rs * @param columnLabel the column label * @return the boolean */ public static Boolean getBoolean(ResultSet rs, String columnLabel) { try { var ret = rs.getBoolean(columnLabel); if (!rs.wasNull()) return ret; } catch (Exception ignored) { } return null; } public static boolean getBoolean(ResultSet rs, String columnLabel, boolean defaultValue) { var ret = getBoolean(rs,columnLabel); if ( ret != null) return ret; return defaultValue; } /** * Gets future player trainings. * * @param playerId the player id * @return the future player trainings */ public List<FuturePlayerTraining> getFuturePlayerTrainings(int playerId) { return ((FuturePlayerTrainingTable) getTable(FuturePlayerTrainingTable.TABLENAME)) .getFuturePlayerTrainingPlan(playerId); } /** * Store future player trainings. * * @param futurePlayerTrainings the future player trainings */ public void storeFuturePlayerTrainings(List<FuturePlayerTraining> futurePlayerTrainings) { ((FuturePlayerTrainingTable) getTable(FuturePlayerTrainingTable.TABLENAME)) .storeFuturePlayerTrainings(futurePlayerTrainings); } /** * Gets last youth match date. * * @return the last youth match date */ public Timestamp getLastYouthMatchDate() { return ((MatchDetailsTable) getTable(MatchDetailsTable.TABLENAME)) .getLastYouthMatchDate(); } /** * Get min scouting date timestamp. * * @return the timestamp */ public Timestamp getMinScoutingDate(){ return ((YouthPlayerTable) getTable(YouthPlayerTable.TABLENAME)) .loadMinScoutingDate(); } /** * Store match lineup. * * @param lineup the lineup * @param teamId the team id, if null both teams are stored */ public void storeMatchLineup(MatchLineup lineup, Integer teamId) { ((MatchLineupTable) getTable(MatchLineupTable.TABLENAME)).storeMatchLineup(lineup); if (teamId == null || teamId == lineup.getHomeTeamId()) { storeMatchLineupTeam(lineup.getHomeTeam()); } if (teamId == null || teamId == lineup.getGuestTeamId()) { storeMatchLineupTeam(lineup.getGuestTeam()); } } /** * Load youth trainer comments list. * * @param id the id * @return the list */ public List<YouthTrainerComment> loadYouthTrainerComments(int id) { return ((YouthTrainerCommentTable) getTable(YouthTrainerCommentTable.TABLENAME)).loadYouthTrainerComments(id); } public List<MatchLineup> getYouthMatchLineups() { return ((MatchLineupTable)getTable(MatchLineupTable.TABLENAME)).loadYouthMatchLineups(); } /** * Delete youth match data. * * @param before the before */ public void deleteYouthMatchDataBefore(Timestamp before){ if ( before != null) { ((MatchHighlightsTable) getTable(MatchHighlightsTable.TABLENAME)).deleteYouthMatchHighlightsBefore(before); ((MatchDetailsTable) getTable(MatchDetailsTable.TABLENAME)).deleteYouthMatchDetailsBefore(before); ((MatchLineupTable) getTable(MatchLineupTable.TABLENAME)).deleteYouthMatchLineupsBefore(before); } } /** * Load youth trainings list. * * @return the list */ public List<YouthTraining> loadYouthTrainings() { return ((YouthTrainingTable)getTable(YouthTrainingTable.TABLENAME)).loadYouthTrainings(); } /** * Store youth training. * * @param youthTraining the youth training */ public void storeYouthTraining(YouthTraining youthTraining) { ((YouthTrainingTable)getTable(YouthTrainingTable.TABLENAME)).storeYouthTraining(youthTraining); } /** * Store match details. * * @param details the details */ public void storeMatchDetails(Matchdetails details) { ((MatchDetailsTable)getTable(MatchDetailsTable.TABLENAME)).storeMatchDetails(details); //Store Match Events ((MatchHighlightsTable)getTable(MatchHighlightsTable.TABLENAME)).storeMatchHighlights(details); } /** * Gets team logo file name BUT it will triggers download of the logo from internet if it is not yet available. * It will also update LAST_ACCESS field * * @param teamID the team id * @return the team logo file name */ public TeamLogoInfo loadTeamLogoInfo(int teamID) { return ((TeamsLogoTable)getTable(TeamsLogoTable.TABLENAME)).loadTeamLogoInfo(teamID); } public void storeTeamLogoInfo(TeamLogoInfo info) { ((TeamsLogoTable)getTable(TeamsLogoTable.TABLENAME)).storeTeamLogoInfo(info); } /** * Store team logo info. * * @param teamID the team id * @param logoURL the logo url * @param lastAccess the last access */ public void storeTeamLogoInfo(int teamID, String logoURL, HODateTime lastAccess){ var info = new TeamLogoInfo(); info.setUrl(logoURL); info.setTeamId(teamID); info.setLastAccess(lastAccess); ((TeamsLogoTable)getTable(TeamsLogoTable.TABLENAME)).storeTeamLogoInfo(info); } public List<HRF> getHRFsSince(Timestamp since) { return ((HRFTable)getTable(HRFTable.TABLENAME)).getHRFsSince(since); } public List<Integer> loadHrfIdPerWeekList(int nWeeks) { return ((HRFTable)getTable(HRFTable.TABLENAME)).getHrfIdPerWeekList(nWeeks); } public void storeTeamRatings(MatchTeamRating teamrating) { ((MatchTeamRatingTable)getTable(MatchTeamRatingTable.TABLENAME)).storeTeamRating(teamrating); } public List<MatchTeamRating> loadMatchTeamRating( int matchtype, int matchId) { return ((MatchTeamRatingTable) getTable(MatchTeamRatingTable.TABLENAME)).load(matchId, matchtype); } // ------------------------------- MatchLineupTeamTable // ------------------------------------------------- public MatchLineupTeam loadMatchLineupTeam(int iMatchType, int matchID, int teamID) { var ret = ((MatchLineupTeamTable) getTable(MatchLineupTeamTable.TABLENAME)).loadMatchLineupTeam(iMatchType, matchID, teamID); if ( ret != null) { ret.loadLineup(); } return ret; } public MatchLineupTeam loadPreviousMatchLineup(int teamID) { return loadLineup(getLastMatchesKurzInfo(teamID), teamID);} public MatchLineupTeam loadNextMatchLineup(int teamID) { return loadLineup(getNextMatchesKurzInfo(teamID), teamID);} private MatchLineupTeam loadLineup(MatchKurzInfo match, int teamID) { if (match != null) { return loadMatchLineupTeam(match.getMatchType().getId(), match.getMatchID(), teamID); } return null; } public void storeMatchLineupTeam(MatchLineupTeam matchLineupTeam) { ((MatchLineupTeamTable)getTable(MatchLineupTeamTable.TABLENAME)).storeMatchLineupTeam(matchLineupTeam); //replace players var matchLineupPlayerTable = (MatchLineupPlayerTable) DBManager.instance().getTable(MatchLineupPlayerTable.TABLENAME); matchLineupPlayerTable.storeMatchLineupPlayers(matchLineupTeam.getLineup().getAllPositions(), matchLineupTeam.getMatchType(), matchLineupTeam.getMatchId(), matchLineupTeam.getTeamID()); // replace Substitutions var matchSubstitutionTable = (MatchSubstitutionTable) DBManager.instance().getTable(MatchSubstitutionTable.TABLENAME); matchSubstitutionTable.storeMatchSubstitutionsByMatchTeam(matchLineupTeam.getMatchType(), matchLineupTeam.getMatchId(), matchLineupTeam.getTeamID(), matchLineupTeam.getSubstitutions()); } public void deleteMatchLineupTeam(MatchLineupTeam matchLineupTeam) { ((MatchLineupTeamTable)getTable(MatchLineupTeamTable.TABLENAME)).deleteMatchLineupTeam(matchLineupTeam); } public List<MatchLineupTeam> loadTemplateMatchLineupTeams() { return ((MatchLineupTeamTable)getTable(MatchLineupTeamTable.TABLENAME)).getTemplateMatchLineupTeams(); } public int getTemplateMatchLineupTeamNextNumber() { return ((MatchLineupTeamTable)getTable(MatchLineupTeamTable.TABLENAME)).getTemplateMatchLineupTeamNextNumber(); } public NtTeamDetails loadNtTeamDetails(int teamId, Timestamp matchDate) { return ((NtTeamTable)getTable(NtTeamTable.TABLENAME)).loadNTTeam(teamId, matchDate); } public List<NtTeamDetails> loadAllNtTeamDetails() { return ((NtTeamTable)getTable(NtTeamTable.TABLENAME)).loadNTTeams(getLatestHRF().getHrfId()); } public void storeNtTeamDetails(NtTeamDetails details) { ((NtTeamTable)getTable(NtTeamTable.TABLENAME)).storeNTTeam(details); } private final String sql = "SELECT TRAININGDATE, TRAININGSART, TRAININGSINTENSITAET, STAMINATRAININGPART, COTRAINER, TRAINER" + " FROM XTRADATA INNER JOIN TEAM on XTRADATA.HRF_ID = TEAM.HRF_ID" + " INNER JOIN VEREIN on XTRADATA.HRF_ID = VEREIN.HRF_ID" + " INNER JOIN SPIELER on XTRADATA.HRF_ID = SPIELER.HRF_ID AND SPIELER.TRAINER > 0" + " INNER JOIN (SELECT TRAININGDATE, %s(HRF_ID) J_HRF_ID FROM XTRADATA GROUP BY TRAININGDATE) IJ1 ON XTRADATA.HRF_ID = IJ1.J_HRF_ID" + " WHERE XTRADATA.TRAININGDATE >= ?"; private final PreparedStatementBuilder loadTrainingPerWeekMaxStatement = new PreparedStatementBuilder(String.format(sql, "max")); private final PreparedStatementBuilder loadTrainingPerWeekMinStatement = new PreparedStatementBuilder(String.format(sql, "min")); public List<TrainingPerWeek> loadTrainingPerWeek(Timestamp startDate, boolean all) { var ret = new ArrayList<TrainingPerWeek>(); try { assert m_clJDBCAdapter != null; final ResultSet rs = m_clJDBCAdapter.executePreparedQuery( all?loadTrainingPerWeekMaxStatement.getStatement():loadTrainingPerWeekMinStatement.getStatement(), startDate); if ( rs != null ) { while (rs.next()) { int trainType = rs.getInt("TRAININGSART"); int trainIntensity = rs.getInt("TRAININGSINTENSITAET"); int trainStaminaPart = rs.getInt("STAMINATRAININGPART"); // subtract one week from next training date to get the past week training date var nextTrainingDate = HODateTime.fromDbTimestamp(rs.getTimestamp("TRAININGDATE")); var trainingDate = nextTrainingDate.plusDaysAtSameLocalTime(-7); int coachLevel = rs.getInt("TRAINER"); int trainingAssistantLevel = rs.getInt("COTRAINER"); TrainingPerWeek tpw = new TrainingPerWeek(trainingDate, trainType, trainIntensity, trainStaminaPart, trainingAssistantLevel, coachLevel, DBDataSource.HRF); ret.add( tpw); } } return ret; } catch (Exception e) { HOLogger.instance().error(this.getClass(), "Error while performing loadTrainingPerWeek(): " + e); } return null; } public List<MatchKurzInfo> getMatchesKurzInfo(int teamId, int status, Timestamp from, List<Integer> matchTypes) { return ((MatchesKurzInfoTable)getTable(MatchesKurzInfoTable.TABLENAME)).getMatchesKurzInfo(teamId, status, from, matchTypes); } private static final DBManager.PreparedStatementBuilder preStatementBuilder = new DBManager.PreparedStatementBuilder( "select marktwert from SPIELER where spielerid=? and verletzt=-1 order by DATUM desc"); private static final DBManager.PreparedStatementBuilder postStatementBuilder = new DBManager.PreparedStatementBuilder( "select marktwert from SPIELER where spielerid=? and verletzt>-1 order by DATUM desc"); public String loadLatestTSINotInjured(int m_iSpielerID) { return loadLatestTSI(preStatementBuilder, m_iSpielerID); } public String loadLatestTSIInjured(int m_iSpielerID) { return loadLatestTSI(postStatementBuilder, m_iSpielerID); } private String loadLatestTSI(DBManager.PreparedStatementBuilder preparedStatementBuilder, int m_iSpielerID) { try { ResultSet rs = Objects.requireNonNull(this.getAdapter()).executePreparedQuery(preparedStatementBuilder.getStatement(), m_iSpielerID); if (rs.next()) { return rs.getString("marktwert"); } } catch (Exception ignored) { } return ""; } public static String getPlaceholders(int count){ return String.join(",", Collections.nCopies(count, "?")); } public void storeSquadInfo(SquadInfo squadInfo) { ((SquadInfoTable)getTable(SquadInfoTable.TABLENAME)).storeSquadInfo(squadInfo); } public List<SquadInfo> loadSquadInfo(int teamId) { return ((SquadInfoTable)getTable(SquadInfoTable.TABLENAME)).loadSquadInfo(teamId); } public static class PreparedStatementBuilder{ private final String sql; public PreparedStatementBuilder(String sql){ this.sql=sql; } private PreparedStatement statement; public PreparedStatement getStatement() { if (statement == null) { statement = Objects.requireNonNull(DBManager.instance().getAdapter()).createPreparedStatement(sql); } return statement; } } }
ddusann/HO
src/main/java/core/db/DBManager.java
46,004
/* * MegaMek - Copyright (C) 2005 Ben Mazur ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. */ package megamek.client.ratgenerator; import megamek.common.*; import org.apache.logging.log4j.LogManager; import java.util.ArrayList; import java.util.EnumSet; import java.util.Set; /** * Specific unit variants; analyzes equipment to determine suitability for certain types * of missions in addition to what is formally declared in the data files. * * @author Neoancient */ public class ModelRecord extends AbstractUnitRecord { public static final int NETWORK_NONE = 0; public static final int NETWORK_C3_SLAVE = 1; public static final int NETWORK_BA_C3 = 1; public static final int NETWORK_C3_MASTER = 1 << 1; public static final int NETWORK_C3I = 1 << 2; public static final int NETWORK_NAVAL_C3 = 1 << 2; public static final int NETWORK_NOVA = 1 << 3; public static final int NETWORK_BOOSTED = 1 << 4; public static final int NETWORK_COMPANY_COMMAND = 1 << 5; public static final int NETWORK_BOOSTED_SLAVE = NETWORK_C3_SLAVE | NETWORK_BOOSTED; public static final int NETWORK_BOOSTED_MASTER = NETWORK_C3_MASTER | NETWORK_BOOSTED; private MechSummary mechSummary; private boolean starLeague; private int weightClass; private EntityMovementMode movementMode; private EnumSet<MissionRole> roles; private ArrayList<String> deployedWith; private ArrayList<String> requiredUnits; private ArrayList<String> excludedFactions; private int networkMask; private double flak; //proportion of weapon BV that can fire flak ammo private double longRange; //proportion of weapon BV with range >= 20 hexes private int speed; private double ammoRequirement; //used to determine suitability for raider role private boolean incendiary; //used to determine suitability for incindiary role private boolean apWeapons; //used to determine suitability for anti-infantry role private boolean mechanizedBA; private boolean magClamp; public ModelRecord(String chassis, String model) { super(chassis); roles = EnumSet.noneOf(MissionRole.class); deployedWith = new ArrayList<>(); requiredUnits = new ArrayList<>(); excludedFactions = new ArrayList<>(); networkMask = NETWORK_NONE; flak = 0.0; longRange = 0.0; } public ModelRecord(MechSummary ms) { this(ms.getChassis(), ms.getModel()); mechSummary = ms; unitType = parseUnitType(ms.getUnitType()); introYear = ms.getYear(); if (unitType == UnitType.MEK) { //TODO: id quads and tripods movementMode = EntityMovementMode.BIPED; omni = ms.getUnitSubType().equals("Omni"); } else { movementMode = EntityMovementMode.parseFromString(ms.getUnitSubType().toLowerCase()); } double totalBV = 0.0; double flakBV = 0.0; double lrBV = 0.0; double ammoBV = 0.0; boolean losTech = false; for (int i = 0; i < ms.getEquipmentNames().size(); i++) { //EquipmentType.get is throwing an NPE intermittently, and the only possibility I can see //is that there is a null equipment name. if (null == ms.getEquipmentNames().get(i)) { LogManager.getLogger().error( "RATGenerator ModelRecord encountered null equipment name in MechSummary for " + ms.getName() + ", index " + i); continue; } EquipmentType eq = EquipmentType.get(ms.getEquipmentNames().get(i)); if (eq == null) { continue; } if (!eq.isAvailableIn(3000)) { //FIXME: needs to filter out primitive losTech = true; } if (eq instanceof WeaponType) { totalBV += eq.getBV(null) * ms.getEquipmentQuantities().get(i); switch (((megamek.common.weapons.Weapon) eq).getAmmoType()) { case AmmoType.T_AC_LBX: case AmmoType.T_HAG: case AmmoType.T_SBGAUSS: flakBV += eq.getBV(null) * ms.getEquipmentQuantities().get(i); } if (eq.hasFlag(WeaponType.F_ARTILLERY)) { flakBV += eq.getBV(null) * ms.getEquipmentQuantities().get(i) / 2.0; roles.add(((WeaponType) eq).getAmmoType() == AmmoType.T_ARROW_IV? MissionRole.MISSILE_ARTILLERY : MissionRole.ARTILLERY); } if (eq.hasFlag(WeaponType.F_FLAMER) || eq.hasFlag(WeaponType.F_INFERNO)) { incendiary = true; apWeapons = true; } incendiary |= ((WeaponType) eq).getAmmoType() == AmmoType.T_SRM || ((WeaponType) eq).getAmmoType() == AmmoType.T_SRM_IMP || ((WeaponType) eq).getAmmoType() == AmmoType.T_MRM; if (eq instanceof megamek.common.weapons.mgs.MGWeapon || eq instanceof megamek.common.weapons.defensivepods.BPodWeapon) { apWeapons = true; } if (((WeaponType) eq).getAmmoType() > megamek.common.AmmoType.T_NA) { ammoBV += eq.getBV(null) * ms.getEquipmentQuantities().get(i); } if (((WeaponType) eq).getLongRange() >= 20) { lrBV += eq.getBV(null) * ms.getEquipmentQuantities().get(i); } if (eq.hasFlag(WeaponType.F_TAG)) { roles.add(MissionRole.SPOTTER); } if (eq.hasFlag(WeaponType.F_C3M)) { networkMask |= NETWORK_C3_MASTER; if (ms.getEquipmentQuantities().get(i) > 1) { networkMask |= NETWORK_COMPANY_COMMAND; } } if (eq.hasFlag(WeaponType.F_C3MBS)) { networkMask |= NETWORK_BOOSTED_MASTER; if (ms.getEquipmentQuantities().get(i) > 1) { networkMask |= NETWORK_COMPANY_COMMAND; } } } else if (eq instanceof MiscType) { if (eq.hasFlag(MiscType.F_UMU)) { movementMode = EntityMovementMode.BIPED_SWIM; } else if (eq.hasFlag(MiscType.F_C3S)) { networkMask |= NETWORK_C3_SLAVE; } else if (eq.hasFlag(MiscType.F_C3I)) { networkMask |= NETWORK_C3I; } else if (eq.hasFlag(MiscType.F_C3SBS)) { networkMask |= NETWORK_BOOSTED_SLAVE; } else if (eq.hasFlag(MiscType.F_NOVA)) { networkMask |= NETWORK_NOVA; } else if (eq.hasFlag(MiscType.F_MAGNETIC_CLAMP)) { magClamp = true; } } } if (totalBV > 0 && (ms.getUnitType().equals("Mek") || ms.getUnitType().equals("Tank") || ms.getUnitType().equals("BattleArmor") || ms.getUnitType().equals("Infantry") || ms.getUnitType().equals("ProtoMek") || ms.getUnitType().equals("Naval") || ms.getUnitType().equals("Gun Emplacement"))) { flak = flakBV / totalBV; longRange = lrBV / totalBV; ammoRequirement = ammoBV / totalBV; } weightClass = ms.getWeightClass(); if (weightClass >= EntityWeightClass.WEIGHT_SMALL_SUPPORT) { if (ms.getTons() <= 39) { weightClass = EntityWeightClass.WEIGHT_LIGHT; } else if (ms.getTons() <= 59) { weightClass = EntityWeightClass.WEIGHT_MEDIUM; } else if (ms.getTons() <= 79) { weightClass = EntityWeightClass.WEIGHT_HEAVY; } else if (ms.getTons() <= 100) { weightClass = EntityWeightClass.WEIGHT_ASSAULT; } else { weightClass = EntityWeightClass.WEIGHT_COLOSSAL; } } clan = ms.isClan(); if (megamek.common.Engine.getEngineTypeByString(ms.getEngineName()) == megamek.common.Engine.XL_ENGINE || ms.getArmorType().contains(EquipmentType.T_ARMOR_FERRO_FIBROUS) || ms.getInternalsType() == EquipmentType.T_STRUCTURE_ENDO_STEEL) { losTech = true; } starLeague = losTech && !clan; speed = ms.getWalkMp(); if (ms.getJumpMp() > 0) { speed++; } } public String getModel() { return mechSummary.getModel(); } public int getWeightClass() { return weightClass; } public EntityMovementMode getMovementMode() { return movementMode; } @Override public boolean isClan() { return clan; } public boolean isSL() { return starLeague; } public Set<MissionRole> getRoles() { return roles; } public ArrayList<String> getDeployedWith() { return deployedWith; } public ArrayList<String> getRequiredUnits() { return requiredUnits; } public ArrayList<String> getExcludedFactions() { return excludedFactions; } public int getNetworkMask() { return networkMask; } public void setNetwork(int network) { this.networkMask = network; } public double getFlak() { return flak; } public void setFlak(double flak) { this.flak = flak; } public double getLongRange() { return longRange; } public int getSpeed() { return speed; } public double getAmmoRequirement() { return ammoRequirement; } public boolean hasIncendiaryWeapon() { return incendiary; } public boolean hasAPWeapons() { return apWeapons; } public MechSummary getMechSummary() { return mechSummary; } public void addRoles(String str) { if (str.isBlank()) { roles.clear(); } else { String[] fields = str.split(","); for (String role : fields) { MissionRole mr = MissionRole.parseRole(role); if (mr != null) { roles.add(mr); } else { LogManager.getLogger().error("Could not parse mission role for " + getChassis() + " " + getModel() + ": " + role); } } } } public void setRequiredUnits(String str) { String[] subfields = str.split(","); for (String unit : subfields) { if (unit.startsWith("req:")) { requiredUnits.add(unit.replace("req:", "")); } else { deployedWith.add(unit); } } } public void setExcludedFactions(String str) { excludedFactions.clear(); String[] fields = str.split(","); for (String faction : fields) { excludedFactions.add(faction); } } public boolean factionIsExcluded(FactionRecord fRec) { return excludedFactions.contains(fRec.getKey()); } public boolean factionIsExcluded(String faction, String subfaction) { if (subfaction == null) { return excludedFactions.contains(faction); } else { return excludedFactions.contains(faction + "." + subfaction); } } @Override public String getKey() { return mechSummary.getName(); } public boolean canDoMechanizedBA() { return mechanizedBA; } public void setMechanizedBA(boolean mech) { mechanizedBA = mech; } public boolean hasMagClamp() { return magClamp; } public void setMagClamp(boolean magClamp) { this.magClamp = magClamp; } }
Narjes-b/megamek
megamek/src/megamek/client/ratgenerator/ModelRecord.java
46,005
package data.hl; /** * This class sets attributes given by the humanoid-league rules. * * @author Michel-Zen */ public class HLDropIn extends HL { public HLDropIn() { /** The league´s directory name with it´s teams and icons. */ leagueDirectory = "hl_dropin"; /** If true, the drop-in player competition is active */ dropInPlayerMode = true; } }
Rhoban/GameController
src/data/hl/HLDropIn.java
46,006
package data.hl; /** * This class sets attributes given by the humanoid-league rules. * * @author Michel-Zen */ public class HLDropIn4 extends HLDropIn { public HLDropIn4() { leagueName = "HL Drop In (4)"; robotsPlaying = 4; teamSize = 4; } }
Rhoban/GameController
src/data/hl/HLDropIn4.java
46,007
package net.datafaker.providers.videogame; import net.datafaker.providers.base.AbstractProvider; /** * Esports, short for electronic sports, is a form of competition using video games. * * @since 0.8.0 */ public class Esports extends AbstractProvider<VideoGameProviders> { protected Esports(final VideoGameProviders faker) { super(faker); } public String player() { return resolve("esport.players"); } public String team() { return resolve("esport.teams"); } public String event() { return resolve("esport.events"); } public String league() { return resolve("esport.leagues"); } public String game() { return resolve("esport.games"); } }
datafaker-net/datafaker
src/main/java/net/datafaker/providers/videogame/Esports.java
46,008
package com.mooveit.fakeit.models; import android.databinding.BaseObservable; import android.databinding.ObservableField; public class ESportData extends BaseObservable { public final ObservableField<String> player = new ObservableField<>(); public final ObservableField<String> team = new ObservableField<>(); public final ObservableField<String> league = new ObservableField<>(); public final ObservableField<String> event = new ObservableField<>(); public final ObservableField<String> game = new ObservableField<>(); }
vaginessa/fakeit
sample/src/main/java/com/mooveit/fakeit/models/ESportData.java
46,009
/* * AtBScenario.java * * Copyright (C) 2014-2021 - The MegaMek Team. All Rights Reserved. * Copyright (c) 2014 Carl Spain. All rights reserved. * * This file is part of MekHQ. * * MekHQ is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MekHQ is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MekHQ. If not, see <http://www.gnu.org/licenses/>. */ package mekhq.campaign.mission; import megamek.Version; import megamek.codeUtilities.ObjectUtility; import megamek.common.*; import megamek.common.annotations.Nullable; import megamek.common.EntityWeightClass; import megamek.common.enums.*; import megamek.common.planetaryconditions.*; import megamek.common.icons.Camouflage; import megamek.common.options.OptionsConstants; import megamek.common.planetaryconditions.Atmosphere; import mekhq.MHQConstants; import mekhq.MekHQ; import mekhq.Utilities; import mekhq.campaign.Campaign; import mekhq.campaign.againstTheBot.AtBConfiguration; import mekhq.campaign.againstTheBot.AtBStaticWeightGenerator; import mekhq.campaign.force.Force; import mekhq.campaign.force.Lance; import mekhq.campaign.mission.ObjectiveEffect.ObjectiveEffectType; import mekhq.campaign.mission.ScenarioObjective.ObjectiveCriterion; import mekhq.campaign.mission.atb.IAtBScenario; import mekhq.campaign.mission.enums.AtBLanceRole; import mekhq.campaign.personnel.SkillType; import mekhq.campaign.rating.IUnitRating; import mekhq.campaign.stratcon.StratconBiomeManifest; import mekhq.campaign.unit.Unit; import mekhq.campaign.universe.*; import mekhq.utilities.MHQXMLUtility; import org.apache.logging.log4j.LogManager; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.io.PrintWriter; import java.text.ParseException; import java.time.LocalDate; import java.util.*; import java.util.stream.Collectors; /** * @author Neoancient */ public abstract class AtBScenario extends Scenario implements IAtBScenario { //region Variable Declarations public static final int DYNAMIC = -1; public static final int BASEATTACK = 0; public static final int EXTRACTION = 1; public static final int CHASE = 2; public static final int HOLDTHELINE = 3; public static final int BREAKTHROUGH = 4; public static final int HIDEANDSEEK = 5; public static final int STANDUP = 6; public static final int RECONRAID = 7; public static final int PROBE = 8; public static final int OFFICERDUEL = 9; // Special Scenario public static final int ACEDUEL = 10; // Special Scenario public static final int AMBUSH = 11; // Special Scenario public static final int CIVILIANHELP = 12; // Special Scenario public static final int ALLIEDTRAITORS = 13; // Special Scenario public static final int PRISONBREAK = 14; // Special Scenario public static final int STARLEAGUECACHE1 = 15; // Special Scenario public static final int STARLEAGUECACHE2 = 16; // Special Scenario public static final int ALLYRESCUE = 17; // Big Battle public static final int CIVILIANRIOT = 18; // Big Battle public static final int CONVOYRESCUE = 19; // Big Battle public static final int CONVOYATTACK = 20; // Big Battle public static final int PIRATEFREEFORALL = 21; // Big Battle public static final int FORCE_MEK = 0; public static final int FORCE_VEHICLE = 1; public static final int FORCE_MIXED = 2; public static final int FORCE_NOVA = 3; public static final int FORCE_VEENOVA = 4; public static final int FORCE_INFANTRY = 5; public static final int FORCE_BA = 6; public static final int FORCE_AERO = 7; public static final int FORCE_PROTOMEK = 8; public static final String[] forceTypeNames = { "Mek", "Vehicle", "Mixed", "Nova", "Nova", "Infantry", "Battle Armor", "Aerospace", "ProtoMek" }; public static final String[] antiRiotWeapons = { "ISERSmallLaser", "Small Laser", "Small Laser Prototype", "ISSmallPulseLaser", "ISSmallXPulseLaser", "Small Re-engineered Laser", "ISSmallVSPLaser", "CLERMicroLaser", "CLERSmallLaser", "ER Small Laser (CP)", "CLHeavySmallLaser", "CLImprovedSmallHeavyLaser", "ClSmall Laser", "CLERSmallPulseLaser", "CLMicroPulseLaser", "CLSmallPulseLaser", "CLSmallChemLaser", "Heavy Machine Gun", "Light Machine Gun", "Machine Gun", "Heavy Rifle", "Light Rifle", "Medium Rifle", "CLHeavyMG", "CLLightMG", "CLMG", "Flamer", "ER Flamer", "CLFlamer", "CLERFlamer", "Vehicle Flamer", "Heavy Flamer", "CLVehicleFlamer", "CLHeavyFlamer" }; /* The starting position chart in the AtB rules includes the four * corner positions as well, but this creates some conflict with * setting the home edge for the bot, which only includes the four * sides. */ protected static final int [] startPos = { Board.START_N, Board.START_E, Board.START_S, Board.START_W }; private static final int[] randomAeroWeights = { EntityWeightClass.WEIGHT_LIGHT, EntityWeightClass.WEIGHT_LIGHT, EntityWeightClass.WEIGHT_LIGHT, EntityWeightClass.WEIGHT_MEDIUM, EntityWeightClass.WEIGHT_MEDIUM, EntityWeightClass.WEIGHT_HEAVY }; public static final int NO_LANCE = -1; private boolean attacker; private int lanceForceId; // -1 if scenario is not generated for a specific lance (special scenario, big battle) private AtBLanceRole lanceRole; /* set when scenario is created in case it is changed for the next week before the scenario is resolved; specifically affects scenarios generated for scout lances, in which the deployment may be delayed for slower units */ private int deploymentDelay; private int lanceCount; private int rerollsRemaining; private int enemyHome; private List<Entity> alliesPlayer; private List<String> alliesPlayerStub; /** * Special Scenarios cannot generate the enemy until the unit is added, but needs the Campaign * object which is not passed by addForce or addUnit. Instead we generate all possibilities * (one for each weight class) when the scenario is created and choose the correct one when a * unit is deployed. */ private List<List<Entity>> specialScenarioEnemies; /* Big battles have a similar problem for attached allies. Though * we could generate the maximum number (4) and remove them as * the player deploys additional units, they would be lost if * any units are undeployed. */ private List<Entity> bigBattleAllies; /* Units that need to be tracked for possible contract breaches * (for destruction), or bonus rolls (for survival). */ private List<UUID> attachedUnitIds; private List<UUID> survivalBonus; private Map<UUID, Entity> entityIds; // key-value pairs linking transports and the units loaded onto them. private Map<String, List<String>> transportLinkages; private Map<Integer, Integer> numPlayerMinefields; private String terrainType; protected final transient ResourceBundle defaultResourceBundle = ResourceBundle.getBundle("mekhq.resources.AtBScenarioBuiltIn", MekHQ.getMHQOptions().getLocale()); private static TerrainConditionsOddsManifest TCO; private static StratconBiomeManifest SB; private int modifiedTemperature; //endregion Variable Declarations public AtBScenario () { super(); lanceForceId = -1; lanceRole = AtBLanceRole.UNASSIGNED; alliesPlayer = new ArrayList<>(); alliesPlayerStub = new ArrayList<>(); attachedUnitIds = new ArrayList<>(); survivalBonus = new ArrayList<>(); entityIds = new HashMap<>(); transportLinkages = new HashMap<>(); numPlayerMinefields = new HashMap<>(); deploymentDelay = 0; lanceCount = 0; rerollsRemaining = 0; TCO = TerrainConditionsOddsManifest.getInstance(); SB = StratconBiomeManifest.getInstance(); } public void initialize(Campaign c, Lance lance, boolean attacker, LocalDate date) { setAttacker(attacker); alliesPlayer = new ArrayList<>(); botForces = new ArrayList<>(); alliesPlayerStub = new ArrayList<>(); botForcesStubs = new ArrayList<>(); attachedUnitIds = new ArrayList<>(); survivalBonus = new ArrayList<>(); entityIds = new HashMap<>(); if (null == lance) { lanceForceId = -1; lanceRole = AtBLanceRole.UNASSIGNED; } else { this.lanceForceId = lance.getForceId(); lanceRole = lance.getRole(); setMissionId(lance.getMissionId()); for (UUID id : c.getForce(lance.getForceId()).getAllUnits(true)) { entityIds.put(id, c.getUnit(id).getEntity()); } } light = Light.DAY; weather = Weather.CLEAR; wind = Wind.CALM; fog = Fog.FOG_NONE; atmosphere = Atmosphere.STANDARD; gravity = (float) 1.0; deploymentDelay = 0; setDate(date); lanceCount = 0; rerollsRemaining = 0; if (isStandardScenario()) { setName(getScenarioTypeDescription() + (isAttacker() ? " (Attacker)" : " (Defender)")); } else { setName(getScenarioTypeDescription()); } initBattle(c); } public String getDesc() { return getScenarioTypeDescription() + (isStandardScenario() ? (isAttacker() ? " (Attacker)" : " (Defender)") : ""); } public String getTerrainType() { return terrainType; } public void setTerrainType(String terrainType) { this.terrainType = terrainType; } @Override public boolean isStandardScenario() { return !isSpecialScenario() && !isBigBattle(); } @Override public boolean isSpecialScenario() { return false; } @Override public boolean isBigBattle() { return false; } @Override public ResourceBundle getResourceBundle() { return defaultResourceBundle; } /** * Determines battle conditions: terrain, weather, map. * * @param campaign */ private void initBattle(Campaign campaign) { setTerrain(); if (campaign.getCampaignOptions().isUsePlanetaryConditions() && null != campaign.getMission(getMissionId())) { setPlanetaryConditions(campaign.getMission(getMissionId()), campaign); } if (campaign.getCampaignOptions().isUseLightConditions()) { setLightConditions(); } if (campaign.getCampaignOptions().isUseWeatherConditions()) { setWeatherConditions(); } setMapSize(); setMapFile(); if (isStandardScenario()) { lanceCount = 1; } else if (isBigBattle()) { lanceCount = 2; } if (null != getLance(campaign)) { getLance(campaign).refreshCommander(campaign); if (null != getLance(campaign).getCommander(campaign).getSkill(SkillType.S_TACTICS)) { rerollsRemaining = getLance(campaign).getCommander(campaign).getSkill(SkillType.S_TACTICS).getLevel(); } } } public int getModifiedTemperature() { return modifiedTemperature; } public void setModifiedTemperature(int modifiedTemperature) { this.modifiedTemperature = modifiedTemperature; } public void setTerrain() { Map<String, StratconBiomeManifest.MapTypeList> mapTypes = SB.getBiomeMapTypes(); List<String> keys = mapTypes.keySet().stream().sorted().collect(Collectors.toList()); setTerrainType(keys.get(Compute.randomInt(keys.size()))); } public void setLightConditions() { setLight(TCO.rollLightCondition(getTerrainType())); } public void setWeatherConditions() { // weather is irrelevant in these situations. if (getBoardType() == AtBScenario.T_SPACE || getBoardType() == AtBScenario.T_ATMOSPHERE) { return; } Wind wind = TCO.rollWindCondition(getTerrainType()); if (WeatherRestriction.IsWindRestricted(wind.ordinal(), getAtmosphere().ordinal(), getTemperature())) { wind = Wind.CALM; } Weather weather = TCO.rollWeatherCondition(getTerrainType()); if (WeatherRestriction.IsWeatherRestricted(weather.ordinal(), getAtmosphere().ordinal(), getTemperature())) { weather = Weather.CLEAR; } Fog fog = TCO.rollFogCondition(getTerrainType()); if (WeatherRestriction.IsFogRestricted(fog.ordinal(), getAtmosphere().ordinal(), getTemperature())) { fog = Fog.FOG_NONE; } BlowingSand blowingSand = TCO.rollBlowingSandCondition(getTerrainType()); if (getAtmosphere().isLighterThan(Atmosphere.TRACE)) { blowingSand = BlowingSand.BLOWING_SAND_NONE; } EMI emi = TCO.rollEMICondition(getTerrainType()); int temp = getTemperature(); temp = PlanetaryConditions.setTempFromWeather(weather, temp); wind = PlanetaryConditions.setWindFromWeather(weather, wind); wind = PlanetaryConditions.setWindFromBlowingSand(blowingSand, wind); setModifiedTemperature(temp); setWind(wind); setWeather(weather); setFog(fog); setBlowingSand(blowingSand); setEMI(emi); } public void setPlanetaryConditions(Mission mission, Campaign campaign) { if (null != mission) { PlanetarySystem psystem = Systems.getInstance().getSystemById(mission.getSystemId()); //assume primary planet for now Planet p = psystem.getPrimaryPlanet(); if (null != p) { setAtmosphere(Atmosphere.getAtmosphere(ObjectUtility.nonNull(p.getPressure(campaign.getLocalDate()), getAtmosphere().ordinal()))); setGravity(ObjectUtility.nonNull(p.getGravity(), getGravity()).floatValue()); } } } public void setMapSize() { int roll = Compute.randomInt(20) + 1; if (roll < 6) { setMapSizeX(20); setMapSizeY(10); } else if (roll < 11) { setMapSizeX(10); setMapSizeY(20); } else if (roll < 13) { setMapSizeX(30); setMapSizeY(10); } else if (roll < 15) { setMapSizeX(10); setMapSizeY(30); } else if (roll < 19) { setMapSizeX(20); setMapSizeY(20); } else if (roll == 19) { setMapSizeX(40); setMapSizeY(10); } else { setMapSizeX(10); setMapSizeY(40); } } public int getMapX() { int base = getMapSizeX() + 5 * lanceCount; return Math.max(base, 20); } public int getMapY() { int base = getMapSizeY() + 5 * lanceCount; return Math.max(base, 20); } public int getBaseMapX() { return (5 * getLanceCount()) + getMapSizeX(); } public int getBaseMapY() { return (5 * getLanceCount()) + getMapSizeY(); } public void setMapFile(String terrainType) { if (terrainType.equals("Space")) { setMap("Space"); } else { Map<String, StratconBiomeManifest.MapTypeList> mapTypes = SB.getBiomeMapTypes(); StratconBiomeManifest.MapTypeList value = mapTypes.get(terrainType); if (value != null) { List<String> mapTypeList = value.mapTypes; setMap(mapTypeList.get(Compute.randomInt(mapTypeList.size()))); } else { setMap("Savannah"); } } } public void setMapFile() { setMapFile(getTerrainType()); } public boolean canRerollTerrain() { return canRerollMap(); } public boolean canRerollMapSize() { return true; } public boolean canRerollMap() { return true; } public boolean canRerollLight() { return true; } public boolean canRerollWeather() { return true; } /** * Determines whether a unit is eligible to deploy to the scenario. The * default is true, but some special scenarios and big battles restrict * the participants. * * @param unit * @param campaign * @return true if the unit is eligible, otherwise false */ @Override public boolean canDeploy(Unit unit, Campaign campaign) { if (isBigBattle() && (getForces(campaign).getAllUnits(true).size() > 7)) { return false; } else { return !isSpecialScenario() || (getForces(campaign).getAllUnits(true).size() <= 0); } } /** * Determines whether a force is eligible to deploy to a scenario by * checking all units contained in the force * * @param force * @param campaign * @return true if the force is eligible to deploy, otherwise false */ public boolean canDeploy(Force force, Campaign campaign) { Vector<UUID> units = force.getAllUnits(true); if (isBigBattle() && getForces(campaign).getAllUnits(true).size() + units.size() > 8) { return false; } else if (isSpecialScenario() && getForces(campaign).getAllUnits(true).size() + units.size() > 0) { return false; } for (UUID id : units) { if (!canDeploy(campaign.getUnit(id), campaign)) { return false; } } return true; } /** * Determines whether a list of units is eligible to deploy to the scenario. * * @param units - a Vector made up of Units to be deployed * @param campaign - a pointer to the Campaign * @return true if all units in the list are eligible, otherwise false */ @Override public boolean canDeployUnits(Vector<Unit> units, Campaign campaign) { if (isBigBattle()) { return getForces(campaign).getAllUnits(true).size() + units.size() <= 8; } else if (isSpecialScenario()) { return getForces(campaign).getAllUnits(true).size() + units.size() <= 1; } else { return units.stream().allMatch(unit -> canDeploy(unit, campaign)); } } /** * Determines whether a list of forces is eligible to deploy to the scenario. * * @param forces list of forces * @param c the campaign that the forces are part of * @return true if all units in all forces in the list are eligible, otherwise false */ @Override public boolean canDeployForces(Vector<Force> forces, Campaign c) { int total = 0; for (Force force : forces) { Vector<UUID> units = force.getAllUnits(true); total += units.size(); if (isBigBattle()) { return getForces(c).getAllUnits(true).size() + units.size() <= 8; } else if (isSpecialScenario()) { return getForces(c).getAllUnits(true).size() + units.size() <= 0; } for (UUID id : units) { if (!canDeploy(c.getUnit(id), c)) { return false; } } } if (isBigBattle()) { return getForces(c).getAllUnits(true).size() + total <= 8; } else if (isSpecialScenario()) { return getForces(c).getAllUnits(true).size() + total <= 0; } return true; } /** * Corrects the enemy (special scenarios) and allies (big battles) * as necessary based on player deployments. This ought to be called * when the scenario details are displayed or the scenario is started. * * @param campaign */ public void refresh(Campaign campaign) { if (isStandardScenario()) { setObjectives(campaign, getContract(campaign)); return; } Vector<UUID> deployed = getForces(campaign).getAllUnits(true); if (isBigBattle()) { int numAllies = Math.min(4, 8 - deployed.size()); alliesPlayer.clear(); for (int i = 0; i < numAllies; i++) { alliesPlayer.add(bigBattleAllies.get(i)); getExternalIDLookup().put(bigBattleAllies.get(i).getExternalIdAsString(), bigBattleAllies.get(i)); } setObjectives(campaign, getContract(campaign)); } else { if (deployed.isEmpty()) { return; } int weight = campaign.getUnit(deployed.get(0)).getEntity().getWeightClass(); /* In the event that Star League Cache 1 generates a primitive 'Mech, * the player can keep the 'Mech without a battle so no enemy * units are generated. */ if (specialScenarioEnemies == null ) { setForces(campaign); } if ((specialScenarioEnemies != null) && (getBotForces().get(0) != null) && (specialScenarioEnemies.get(weight) != null)) { getBotForces().get(0).setFixedEntityList(specialScenarioEnemies.get(weight)); } setObjectives(campaign, getContract(campaign)); } } /** * Determines enemy and allied forces for the scenario. The forces for a standard * battle are based on the player's deployed lance. The enemy forces for * special scenarios depend on the weight class of the player's deployed * unit and the number of allies in big battles varies according to the * number the player deploys. Since the various possibilities are rather * limited, all possibilities are generated and the most appropriate is * chosen rather than rerolling every time the player changes. This is * both for efficiency and to prevent shopping. * * @param campaign */ public void setForces(Campaign campaign) { if (isStandardScenario()) { setStandardScenarioForces(campaign); } else if (isSpecialScenario()) { setSpecialScenarioForces(campaign); } else { setBigBattleForces(campaign); } setObjectives(campaign, getContract(campaign)); } /** * Generates attached allied units (bot or player controlled), the main * enemy force, any enemy reinforcements, and any additional forces * (such as civilian). * * @param campaign */ private void setStandardScenarioForces(Campaign campaign) { /* Find the number of attached units required by the command rights clause */ int attachedUnitWeight = EntityWeightClass.WEIGHT_MEDIUM; if (lanceRole.isScouting() || lanceRole.isTraining()) { attachedUnitWeight = EntityWeightClass.WEIGHT_LIGHT; } int numAttachedPlayer = 0; int numAttachedBot = 0; if (getContract(campaign).getContractType().isCadreDuty()) { numAttachedPlayer = 3; } else if (campaign.getFactionCode().equals("MERC")) { switch (getContract(campaign).getCommandRights()) { case INTEGRATED: if (campaign.getCampaignOptions().isPlayerControlsAttachedUnits()) { numAttachedPlayer = 2; } else { numAttachedBot = 2; } break; case HOUSE: if (campaign.getCampaignOptions().isPlayerControlsAttachedUnits()) { numAttachedPlayer = 1; } else { numAttachedBot = 1; } break; case LIAISON: numAttachedPlayer = 1; break; default: break; } } /* The entities in the attachedAllies list will be added to the player's forces * in MM and don't require a separate BotForce */ final Camouflage camouflage = getContract(campaign).getAllyCamouflage(); for (int i = 0; i < numAttachedPlayer; i++) { Entity en = getEntity(getContract(campaign).getEmployerCode(), getContract(campaign).getAllySkill(), getContract(campaign).getAllyQuality(), UnitType.MEK, attachedUnitWeight, campaign); if (null != en) { alliesPlayer.add(en); attachedUnitIds.add(UUID.fromString(en.getExternalIdAsString())); getExternalIDLookup().put(en.getExternalIdAsString(), en); if (!campaign.getCampaignOptions().isAttachedPlayerCamouflage()) { en.setCamouflage(camouflage.clone()); } } else { LogManager.getLogger().error("Entity for player-controlled allies is null"); } } /* The allyBot list will be passed to the BotForce constructor */ ArrayList<Entity> allyEntities = new ArrayList<>(); for (int i = 0; i < numAttachedBot; i++) { Entity en = getEntity(getContract(campaign).getEmployerCode(), getContract(campaign).getAllySkill(), getContract(campaign).getAllyQuality(), UnitType.MEK, attachedUnitWeight, campaign); if (null != en) { allyEntities.add(en); attachedUnitIds.add(UUID.fromString(en.getExternalIdAsString())); } else { LogManager.getLogger().error("Entity for ally bot is null"); } } ArrayList<Entity> enemyEntities = new ArrayList<>(); setExtraScenarioForces(campaign, allyEntities, enemyEntities); addAeroReinforcements(campaign); addScrubReinforcements(campaign); /* Possible enemy reinforcements */ int roll = Compute.d6(); if (roll > 3) { ArrayList<Entity> reinforcements = new ArrayList<>(); if (roll == 6) { addLance(reinforcements, getContract(campaign).getEnemyCode(), getContract(campaign).getEnemySkill(), getContract(campaign).getEnemyQuality(), EntityWeightClass.WEIGHT_MEDIUM, EntityWeightClass.WEIGHT_ASSAULT, campaign, 8); } else { addLance(reinforcements, getContract(campaign).getEnemyCode(), getContract(campaign).getEnemySkill(), getContract(campaign).getEnemyQuality(), EntityWeightClass.WEIGHT_LIGHT, EntityWeightClass.WEIGHT_ASSAULT, campaign, 6); } /* Must set per-entity start pos for units after start of scenarios. Reinforcements * arrive from the enemy home edge, which is not necessarily the start pos. */ final int enemyDir = enemyHome; reinforcements.stream().filter(Objects::nonNull).forEach(en -> { en.setStartingPos(enemyDir); }); if (campaign.getCampaignOptions().isAllowOpForLocalUnits()) { reinforcements.addAll(AtBDynamicScenarioFactory.fillTransports(this, reinforcements, getContract(campaign).getEnemyCode(), getContract(campaign).getEnemySkill(), getContract(campaign).getEnemyQuality(), campaign)); } BotForce bf = getEnemyBotForce(getContract(campaign), enemyHome, enemyHome, reinforcements); bf.setName(bf.getName() + " (Reinforcements)"); addBotForce(bf, campaign); } if (campaign.getCampaignOptions().isUseDropShips()) { if (canAddDropShips()) { boolean dropshipFound = false; for (UUID id : campaign.getForces().getAllUnits(true)) { if ((campaign.getUnit(id).getEntity().getEntityType() & Entity.ETYPE_DROPSHIP) != 0 && campaign.getUnit(id).isAvailable()) { addUnit(id); campaign.getUnit(id).setScenarioId(getId()); dropshipFound = true; break; } } if (!dropshipFound) { addDropship(campaign); } for (int i = 0; i < Compute.d6() - 3; i++) { addLance(enemyEntities, getContract(campaign).getEnemyCode(), getContract(campaign).getEnemySkill(), getContract(campaign).getEnemyQuality(), AtBStaticWeightGenerator.getRandomWeight(campaign, UnitType.MEK, getContract(campaign).getEnemy()), EntityWeightClass.WEIGHT_ASSAULT, campaign); } } else if (getLanceRole().isScouting()) { /* Set allied forces to deploy in (6 - speed) turns just as player's units, * but only if not deploying by DropShip. */ alliesPlayer.stream().filter(Objects::nonNull).forEach(entity -> { int speed = entity.getWalkMP(); if (entity.getJumpMP() > 0) { if (entity instanceof megamek.common.Infantry) { speed = entity.getJumpMP(); } else { speed++; } } entity.setDeployRound(Math.max(0, 6 - speed)); }); allyEntities.stream().filter(Objects::nonNull).forEach(entity -> { int speed = entity.getWalkMP(); if (entity.getJumpMP() > 0) { if (entity instanceof megamek.common.Infantry) { speed = entity.getJumpMP(); } else { speed++; } } entity.setDeployRound(Math.max(0, 6 - speed)); }); } } // aaand for fun, run everyone through the crew upgrader if (campaign.getCampaignOptions().isUseAbilities()) { AtBDynamicScenarioFactory.upgradeBotCrews(this, campaign); } } @Override public void setExtraScenarioForces(Campaign campaign, ArrayList<Entity> allyEntities, ArrayList<Entity> enemyEntities) { int enemyStart; int playerHome; playerHome = startPos[Compute.randomInt(4)]; setStartingPos(playerHome); enemyStart = getStartingPos() + 4; if (enemyStart > 8) { enemyStart -= 8; } enemyHome = enemyStart; if (!allyEntities.isEmpty()) { addBotForce(getAllyBotForce(getContract(campaign), getStartingPos(), playerHome, allyEntities), campaign); } addEnemyForce(enemyEntities, getLance(campaign).getWeightClass(campaign), campaign); addBotForce(getEnemyBotForce(getContract(campaign), enemyHome, enemyHome, enemyEntities), campaign); } @Override public boolean canAddDropShips() { return false; } /** * Generate four sets of forces: one for each weight class the player * can choose to deploy. * * @param campaign */ private void setSpecialScenarioForces(Campaign campaign) { // enemy must always be the first on the botforce list so we can find it on refresh() specialScenarioEnemies = new ArrayList<>(); ArrayList<Entity> enemyEntities = new ArrayList<>(); ArrayList<Entity> allyEntities = new ArrayList<>(); setExtraScenarioForces(campaign, allyEntities, enemyEntities); } public List<List<Entity>> getSpecialScenarioEnemies() { return specialScenarioEnemies; } /** * Generates enemy forces and four allied units that may be used if the player * deploys fewer than eight of his or her own units. * * @param campaign */ private void setBigBattleForces(Campaign campaign) { ArrayList<Entity> enemyEntities = new ArrayList<>(); ArrayList<Entity> allyEntities = new ArrayList<>(); setExtraScenarioForces(campaign, allyEntities, enemyEntities); bigBattleAllies = new ArrayList<>(); bigBattleAllies.addAll(alliesPlayer); } protected void addEnemyForce(List<Entity> list, int weightClass, Campaign c) { addEnemyForce(list, weightClass, EntityWeightClass.WEIGHT_ASSAULT, 0, 0, c); } /** * Generates the enemy force based on the weight class of the lance deployed * by the player. Certain scenario types may set a maximum weight class for * enemy units or modify the roll. * * @param list All generated enemy entities are added to this list. * @param weightClass The weight class of the player's lance. * @param maxWeight The maximum weight class of each generated enemy entity * @param rollMod Modifier to the enemy lances roll. * @param weightMod Modifier to the weight class of enemy lances. * @param campaign */ protected void addEnemyForce(List<Entity> list, int weightClass, int maxWeight, int rollMod, int weightMod, Campaign campaign) { String org = AtBConfiguration.getParentFactionType(getContract(campaign).getEnemy()); String lances = campaign.getAtBConfig().selectBotLances(org, weightClass, rollMod / 20f); if (lances == null) { LogManager.getLogger().error(String.format( "Cannot add enemy force: failed to generate lances for faction %s at weight class %s", org, weightClass)); return; } int maxLances = Math.min(lances.length(), campaign.getCampaignOptions().getSkillLevel().getAdjustedValue() + 1); for (int i = 0; i < maxLances; i++) { addEnemyLance(list, AtBConfiguration.decodeWeightStr(lances, i) + weightMod, maxWeight, campaign); } if (campaign.getCampaignOptions().isAllowOpForLocalUnits()) { list.addAll(AtBDynamicScenarioFactory.fillTransports(this, list, getContract(campaign).getEnemyCode(), getContract(campaign).getEnemySkill(), getContract(campaign).getEnemyQuality(), campaign)); } } /** * Generates an enemy lance of a given weight class. * * @param list Generated enemy entities are added to this list. * @param weight Weight class of the enemy lance. * @param maxWeight Maximum weight of enemy entities. * @param campaign The current campaign */ private void addEnemyLance(List<Entity> list, int weight, int maxWeight, Campaign campaign) { if (weight < EntityWeightClass.WEIGHT_LIGHT) { weight = EntityWeightClass.WEIGHT_LIGHT; } if (weight > EntityWeightClass.WEIGHT_ASSAULT) { weight = EntityWeightClass.WEIGHT_ASSAULT; } addLance(list, getContract(campaign).getEnemyCode(), getContract(campaign).getEnemySkill(), getContract(campaign).getEnemyQuality(), weight, maxWeight, campaign); lanceCount++; } /** * Determines the most appropriate RAT and uses it to generate a random Entity * * @param faction The faction code to use for locating the correct RAT and assigning a crew name * @param skill The {@link SkillLevel} that represents the skill level of the overall force. * @param quality The equipment rating of the force. * @param unitType The UnitTableData constant for the type of unit to generate. * @param weightClass The weight class of the unit to generate * @param campaign The current campaign * @return A new Entity with crew. */ protected @Nullable Entity getEntity(String faction, SkillLevel skill, int quality, int unitType, int weightClass, Campaign campaign) { return AtBDynamicScenarioFactory.getEntity(faction, skill, quality, unitType, weightClass, false, campaign); } /** * Units that exceed the maximum weight for individual entities in the scenario * are replaced in the lance by two lighter units. * * @param weights A string of single-character letter codes for the weights of the units in the lance (e.g. "LMMH") * @param maxWeight The maximum weight allowed for the force by the parameters of the scenario type * @return A new String of the same format as weights */ private String adjustForMaxWeight(String weights, int maxWeight) { String retVal = weights; if (maxWeight == EntityWeightClass.WEIGHT_HEAVY) { //Hide and Seek (defender) retVal = weights.replaceAll("A", "LM"); } else if (maxWeight == EntityWeightClass.WEIGHT_MEDIUM) { //Probe, Recon Raid (attacker) retVal = weights.replaceAll("A", "MM"); retVal = retVal.replaceAll("H", "LM"); } return retVal; } /** * Adjust weights of units in a lance for factions that do not fit the typical * weight distribution. * * @param weights A string of single-character letter codes for the weights of the units in the lance (e.g. "LMMH") * @param faction The code of the faction to which the force belongs. * @return A new String of the same format as weights */ private String adjustWeightsForFaction(String weights, String faction) { /* Official AtB rules only specify DC, LA, and FWL; I have added * variations for some Clans. */ String retVal = weights; if (faction.equals("DC")) { retVal = weights.replaceFirst("MM", "LH"); } if ((faction.equals("LA") || faction.equals("CCO") || faction.equals("CGB")) && weights.matches("[LM]{3,}")) { retVal = weights.replaceFirst("M", "H"); } if (faction.equals("FWL") || faction.equals("CIH")) { retVal = weights.replaceFirst("HA", "HH"); } return retVal; } /* * Convenience functions overloaded to provide default values. */ protected void addLance(List<Entity> list, String faction, SkillLevel skill, int quality, int weightClass, Campaign campaign) { addLance(list, faction, skill, quality, weightClass, EntityWeightClass.WEIGHT_ASSAULT, campaign, 0); } protected void addLance(List<Entity> list, String faction, SkillLevel skill, int quality, int weightClass, int maxWeight, Campaign c) { addLance(list, faction, skill, quality, weightClass, maxWeight, c, 0); } /** * * Generates a lance of the indicated weight class. If the faction is Clan, * calls addStar instead. If the faction is CS/WoB, calls addLevelII. * * @param list Generated Entities are added to this list. * @param faction The faction code to use in generating the Entity * @param skill The overall skill level of the force * @param quality The force's equipment level * @param weightClass The weight class of the lance or equivalent to generate * @param campaign * @param arrivalTurn The turn in which the Lance is deployed in the scenario. */ private void addLance(List<Entity> list, String faction, SkillLevel skill, int quality, int weightClass, int maxWeight, Campaign campaign, int arrivalTurn) { if (Factions.getInstance().getFaction(faction).isClan()) { addStar(list, faction, skill, quality, weightClass, maxWeight, campaign, arrivalTurn); return; } else if (faction.equals("CS") || faction.equals("WOB")) { addLevelII(list, faction, skill, quality, weightClass, maxWeight, campaign, arrivalTurn); return; } String weights = campaign.getAtBConfig().selectBotUnitWeights(AtBConfiguration.ORG_IS, weightClass); if (weights == null) { // we can't generate a weight, so cancel adding the lance LogManager.getLogger().error("Cannot add lance: failed to generate weights for faction IS with weight class " + weightClass); return; } weights = adjustForMaxWeight(weights, maxWeight); int forceType = FORCE_MEK; if (campaign.getCampaignOptions().isUseVehicles()) { int totalWeight = campaign.getCampaignOptions().getOpForLanceTypeMechs() + campaign.getCampaignOptions().getOpForLanceTypeMixed() + campaign.getCampaignOptions().getOpForLanceTypeVehicles(); if (totalWeight > 0) { int roll = Compute.randomInt(totalWeight); if (roll < campaign.getCampaignOptions().getOpForLanceTypeVehicles()) { forceType = FORCE_VEHICLE; } else if (roll < campaign.getCampaignOptions().getOpForLanceTypeVehicles() + campaign.getCampaignOptions().getOpForLanceTypeMixed()) { forceType = FORCE_MIXED; } } } if (forceType == FORCE_MEK && campaign.getCampaignOptions().isRegionalMechVariations()) { weights = adjustWeightsForFaction(weights, faction); } int[] unitTypes = new int[weights.length()]; Arrays.fill(unitTypes, (forceType == FORCE_VEHICLE) ? UnitType.TANK : UnitType.MEK); /* Distribute vehicles randomly(-ish) through mixed units */ if (forceType == FORCE_MIXED) { for (int i = 0; i < weights.length() / 2; i++) { int j = Compute.randomInt(weights.length()); while (unitTypes[j] == UnitType.TANK) { j++; if (j >= weights.length()) { j = 0; } } unitTypes[j] = UnitType.TANK; } } for (int i = 0; i < weights.length(); i++) { Entity en = getEntity(faction, skill, quality, unitTypes[i], AtBConfiguration.decodeWeightStr(weights, i), campaign); if (en != null) { en.setDeployRound(arrivalTurn); list.add(en); } if ((unitTypes[i] == UnitType.TANK) && campaign.getCampaignOptions().isDoubleVehicles()) { en = getEntity(faction, skill, quality, unitTypes[i], AtBConfiguration.decodeWeightStr(weights, i), campaign); if (en != null) { en.setDeployRound(arrivalTurn); list.add(en); } } } } /** * Generates a Star of the indicated weight class. * * @param list Generated Entities are added to this list. * @param faction The faction code to use in generating the Entity * @param skill The overall skill level of the force * @param quality The force's equipment level * @param weightClass The weight class of the lance or equivalent to generate * @param campaign * @param arrivalTurn The turn in which the Lance is deployed in the scenario. */ private void addStar(List<Entity> list, String faction, SkillLevel skill, int quality, int weightClass, int maxWeight, Campaign campaign, int arrivalTurn) { int forceType = FORCE_MEK; /* 1 chance in 12 of a Nova, per AtB rules; CHH/CSL * close to 1/2, no chance for CBS. Added a chance to encounter * a vehicle Star in Clan second-line (rating C or lower) units, * or all unit ratings for CHH/CSL and CBS. */ int roll = Compute.d6(2); int novaTarget = 11; if (faction.equals("CHH") || faction.equals("CSL")) { novaTarget = 8; } else if (faction.equals("CBS")) { novaTarget = TargetRoll.AUTOMATIC_FAIL; } int vehicleTarget = 4; if (!faction.equals("CHH") && !faction.equals("CSL") && !faction.equals("CBS")) { vehicleTarget -= quality; } if (roll >= novaTarget) { forceType = FORCE_NOVA; } else if (campaign.getCampaignOptions().isClanVehicles() && roll <= vehicleTarget) { forceType = FORCE_VEHICLE; } String weights = campaign.getAtBConfig().selectBotUnitWeights(AtBConfiguration.ORG_CLAN, weightClass); if (weights == null) { // we can't generate a weight, so cancel adding the star LogManager.getLogger().error("Cannot add star: failed to generate weights for faction CLAN with weight class " + weightClass); return; } weights = adjustForMaxWeight(weights, maxWeight); int unitType = (forceType == FORCE_VEHICLE) ? UnitType.TANK : UnitType.MEK; if (campaign.getCampaignOptions().isRegionalMechVariations()) { if (unitType == UnitType.MEK) { weights = adjustWeightsForFaction(weights, faction); } /* medium vees are rare among the Clans, FM:CC, p. 8 */ if (unitType == UnitType.TANK) { weights = adjustWeightsForFaction(weights, "DC"); } } int unitsPerPoint; switch (unitType) { case UnitType.TANK: case UnitType.AEROSPACEFIGHTER: unitsPerPoint = 2; break; case UnitType.PROTOMEK: unitsPerPoint = 5; break; case UnitType.MEK: case UnitType.INFANTRY: case UnitType.BATTLE_ARMOR: default: unitsPerPoint = 1; break; } /* Ensure Novas use Frontline tables to get best chance at Omnis */ int tmpQuality = quality; if (forceType == FORCE_NOVA && quality < IUnitRating.DRAGOON_B) { tmpQuality = IUnitRating.DRAGOON_B; } for (int point = 0; point < weights.length(); point++) { for (int unit = 0; unit < unitsPerPoint; unit++) { Entity en = getEntity(faction, skill, tmpQuality, unitType, AtBConfiguration.decodeWeightStr(weights, point), campaign); if (en != null) { en.setDeployRound(arrivalTurn); list.add(en); } } } if (forceType == FORCE_NOVA) { unitType = UnitType.BATTLE_ARMOR; for (int i = 0; i < 5; i++) { Entity en = getEntity(faction, skill, quality, unitType, -1, campaign); if (en != null) { en.setDeployRound(arrivalTurn); list.add(en); } } } } /** * Generates a ComStar/WoB Level II of the indicated weight class. * * @param list Generated Entities are added to this list. * @param faction The faction code to use in generating the Entity * @param skill The overall skill level of the force * @param quality The force's equipment level * @param weightClass The weight class of the lance or equivalent to generate * @param campaign * @param arrivalTurn The turn in which the Lance is deployed in the scenario. */ private void addLevelII(List<Entity> list, String faction, SkillLevel skill, int quality, int weightClass, int maxWeight, Campaign campaign, int arrivalTurn) { String weights = campaign.getAtBConfig().selectBotUnitWeights(AtBConfiguration.ORG_CS, weightClass); if (weights == null) { // we can't generate a weight, so cancel adding the Level II LogManager.getLogger().error("Cannot add Level II: failed to generate weights for faction CS with weight class " + weightClass); return; } weights = adjustForMaxWeight(weights, maxWeight); int forceType = FORCE_MEK; int roll = Compute.d6(); if (roll < 4) { forceType = FORCE_VEHICLE; } else if (roll < 6) { forceType = FORCE_MIXED; } int[] unitTypes = new int[weights.length()]; Arrays.fill(unitTypes, (forceType == FORCE_VEHICLE) ? UnitType.TANK : UnitType.MEK); /* Distribute vehicles randomly(-ish) through mixed units */ if (forceType == FORCE_MIXED) { for (int i = 0; i < weights.length() / 2; i++) { int j = Compute.randomInt(weights.length()); while (unitTypes[j] == UnitType.TANK) { j++; if (j >= weights.length()) { j = 0; } } unitTypes[j] = UnitType.TANK; } } for (int i = 0; i < weights.length(); i++) { Entity en = getEntity(faction, skill, quality, unitTypes[i], AtBConfiguration.decodeWeightStr(weights, i), campaign); if (en != null) { en.setDeployRound(arrivalTurn); list.add(en); } if (unitTypes[i] == UnitType.TANK && campaign.getCampaignOptions().isDoubleVehicles()) { en = getEntity(faction, skill, quality, unitTypes[i], AtBConfiguration.decodeWeightStr(weights, i), campaign); if (en != null) { en.setDeployRound(arrivalTurn); list.add(en); } } } } /** * Generates the indicated number of civilian entities. * * @param list Generated entities are added to this list * @param num The number of civilian entities to generate * @param campaign */ protected void addCivilianUnits(List<Entity> list, int num, Campaign campaign) { list.addAll(AtBDynamicScenarioFactory.generateCivilianUnits(num, campaign)); } /** * Generates the indicated number of turret entities. * * @param list Generated entities are added to this list * @param num The number of turrets to generate * @param skill The skill level of the turret operators * @param quality The quality level of the turrets * @param campaign The campaign for which the turrets are being generated. * @param faction The faction the turrets are being generated for */ protected void addTurrets(List<Entity> list, int num, SkillLevel skill, int quality, Campaign campaign, Faction faction) { list.addAll(AtBDynamicScenarioFactory.generateTurrets(num, skill, quality, campaign, faction)); } /** * Potentially generates and adds a force of enemy aircraft to the mix of opposing force. * @param campaign The campaign for which the aircraft are being generated. */ protected void addAeroReinforcements(Campaign campaign) { // if the campaign is configured to it and we're in a 'standard' scenario or 'big battle' (don't add extra units to special scenarios) // if the opfor owns the planet, we have a user-defined chance of seeing 1-5 hostile conventional aircraft, // one per "pip" of difficulty. // if the opfor does not own the planet, we have a (slightly lower) user-defined chance of seeing 1-5 hostile aerotechs, // one per "pip" of difficulty. // if generating aeros (crude approximation), we have a 1/2 chance of a light, 1/3 chance of medium and 1/6 chance of heavy if (!(campaign.getCampaignOptions().isAllowOpForAeros() && (isStandardScenario() || isBigBattle()))) { return; } AtBContract contract = getContract(campaign); boolean opForOwnsPlanet = contract.getSystem().getFactions(campaign.getLocalDate()) .contains(contract.getEnemyCode()); boolean spawnConventional = opForOwnsPlanet && Compute.d6() >= MHQConstants.MAXIMUM_D6_VALUE - campaign.getCampaignOptions().getOpForAeroChance(); // aerotechs are rarer, so spawn them less often boolean spawnAerotech = !opForOwnsPlanet && Compute.d6() > MHQConstants.MAXIMUM_D6_VALUE - campaign.getCampaignOptions().getOpForAeroChance() / 2; ArrayList<Entity> aircraft = new ArrayList<>(); Entity aero; if (spawnConventional) { // skill level is an enum going from ultra-green to legendary for (int unitCount = 0; unitCount <= campaign.getCampaignOptions().getSkillLevel().getAdjustedValue(); unitCount++) { aero = getEntity(contract.getEnemyCode(), contract.getEnemySkill(), contract.getEnemyQuality(), UnitType.CONV_FIGHTER, EntityWeightClass.WEIGHT_LIGHT, campaign); if (aero != null) { aircraft.add(aero); } } } else if (spawnAerotech) { for (int unitCount = 0; unitCount <= campaign.getCampaignOptions().getSkillLevel().getAdjustedValue(); unitCount++) { // compute weight class int weightClass = randomAeroWeights[Compute.d6() - 1]; aero = getEntity(contract.getEnemyCode(), contract.getEnemySkill(), contract.getEnemyQuality(), UnitType.AEROSPACEFIGHTER, weightClass, campaign); if (aero != null) { aircraft.add(aero); } } } if (!aircraft.isEmpty()) { /* Must set per-entity start pos for units after start of scenarios. Reinforcements * arrive from the enemy home edge, which is not necessarily the start pos. */ final int deployRound = Compute.d6() + 2; // deploy the new aircraft some time after the start of the game aircraft.stream().filter(Objects::nonNull).forEach(en -> { en.setStartingPos(enemyHome); en.setDeployRound(deployRound); }); boolean isAeroMap = getBoardType() == T_SPACE || getBoardType() == T_ATMOSPHERE; AtBDynamicScenarioFactory.populateAeroBombs(aircraft, campaign, !isAeroMap); BotForce bf = getEnemyBotForce(getContract(campaign), enemyHome, enemyHome, aircraft); bf.setName(bf.getName() + " (Air Support)"); addBotForce(bf, campaign); } } /** * Potentially generates some scrubs (turrets and/or infantry) to be randomly added to the opposing force. * @param campaign The campaign for which the scrubs are being generated. */ protected void addScrubReinforcements(Campaign campaign) { // if the campaign is configured to it and we are in a standard scenario or big battle // if the opfor owns the planet, and the opfor is defender we have a 1/3 chance of seeing 1-5 hostile turrets, one per "pip" of difficulty. // if the opfor owns the planet, and the opfor is defender we have a 1/3 chance of seeing 1-5 hostile conventional infantry, one per "pip". // if the opfor does not own the planet, we have a 1/6 chance of seeing 1-5 hostile battle armor, one per "pip" of difficulty. if (!(campaign.getCampaignOptions().isAllowOpForLocalUnits() && isAttacker() && (isStandardScenario() || isBigBattle()))) { return; } AtBContract contract = getContract(campaign); boolean opForOwnsPlanet = contract.getSystem().getFactions(campaign.getLocalDate()) .contains(contract.getEnemyCode()); boolean spawnTurrets = opForOwnsPlanet && Compute.d6() >= MHQConstants.MAXIMUM_D6_VALUE - campaign.getCampaignOptions().getOpForLocalUnitChance(); boolean spawnConventionalInfantry = opForOwnsPlanet && Compute.d6() >= MHQConstants.MAXIMUM_D6_VALUE - campaign.getCampaignOptions().getOpForLocalUnitChance(); // battle armor is more rare boolean spawnBattleArmor = !opForOwnsPlanet && Compute.d6() >= MHQConstants.MAXIMUM_D6_VALUE - campaign.getCampaignOptions().getOpForLocalUnitChance() / 2; boolean isTurretAppropriateTerrain = (getTerrainType().toUpperCase().contains("URBAN") || getTerrainType().toUpperCase().contains("FACILITY")); boolean isInfantryAppropriateTerrain = isTurretAppropriateTerrain || (getTerrainType().toUpperCase().contains("FOREST")); ArrayList<Entity> scrubs = new ArrayList<>(); // don't bother spawning turrets if there won't be anything to put them on if (spawnTurrets && isTurretAppropriateTerrain) { // skill level is an enum from ultra-green to legendary, and drives the number of extra units addTurrets(scrubs, campaign.getCampaignOptions().getSkillLevel().getAdjustedValue() + 1, contract.getEnemySkill(), contract.getEnemyQuality(), campaign, contract.getEnemy()); } if (spawnConventionalInfantry && isInfantryAppropriateTerrain) { for (int unitCount = 0; unitCount <= campaign.getCampaignOptions().getSkillLevel().getAdjustedValue(); unitCount++) { Entity infantry = getEntity(contract.getEnemyCode(), contract.getEnemySkill(), contract.getEnemyQuality(), UnitType.INFANTRY, EntityWeightClass.WEIGHT_LIGHT, campaign); if (infantry != null) { scrubs.add(infantry); } } } if (spawnBattleArmor && isInfantryAppropriateTerrain) { for (int unitCount = 0; unitCount <= campaign.getCampaignOptions().getSkillLevel().getAdjustedValue(); unitCount++) { // some factions don't have access to battle armor, so they get conventional infantry instead Entity generatedUnit = getEntity(contract.getEnemyCode(), contract.getEnemySkill(), contract.getEnemyQuality(), UnitType.BATTLE_ARMOR, EntityWeightClass.WEIGHT_LIGHT, campaign); if (generatedUnit != null) { scrubs.add(generatedUnit); } else { Entity infantry = getEntity(contract.getEnemyCode(), contract.getEnemySkill(), contract.getEnemyQuality(), UnitType.INFANTRY, EntityWeightClass.WEIGHT_LIGHT, campaign); if (infantry != null) { scrubs.add(infantry); } } } } if (!scrubs.isEmpty()) { /* Must set per-entity start pos for units after start of scenarios. Scrubs start in the center of the map. */ scrubs.stream().filter(Objects::nonNull).forEach(en -> { en.setStartingPos(Board.START_CENTER); // if it's a short range enemy unit, it has a chance to be hidden based on // the option being enabled and the difficulty if (campaign.getGameOptions().booleanOption(OptionsConstants.ADVANCED_HIDDEN_UNITS) && (en.getMaxWeaponRange() <= 4) && (Compute.randomInt(5) <= campaign.getCampaignOptions().getSkillLevel().getAdjustedValue())) { en.setHidden(true); } }); BotForce bf = getEnemyBotForce(getContract(campaign), Board.START_CENTER, enemyHome, scrubs); bf.setName(bf.getName() + " (Local Forces)"); addBotForce(bf, campaign); } } /** * Worker method that adds a DropShip and related objective to the scenario. * @param campaign */ protected void addDropship(Campaign campaign) { Entity dropship = AtBDynamicScenarioFactory.getEntity(getContract(campaign).getEmployerCode(), getContract(campaign).getAllySkill(), getContract(campaign).getAllyQuality(), UnitType.DROPSHIP, AtBDynamicScenarioFactory.UNIT_WEIGHT_UNSPECIFIED, campaign); if (dropship != null) { alliesPlayer.add(dropship); attachedUnitIds.add(UUID.fromString(dropship.getExternalIdAsString())); getExternalIDLookup().put(dropship.getExternalIdAsString(), dropship); ScenarioObjective dropshipObjective = new ScenarioObjective(); dropshipObjective.setDescription("The employer has provided a DropShip for your use in this battle. Ensure it survives. Losing it will result in a 5 point penalty to your contract score."); dropshipObjective.setObjectiveCriterion(ObjectiveCriterion.Preserve); dropshipObjective.setPercentage(100); dropshipObjective.addUnit(dropship.getExternalIdAsString()); // update the contract score by -5 if the objective is failed. ObjectiveEffect failureEffect = new ObjectiveEffect(); failureEffect.effectType = ObjectiveEffectType.ContractScoreUpdate; failureEffect.howMuch = -5; dropshipObjective.addFailureEffect(failureEffect); getScenarioObjectives().add(dropshipObjective); } } /* Convenience methods for frequently-used arguments */ protected BotForce getAllyBotForce(AtBContract c, int start, int home, List<Entity> entities) { return new BotForce(c.getAllyBotName(), 1, start, home, entities, c.getAllyCamouflage().clone(), c.getAllyColour()); } protected BotForce getEnemyBotForce(AtBContract c, int start, List<Entity> entities) { return getEnemyBotForce(c, start, start, entities); } protected BotForce getEnemyBotForce(AtBContract c, int start, int home, List<Entity> entities) { return new BotForce(c.getEnemyBotName(), 2, start, home, entities, c.getEnemyCamouflage().clone(), c.getEnemyColour()); } @Override public void generateStub(Campaign c) { super.generateStub(c); alliesPlayerStub = Utilities.generateEntityStub(alliesPlayer); alliesPlayer.clear(); if (null != bigBattleAllies) { bigBattleAllies.clear(); } if (null != specialScenarioEnemies) { specialScenarioEnemies.clear(); } } protected void setObjectives(Campaign c, AtBContract contract) { getScenarioObjectives().clear(); } @Override protected void writeToXMLEnd(final PrintWriter pw, int indent) { MHQXMLUtility.writeSimpleXMLTag(pw, indent, "attacker", isAttacker()); MHQXMLUtility.writeSimpleXMLTag(pw, indent, "lanceForceId", lanceForceId); MHQXMLUtility.writeSimpleXMLTag(pw, indent, "lanceRole", lanceRole.name()); MHQXMLUtility.writeSimpleXMLTag(pw, indent, "deploymentDelay", deploymentDelay); MHQXMLUtility.writeSimpleXMLTag(pw, indent, "lanceCount", lanceCount); MHQXMLUtility.writeSimpleXMLTag(pw, indent, "rerollsRemaining", rerollsRemaining); MHQXMLUtility.writeSimpleXMLTag(pw, indent, "modifiedTemperature", modifiedTemperature); MHQXMLUtility.writeSimpleXMLTag(pw, indent, "terrainType", terrainType); if (null != bigBattleAllies && !bigBattleAllies.isEmpty()) { MHQXMLUtility.writeSimpleXMLOpenTag(pw, indent++, "bigBattleAllies"); for (Entity entity : bigBattleAllies) { if (entity != null) { MHQXMLUtility.writeEntityWithCrewToXML(pw, indent, entity, bigBattleAllies); } } MHQXMLUtility.writeSimpleXMLCloseTag(pw, --indent, "bigBattleAllies"); } else if (!alliesPlayer.isEmpty()) { MHQXMLUtility.writeSimpleXMLOpenTag(pw, indent++, "alliesPlayer"); for (Entity entity : alliesPlayer) { if (entity != null) { MHQXMLUtility.writeEntityWithCrewToXML(pw, indent, entity, alliesPlayer); } } MHQXMLUtility.writeSimpleXMLCloseTag(pw, --indent, "alliesPlayer"); } if (!alliesPlayerStub.isEmpty()) { MHQXMLUtility.writeSimpleXMLOpenTag(pw, indent++, "alliesPlayerStub"); for (String stub : alliesPlayerStub) { MHQXMLUtility.writeSimpleXMLTag(pw, indent, "entityStub", stub); } MHQXMLUtility.writeSimpleXMLCloseTag(pw, --indent, "alliesPlayerStub"); } if (!attachedUnitIds.isEmpty()) { MHQXMLUtility.writeSimpleXMLTag(pw, indent, "attachedUnits", getCsvFromList(attachedUnitIds)); } if (!survivalBonus.isEmpty()) { MHQXMLUtility.writeSimpleXMLTag(pw, indent, "survivalBonus", getCsvFromList(survivalBonus)); } if (null != specialScenarioEnemies && !specialScenarioEnemies.isEmpty()) { MHQXMLUtility.writeSimpleXMLOpenTag(pw, indent++, "specialScenarioEnemies"); for (int i = 0; i < specialScenarioEnemies.size(); i++) { MHQXMLUtility.writeSimpleXMLOpenTag(pw, indent++, "playerWeight", "class", i); for (Entity entity : specialScenarioEnemies.get(i)) { if (entity != null) { MHQXMLUtility.writeEntityWithCrewToXML(pw, indent, entity, specialScenarioEnemies.get(i)); } } MHQXMLUtility.writeSimpleXMLCloseTag(pw, --indent, "playerWeight"); } MHQXMLUtility.writeSimpleXMLCloseTag(pw, --indent, "specialScenarioEnemies"); } if (!transportLinkages.isEmpty()) { MHQXMLUtility.writeSimpleXMLOpenTag(pw, indent++, "transportLinkages"); for (String key : transportLinkages.keySet()) { MHQXMLUtility.writeSimpleXMLOpenTag(pw, indent++, "transportLinkage"); MHQXMLUtility.writeSimpleXMLTag(pw, indent, "transportID", key); MHQXMLUtility.writeSimpleXMLTag(pw, indent, "transportedUnits", transportLinkages.get(key)); MHQXMLUtility.writeSimpleXMLCloseTag(pw, --indent, "transportLinkage"); } MHQXMLUtility.writeSimpleXMLCloseTag(pw, --indent, "transportLinkages"); } if (!numPlayerMinefields.isEmpty()) { MHQXMLUtility.writeSimpleXMLOpenTag(pw, indent++, "numPlayerMinefields"); for (int key : numPlayerMinefields.keySet()) { MHQXMLUtility.writeSimpleXMLOpenTag(pw, indent++, "numPlayerMinefield"); MHQXMLUtility.writeSimpleXMLTag(pw, indent, "minefieldType", key); MHQXMLUtility.writeSimpleXMLTag(pw, indent, "minefieldCount", numPlayerMinefields.get(key).toString()); MHQXMLUtility.writeSimpleXMLCloseTag(pw, --indent, "numPlayerMinefield"); } MHQXMLUtility.writeSimpleXMLCloseTag(pw, --indent, "numPlayerMinefields"); } super.writeToXMLEnd(pw, indent); } @Override protected void loadFieldsFromXmlNode(final Node wn, final Version version, final Campaign campaign) throws ParseException { super.loadFieldsFromXmlNode(wn, version, campaign); NodeList nl = wn.getChildNodes(); for (int x = 0; x < nl.getLength(); x++) { Node wn2 = nl.item(x); try { if (wn2.getNodeName().equalsIgnoreCase("attacker")) { setAttacker(Boolean.parseBoolean(wn2.getTextContent().trim())); } else if (wn2.getNodeName().equalsIgnoreCase("lanceForceId")) { lanceForceId = Integer.parseInt(wn2.getTextContent()); } else if (wn2.getNodeName().equalsIgnoreCase("lanceRole")) { lanceRole = AtBLanceRole.parseFromString(wn2.getTextContent().trim()); } else if (wn2.getNodeName().equalsIgnoreCase("deploymentDelay")) { deploymentDelay = Integer.parseInt(wn2.getTextContent()); } else if (wn2.getNodeName().equalsIgnoreCase("usingFixedMap")) { setUsingFixedMap(Boolean.parseBoolean(wn2.getTextContent().trim())); } else if (wn2.getNodeName().equalsIgnoreCase("lanceCount")) { lanceCount = Integer.parseInt(wn2.getTextContent()); } else if (wn2.getNodeName().equalsIgnoreCase("rerollsRemaining")) { rerollsRemaining = Integer.parseInt(wn2.getTextContent()); } else if (wn2.getNodeName().equalsIgnoreCase("modifiedTemperature")) { modifiedTemperature = Integer.parseInt(wn2.getTextContent()); } else if (wn2.getNodeName().equalsIgnoreCase("terrainType")) { terrainType = wn2.getTextContent(); } else if (wn2.getNodeName().equalsIgnoreCase("alliesPlayer")) { NodeList nl2 = wn2.getChildNodes(); for (int i = 0; i < nl2.getLength(); i++) { Node wn3 = nl2.item(i); if (wn3.getNodeName().equalsIgnoreCase("entity")) { Entity en = null; try { en = MHQXMLUtility.parseSingleEntityMul((Element) wn3, campaign); } catch (Exception ex) { LogManager.getLogger().error("Error loading allied unit in scenario", ex); } if (en != null) { alliesPlayer.add(en); entityIds.put(UUID.fromString(en.getExternalIdAsString()), en); getExternalIDLookup().put(en.getExternalIdAsString(), en); } } } } else if (wn2.getNodeName().equalsIgnoreCase("bigBattleAllies")) { bigBattleAllies = new ArrayList<>(); NodeList nl2 = wn2.getChildNodes(); for (int i = 0; i < nl2.getLength(); i++) { Node wn3 = nl2.item(i); if (wn3.getNodeName().equalsIgnoreCase("entity")) { Entity en = null; try { en = MHQXMLUtility.parseSingleEntityMul((Element) wn3, campaign); } catch (Exception ex) { LogManager.getLogger().error("Error loading allied unit in scenario", ex); } if (en != null) { bigBattleAllies.add(en); entityIds.put(UUID.fromString(en.getExternalIdAsString()), en); getExternalIDLookup().put(en.getExternalIdAsString(), en); } } } } else if (wn2.getNodeName().equalsIgnoreCase("specMissionEnemies") // Legacy - 0.49.11 removal || wn2.getNodeName().equalsIgnoreCase("specialScenarioEnemies")) { specialScenarioEnemies = new ArrayList<>(); for (int i = EntityWeightClass.WEIGHT_ULTRA_LIGHT; i <= EntityWeightClass.WEIGHT_COLOSSAL; i++) { specialScenarioEnemies.add(new ArrayList<>()); } NodeList nl2 = wn2.getChildNodes(); for (int i = 0; i < nl2.getLength(); i++) { Node wn3 = nl2.item(i); if (wn3.getNodeName().equalsIgnoreCase("playerWeight")) { int weightClass = Integer.parseInt(wn3.getAttributes().getNamedItem("class").getTextContent()); NodeList nl3 = wn3.getChildNodes(); for (int j = 0; j < nl3.getLength(); j++) { Node wn4 = nl3.item(j); if (wn4.getNodeName().equalsIgnoreCase("entity")) { Entity en = null; try { en = MHQXMLUtility.parseSingleEntityMul((Element) wn4, campaign); } catch (Exception ex) { LogManager.getLogger().error("Error loading enemy unit in scenario", ex); } if (null != en) { specialScenarioEnemies.get(weightClass).add(en); entityIds.put(UUID.fromString(en.getExternalIdAsString()), en); getExternalIDLookup().put(en.getExternalIdAsString(), en); } } } } } } else if (wn2.getNodeName().equalsIgnoreCase("alliesPlayerStub")) { alliesPlayerStub = getEntityStub(wn2); } else if (wn2.getNodeName().equalsIgnoreCase("attachedUnits")) { String[] ids = wn2.getTextContent().split(","); for (String s : ids) { attachedUnitIds.add(UUID.fromString(s)); } } else if (wn2.getNodeName().equalsIgnoreCase("survivalBonus")) { String[] ids = wn2.getTextContent().split(","); for (String s : ids) { survivalBonus.add(UUID.fromString(s)); } } else if (wn2.getNodeName().equalsIgnoreCase("transportLinkages")) { try { transportLinkages = loadTransportLinkages(wn2); } catch (Exception e) { LogManager.getLogger().error("Error loading transport linkages in scenario", e); } } else if (wn2.getNodeName().equalsIgnoreCase("numPlayerMinefields")) { try { loadMinefieldCounts(wn2); } catch (Exception e) { LogManager.getLogger().error("Error loading minefield counts in scenario", e); } } } catch (Exception e) { LogManager.getLogger().error("", e); } } /* In the event a discrepancy occurs between a RAT entry and the unit lookup name, * remove the entry from the list of entities that give survival bonuses * to avoid an critical error that prevents battle resolution. */ ArrayList<UUID> toRemove = new ArrayList<>(); for (UUID uid : survivalBonus) { if (!entityIds.containsKey(uid)) { toRemove.add(uid); } } survivalBonus.removeAll(toRemove); } private static Map<String, List<String>> loadTransportLinkages(Node wn) { NodeList nl = wn.getChildNodes(); Map<String, List<String>> transportLinkages = new HashMap<>(); for (int x = 0; x < nl.getLength(); x++) { Node wn2 = nl.item(x); if (wn2.getNodeName().equalsIgnoreCase("transportLinkage")) { loadTransportLinkage(wn2, transportLinkages); } } return transportLinkages; } private static void loadTransportLinkage(Node wn, Map<String, List<String>> transportLinkages) { NodeList nl = wn.getChildNodes(); String transportID = null; List<String> transportedUnitIDs = null; for (int x = 0; x < nl.getLength(); x++) { Node wn2 = nl.item(x); if (wn2.getNodeName().equalsIgnoreCase("transportID")) { transportID = wn2.getTextContent().trim(); } else if (wn2.getNodeName().equalsIgnoreCase("transportedUnits")) { transportedUnitIDs = Arrays.asList(wn2.getTextContent().split(",")); } } if ((transportID != null) && (transportedUnitIDs != null)) { transportLinkages.put(transportID, transportedUnitIDs); } } /** * Worker function that loads the minefield counts for the player */ private void loadMinefieldCounts(Node wn) throws NumberFormatException { NodeList nl = wn.getChildNodes(); for (int x = 0; x < nl.getLength(); x++) { Node wn2 = nl.item(x); if (wn2.getNodeName().equalsIgnoreCase("numPlayerMinefield")) { NodeList minefieldNodes = wn2.getChildNodes(); int minefieldType = 0; int minefieldCount = 0; for (int minefieldIndex = 0; minefieldIndex < minefieldNodes.getLength(); minefieldIndex++) { Node wn3 = minefieldNodes.item(minefieldIndex); if (wn3.getNodeName().equalsIgnoreCase("minefieldType")) { minefieldType = Integer.parseInt(wn3.getTextContent()); } else if (wn3.getNodeName().equalsIgnoreCase("minefieldCount")) { minefieldCount = Integer.parseInt(wn3.getTextContent()); } } numPlayerMinefields.put(minefieldType, minefieldCount); } } } protected String getCsvFromList(List<?> list) { StringJoiner retVal = new StringJoiner(","); for (Object item : list) { retVal.add(item.toString()); } return retVal.toString(); } public AtBContract getContract(Campaign c) { return (AtBContract) c.getMission(getMissionId()); } /** * Gets all the entities that are part of the given entity list and are * not in this scenario's transport linkages as a transported unit. */ public List<Entity> filterUntransportedUnits(List<Entity> entities) { List<Entity> retVal = new ArrayList<>(); // assemble a set of transported units for easier lookup Set<String> transportedUnits = new HashSet<>(); for (List<String> transported : getTransportLinkages().values()) { transportedUnits.addAll(transported); } for (Entity entity : entities) { if (!transportedUnits.contains(entity.getExternalIdAsString())) { retVal.add(entity); } } return retVal; } public int getLanceForceId() { return lanceForceId; } public AtBLanceRole getLanceRole() { return lanceRole; } public Lance getLance(Campaign c) { return c.getLances().get(lanceForceId); } public void setLance(Lance l) { lanceForceId = l.getForceId(); } public boolean isAttacker() { return attacker; } public void setAttacker(boolean attacker) { this.attacker = attacker; } public List<Entity> getAlliesPlayer() { return alliesPlayer; } public List<UUID> getAttachedUnitIds() { return attachedUnitIds; } public List<UUID> getSurvivalBonusIds() { return survivalBonus; } public Entity getEntity(UUID id) { return entityIds.get(id); } public List<String> getAlliesPlayerStub() { return alliesPlayerStub; } public int getDeploymentDelay() { return deploymentDelay; } public void setDeploymentDelay(int delay) { this.deploymentDelay = delay; } public int getLanceCount() { return lanceCount; } public void setLanceCount(int lanceCount) { this.lanceCount = lanceCount; } public int getRerollsRemaining() { return rerollsRemaining; } public void useReroll() { rerollsRemaining--; } public void setRerolls(int rerolls) { rerollsRemaining = rerolls; } public int getEnemyHome() { return enemyHome; } public void setEnemyHome(int enemyHome) { this.enemyHome = enemyHome; } public int getNumPlayerMinefields(int minefieldType) { return numPlayerMinefields.containsKey(minefieldType) ? numPlayerMinefields.get(minefieldType) : 0; } public void setNumPlayerMinefields(int minefieldType, int numPlayerMinefields) { this.numPlayerMinefields.put(minefieldType, numPlayerMinefields); } public Map<String, List<String>> getTransportLinkages() { return transportLinkages; } public void setTransportLinkages(HashMap<String, List<String>> transportLinkages) { this.transportLinkages = transportLinkages; } /** * Adds a transport-cargo pair to the internal transport relationship store. * @param transport * @param cargo */ public void addTransportRelationship(String transport, String cargo) { if (!transportLinkages.containsKey(transport)) { transportLinkages.put(transport, new ArrayList<>()); } transportLinkages.get(transport).add(cargo); } @Override public boolean isFriendlyUnit(Entity entity, Campaign campaign) { return getAlliesPlayer().stream().anyMatch(unit -> unit.getExternalIdAsString().equals(entity.getExternalIdAsString())) || super.isFriendlyUnit(entity, campaign); } public String getBattlefieldControlDescription() { return getResourceBundle().getString("battleDetails.common.winnerControlsBattlefield"); } public String getDeploymentInstructions() { if (this.isBigBattle()) { return getResourceBundle().getString("battleDetails.deployEightMeks"); } else if (isSpecialScenario()) { return getResourceBundle().getString("battleDetails.deploySingleMek"); } else { return ""; } } @Override public boolean canStartScenario(Campaign c) { return c.getLocalDate().equals(getDate()) && super.canStartScenario(c); } }
MegaMek/mekhq
MekHQ/src/mekhq/campaign/mission/AtBScenario.java
46,010
/* * Copyright (c) 2017, Adam <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.runelite.client.hiscore; import java.util.Set; import lombok.Getter; import net.runelite.api.WorldType; import okhttp3.HttpUrl; @Getter public enum HiscoreEndpoint { NORMAL("Normal", "https://services.runescape.com/m=hiscore_oldschool/index_lite.json"), IRONMAN("Ironman", "https://services.runescape.com/m=hiscore_oldschool_ironman/index_lite.json"), HARDCORE_IRONMAN("Hardcore Ironman", "https://services.runescape.com/m=hiscore_oldschool_hardcore_ironman/index_lite.json"), ULTIMATE_IRONMAN("Ultimate Ironman", "https://services.runescape.com/m=hiscore_oldschool_ultimate/index_lite.json"), DEADMAN("Deadman", "https://services.runescape.com/m=hiscore_oldschool_deadman/index_lite.json"), LEAGUE("Leagues", "https://services.runescape.com/m=hiscore_oldschool_seasonal/index_lite.json"), TOURNAMENT("Tournament", "https://services.runescape.com/m=hiscore_oldschool_tournament/index_lite.json"), FRESH_START_WORLD("Fresh Start", "https://secure.runescape.com/m=hiscore_oldschool_fresh_start/index_lite.json"), PURE("1 Defence Pure", "https://secure.runescape.com/m=hiscore_oldschool_skiller_defence/index_lite.json"), LEVEL_3_SKILLER("Level 3 Skiller", "https://secure.runescape.com/m=hiscore_oldschool_skiller/index_lite.json"); private final String name; private final HttpUrl hiscoreURL; HiscoreEndpoint(String name, String hiscoreURL) { this.name = name; this.hiscoreURL = HttpUrl.get(hiscoreURL); } public static HiscoreEndpoint fromWorldTypes(Set<WorldType> worldTypes) { if (worldTypes.contains(WorldType.SEASONAL)) { // this changes between LEAGUE and TOURNAMENT return HiscoreEndpoint.LEAGUE; } else if (worldTypes.contains(WorldType.TOURNAMENT_WORLD)) { return HiscoreEndpoint.TOURNAMENT; } else if (worldTypes.contains(WorldType.DEADMAN)) { return HiscoreEndpoint.DEADMAN; } else if (worldTypes.contains(WorldType.FRESH_START_WORLD)) { return HiscoreEndpoint.FRESH_START_WORLD; } else { return HiscoreEndpoint.NORMAL; } } }
runelite/runelite
runelite-client/src/main/java/net/runelite/client/hiscore/HiscoreEndpoint.java
46,011
/* * Copyright (c) 2020 Abex * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.runelite.client.config; import lombok.Data; /** * A profile/save of a OSRS account. Each account can 1 profile per {@link RuneScapeProfileType} * (ie Standard/League/DMM}. */ @Data public class RuneScapeProfile { public static final int ACCOUNT_HASH_INVALID = -1; private final String displayName; private final RuneScapeProfileType type; private final long accountHash; /** * Profile key used to save configs for this profile to the config store. This will * always start with {@link ConfigManager#RSPROFILE_GROUP} */ private final String key; }
runelite/runelite
runelite-client/src/main/java/net/runelite/client/config/RuneScapeProfile.java
46,012
/* * Copyright (c) 2018. Aberic - [email protected] - All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.aberic.fabric.service.impl; import cn.aberic.fabric.dao.entity.League; import cn.aberic.fabric.dao.entity.Orderer; import cn.aberic.fabric.dao.entity.Org; import cn.aberic.fabric.dao.mapper.*; import cn.aberic.fabric.service.OrdererService; import cn.aberic.fabric.utils.CacheUtil; import cn.aberic.fabric.utils.DateUtil; import cn.aberic.fabric.utils.FabricHelper; import cn.aberic.fabric.utils.FileUtil; import org.apache.commons.lang3.StringUtils; import org.springframework.core.env.Environment; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; @Service("ordererService") public class OrdererServiceImpl implements OrdererService { @Resource private LeagueMapper leagueMapper; @Resource private OrgMapper orgMapper; @Resource private OrdererMapper ordererMapper; @Resource private PeerMapper peerMapper; @Resource private ChannelMapper channelMapper; @Resource private ChaincodeMapper chaincodeMapper; @Resource private Environment env; @Override public int add(Orderer orderer, MultipartFile serverCrtFile, MultipartFile clientCertFile, MultipartFile clientKeyFile) { if (StringUtils.isEmpty(orderer.getName()) || StringUtils.isEmpty(orderer.getLocation())) { return 0; } if (StringUtils.isNotEmpty(serverCrtFile.getOriginalFilename()) && StringUtils.isNotEmpty(clientCertFile.getOriginalFilename()) && StringUtils.isNotEmpty(clientKeyFile.getOriginalFilename())) { if (saveFileFail(orderer, serverCrtFile, clientCertFile, clientKeyFile)) { return 0; } } orderer.setDate(DateUtil.getCurrent("yyyy-MM-dd")); CacheUtil.removeHome(); return ordererMapper.add(orderer); } @Override public int update(Orderer orderer, MultipartFile serverCrtFile, MultipartFile clientCertFile, MultipartFile clientKeyFile) { FabricHelper.obtain().removeChaincodeManager(peerMapper.list(orderer.getOrgId()), channelMapper, chaincodeMapper); CacheUtil.removeHome(); if (null == serverCrtFile || null == clientCertFile || null == clientKeyFile) { return ordererMapper.updateWithNoFile(orderer); } if (saveFileFail(orderer, serverCrtFile, clientCertFile, clientKeyFile)) { return 0; } return ordererMapper.update(orderer); } @Override public List<Orderer> listAll() { List<Orderer> orderers = ordererMapper.listAll(); for (Orderer orderer : orderers) { Org org = orgMapper.get(orderer.getOrgId()); orderer.setLeagueName(leagueMapper.get(org.getLeagueId()).getName()); orderer.setOrgName(org.getMspId()); } return orderers; } @Override public List<Orderer> listById(int id) { return ordererMapper.list(id); } @Override public Orderer get(int id) { return ordererMapper.get(id); } @Override public int countById(int id) { return ordererMapper.count(id); } @Override public int count() { return ordererMapper.countAll(); } @Override public int delete(int id) { CacheUtil.removeHome(); return ordererMapper.delete(id); } @Override public List<Org> listOrgById(int orgId) { League league = leagueMapper.get(orgMapper.get(orgId).getLeagueId()); List<Org> orgs = orgMapper.list(league.getId()); for (Org org : orgs) { org.setLeagueName(league.getName()); } return orgs; } @Override public List<Org> listAllOrg() { List<Org> orgs = new ArrayList<>(orgMapper.listAll()); for (Org org : orgs) { org.setLeagueName(leagueMapper.get(org.getLeagueId()).getName()); } return orgs; } @Override public Orderer resetOrderer(Orderer orderer) { Org org = orgMapper.get(orderer.getOrgId()); League league = leagueMapper.get(org.getLeagueId()); orderer.setLeagueName(league.getName()); orderer.setOrgName(org.getMspId()); return orderer; } private boolean saveFileFail(Orderer orderer, MultipartFile serverCrtFile, MultipartFile clientCertFile, MultipartFile clientKeyFile) { String ordererTlsPath = String.format("%s%s%s%s%s%s%s%s", env.getProperty("config.dir"), File.separator, orderer.getLeagueName(), File.separator, orderer.getOrgName(), File.separator, orderer.getName(), File.separator); String serverCrtPath = String.format("%s%s", ordererTlsPath, serverCrtFile.getOriginalFilename()); String clientCertPath = String.format("%s%s", ordererTlsPath, clientCertFile.getOriginalFilename()); String clientKeyPath = String.format("%s%s", ordererTlsPath, clientKeyFile.getOriginalFilename()); orderer.setServerCrtPath(serverCrtPath); orderer.setClientCertPath(clientCertPath); orderer.setClientKeyPath(clientKeyPath); try { FileUtil.save(serverCrtFile, clientCertFile, clientKeyFile, serverCrtPath, clientCertPath, clientKeyPath); } catch (IOException e) { e.printStackTrace(); return true; } return false; } }
lipengyu/fabric-net-server
fabric-edge/src/main/java/cn/aberic/fabric/service/impl/OrdererServiceImpl.java
46,013
package data; import common.Log; import java.awt.Color; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import javax.imageio.ImageIO; /** * This class provides the icons and names including unique teamNumbers of all * teams written in the config file. * * This class is a singleton! * * @author Michel Bartsch */ public class Teams { /** * Information about each team. */ public static class Info { /** The name of the team. */ public String name; /** The icon of the team. */ public BufferedImage icon; /** The first and secondary jersey colors of the team. */ public String[] colors; /** * Create a new team information. * @param name The name of the team. * @param colors The names of the jersey colors used by the team. * Can be null if no colors were specified. */ public Info(String name, String[] colors) { this.name = name; this.colors = colors; } } /** Dynamically settable path to the config root folder */ private static final String CONFIG_ROOT = System.getProperty("CONFIG_ROOT", ""); /** The path to the leagues directories. */ private static final String PATH = CONFIG_ROOT + "config/"; /** The name of the config file. */ private static final String CONFIG = "teams.cfg"; /** The charset to read the config file. */ private final static String CHARSET = "UTF-8"; /** * The possible file-endings icons may have. * The full name of an icon must be "<teamNumber>.<png|gif>", for example * "7.png". */ private static final String[] PIC_ENDING = {"png", "gif", "jpg", "jpeg"}; /** The instance of the singleton. */ private static Teams instance = new Teams(); /** The information read from the config files. */ private Info[][] teams; /** * Creates a new Teams object. */ private Teams() { teams = new Info[Rules.LEAGUES.length][]; for (int i=0; i < Rules.LEAGUES.length; i++) { String dir = Rules.LEAGUES[i].leagueDirectory; int value; int maxValue = 0; BufferedReader br = null; try { InputStream inStream = new FileInputStream(PATH+dir+"/"+CONFIG); br = new BufferedReader( new InputStreamReader(inStream, CHARSET)); String line; while ((line = br.readLine()) != null) { value = Integer.valueOf(line.split("=")[0]); if (value > maxValue) { maxValue = value; } } } catch (IOException e) { Log.error("cannot load "+PATH+dir+"/"+CONFIG); } finally { if (br != null) { try { br.close(); } catch (Exception e) {} } } teams[i] = new Info[maxValue+1]; } } public static Teams.Info[] getTeamArrayForLeague(Rules rules){ for (int i=0; i < Rules.LEAGUES.length; i++) { if (Rules.LEAGUES[i].leagueName.equals(rules.leagueName)) { return Teams.instance.teams[i]; } } return null; } /** * Returns the index the current league has within the LEAGUES-array. * @return the leagues index. */ private static int getLeagueIndex() { for (int i=0; i < Rules.LEAGUES.length; i++) { if (Rules.LEAGUES[i] == Rules.league) { return i; } } //should never happen Log.error("selected league is odd"); return -1; } /** * Reads the names of all teams in the config file. * You don't need to use this because the getNames method automatically * uses this if needed. */ public static void readTeams() { BufferedReader br = null; try { InputStream inStream = new FileInputStream(PATH+Rules.league.leagueDirectory+"/"+CONFIG); br = new BufferedReader( new InputStreamReader(inStream, CHARSET)); String line; while ((line = br.readLine()) != null) { int key = Integer.valueOf(line.split("=")[0]); String value = line.split("=")[1]; String[] values = value.split(","); instance.teams[getLeagueIndex()][key] = new Info(values[0], values.length >= 3 ? new String[]{values[1], values[2]} : values.length == 2 ? new String[] {values[1]} : new String[0]); } } catch (IOException e) { Log.error("cannot load "+PATH+Rules.league.leagueDirectory+"/"+CONFIG); } finally { if (br != null) { try { br.close(); } catch (Exception e) {} } } } /** * Returns an array containing the names of all teams. * @param withNumbers If true, each name starts with "<teamNumber>: ". * @return An array containing the names at their teamNumber's position. */ public static String[] getNames(boolean withNumbers) { int leagueIndex = getLeagueIndex(); if (instance.teams[leagueIndex][0] == null) { readTeams(); } String[] out = new String[instance.teams[leagueIndex].length]; for (int i=0; i<instance.teams[leagueIndex].length; i++) { if (instance.teams[leagueIndex][i] != null) { out[i] = instance.teams[leagueIndex][i].name + (withNumbers ? " (" + i + ")" : ""); } } return out; } /** * Loads a team's icon. * You don't need to use this because the getIcon method automatically * uses this if needed. * @param team Number of the team which icon should be read. */ private static void readIcon(int team) { BufferedImage out = null; File file = getIconPath(team); if (file != null) { try{ out = ImageIO.read(file); } catch (IOException e) { Log.error("cannot load "+file); } } if (out == null) { out = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB); Graphics graphics = out.getGraphics(); graphics.setColor(new Color(0f, 0f, 0f, 0f)); graphics.fillRect(0, 0, out.getWidth(), out.getHeight()); } instance.teams[getLeagueIndex()][team].icon = out; } /** * Returns the file path to a team's icon * @param team The unique team number of the team you want the icon for. * @return The team's icon. */ public static File getIconPath(int team) { for (final String ending : PIC_ENDING) { final File file = new File(PATH+Rules.league.leagueDirectory+"/"+team+"."+ending); if (file.exists()) { return file; } } return null; } /** * Returns a team's icon. * @param team The unique team number of the team you want the icon for. * @return The team's icon. */ public static BufferedImage getIcon(int team) { int leagueIndex = getLeagueIndex(); if (instance.teams[leagueIndex][team] == null) { readTeams(); } if (instance.teams[leagueIndex][team].icon == null) { readIcon(team); } return instance.teams[leagueIndex][team].icon; } /** * Returns a team's jersey colors. * @param team The unique team number of the team you want the icon for. * @return The team's jersey colors or null if none were specified. */ public static String[] getColors(int team) { int leagueIndex = getLeagueIndex(); if (instance.teams[leagueIndex][team] == null) { readTeams(); } return instance.teams[leagueIndex][team].colors; } }
Rhoban/GameController
src/data/Teams.java
46,014
package org.synyx.urlaubsverwaltung.department; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.synyx.urlaubsverwaltung.application.application.Application; import org.synyx.urlaubsverwaltung.person.Person; import org.synyx.urlaubsverwaltung.person.PersonId; import org.synyx.urlaubsverwaltung.search.PageableSearchQuery; import java.time.LocalDate; import java.util.List; import java.util.Map; import java.util.Optional; /** * Service for handling {@link Department}s. */ public interface DepartmentService { /** * Check if a {@link Department} with the given departmentId exists or not. * * @param departmentId id of a {@link Department} to check * @return <code>true</code> if the departmentId exists, <code>false</code> otherwise */ boolean departmentExists(Long departmentId); /** * Returns a department by its unique identifier * * @param departmentId the unique identifier to of a department * @return department to given id */ Optional<Department> getDepartmentById(Long departmentId); /** * Returns a department by its name * * @param departmentName the name of a department * @return department to given name */ Optional<Department> getDepartmentByName(String departmentName); /** * adds the given department to repository. * * @param department the {@link Department} to create */ Department create(Department department); /** * Updates a given department in repository. * * @param department the {@link Department} to update */ Department update(Department department); /** * Deletes department with given id. * * @param departmentId the unique identifier to delete a department */ void delete(Long departmentId); /** * @return all departments ordered by the department name */ List<Department> getAllDepartments(); /** * Finds all departments the given person is member of. * * @param member to get the departments of * @return list of departments the given person is assigned to */ List<Department> getAssignedDepartmentsOfMember(Person member); /** * Finds all departments the given person is set as department head. * * @param departmentHead to get the departments of * @return list of departments the department head manages */ List<Department> getManagedDepartmentsOfDepartmentHead(Person departmentHead); /** * Finds all departments the given person is set as second stage authority. * * @param secondStageAuthority to get the departments of * @return list of departments the second stage authority manages */ List<Department> getManagedDepartmentsOfSecondStageAuthority(Person secondStageAuthority); /** * Finds all departments the given person has access to see the data * <p> * If the person has the permission: * <ul> * <li>BOSS or OFFICE - return all departments</li> * <li>DEPARTMENT_HEAD - return all managed department of the person as department head</li> * <li>SECOND_STAGE_AUTHORITY - return all managed department of the person as second stage authority</li> * </ul> * </p> * * @param person to check the permissions * @return List of departments which are accessible by the given person */ List<Department> getDepartmentsPersonHasAccessTo(Person person); /** * Get all active (waiting or allowed) applications for leave of the members of the departments of the given person * for the provided period. Sorted by the start date of the application. * * @param member to get the departments of * @param startDate of the period * @param endDate of the period * @return list of waiting or allowed applications for leave of departments members */ List<Application> getApplicationsFromColleaguesOf(Person member, LocalDate startDate, LocalDate endDate); /** * Get all distinct members of the departments where the given person is department head. * (including the given person and second stage authorities) * * @param departmentHead to know all the members of the department * @return all unique members of the departments where the given person is department head. */ List<Person> getMembersForDepartmentHead(Person departmentHead); /** * Get all distinct members of the departments where the given person is second stage authority. * (including the given person) * * @param secondStageAuthority to know all the members of the department * @return all unique members of the departments where the given person is second stage authority. */ List<Person> getMembersForSecondStageAuthority(Person secondStageAuthority); /** * Check if the given department head manages a department that the given person is assigned to. * * @param departmentHead to be checked if he is the department head of a department that the given person is * assigned to * @param person to be checked if he is assigned to a department that has the given department head * @return {@code true} if the given department head manages a department that the given person is assigned to, * else {@code false} */ boolean isDepartmentHeadAllowedToManagePerson(Person departmentHead, Person person); /** * Check the role of the given person and return a {@link Page} of all managed and active {@link Person}s for the * {@link Pageable} request. Managed members are all persons for which a privileged person are responsible * for and can perform actions for this person. * * @param person person to get managed members for * @param personPageableSearchQuery search query containing pageable and an optional query for firstname/lastname * @return all managed and active members for the person */ Page<Person> getManagedMembersOfPerson(Person person, PageableSearchQuery personPageableSearchQuery); /** * Check the role of the given person and return a {@link List} of all managed and active {@link Person}s. * Managed members are all persons for which a privileged person are responsible * for and can perform actions for this person. * * @param person person to get managed members for * @return all managed and active members for the person */ List<Person> getManagedActiveMembersOfPerson(Person person); /** * Check the role of the given person and return a {@link Page} of all managed and active {@link Person}s for the * {@link Pageable} request. Managed members are all persons for which a privileged person are responsible * for and can perform actions for this person. * * @param person person to get managed members for * @param personPageableSearchQuery search query containing pageable and an optional query for firstname/lastname * @return all managed and inactive members for the person */ Page<Person> getManagedInactiveMembersOfPerson(Person person, PageableSearchQuery personPageableSearchQuery); /** * Check the role of the given person and return a {@link Page} of all managed and active {@link Person}s for the * {@link Pageable} request. Managed members are all persons for which a privileged person are responsible * for and can perform actions for this person. * * @param person person to get managed members for * @param departmentId departmentId to get managed members for * @param pageableSearchQuery searchQuery to restrict the result set * @return all managed and active members for the person */ Page<Person> getManagedMembersOfPersonAndDepartment(Person person, Long departmentId, PageableSearchQuery pageableSearchQuery); /** * Check the role of the given person and return a {@link Page} of all managed and inactive {@link Person}s for the * {@link Pageable} request. Managed members are all persons for which a privileged person are responsible * for and can perform actions for this person. * * @param person person to get managed members for * @param departmentId departmentId to get managed members for * @param pageableSearchQuery search query containing pageable and an optional query for firstname/lastname * @return all managed and inactive members for the person */ Page<Person> getManagedInactiveMembersOfPersonAndDepartment(Person person, Long departmentId, PageableSearchQuery pageableSearchQuery); /** * Get all distinct managed members of the department head. * Managed members are all persons for which the department head are responsible for and can * perform actions for this person. * * @param departmentHead to know all the members of the department * @return all managed members of the department head */ List<Person> getManagedMembersOfDepartmentHead(Person departmentHead); /** * Check if the given secondStageAuthority is responsible for the department that the given person is assigned to. * * @param secondStageAuthority to be checked if he is responsible for a department that the given person is * assigned to * @param person to be checked if he is assigned to a department that has the given secondStageAuthority * @return {@code true} if the given secondStageAuthority is responsible for a department that the given person is * assigned to, else {@code false} */ boolean isSecondStageAuthorityAllowedToManagePerson(Person secondStageAuthority, Person person); /** * Get all distinct managed members of the second stage authority. * Managed members are all persons for which the second stage authority are responsible for and can * perform actions for this person. * * @param secondStageAuthority to know all the members of the department * @return all managed members of the second stage authority */ List<Person> getManagedMembersForSecondStageAuthority(Person secondStageAuthority); /** * Check if the given signed in user is allowed to access the data of the given person. * * @param signedInUser to check the permissions * @param person which data should be accessed * @return {@code true} if the given user may access the data of the given person, else {@code false} */ boolean isSignedInUserAllowedToAccessPersonData(Person signedInUser, Person person); /** * Check if the given {@link Person} is allowed to access the data of the {@link Department}. * * @param person to check the permissions * @param department which data should be accessed * @return {@code true} if the given user may access the data of the given person, else {@code false} */ boolean isPersonAllowedToManageDepartment(Person person, Department department); /** * Returns the number of departments * * @return number of departments */ long getNumberOfDepartments(); /** * Get all department names for the given persons as a map. * * @param persons * @return a map of personId mapped to department names */ Map<PersonId, List<String>> getDepartmentNamesByMembers(List<Person> persons); /** * Checks whether two persons are in the same department or not or one person of both is * {@linkplain org.synyx.urlaubsverwaltung.person.Role#DEPARTMENT_HEAD} or {@linkplain org.synyx.urlaubsverwaltung.person.Role#SECOND_STAGE_AUTHORITY} * of the other person. * * @param person a person * @param otherPerson another person * @return {@code true} when the persons have a department match, {@code false} otherwise */ boolean hasDepartmentMatch(Person person, Person otherPerson); }
urlaubsverwaltung/urlaubsverwaltung
src/main/java/org/synyx/urlaubsverwaltung/department/DepartmentService.java
46,015
404: Not Found
FAForever/downlords-faf-client
src/main/java/com/faforever/client/domain/api/League.java
46,016
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package consulo.language.psi; import consulo.logging.Logger; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; /** * @author peter */ public final class PsiElementRef<T extends PsiElement> { private static final Logger LOG = Logger.getInstance(PsiElementRef.class); private volatile PsiRefColleague<T> myColleague; public PsiElementRef(PsiRefColleague<T> colleague) { myColleague = colleague; } public final boolean isImaginary() { return getPsiElement() == null; } @Nullable public final T getPsiElement() { return myColleague.getPsiElement(); } @Nonnull public final T ensurePsiElementExists() { final PsiRefColleague.Real<T> realColleague = myColleague.makeReal(); myColleague = realColleague; return realColleague.getPsiElement(); } @Nonnull public final PsiElement getRoot() { return myColleague.getRoot(); } @Override public boolean equals(Object o) { return o instanceof PsiElementRef && myColleague.equals(((PsiElementRef) o).myColleague); } @Override public int hashCode() { return myColleague.hashCode(); } public final boolean isValid() { return myColleague.isValid(); } public static <T extends PsiElement> PsiElementRef<T> real(@Nonnull final T element) { return new PsiElementRef<T>(new PsiRefColleague.Real<T>(element)); } public static <Child extends PsiElement, Parent extends PsiElement> PsiElementRef<Child> imaginary(final PsiElementRef<? extends Parent> parent, final PsiRefElementCreator<Parent, Child> creator) { return new PsiElementRef<Child>(new PsiRefColleague.Imaginary<Child, Parent>(parent, creator)); } public PsiManager getPsiManager() { return myColleague.getRoot().getManager(); } private interface PsiRefColleague<T extends PsiElement> { boolean isValid(); @Nullable T getPsiElement(); @Nonnull Real<T> makeReal(); @Nonnull PsiElement getRoot(); class Real<T extends PsiElement> implements PsiRefColleague<T> { private final T myElement; public Real(@Nonnull T element) { LOG.assertTrue(element.isValid()); myElement = element; } @Override @Nonnull public T getPsiElement() { return myElement; } @Override public boolean isValid() { return myElement.isValid(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Real real = (Real)o; if (!myElement.equals(real.myElement)) return false; return true; } @Override public int hashCode() { return myElement.hashCode(); } @Override @Nonnull public Real<T> makeReal() { return this; } @Override @Nonnull public PsiElement getRoot() { return myElement; } } class Imaginary<Child extends PsiElement, Parent extends PsiElement> implements PsiRefColleague<Child> { private final PsiElementRef<? extends Parent> myParent; private final PsiRefElementCreator<Parent, Child> myCreator; public Imaginary(PsiElementRef<? extends Parent> parent, PsiRefElementCreator<Parent, Child> creator) { myParent = parent; myCreator = creator; } @Override public boolean isValid() { return myParent.isValid(); } @Override public Child getPsiElement() { return null; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Imaginary imaginary = (Imaginary)o; if (!myCreator.equals(imaginary.myCreator)) return false; if (!myParent.equals(imaginary.myParent)) return false; return true; } @Override public int hashCode() { int result = myParent.hashCode(); result = 31 * result + myCreator.hashCode(); return result; } @Override @Nonnull public Real<Child> makeReal() { return new Real<Child>(myCreator.createChild(myParent.ensurePsiElementExists())); } @Override @Nonnull public PsiElement getRoot() { return myParent.getRoot(); } } } }
consulo/consulo
modules/base/language-api/src/main/java/consulo/language/psi/PsiElementRef.java
46,017
package mediator; interface Mediator { public void send(String msg, Colleague c); } public class ConcreteMediator implements Mediator { private ConcreteColleague1 colleague1; private ConcreteColleague2 colleague2; public void setColleague1(ConcreteColleague1 colleague1) { this.colleague1 = colleague1; } public void setColleague2(ConcreteColleague2 colleague2) { this.colleague2 = colleague2; } public void send(String msg, Colleague c) { if (c == colleague1) { colleague2.readMsg(msg); } else { colleague1.readMsg(msg); } } }
liheng5661/design-patterns
src/mediator/java/ConcreteMediator.java
46,018
package com.matter.tv.server.tvapp; public enum ContentLaunchSearchParameterType { /** Actor represents an actor credited in video media content; for example, "Gaby sHoffman" */ ACTOR, /** Channel represents the identifying data for a television channel; for example, "PBS" */ CHANNEL, /** A character represented in video media content; for example, "Snow White" */ CHARACTER, /** A director of the video media content; for example, "Spike Lee" */ DIRECTOR, /** * An event is a reference to a type of event; examples would include sports, music, or other * types of events. For example, searching for "Football games" would search for a 'game' event * entity and a 'football' sport entity. */ EVENT, /** * A franchise is a video entity which can represent a number of video entities, like movies or TV * shows. For example, take the fictional franchise "Intergalactic Wars" which represents a * collection of movie trilogies, as well as animated and live action TV shows. This entity type * was introduced to account for requests by customers such as "Find Intergalactic Wars movies", * which would search for all 'Intergalactic Wars' programs of the MOVIE MediaType, rather than * attempting to match to a single title. */ FRANCHISE, /** Genre represents the genre of video media content such as action, drama or comedy. */ GENRE, /** League represents the categorical information for a sporting league; for example, "NCAA" */ LEAGUE, /** Popularity indicates whether the user asks for popular content. */ POPULARITY, /** The provider (MSP) the user wants this media to be played on; for example, "Netflix". */ PROVIDER, /** Sport represents the categorical information of a sport; for example, football */ SPORT, /** * SportsTeam represents the categorical information of a professional sports team; for example, * "University of Washington Huskies" */ SPORTS_TEAM, /** * The type of content requested. Supported types are "Movie", "MovieSeries", "TVSeries", * "TVSeason", "TVEpisode", "SportsEvent", and "Video" */ TYPE, UNKNOWN }
project-chip/connectedhomeip
examples/tv-app/android/java/src/com/matter/tv/server/tvapp/ContentLaunchSearchParameterType.java
46,019
package core.net; import com.github.scribejava.core.model.*; import core.file.xml.XMLCHPPPreParser; import core.file.xml.XMLTeamDetailsParser; import core.gui.CursorToolkit; import core.gui.HOMainFrame; import core.model.HOVerwaltung; import core.model.UserParameter; import core.model.enums.MatchType; import core.model.match.SourceSystem; import core.net.login.OAuthDialog; import core.net.login.ProxyDialog; import core.net.login.ProxySettings; import core.util.*; import org.jetbrains.annotations.Nullable; import tool.updater.VersionInfo; import core.HO; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.util.*; import java.util.zip.GZIPInputStream; import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; import javax.swing.JOptionPane; import com.github.scribejava.core.builder.ServiceBuilder; import com.github.scribejava.core.oauth.OAuth10aService; import org.w3c.dom.Document; public class MyConnector { private static final String htUrl = "https://chpp.hattrick.org/chppxml.ashx"; public static String m_sIDENTIFIER = "HO! Hattrick Organizer V" + HO.VERSION; private static MyConnector m_clInstance; public final static String VERSION_AVATARS = "1.1"; public final static String VERSION_ECONOMY = "1.3"; private final static String VERSION_TRAINING = "2.1"; private final static String VERSION_MATCHORDERS = "3.0"; // private final static String VERSION_MATCHORDERS_NT = "2.1"; private final static String VERSION_MATCHLINEUP = "2.0"; private final static String VERSION_MATCHDETAILS = "3.0"; private final static String VERSION_TEAM_DETAILS = "3.5"; private final static String VERSION_PLAYERS = "2.5"; private final static String VERSION_YOUTHPLAYERLIST = "1.1"; private final static String VERSION_WORLDDETAILS = "1.9"; private final static String VERSION_TOURNAMENTDETAILS = "1.0"; private final static String VERSION_LEAGUE_DETAILS = "1.5"; private final static String CONSUMER_KEY = ">Ij-pDTDpCq+TDrKA^nnE9"; private final static String CONSUMER_SECRET = "2/Td)Cprd/?q`nAbkAL//F+eGD@KnnCc>)dQgtP,p+p"; private ProxySettings proxySettings; private final OAuth10aService m_OAService; private OAuth1AccessToken m_OAAccessToken; private static boolean DEBUGSAVE = false; private boolean silentDownload = false; /** * Creates a new instance of MyConnector. */ private MyConnector() { m_OAService = new ServiceBuilder(Helper.decryptString(CONSUMER_KEY)) .apiSecret(Helper.decryptString(CONSUMER_SECRET)) .build(HattrickAPI.instance()); m_OAAccessToken = createOAAccessToken(); } private OAuth1AccessToken createOAAccessToken() { return new OAuth1AccessToken(Helper.decryptString(UserParameter.instance().AccessToken), Helper.decryptString(UserParameter.instance().TokenSecret)); } /** * Get the MyConnector instance. */ public static MyConnector instance() { if (m_clInstance == null) { m_clInstance = new MyConnector(); } return m_clInstance; } /** * Sets the DEBUGSAVE flag. Setting the flag to true will save downloaded * CHPP files. * * @param debugSave * true to save downloaded CHPP files, false otherwise. */ public static void setDebugSave(boolean debugSave) { DEBUGSAVE = debugSave; } /** * Fetch a specific arena * * @param arenaId * id of the arena to fetch (-1 = our arena) * @return arena xml */ public String downloadArena(int arenaId) { String url = htUrl + "?file=arenadetails"; if (arenaId > 0) { url += "&arenaID=" + arenaId; } return getCHPPWebFile(url); } /** * Fetch a specific region * * @param regionId * id of the region to fetch * @return regiondetails xml */ public String getRegion(int regionId) { String url = htUrl + "?file=regiondetails"; if (regionId > 0) { url += "&regionID=" + regionId; } return getCHPPWebFile(url); } /** * holt die Finanzen */ public String getEconomy(int teamId){ final String url = htUrl + "?file=economy&version=" + VERSION_ECONOMY + "&teamId=" + teamId; return getCHPPWebFile(url); } // /////////////////////////////////////////////////////////////////////////////// // get-XML-Files // ////////////////////////////////////////////////////////////////////////////// /** * downloads an xml File from hattrick Behavior has changed with oauth, but * we try to convert old syntaxes. * * @param file * ex. = "?file=leaguedetails&[leagueLevelUnitID = integer]" * * @return the complete file as String */ public String getHattrickXMLFile(String file){ String url; // An attempt at solving old syntaxes. if (file.contains("chppxml.axd")) { file = file.substring(file.indexOf("?")); } else if (file.contains(".asp")) { String s = file.substring(0, file.indexOf("?")).replace(".asp", "") .replace("/common/", ""); file = "?file=" + s + "&" + file.substring(file.indexOf("?") + 1); } url = htUrl + file; return getCHPPWebFile(url); } /** * lädt die Tabelle */ public String getLeagueDetails(String leagueUnitId) { String url = htUrl + "?file=leaguedetails&version=" + VERSION_LEAGUE_DETAILS + "&leagueLevelUnitID=" + leagueUnitId; return getCHPPWebFile(url); } /** * lädt den Spielplan */ public String getLeagueFixtures(int season, int leagueID){ String url = htUrl + "?file=leaguefixtures"; if (season > 0) { url += "&season=" + season; } if (leagueID > 0) { url += "&leagueLevelUnitID=" + leagueID; } return getCHPPWebFile(url); } /** * Fetches matches from Hattrick's matches archive (see 'matchesarchive' in * Hattrick's CHPP API documentation) for the given team and a specified * period of time. * * @param teamId * the ID of the team to fetch the matches for. * @param firstDate * the first date of the period of time. * @param lastDate * the last date of the period of time. * @return the a string containing the matches data in XML format. */ public String getMatchesArchive(int teamId, HODateTime firstDate, HODateTime lastDate){ StringBuilder url = new StringBuilder(); url.append(htUrl).append("?file=matchesarchive&version=1.4"); if (teamId > 0) { url.append("&teamID=").append(teamId); } if (firstDate != null) { url.append("&FirstMatchDate=").append(URLEncoder.encode(firstDate.toHT(), StandardCharsets.UTF_8)); } if (lastDate != null) { url.append("&LastMatchDate=").append(URLEncoder.encode(lastDate.toHT(),StandardCharsets.UTF_8)); } url.append("&includeHTO=true"); return getCHPPWebFile(url.toString()); } public String getMatchesArchive(SourceSystem sourceSystem, int teamId, HODateTime firstDate, HODateTime lastDate) throws IOException { StringBuilder url = new StringBuilder(); url.append(htUrl).append("?file=matchesarchive&version=1.4"); if (teamId > 0) { url.append("&teamID=").append(teamId); } if (firstDate != null) { url.append("&FirstMatchDate=").append(URLEncoder.encode(firstDate.toHT(), StandardCharsets.UTF_8)); } if (lastDate != null) { url.append("&LastMatchDate=").append(URLEncoder.encode(lastDate.toHT(), StandardCharsets.UTF_8)); } if ( sourceSystem == SourceSystem.HTOINTEGRATED) url.append("&includeHTO=true"); else if ( sourceSystem == SourceSystem.YOUTH) url.append("&isYouth=true"); return getCHPPWebFile(url.toString()); } /** * Get information about a tournament. This is only available for the current season. */ public String getTournamentDetails(int tournamentId) throws IOException{ String url = htUrl + "?file=tournamentdetails&version=" + VERSION_TOURNAMENTDETAILS + "&tournamentId=" + tournamentId; return getCHPPWebFile(url); } /** * lädt die Aufstellungsbewertung zu einem Spiel */ public String downloadMatchLineup(int matchId, int teamId, MatchType matchType) { String url = htUrl + "?file=matchlineup&version=" + VERSION_MATCHLINEUP; if (matchId > 0) { url += ("&matchID=" + matchId); } // Had to remove check for negative team ID. Street teams used in cup have that. url += ("&teamID=" + teamId); url += "&sourceSystem=" + matchType.getSourceString(); return getCHPPWebFile(url); } /** * lädt die Aufstellungsbewertung zu einem Spiel */ public String getRatingsPrediction(int matchId, int teamId, MatchType matchType) { String url = htUrl + "?file=matchorders&version=" + VERSION_MATCHORDERS; url += "&actionType=predictratings"; if (matchId > 0) { url += ("&matchID=" + matchId); } url += ("&teamID=" + teamId); url += "&sourceSystem=" + matchType.getSourceString(); return getCHPPWebFile(url); } /** * Fetches the match order xml from Hattrick * * @param matchId * The match id to fetch the lineup for * @param matchType * The match type connected to the match * @return The api content (xml) */ public String downloadMatchOrder(int matchId, MatchType matchType, int teamId) { String url = htUrl + "?file=matchorders&matchID=" + matchId + "&sourceSystem=" + matchType.getSourceString() + "&version=" + VERSION_MATCHORDERS; if (!HOVerwaltung.instance().getModel().getBasics().isNationalTeam()) { url += "&teamId=" + teamId; } return getCHPPWebFile(url); } /** * Sets the match order with the provided content to the provided match. * * @param matchId * The match id to upload the order to * @param matchType * The match type of the match to upload the order to * @param orderString * The string with the actual orders. See the CHPP API * documentation. * @return the result xml from the upload */ public String uploadMatchOrder(int matchId, int teamId, MatchType matchType, String orderString) throws IOException { StringBuilder urlpara = new StringBuilder(); urlpara.append("?file=matchorders&version=").append(VERSION_MATCHORDERS); if (teamId > 0 && !HOVerwaltung.instance().getModel().getBasics().isNationalTeam()) { urlpara.append("&teamId=").append(teamId); } if (matchId > 0) { urlpara.append("&matchID=").append(matchId); } urlpara.append("&actionType=setmatchorder"); urlpara.append("&sourceSystem=").append(matchType.getSourceString()); Map<String, String> paras = new HashMap<>(); paras.put("lineup", orderString); String result = readStream(postWebFileWithBodyParameters(htUrl + urlpara, paras, true, "set_matchorder")); String sError = XMLCHPPPreParser.getError(result); if (sError.length() > 0) { throw new RuntimeException(sError); } return result; } /** * Download match details, including match events */ public String downloadMatchdetails(int matchId, MatchType matchType) { String url = htUrl + "?file=matchdetails&version=" + VERSION_MATCHDETAILS; if (matchId > 0) { url += ("&matchID=" + matchId); } url += "&sourceSystem=" + matchType.getSourceString(); url += "&matchEvents=true"; return getCHPPWebFile(url); } /** * Gets the most recent and upcoming matches for a given teamId and up to a * specific date. * * @param teamId * the id of the team. * @param forceRefresh * <code>true</code> if cache should be refreshed, * <code>false</code> otherwise. * @param date * last date (+time) to get matches to. * @return a string containing the xml data for the downloaded matches (to * be used for MatchKurzInfo). * @throws IOException * if an IO error occurs during download. */ public String getMatches(int teamId, boolean forceRefresh, HODateTime date) throws IOException { StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append(htUrl).append("?file=matches&version=2.8"); urlBuilder.append("&teamID=").append(teamId); if (forceRefresh) { urlBuilder.append("&actionType=refreshCache"); } urlBuilder.append("&LastMatchDate="); urlBuilder.append(URLEncoder.encode(date.toHT(), StandardCharsets.UTF_8)); return getCHPPWebFile(urlBuilder.toString()); } /** * Get Matches */ public String getMatchesOfSeason(int teamId, int season){ var url = new StringBuilder(htUrl).append("?file=matchesarchive&version=1.5"); if (teamId > 0) { url.append( "&teamID=").append(teamId); } if (season > 0) { url.append( "&season=").append(season); } return getCHPPWebFile(url.toString()); } public String getMatches(int teamId, boolean forceRefresh, boolean upcoming) throws IOException { String url = htUrl + "?file=matches&version=2.8"; if (teamId > 0) { url += "&teamID=" + teamId; } if (forceRefresh) { url += "&actionType=refreshCache"; } GregorianCalendar cal = new GregorianCalendar(); cal.setTimeInMillis(System.currentTimeMillis()); if (upcoming) { cal.add(java.util.Calendar.MONTH, 5); } // Paranoia against inaccurate system clock. cal.add(java.util.Calendar.DAY_OF_MONTH, 1); url += "&LastMatchDate="; url += new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()); return getCHPPWebFile(url); } /** * Get Players */ public String downloadPlayers(int teamId) { String url = htUrl + "?file=players&version=" + VERSION_PLAYERS + "&includeMatchInfo=true&teamID=" + teamId; return getCHPPWebFile(url); } public String downloadPlayerDetails(String playerID) { return getCHPPWebFile(htUrl+"?file=playerdetails&version=2.9&includeMatchInfo=true&playerID=" + playerID); } public String downloadYouthPlayers(int youthteamId) { String url = htUrl + "?file=youthplayerlist&version=" + VERSION_YOUTHPLAYERLIST + "&actionType=unlockskills&showScoutCall=true&showLastMatch=true&youthTeamID=" + youthteamId; var silent = setSilentDownload(true); // try unlock skills var ret = getCHPPWebFile(url); setSilentDownload(silent); if (StringUtils.isEmpty(ret)) { // get details without unlock skills ret = getCHPPWebFile(url.replace("unlockskills", "details")); } return ret; } /** * Get Staff */ public String getStaff(int teamId) { String url = htUrl + "?file=stafflist&version=1.1&teamId=" + teamId; return getCHPPWebFile(url); } /** * holt die Teamdetails */ public String getTeamdetails(int teamId) throws IOException { String url = htUrl + "?file=teamdetails&version=3.5"; if (teamId > 0) { url += ("&teamID=" + teamId); } return getCHPPWebFile(url); } /** * holt die Teamdetails */ public String getAvatars(int teamId) { String url = htUrl + "?file=avatars&version=" + VERSION_AVATARS +"&actionType=players"; if (teamId > 0) { url += ("&teamID=" + teamId); } return getCHPPWebFile(url); } /** * Get the training XML data. */ public String getTraining(int teamId) { final String url = htUrl + "?file=training&version=" + VERSION_TRAINING + "&teamId=" + teamId; return getCHPPWebFile(url); } /** * Get the transfer data for a player */ public String getTransfersForPlayer(int playerId) { final String url = htUrl + "?file=transfersPlayer&playerID=" + playerId; return getCHPPWebFile(url); } /** * holt die Vereinsdaten */ public String getVerein(int teamId) { final String url = htUrl + "?file=club&version=1.5&teamId=" + teamId; return getCHPPWebFile(url); } /** * holt die Weltdaten */ public String getWorldDetails(int leagueId) throws IOException { String url = htUrl + "?file=worlddetails&version=" + VERSION_WORLDDETAILS; if (leagueId > 0) url += "&leagueID=" + leagueId; return getCHPPWebFile(url); } // /////////////////////////////////////////////////////////////////////////////// // Update Checker // ////////////////////////////////////////////////////////////////////////////// public VersionInfo getVersion(String url) { InputStream is = null; BufferedReader reader = null; try { is = getWebFile(url, false); if (is != null) { reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8)); var comment = reader.readLine(); SimpleDateFormat parser = new SimpleDateFormat("#EEE MMM d HH:mm:ss zzz yyyy", Locale.US); var released = parser.parse(comment); var versionProperties = new Properties(); versionProperties.load(reader); var ret = new VersionInfo(); ret.setReleasedDate(released); ret.setAllButReleaseDate(versionProperties.getProperty("version")); return ret; } else { HOLogger.instance().log(getClass(), "Unable to connect to the update server (HO)."); } } catch (Exception e) { HOLogger.instance() .log(getClass(), "Unable to connect to the update server (HO): " + e); } finally { IOUtils.closeQuietly(reader); IOUtils.closeQuietly(is); } return null; } public VersionInfo getLatestStableVersion() { return getVersion("https://github.com/akasolace/HO/releases/download/tag_stable/version.properties"); } public VersionInfo getLatestVersion() { return getVersion("https://github.com/akasolace/HO/releases/download/dev/version.properties"); } public VersionInfo getLatestBetaVersion() { return getVersion("https://github.com/akasolace/HO/releases/download/beta/version.properties"); } // /////////////////////////////////////////////////////////////////////////////// // Proxy // ////////////////////////////////////////////////////////////////////////////// public void enableProxy(ProxySettings proxySettings) { this.proxySettings = proxySettings; if (this.proxySettings != null && this.proxySettings.isUseProxy()) { System.getProperties().setProperty("https.proxyHost", proxySettings.getProxyHost()); System.getProperties().setProperty("https.proxyPort", String.valueOf(proxySettings.getProxyPort())); System.getProperties().setProperty("http.proxyHost", proxySettings.getProxyHost()); System.getProperties().setProperty("http.proxyPort", String.valueOf(proxySettings.getProxyPort())); } else { System.getProperties().remove("https.proxyHost"); System.getProperties().remove("https.proxyPort"); System.getProperties().remove("http.proxyHost"); System.getProperties().remove("http.proxyPort"); } } /** * Get the region id for a certain team. */ public String fetchRegionID(int teamId) { String xml = fetchTeamDetails(teamId); if ( xml.length()>0){ return XMLTeamDetailsParser.fetchRegionID(xml); } return "-1"; } public String fetchTeamDetails(int teamId) { try { String xmlFile = htUrl + "?file=teamdetails&version=" + VERSION_TEAM_DETAILS + "&teamID=" + teamId; return getCHPPWebFile(xmlFile); } catch (Exception e) { HOLogger.instance().log(getClass(), e); } return ""; } public InputStream getFileFromWeb(String url, boolean displaysettingsScreen) { if (displaysettingsScreen) { // Show Screen new ProxyDialog(HOMainFrame.instance()); } return getNonCHPPWebFile(url, false); } /** * Get a web page using a URLconnection. */ private String getCHPPWebFile(String surl) { String returnString = ""; OAuthDialog authDialog = null; Response response = null; int iResponse; boolean tryAgain = true; try { while (tryAgain) { OAuthRequest request = new OAuthRequest(Verb.GET, surl); infoHO(request); if (m_OAAccessToken == null || m_OAAccessToken.getToken().length() == 0) { iResponse = 401; } else { m_OAService.signRequest(m_OAAccessToken, request); response = m_OAService.execute(request); iResponse = response.getCode(); } switch (iResponse) { case 200, 201 -> { // We are done! returnString = readStream(getResultStream(response)); if (DEBUGSAVE) { saveCHPP(surl, returnString); } String sError = XMLCHPPPreParser.getError(returnString); if (sError.length() > 0) { throw new RuntimeException(sError); } tryAgain = false; } case 401 -> { if (!silentDownload) { if (authDialog == null) { HOMainFrame mainFrame = null; // If the main frame is not in the process of loading, use it, // otherwise use null frame. if (!HOMainFrame.launching.get()) { mainFrame = HOMainFrame.instance(); } // disable WaitCursor to unblock GUI if (mainFrame != null) { CursorToolkit.stopWaitCursor(mainFrame.getRootPane()); } authDialog = new OAuthDialog(mainFrame, m_OAService, ""); } authDialog.setVisible(true); // A way out for a user unable to authorize for some reason if (authDialog.getUserCancel()) { return null; } m_OAAccessToken = authDialog.getAccessToken(); if (m_OAAccessToken == null) { m_OAAccessToken = createOAAccessToken(); } } else { throw new RuntimeException("HTTP Response Code 401: CHPP Connection failed."); } } case 407 -> throw new RuntimeException( "HTTP Response Code 407: Proxy authentication required."); default -> throw new RuntimeException("HTTP Response Code: " + iResponse); } } } catch (Exception sox) { if ( !silentDownload) { HOLogger.instance().error(getClass(), sox); JOptionPane.showMessageDialog(null, sox.getMessage() + "\n\n" + "URL:" + surl + "\n", HOVerwaltung.instance().getLanguageString("Fehler"), JOptionPane.ERROR_MESSAGE); } returnString = ""; } return returnString; } /** * Get input stream from web url (file download) */ public @Nullable InputStream getWebFile(String url, boolean showErrorMessage) { try { return new URL(url).openStream(); } catch (Exception sox) { HOLogger.instance().error(getClass(), sox); if (showErrorMessage) JOptionPane.showMessageDialog(null, sox.getMessage() + "\nURL: " + url, HOVerwaltung.instance().getLanguageString("Fehler"), JOptionPane.ERROR_MESSAGE); } return null; } private @Nullable InputStream getNonCHPPWebFile(String surl, boolean showErrorMessage) { InputStream returnStream = null; try { Response response; OAuthRequest request = new OAuthRequest(Verb.GET, surl); infoHO(request); response = m_OAService.execute(request); int iResponse = response.getCode(); returnStream = switch (iResponse) { case 200, 201 -> getResultStream(response); case 404 -> throw new RuntimeException("Download Update Error: code 404: the following page does not exist: " + surl); case 407 -> throw new RuntimeException("Download Update Error: code 407: Proxy authentication required."); default -> throw new RuntimeException("Download Update Error: code: " + iResponse); }; } catch (Exception sox) { HOLogger.instance().error(getClass(), sox); if (showErrorMessage) JOptionPane.showMessageDialog(null, sox.getMessage() + "\nURL: " + surl, HOVerwaltung.instance().getLanguageString("Fehler"), JOptionPane.ERROR_MESSAGE); } return returnStream; } /** * Post a web file containing single value in the body (no key) * * @param surl * the full url with parameters * @param bodyParas * A hash map of string, string where key is parameter key and value is parameter value * @param showErrorMessage * Whether to show message on error or not * @param scope * The scope of the request is required, if no scope, put "". * Example: "set_matchorder". */ public InputStream postWebFileWithBodyParameters(String surl, Map<String, String> bodyParas, boolean showErrorMessage, String scope) { OAuthDialog authDialog = null; Response response = null; int iResponse; try { while (true) { OAuthRequest request = new OAuthRequest(Verb.POST, surl); for (Map.Entry<String, String> entry : bodyParas.entrySet()) { request.addBodyParameter(entry.getKey(), entry.getValue()); } infoHO(request); request.addHeader("Content-Type", "application/x-www-form-urlencoded"); if (m_OAAccessToken == null || m_OAAccessToken.getToken().length() == 0) { iResponse = 401; } else { m_OAService.signRequest(m_OAAccessToken, request); response = m_OAService.execute(request); iResponse = response.getCode(); } switch (iResponse) { case 200, 201 -> { // We are done! return getResultStream(response); } case 401 -> { // disable WaitCursor to unblock GUI CursorToolkit.stopWaitCursor(HOMainFrame.instance().getRootPane()); if (authDialog == null) { authDialog = new OAuthDialog(HOMainFrame.instance(), m_OAService, scope); } authDialog.setVisible(true); // A way out for a user unable to authorize for some reason if (authDialog.getUserCancel()) { return null; } m_OAAccessToken = authDialog.getAccessToken(); if (m_OAAccessToken == null) { m_OAAccessToken = new OAuth1AccessToken( Helper.decryptString(UserParameter.instance().AccessToken), Helper.decryptString(UserParameter.instance().TokenSecret)); } } // Try again... case 407 -> throw new RuntimeException( "Download Error\nHTTP Response Code 407: Proxy authentication required."); default -> throw new RuntimeException("Download Error\nHTTP Response Code: " + iResponse); } } } catch (Exception sox) { HOLogger.instance().error(getClass(), sox); if (showErrorMessage) { JOptionPane.showMessageDialog(null, sox.getMessage() + "\nURL: " + surl, HOVerwaltung.instance().getLanguageString("Fehler"), JOptionPane.ERROR_MESSAGE); } } return null; } private InputStream getResultStream(Response response) throws IOException { InputStream resultingInputStream = null; if (response != null) { String encoding = response.getHeader("Content-Encoding"); if ((encoding != null) && encoding.equalsIgnoreCase("gzip")) { resultingInputStream = new GZIPInputStream(response.getStream()); } else if ((encoding != null) && encoding.equalsIgnoreCase("deflate")) { resultingInputStream = new InflaterInputStream(response.getStream(), new Inflater( true)); // HOLogger.instance().log(getClass(), " Read Deflated."); } else { resultingInputStream = response.getStream(); // HOLogger.instance().log(getClass(), " Read Normal."); } } return resultingInputStream; } private String readStream(InputStream stream) throws IOException { StringBuilder builder = new StringBuilder(); if (stream != null) { BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8)); String line = bufferedreader.readLine(); if (line != null) { builder.append(line); while ((line = bufferedreader.readLine()) != null) { builder.append('\n'); builder.append(line); } } bufferedreader.close(); } return builder.toString(); } // /////////////////////////////////////////////////////////////////////////////// // Identifikation // ////////////////////////////////////////////////////////////////////////////// private void infoHO(OAuthRequest request) { request.addHeader("accept-language", "en"); // request.setConnectionKeepAlive(true); // request.setConnectTimeout(60, TimeUnit.SECONDS); request.addHeader("accept", "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*"); request.addHeader("accept-encoding", "gzip, deflate"); request.addHeader("user-agent", m_sIDENTIFIER); // ProxyAuth hier einbinden da diese Funk immer aufgerufen wird if (this.proxySettings != null && this.proxySettings.isAuthenticationNeeded()) { final String pw = this.proxySettings.getUsername() + ":" + this.proxySettings.getPassword(); final String epw = new String(Base64.getEncoder().encode(pw.getBytes())); request.addHeader("Proxy-Authorization", "Basic " + epw); } } /** * Save downloaded data to a temp-file for debugging purposes. * * @param url * the url where the content was downloaded from * @param content * the content to save */ private void saveCHPP(String url, String content) { File outDir = new File("tmp"); if (!outDir.exists()) { outDir.mkdirs(); } String xmlName = null; try { Document doc = XMLUtils.createDocument(content); xmlName = XMLUtils.getTagData(doc, "FileName"); if (xmlName != null && xmlName.indexOf('.') != -1) { xmlName = xmlName.substring(0, xmlName.lastIndexOf('.')); } } catch (Exception ex) { HOLogger.instance().error(getClass(), ex); } Date downloadDate = new Date(); SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd-HHmmss-S"); String outFileName = df.format(downloadDate) + ".txt"; if (!StringUtils.isEmpty(xmlName)) { outFileName = xmlName + "_" + outFileName; } File outFile = new File(outDir, outFileName); df = new SimpleDateFormat("yyyy-MM-dd, HH:mm:ss"); StringBuilder builder = new StringBuilder(); builder.append("Downloaded at ").append(df.format(downloadDate)).append('\n'); builder.append("From ").append(url).append("\n\n"); builder.append(content); try { IOUtils.writeToFile(builder.toString(), outFile, "UTF-8"); } catch (Exception e) { HOLogger.instance().error(MyConnector.class, e); } } public boolean isSilentDownload() { return silentDownload; } public boolean setSilentDownload(boolean silentDownload) { var ret = this.silentDownload; this.silentDownload = silentDownload; return ret; } public String downloadNtTeamDetails(int teamId) { String url = htUrl + "?file=nationalteamdetails&version=1.9&teamid=" + teamId; return getCHPPWebFile(url); } }
ddusann/HO
src/main/java/core/net/MyConnector.java
46,020
/* * Copyright (c) 2018, Hydrox6 <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.runelite.api; import lombok.Getter; import lombok.RequiredArgsConstructor; /** * Enum of all official icons that Jagex uses in chat. */ @RequiredArgsConstructor @Getter public enum IconID { PLAYER_MODERATOR(0), JAGEX_MODERATOR(1), IRONMAN(2), ULTIMATE_IRONMAN(3), DMM_SKULL_5_KEYS(4), DMM_SKULL_4_KEYS(5), DMM_SKULL_3_KEYS(6), DMM_SKULL_2_KEYS(7), DMM_SKULL_1_KEYS(8), SKULL(9), HARDCORE_IRONMAN(10), NO_ENTRY(11), CHAIN_LINK(12), BOUNTY_HUNTER_EMBLEM(20), LEAGUE(22); private final int index; @Override public String toString() { return "<img=" + String.valueOf(this.index) + ">"; } }
runelite/runelite
runelite-api/src/main/java/net/runelite/api/IconID.java
46,021
/* * Copyright (c) 2020 Abex * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.runelite.client.config; import java.util.function.Predicate; import lombok.Getter; import lombok.RequiredArgsConstructor; import net.runelite.api.Client; import net.runelite.api.WorldType; @Getter @RequiredArgsConstructor public enum RuneScapeProfileType { // This enum should be ordinal-stable; new entries should only be added to the // end and entries should never be removed STANDARD(client -> true), BETA(client -> client.getWorldType().contains(WorldType.NOSAVE_MODE) || client.getWorldType().contains(WorldType.BETA_WORLD)), QUEST_SPEEDRUNNING(client -> client.getWorldType().contains(WorldType.QUEST_SPEEDRUNNING)), DEADMAN(client -> client.getWorldType().contains(WorldType.DEADMAN)), PVP_ARENA(client -> client.getWorldType().contains(WorldType.PVP_ARENA)), TRAILBLAZER_LEAGUE, DEADMAN_REBORN, SHATTERED_RELICS_LEAGUE, TRAILBLAZER_RELOADED_LEAGUE(client -> client.getWorldType().contains(WorldType.SEASONAL)), ; private final Predicate<Client> test; RuneScapeProfileType() { this(client -> false); } public static RuneScapeProfileType getCurrent(Client client) { RuneScapeProfileType[] types = values(); for (int i = types.length - 1; i >= 0; i--) { RuneScapeProfileType type = types[i]; if (types[i].test.test(client)) { return type; } } return STANDARD; } }
runelite/runelite
runelite-client/src/main/java/net/runelite/client/config/RuneScapeProfileType.java
46,022
package cc.hicore.qtool.XPWork.LittleHook; import cc.hicore.HookItemLoader.Annotations.CommonExecutor; import cc.hicore.HookItemLoader.Annotations.VerController; import cc.hicore.HookItemLoader.Annotations.XPItem; import cc.hicore.ReflectUtils.Classes; import cc.hicore.ReflectUtils.MClass; import cc.hicore.ReflectUtils.MMethod; import de.robv.android.xposed.XC_MethodHook; import de.robv.android.xposed.XposedHelpers; @XPItem(name = "XP_Save", itemType = XPItem.ITEM_Hook) public class SavedToXml { @VerController @CommonExecutor public void execute() { XposedHelpers.findAndHookMethod(MClass.loadClass("com.tencent.mobileqq.data.MessageForStarLeague"), "decodeMsgFromXmlBuff", Classes.QQAppinterFace(), int.class, long.class, byte[].class, int.class, new XC_MethodHook() { @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { byte[] arr = MMethod.CallMethod(null, MClass.loadClass("com.tencent.mobileqq.structmsg.StructMsgUtils"), "a", byte[].class, new Class[]{byte[].class, int.class}, param.args[3], -1); MMethod.CallMethodParams(param.getResult(), "saveExtInfoToExtStr", void.class, "SavedXml", new String(arr)); } }); } }
Hicores/QTool
QTool/src/main/java/cc/hicore/qtool/XPWork/LittleHook/SavedToXml.java
46,023
package com.github.guang19.designpattern.mediator; /** * @author guang19 * @date 2020/5/30 * @description 抽象中介者 * @since 1.0.0 */ public abstract class Mediator { //注册同事 public abstract void registerColleague(Colleague colleague); //转发消息 public abstract void forwardMessage(Colleague colleague,String message); }
imlhx/framework-learning
design_pattern/src/main/java/com/github/guang19/designpattern/mediator/Mediator.java
46,024
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; class Main { public static int f91 (int n) { if (n<=100) { return f91(f91(n+11)); } return n-10; } public static void main(String[]args) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String s; while (!(s=br.readLine()).equals("0")) { int value=Integer.parseInt(s); System.out.println("f91("+value+") = "+f91(value)); } } }
PuzzlesLab/PuzzlesCon
PuzzlesCon Bronze League/Bronze League V/A/5980639_kingkingyyk_A.java
46,025
import java.util.Scanner; import java.util.StringTokenizer; public class Main { public static void main (String [] args) { Scanner sc=new Scanner(System.in); StringTokenizer st; int n=Integer.parseInt(sc.nextLine()); for (int gg=0;gg<n;gg++) { st=new StringTokenizer(sc.nextLine()); int sum=Integer.parseInt(st.nextToken()); int diff=Integer.parseInt(st.nextToken()); if (sum<diff || (sum+diff)%2!=0) { System.out.println("impossible"); } else { int x=(sum+diff)/2; int y=(sum-diff)/2; System.out.println(Math.max(x,y)+" "+Math.min(x,y)); } } } }
PuzzlesLab/PuzzlesCon
PuzzlesCon Bronze League/Bronze League I/B/2837374_kingkingyyk_B.java
46,026
package com.matter.tv.app.api; /** * Helper class to hold the IDs and corresponding constants for media related clusters. TODO : Add * the rest of the media clusters TODO : Maybe generate using ZAP tool */ public class Clusters { // Clusters public static class AccountLogin { public static final int Id = 0x050E; public static class Commands { public static class GetSetupPIN { public static final int ID = 0x00; public static class Fields { public static final int TempAccountIdentifier = 0x00; } } public static class GetSetupPINResponse { public static final int ID = 0x01; public static class Fields { public static final int SetupPIN = 0x00; } } public static class Login { public static final int ID = 0x02; } public static class Logout { public static final int ID = 0x03; } } } public static class MediaPlayback { public static final int Id = 0x0506; public static class Commands { public static class Play { public static final int ID = 0x00; } public static class Pause { public static final int ID = 0x01; } public static class StopPlayback { public static final int ID = 0x02; } public static class StartOver { public static final int ID = 0x03; } public static class Previous { public static final int ID = 0x04; } public static class Next { public static final int ID = 0x05; } public static class Rewind { public static final int ID = 0x06; } public static class FastForward { public static final int ID = 0x07; } public static class SkipForward { public static final int ID = 0x08; public static class Fields { public static final int DeltaPositionMilliseconds = 0x00; } } public static class SkipBackward { public static final int ID = 0x09; public static class Fields { public static final int DeltaPositionMilliseconds = 0x00; } } public static class Seek { public static final int ID = 0x0B; public static class Fields { public static final int Position = 0x00; } } public static class PlaybackResponse { public static final int ID = 0x0A; public static class Fields { public static final int Status = 0x00; public static final int Data = 0x01; } } } public static class Attributes { public static final int CurrentState = 0x00; public static final int StartTime = 0x01; public static final int Duration = 0x02; public static final int SampledPosition = 0x03; public static final int PlaybackSpeed = 0x04; public static final int SeekRangeEnd = 0x05; public static final int SeekRangeStart = 0x06; } public static class Types { public static class PlaybackStateEnum { public static final int Playing = 0x00; public static final int Paused = 0x01; public static final int NotPlaying = 0x02; public static final int Buffering = 0x03; } public static class StatusEnum { public static final int Success = 0x00; public static final int InvalidStateForCommand = 0x01; public static final int NotAllowed = 0x02; public static final int NotActive = 0x03; public static final int SpeedOutOfRange = 0x04; public static final int SeekOutOfRange = 0x05; } public static class PlaybackPosition { public static final int UpdatedAt = 0x00; public static final int Position = 0x01; } } } public static class ContentLauncher { public static final int Id = 0x050A; public static class Commands { public static class LaunchContent { public static final int ID = 0x00; public static class Fields { public static final int Search = 0x00; public static final int AutoPlay = 0x01; public static final int Data = 0x02; } } public static class LaunchURL { public static final int ID = 0x01; public static class Fields { public static final int ContentURL = 0x00; public static final int DisplayString = 0x01; public static final int BrandingInformation = 0x02; } } public static class LaunchResponse { public static final int ID = 0x02; public static class Fields { public static final int Status = 0x00; public static final int Data = 0x01; } } } public static class Attributes { public static final int AcceptHeader = 0x00; public static final int SupportedStreamingProtocols = 0x01; } public static class Types { public static class ContentSearch { public static final int ParameterList = 0x00; } public static class StatusEnum { public static final int Success = 0x00; public static final int UrlNotAvailable = 0x01; public static final int AuthFailed = 0x02; } public static class Parameter { public static final int Type = 0x00; public static final int Value = 0x01; public static final int ExternalIDList = 0x02; } public static class ParameterEnum { public static final int Actor = 0x00; public static final int Channel = 0x01; public static final int Character = 0x02; public static final int Director = 0x03; public static final int Event = 0x04; public static final int Franchise = 0x05; public static final int Genre = 0x06; public static final int League = 0x07; public static final int Popularity = 0x08; public static final int Provider = 0x09; public static final int Sport = 0x0A; public static final int SportsTeam = 0x0B; public static final int Type = 0x0C; public static final int Video = 0x0D; } public static class AdditionalInfo { public static final int Name = 0x00; public static final int Value = 0x01; } public static class BrandingInformation { public static final int ProviderName = 0x00; public static final int Background = 0x01; public static final int Logo = 0x02; public static final int ProgressBar = 0x03; public static final int Splash = 0x04; public static final int WaterMark = 0x05; } public static class StyleInformation { public static final int ProviderName = 0x00; public static final int Background = 0x01; public static final int Logo = 0x02; } public static class Dimension { public static final int ImageUrl = 0x00; public static final int Color = 0x01; public static final int Size = 0x02; } public static class MetricTypeEnum { public static final int Pixels = 0x00; public static final int Percentage = 0x01; } } } public static class TargetNavigator { public static final int Id = 0x0505; public static class Commands { public static class NavigateTarget { public static final int ID = 0x00; public static class Fields { public static final int Target = 0x00; public static final int Data = 0x01; } } public static class NavigateTargetResponse { public static final int ID = 0x01; public static class Fields { public static final int Status = 0x00; public static final int Data = 0x01; } } } public static class Attributes { public static final int TargetList = 0x00; public static final int CurrentTarget = 0x01; } public static class Types { public static class TargetInfo { public static final int Identifier = 0x00; public static final int Name = 0x01; } public static class StatusEnum { public static final int Success = 0x00; public static final int TargetNotFound = 0x01; public static final int NotAllowed = 0x02; } } } }
project-chip/connectedhomeip
examples/tv-app/android/App/common-api/src/main/java/com/matter/tv/app/api/Clusters.java
46,027
/* * Copyright (c) 2018, Adam <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.runelite.client.plugins.xptracker; import net.runelite.api.Client; import net.runelite.api.WorldType; enum XpWorldType { NORMAL, TOURNEY, DMM { @Override int modifier(Client client) { return 5; } }, LEAGUE { @Override int modifier(Client client) { return 5; } }; int modifier(Client client) { return 1; } static XpWorldType of(WorldType type) { switch (type) { case NOSAVE_MODE: return TOURNEY; case DEADMAN: return DMM; case SEASONAL: return LEAGUE; default: return NORMAL; } } }
runelite/runelite
runelite-client/src/main/java/net/runelite/client/plugins/xptracker/XpWorldType.java
46,028
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static int emptyCount=0; public static int getValue (int v) { int count=v; while (v>=1) { if (v%3==2) { if (emptyCount>0) { v=v+1; emptyCount--; } else { v=v-2; emptyCount+=2; } } else if (v%3==1) { if (emptyCount>=2) { v=v+2; emptyCount-=2; } else { v=v-1; emptyCount++; } } v/=3; count+=v; } return count; } public static void main(String[]args) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String s; while ((s=br.readLine())!=null) { int v=Integer.parseInt(s); emptyCount=1; int sum=getValue(v); System.out.println(sum); } } }
PuzzlesLab/PuzzlesCon
PuzzlesCon Bronze League/Bronze League IV/D/5867898_kingkingyyk_D.java
46,029
/* * MegaMek - Copyright (C) 2005 Ben Mazur ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. */ package megamek.client.ratgenerator; import megamek.common.*; import org.apache.logging.log4j.LogManager; import java.util.ArrayList; import java.util.EnumSet; import java.util.Set; /** * Specific unit variants; analyzes equipment to determine suitability for certain types * of missions in addition to what is formally declared in the data files. * * @author Neoancient */ public class ModelRecord extends AbstractUnitRecord { public static final int NETWORK_NONE = 0; public static final int NETWORK_C3_SLAVE = 1; public static final int NETWORK_BA_C3 = 1; public static final int NETWORK_C3_MASTER = 1 << 1; public static final int NETWORK_C3I = 1 << 2; public static final int NETWORK_NAVAL_C3 = 1 << 2; public static final int NETWORK_NOVA = 1 << 3; public static final int NETWORK_BOOSTED = 1 << 4; public static final int NETWORK_COMPANY_COMMAND = 1 << 5; public static final int NETWORK_BOOSTED_SLAVE = NETWORK_C3_SLAVE | NETWORK_BOOSTED; public static final int NETWORK_BOOSTED_MASTER = NETWORK_C3_MASTER | NETWORK_BOOSTED; private MechSummary mechSummary; private boolean starLeague; private int weightClass; private EntityMovementMode movementMode; private EnumSet<MissionRole> roles; private ArrayList<String> deployedWith; private ArrayList<String> requiredUnits; private ArrayList<String> excludedFactions; private int networkMask; private double flak; //proportion of weapon BV that can fire flak ammo private double longRange; //proportion of weapon BV with range >= 20 hexes private int speed; private double ammoRequirement; //used to determine suitability for raider role private boolean incendiary; //used to determine suitability for incindiary role private boolean apWeapons; //used to determine suitability for anti-infantry role private boolean mechanizedBA; private boolean magClamp; public ModelRecord(String chassis, String model) { super(chassis); roles = EnumSet.noneOf(MissionRole.class); deployedWith = new ArrayList<>(); requiredUnits = new ArrayList<>(); excludedFactions = new ArrayList<>(); networkMask = NETWORK_NONE; flak = 0.0; longRange = 0.0; } public ModelRecord(MechSummary ms) { this(ms.getFullChassis(), ms.getModel()); mechSummary = ms; unitType = parseUnitType(ms.getUnitType()); introYear = ms.getYear(); if (unitType == UnitType.MEK) { //TODO: id quads and tripods movementMode = EntityMovementMode.BIPED; omni = ms.getUnitSubType().equals("Omni"); } else { movementMode = EntityMovementMode.parseFromString(ms.getUnitSubType().toLowerCase()); } double totalBV = 0.0; double flakBV = 0.0; double lrBV = 0.0; double ammoBV = 0.0; boolean losTech = false; for (int i = 0; i < ms.getEquipmentNames().size(); i++) { //EquipmentType.get is throwing an NPE intermittently, and the only possibility I can see //is that there is a null equipment name. if (null == ms.getEquipmentNames().get(i)) { LogManager.getLogger().error( "RATGenerator ModelRecord encountered null equipment name in MechSummary for " + ms.getName() + ", index " + i); continue; } EquipmentType eq = EquipmentType.get(ms.getEquipmentNames().get(i)); if (eq == null) { continue; } if (!eq.isAvailableIn(3000, false)) { //FIXME: needs to filter out primitive losTech = true; } if (eq instanceof WeaponType) { totalBV += eq.getBV(null) * ms.getEquipmentQuantities().get(i); switch (((megamek.common.weapons.Weapon) eq).getAmmoType()) { case AmmoType.T_AC_LBX: case AmmoType.T_HAG: case AmmoType.T_SBGAUSS: flakBV += eq.getBV(null) * ms.getEquipmentQuantities().get(i); } if (eq.hasFlag(WeaponType.F_ARTILLERY)) { flakBV += eq.getBV(null) * ms.getEquipmentQuantities().get(i) / 2.0; roles.add(((WeaponType) eq).getAmmoType() == AmmoType.T_ARROW_IV? MissionRole.MISSILE_ARTILLERY : MissionRole.ARTILLERY); } if (eq.hasFlag(WeaponType.F_FLAMER) || eq.hasFlag(WeaponType.F_INFERNO)) { incendiary = true; apWeapons = true; } incendiary |= ((WeaponType) eq).getAmmoType() == AmmoType.T_SRM || ((WeaponType) eq).getAmmoType() == AmmoType.T_SRM_IMP || ((WeaponType) eq).getAmmoType() == AmmoType.T_MRM; if (eq instanceof megamek.common.weapons.mgs.MGWeapon || eq instanceof megamek.common.weapons.defensivepods.BPodWeapon) { apWeapons = true; } if (((WeaponType) eq).getAmmoType() > megamek.common.AmmoType.T_NA) { ammoBV += eq.getBV(null) * ms.getEquipmentQuantities().get(i); } if (((WeaponType) eq).getLongRange() >= 20) { lrBV += eq.getBV(null) * ms.getEquipmentQuantities().get(i); } if (eq.hasFlag(WeaponType.F_TAG)) { roles.add(MissionRole.SPOTTER); } if (eq.hasFlag(WeaponType.F_C3M)) { networkMask |= NETWORK_C3_MASTER; if (ms.getEquipmentQuantities().get(i) > 1) { networkMask |= NETWORK_COMPANY_COMMAND; } } if (eq.hasFlag(WeaponType.F_C3MBS)) { networkMask |= NETWORK_BOOSTED_MASTER; if (ms.getEquipmentQuantities().get(i) > 1) { networkMask |= NETWORK_COMPANY_COMMAND; } } } else if (eq instanceof MiscType) { if (eq.hasFlag(MiscType.F_UMU)) { movementMode = EntityMovementMode.BIPED_SWIM; } else if (eq.hasFlag(MiscType.F_C3S)) { networkMask |= NETWORK_C3_SLAVE; } else if (eq.hasFlag(MiscType.F_C3I)) { networkMask |= NETWORK_C3I; } else if (eq.hasFlag(MiscType.F_C3SBS)) { networkMask |= NETWORK_BOOSTED_SLAVE; } else if (eq.hasFlag(MiscType.F_NOVA)) { networkMask |= NETWORK_NOVA; } else if (eq.hasFlag(MiscType.F_MAGNETIC_CLAMP)) { magClamp = true; } } } if (totalBV > 0 && (ms.getUnitType().equals("Mek") || ms.getUnitType().equals("Tank") || ms.getUnitType().equals("BattleArmor") || ms.getUnitType().equals("Infantry") || ms.getUnitType().equals("ProtoMek") || ms.getUnitType().equals("Naval") || ms.getUnitType().equals("Gun Emplacement"))) { flak = flakBV / totalBV; longRange = lrBV / totalBV; ammoRequirement = ammoBV / totalBV; } weightClass = ms.getWeightClass(); if (weightClass >= EntityWeightClass.WEIGHT_SMALL_SUPPORT) { if (ms.getTons() <= 39) { weightClass = EntityWeightClass.WEIGHT_LIGHT; } else if (ms.getTons() <= 59) { weightClass = EntityWeightClass.WEIGHT_MEDIUM; } else if (ms.getTons() <= 79) { weightClass = EntityWeightClass.WEIGHT_HEAVY; } else if (ms.getTons() <= 100) { weightClass = EntityWeightClass.WEIGHT_ASSAULT; } else { weightClass = EntityWeightClass.WEIGHT_COLOSSAL; } } clan = ms.isClan(); if (megamek.common.Engine.getEngineTypeByString(ms.getEngineName()) == megamek.common.Engine.XL_ENGINE || ms.getArmorType().contains(EquipmentType.T_ARMOR_FERRO_FIBROUS) || ms.getInternalsType() == EquipmentType.T_STRUCTURE_ENDO_STEEL) { losTech = true; } starLeague = losTech && !clan; speed = ms.getWalkMp(); if (ms.getJumpMp() > 0) { speed++; } } public String getModel() { return mechSummary.getModel(); } public int getWeightClass() { return weightClass; } public EntityMovementMode getMovementMode() { return movementMode; } @Override public boolean isClan() { return clan; } public boolean isSL() { return starLeague; } public Set<MissionRole> getRoles() { return roles; } public ArrayList<String> getDeployedWith() { return deployedWith; } public ArrayList<String> getRequiredUnits() { return requiredUnits; } public ArrayList<String> getExcludedFactions() { return excludedFactions; } public int getNetworkMask() { return networkMask; } public void setNetwork(int network) { this.networkMask = network; } public double getFlak() { return flak; } public void setFlak(double flak) { this.flak = flak; } public double getLongRange() { return longRange; } public int getSpeed() { return speed; } public double getAmmoRequirement() { return ammoRequirement; } public boolean hasIncendiaryWeapon() { return incendiary; } public boolean hasAPWeapons() { return apWeapons; } public MechSummary getMechSummary() { return mechSummary; } public void addRoles(String str) { if (str.isBlank()) { roles.clear(); } else { String[] fields = str.split(","); for (String role : fields) { MissionRole mr = MissionRole.parseRole(role); if (mr != null) { roles.add(mr); } else { LogManager.getLogger().error("Could not parse mission role for " + getChassis() + " " + getModel() + ": " + role); } } } } public void setRequiredUnits(String str) { String[] subfields = str.split(","); for (String unit : subfields) { if (unit.startsWith("req:")) { requiredUnits.add(unit.replace("req:", "")); } else { deployedWith.add(unit); } } } public void setExcludedFactions(String str) { excludedFactions.clear(); String[] fields = str.split(","); for (String faction : fields) { excludedFactions.add(faction); } } public boolean factionIsExcluded(FactionRecord fRec) { return excludedFactions.contains(fRec.getKey()); } public boolean factionIsExcluded(String faction, String subfaction) { if (subfaction == null) { return excludedFactions.contains(faction); } else { return excludedFactions.contains(faction + "." + subfaction); } } @Override public String getKey() { return mechSummary.getName(); } public boolean canDoMechanizedBA() { return mechanizedBA; } public void setMechanizedBA(boolean mech) { mechanizedBA = mech; } public boolean hasMagClamp() { return magClamp; } public void setMagClamp(boolean magClamp) { this.magClamp = magClamp; } }
MegaMek/megamek
megamek/src/megamek/client/ratgenerator/ModelRecord.java
46,030
package com.hundredwordsgof.mediator; /** * Mediator defines an interface for communicating with Colleague objects. * */ public interface Mediator { void notifyColleague(Colleague colleague, String message); }
CS3398-Jedda-Knights/100-words-design-patterns-java
src/main/java/com/hundredwordsgof/mediator/Mediator.java
46,031
/* * Copyright (c) 2021-2022 - The MegaMek Team. All Rights Reserved. * * This file is part of MekHQ. * * MekHQ is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MekHQ is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MekHQ. If not, see <http://www.gnu.org/licenses/>. */ package mekhq.gui.panels; import megamek.client.ui.baseComponents.MMComboBox; import megamek.client.ui.enums.ValidationState; import megamek.common.EntityWeightClass; import megamek.common.annotations.Nullable; import mekhq.MekHQ; import mekhq.campaign.Campaign; import mekhq.campaign.personnel.enums.PersonnelRole; import mekhq.campaign.universe.Factions; import mekhq.campaign.universe.companyGeneration.CompanyGenerationOptions; import mekhq.campaign.universe.enums.*; import mekhq.gui.FileDialogs; import mekhq.gui.baseComponents.AbstractMHQScrollablePanel; import megamek.client.ui.baseComponents.JDisableablePanel; import mekhq.gui.displayWrappers.FactionDisplay; import javax.swing.*; import javax.swing.GroupLayout.Alignment; import javax.swing.JSpinner.NumberEditor; import java.awt.*; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.TreeMap; /** * @author Justin "Windchild" Bowen */ public class CompanyGenerationOptionsPanel extends AbstractMHQScrollablePanel { //region Variable Declarations private final Campaign campaign; // Base Information private MMComboBox<CompanyGenerationMethod> comboCompanyGenerationMethod; private MMComboBox<FactionDisplay> comboSpecifiedFaction; private JCheckBox chkGenerateMercenaryCompanyCommandLance; private JSpinner spnCompanyCount; private JSpinner spnIndividualLanceCount; private JSpinner spnLancesPerCompany; private JSpinner spnLanceSize; private JSpinner spnStarLeagueYear; // Personnel private JLabel lblTotalSupportPersonnel; private Map<PersonnelRole, JSpinner> spnSupportPersonnelNumbers; private JCheckBox chkPoolAssistants; private JCheckBox chkGenerateCaptains; private JCheckBox chkAssignCompanyCommanderFlag; private JCheckBox chkApplyOfficerStatBonusToWorstSkill; private JCheckBox chkAssignBestCompanyCommander; private JCheckBox chkPrioritizeCompanyCommanderCombatSkills; private JCheckBox chkAssignBestOfficers; private JCheckBox chkPrioritizeOfficerCombatSkills; private JCheckBox chkAssignMostSkilledToPrimaryLances; private JCheckBox chkAutomaticallyAssignRanks; private JCheckBox chkUseSpecifiedFactionToAssignRanks; private JCheckBox chkAssignMechWarriorsCallsigns; private JCheckBox chkAssignFounderFlag; // Personnel Randomization private RandomOriginOptionsPanel randomOriginOptionsPanel; // Starting Simulation private JCheckBox chkRunStartingSimulation; private JSpinner spnSimulationDuration; private JCheckBox chkSimulateRandomMarriages; private JCheckBox chkSimulateRandomProcreation; // Units private MMComboBox<BattleMechFactionGenerationMethod> comboBattleMechFactionGenerationMethod; private MMComboBox<BattleMechWeightClassGenerationMethod> comboBattleMechWeightClassGenerationMethod; private MMComboBox<BattleMechQualityGenerationMethod> comboBattleMechQualityGenerationMethod; private JCheckBox chkNeverGenerateStarLeagueMechs; private JCheckBox chkOnlyGenerateStarLeagueMechs; private JCheckBox chkOnlyGenerateOmniMechs; private JCheckBox chkGenerateUnitsAsAttached; private JCheckBox chkAssignBestRollToCompanyCommander; private JCheckBox chkSortStarLeagueUnitsFirst; private JCheckBox chkGroupByWeight; private JCheckBox chkGroupByQuality; private JCheckBox chkKeepOfficerRollsSeparate; private JCheckBox chkAssignTechsToUnits; // Unit private MMComboBox<ForceNamingMethod> comboForceNamingMethod; private JCheckBox chkGenerateForceIcons; private JCheckBox chkUseSpecifiedFactionToGenerateForceIcons; private JCheckBox chkGenerateOriginNodeForceIcon; private JCheckBox chkUseOriginNodeForceIconLogo; private Map<Integer, JSpinner> spnForceWeightLimits; // Spares private JCheckBox chkGenerateMothballedSpareUnits; private JSpinner spnSparesPercentOfActiveUnits; private MMComboBox<PartGenerationMethod> comboPartGenerationMethod; private JSpinner spnStartingArmourWeight; private JCheckBox chkGenerateSpareAmmunition; private JSpinner spnNumberReloadsPerWeapon; private JCheckBox chkGenerateFractionalMachineGunAmmunition; // Contracts private JCheckBox chkSelectStartingContract; private JCheckBox chkStartCourseToContractPlanet; // Finances private JCheckBox chkProcessFinances; private JSpinner spnStartingCash; private JCheckBox chkRandomizeStartingCash; private JSpinner spnRandomStartingCashDiceCount; private JSpinner spnMinimumStartingFloat; private JCheckBox chkIncludeInitialContractPayment; private JCheckBox chkStartingLoan; private JCheckBox chkPayForSetup; private JCheckBox chkPayForPersonnel; private JCheckBox chkPayForUnits; private JCheckBox chkPayForParts; private JCheckBox chkPayForArmour; private JCheckBox chkPayForAmmunition; // Surprises private JCheckBox chkGenerateSurprises; private JCheckBox chkGenerateMysteryBoxes; private Map<MysteryBoxType, JCheckBox> chkGenerateMysteryBoxTypes; //endregion Variable Declarations //region Constructors public CompanyGenerationOptionsPanel(final JFrame frame, final Campaign campaign, final @Nullable CompanyGenerationOptions companyGenerationOptions) { super(frame, "CompanyGenerationOptionsPanel", new GridBagLayout()); this.campaign = campaign; setTracksViewportWidth(false); initialize(); if (companyGenerationOptions == null) { setOptions(MekHQ.getMHQOptions().getDefaultCompanyGenerationMethod()); } else { setOptions(companyGenerationOptions); } } //endregion Constructors //region Getters/Setters public Campaign getCampaign() { return campaign; } //region Base Information public MMComboBox<CompanyGenerationMethod> getComboCompanyGenerationMethod() { return comboCompanyGenerationMethod; } public void setComboCompanyGenerationMethod(final MMComboBox<CompanyGenerationMethod> comboCompanyGenerationMethod) { this.comboCompanyGenerationMethod = comboCompanyGenerationMethod; } public MMComboBox<FactionDisplay> getComboSpecifiedFaction() { return comboSpecifiedFaction; } public void setComboSpecifiedFaction(final MMComboBox<FactionDisplay> comboSpecifiedFaction) { this.comboSpecifiedFaction = comboSpecifiedFaction; } public JCheckBox getChkGenerateMercenaryCompanyCommandLance() { return chkGenerateMercenaryCompanyCommandLance; } public void setChkGenerateMercenaryCompanyCommandLance(final JCheckBox chkGenerateMercenaryCompanyCommandLance) { this.chkGenerateMercenaryCompanyCommandLance = chkGenerateMercenaryCompanyCommandLance; } public JSpinner getSpnCompanyCount() { return spnCompanyCount; } public void setSpnCompanyCount(final JSpinner spnCompanyCount) { this.spnCompanyCount = spnCompanyCount; } public JSpinner getSpnIndividualLanceCount() { return spnIndividualLanceCount; } public void setSpnIndividualLanceCount(final JSpinner spnIndividualLanceCount) { this.spnIndividualLanceCount = spnIndividualLanceCount; } public JSpinner getSpnLancesPerCompany() { return spnLancesPerCompany; } public void setSpnLancesPerCompany(final JSpinner spnLancesPerCompany) { this.spnLancesPerCompany = spnLancesPerCompany; } public JSpinner getSpnLanceSize() { return spnLanceSize; } public void setSpnLanceSize(final JSpinner spnLanceSize) { this.spnLanceSize = spnLanceSize; } public JSpinner getSpnStarLeagueYear() { return spnStarLeagueYear; } public void setSpnStarLeagueYear(final JSpinner spnStarLeagueYear) { this.spnStarLeagueYear = spnStarLeagueYear; } //endregion Base Information //region Personnel public JLabel getLblTotalSupportPersonnel() { return lblTotalSupportPersonnel; } public void updateLblTotalSupportPersonnel(final int numSupportPersonnel) { getLblTotalSupportPersonnel().setText(String.format( resources.getString("lblTotalSupportPersonnel.text"), numSupportPersonnel)); } public void setLblTotalSupportPersonnel(final JLabel lblTotalSupportPersonnel) { this.lblTotalSupportPersonnel = lblTotalSupportPersonnel; } public Map<PersonnelRole, JSpinner> getSpnSupportPersonnelNumbers() { return spnSupportPersonnelNumbers; } public void setSpnSupportPersonnelNumbers(final Map<PersonnelRole, JSpinner> spnSupportPersonnelNumbers) { this.spnSupportPersonnelNumbers = spnSupportPersonnelNumbers; } public JCheckBox getChkPoolAssistants() { return chkPoolAssistants; } public void setChkPoolAssistants(final JCheckBox chkPoolAssistants) { this.chkPoolAssistants = chkPoolAssistants; } public JCheckBox getChkGenerateCaptains() { return chkGenerateCaptains; } public void setChkGenerateCaptains(final JCheckBox chkGenerateCaptains) { this.chkGenerateCaptains = chkGenerateCaptains; } public JCheckBox getChkAssignCompanyCommanderFlag() { return chkAssignCompanyCommanderFlag; } public void setChkAssignCompanyCommanderFlag(final JCheckBox chkAssignCompanyCommanderFlag) { this.chkAssignCompanyCommanderFlag = chkAssignCompanyCommanderFlag; } public JCheckBox getChkApplyOfficerStatBonusToWorstSkill() { return chkApplyOfficerStatBonusToWorstSkill; } public void setChkApplyOfficerStatBonusToWorstSkill(final JCheckBox chkApplyOfficerStatBonusToWorstSkill) { this.chkApplyOfficerStatBonusToWorstSkill = chkApplyOfficerStatBonusToWorstSkill; } public JCheckBox getChkAssignBestCompanyCommander() { return chkAssignBestCompanyCommander; } public void setChkAssignBestCompanyCommander(final JCheckBox chkAssignBestCompanyCommander) { this.chkAssignBestCompanyCommander = chkAssignBestCompanyCommander; } public JCheckBox getChkPrioritizeCompanyCommanderCombatSkills() { return chkPrioritizeCompanyCommanderCombatSkills; } public void setChkPrioritizeCompanyCommanderCombatSkills(final JCheckBox chkPrioritizeCompanyCommanderCombatSkills) { this.chkPrioritizeCompanyCommanderCombatSkills = chkPrioritizeCompanyCommanderCombatSkills; } public JCheckBox getChkAssignBestOfficers() { return chkAssignBestOfficers; } public void setChkAssignBestOfficers(final JCheckBox chkAssignBestOfficers) { this.chkAssignBestOfficers = chkAssignBestOfficers; } public JCheckBox getChkPrioritizeOfficerCombatSkills() { return chkPrioritizeOfficerCombatSkills; } public void setChkPrioritizeOfficerCombatSkills(final JCheckBox chkPrioritizeOfficerCombatSkills) { this.chkPrioritizeOfficerCombatSkills = chkPrioritizeOfficerCombatSkills; } public JCheckBox getChkAssignMostSkilledToPrimaryLances() { return chkAssignMostSkilledToPrimaryLances; } public void setChkAssignMostSkilledToPrimaryLances(final JCheckBox chkAssignMostSkilledToPrimaryLances) { this.chkAssignMostSkilledToPrimaryLances = chkAssignMostSkilledToPrimaryLances; } public JCheckBox getChkAutomaticallyAssignRanks() { return chkAutomaticallyAssignRanks; } public void setChkAutomaticallyAssignRanks(final JCheckBox chkAutomaticallyAssignRanks) { this.chkAutomaticallyAssignRanks = chkAutomaticallyAssignRanks; } public JCheckBox getChkUseSpecifiedFactionToAssignRanks() { return chkUseSpecifiedFactionToAssignRanks; } public void setChkUseSpecifiedFactionToAssignRanks(final JCheckBox chkUseSpecifiedFactionToAssignRanks) { this.chkUseSpecifiedFactionToAssignRanks = chkUseSpecifiedFactionToAssignRanks; } public JCheckBox getChkAssignMechWarriorsCallsigns() { return chkAssignMechWarriorsCallsigns; } public void setChkAssignMechWarriorsCallsigns(final JCheckBox chkAssignMechWarriorsCallsigns) { this.chkAssignMechWarriorsCallsigns = chkAssignMechWarriorsCallsigns; } public JCheckBox getChkAssignFounderFlag() { return chkAssignFounderFlag; } public void setChkAssignFounderFlag(final JCheckBox chkAssignFounderFlag) { this.chkAssignFounderFlag = chkAssignFounderFlag; } //endregion Personnel //region Personnel Randomization public RandomOriginOptionsPanel getRandomOriginOptionsPanel() { return randomOriginOptionsPanel; } public void setRandomOriginOptionsPanel(final RandomOriginOptionsPanel randomOriginOptionsPanel) { this.randomOriginOptionsPanel = randomOriginOptionsPanel; } //endregion Personnel Randomization //region Starting Simulation public JCheckBox getChkRunStartingSimulation() { return chkRunStartingSimulation; } public void setChkRunStartingSimulation(final JCheckBox chkRunStartingSimulation) { this.chkRunStartingSimulation = chkRunStartingSimulation; } public JSpinner getSpnSimulationDuration() { return spnSimulationDuration; } public void setSpnSimulationDuration(final JSpinner spnSimulationDuration) { this.spnSimulationDuration = spnSimulationDuration; } public JCheckBox getChkSimulateRandomMarriages() { return chkSimulateRandomMarriages; } public void setChkSimulateRandomMarriages(final JCheckBox chkSimulateRandomMarriages) { this.chkSimulateRandomMarriages = chkSimulateRandomMarriages; } public JCheckBox getChkSimulateRandomProcreation() { return chkSimulateRandomProcreation; } public void setChkSimulateRandomProcreation(final JCheckBox chkSimulateRandomProcreation) { this.chkSimulateRandomProcreation = chkSimulateRandomProcreation; } //endregion Starting Simulation //region Units public MMComboBox<BattleMechFactionGenerationMethod> getComboBattleMechFactionGenerationMethod() { return comboBattleMechFactionGenerationMethod; } public void setComboBattleMechFactionGenerationMethod( final MMComboBox<BattleMechFactionGenerationMethod> comboBattleMechFactionGenerationMethod) { this.comboBattleMechFactionGenerationMethod = comboBattleMechFactionGenerationMethod; } public MMComboBox<BattleMechWeightClassGenerationMethod> getComboBattleMechWeightClassGenerationMethod() { return comboBattleMechWeightClassGenerationMethod; } public void setComboBattleMechWeightClassGenerationMethod( final MMComboBox<BattleMechWeightClassGenerationMethod> comboBattleMechWeightClassGenerationMethod) { this.comboBattleMechWeightClassGenerationMethod = comboBattleMechWeightClassGenerationMethod; } public MMComboBox<BattleMechQualityGenerationMethod> getComboBattleMechQualityGenerationMethod() { return comboBattleMechQualityGenerationMethod; } public void setComboBattleMechQualityGenerationMethod( final MMComboBox<BattleMechQualityGenerationMethod> comboBattleMechQualityGenerationMethod) { this.comboBattleMechQualityGenerationMethod = comboBattleMechQualityGenerationMethod; } public JCheckBox getChkNeverGenerateStarLeagueMechs() { return chkNeverGenerateStarLeagueMechs; } public void setChkNeverGenerateStarLeagueMechs(final JCheckBox chkNeverGenerateStarLeagueMechs) { this.chkNeverGenerateStarLeagueMechs = chkNeverGenerateStarLeagueMechs; } public JCheckBox getChkOnlyGenerateStarLeagueMechs() { return chkOnlyGenerateStarLeagueMechs; } public void setChkOnlyGenerateStarLeagueMechs(JCheckBox chkOnlyGenerateStarLeagueMechs) { this.chkOnlyGenerateStarLeagueMechs = chkOnlyGenerateStarLeagueMechs; } public JCheckBox getChkOnlyGenerateOmniMechs() { return chkOnlyGenerateOmniMechs; } public void setChkOnlyGenerateOmniMechs(JCheckBox chkOnlyGenerateOmniMechs) { this.chkOnlyGenerateOmniMechs = chkOnlyGenerateOmniMechs; } public JCheckBox getChkGenerateUnitsAsAttached() { return chkGenerateUnitsAsAttached; } public void setChkGenerateUnitsAsAttached(final JCheckBox chkGenerateUnitsAsAttached) { this.chkGenerateUnitsAsAttached = chkGenerateUnitsAsAttached; } public JCheckBox getChkAssignBestRollToCompanyCommander() { return chkAssignBestRollToCompanyCommander; } public void setChkAssignBestRollToCompanyCommander(final JCheckBox chkAssignBestRollToCompanyCommander) { this.chkAssignBestRollToCompanyCommander = chkAssignBestRollToCompanyCommander; } public JCheckBox getChkSortStarLeagueUnitsFirst() { return chkSortStarLeagueUnitsFirst; } public void setChkSortStarLeagueUnitsFirst(final JCheckBox chkSortStarLeagueUnitsFirst) { this.chkSortStarLeagueUnitsFirst = chkSortStarLeagueUnitsFirst; } public JCheckBox getChkGroupByWeight() { return chkGroupByWeight; } public void setChkGroupByWeight(final JCheckBox chkGroupByWeight) { this.chkGroupByWeight = chkGroupByWeight; } public JCheckBox getChkGroupByQuality() { return chkGroupByQuality; } public void setChkGroupByQuality(final JCheckBox chkGroupByQuality) { this.chkGroupByQuality = chkGroupByQuality; } public JCheckBox getChkKeepOfficerRollsSeparate() { return chkKeepOfficerRollsSeparate; } public void setChkKeepOfficerRollsSeparate(final JCheckBox chkKeepOfficerRollsSeparate) { this.chkKeepOfficerRollsSeparate = chkKeepOfficerRollsSeparate; } public JCheckBox getChkAssignTechsToUnits() { return chkAssignTechsToUnits; } public void setChkAssignTechsToUnits(final JCheckBox chkAssignTechsToUnits) { this.chkAssignTechsToUnits = chkAssignTechsToUnits; } //endregion Units //region Unit public MMComboBox<ForceNamingMethod> getComboForceNamingMethod() { return comboForceNamingMethod; } public void setComboForceNamingMethod(final MMComboBox<ForceNamingMethod> comboForceNamingMethod) { this.comboForceNamingMethod = comboForceNamingMethod; } public JCheckBox getChkGenerateForceIcons() { return chkGenerateForceIcons; } public void setChkGenerateForceIcons(final JCheckBox chkGenerateForceIcons) { this.chkGenerateForceIcons = chkGenerateForceIcons; } public JCheckBox getChkUseSpecifiedFactionToGenerateForceIcons() { return chkUseSpecifiedFactionToGenerateForceIcons; } public void setChkUseSpecifiedFactionToGenerateForceIcons( final JCheckBox chkUseSpecifiedFactionToGenerateForceIcons) { this.chkUseSpecifiedFactionToGenerateForceIcons = chkUseSpecifiedFactionToGenerateForceIcons; } public JCheckBox getChkGenerateOriginNodeForceIcon() { return chkGenerateOriginNodeForceIcon; } public void setChkGenerateOriginNodeForceIcon(final JCheckBox chkGenerateOriginNodeForceIcon) { this.chkGenerateOriginNodeForceIcon = chkGenerateOriginNodeForceIcon; } public JCheckBox getChkUseOriginNodeForceIconLogo() { return chkUseOriginNodeForceIconLogo; } public void setChkUseOriginNodeForceIconLogo(final JCheckBox chkUseOriginNodeForceIconLogo) { this.chkUseOriginNodeForceIconLogo = chkUseOriginNodeForceIconLogo; } public Map<Integer, JSpinner> getSpnForceWeightLimits() { return spnForceWeightLimits; } public void setSpnForceWeightLimits(final Map<Integer, JSpinner> spnForceWeightLimits) { this.spnForceWeightLimits = spnForceWeightLimits; } //endregion Unit //region Spares public JCheckBox getChkGenerateMothballedSpareUnits() { return chkGenerateMothballedSpareUnits; } public void setChkGenerateMothballedSpareUnits(final JCheckBox chkGenerateMothballedSpareUnits) { this.chkGenerateMothballedSpareUnits = chkGenerateMothballedSpareUnits; } public JSpinner getSpnSparesPercentOfActiveUnits() { return spnSparesPercentOfActiveUnits; } public void setSpnSparesPercentOfActiveUnits(final JSpinner spnSparesPercentOfActiveUnits) { this.spnSparesPercentOfActiveUnits = spnSparesPercentOfActiveUnits; } public MMComboBox<PartGenerationMethod> getComboPartGenerationMethod() { return comboPartGenerationMethod; } public void setComboPartGenerationMethod(final MMComboBox<PartGenerationMethod> comboPartGenerationMethod) { this.comboPartGenerationMethod = comboPartGenerationMethod; } public JSpinner getSpnStartingArmourWeight() { return spnStartingArmourWeight; } public void setSpnStartingArmourWeight(final JSpinner spnStartingArmourWeight) { this.spnStartingArmourWeight = spnStartingArmourWeight; } public JCheckBox getChkGenerateSpareAmmunition() { return chkGenerateSpareAmmunition; } public void setChkGenerateSpareAmmunition(final JCheckBox chkGenerateSpareAmmunition) { this.chkGenerateSpareAmmunition = chkGenerateSpareAmmunition; } public JSpinner getSpnNumberReloadsPerWeapon() { return spnNumberReloadsPerWeapon; } public void setSpnNumberReloadsPerWeapon(final JSpinner spnNumberReloadsPerWeapon) { this.spnNumberReloadsPerWeapon = spnNumberReloadsPerWeapon; } public JCheckBox getChkGenerateFractionalMachineGunAmmunition() { return chkGenerateFractionalMachineGunAmmunition; } public void setChkGenerateFractionalMachineGunAmmunition(final JCheckBox chkGenerateFractionalMachineGunAmmunition) { this.chkGenerateFractionalMachineGunAmmunition = chkGenerateFractionalMachineGunAmmunition; } //endregion Spares //region Contracts public JCheckBox getChkSelectStartingContract() { return chkSelectStartingContract; } public void setChkSelectStartingContract(final JCheckBox chkSelectStartingContract) { this.chkSelectStartingContract = chkSelectStartingContract; } public JCheckBox getChkStartCourseToContractPlanet() { return chkStartCourseToContractPlanet; } public void setChkStartCourseToContractPlanet(final JCheckBox chkStartCourseToContractPlanet) { this.chkStartCourseToContractPlanet = chkStartCourseToContractPlanet; } //endregion Contracts //region Finances public JCheckBox getChkProcessFinances() { return chkProcessFinances; } public void setChkProcessFinances(final JCheckBox chkProcessFinances) { this.chkProcessFinances = chkProcessFinances; } public JSpinner getSpnStartingCash() { return spnStartingCash; } public void setSpnStartingCash(final JSpinner spnStartingCash) { this.spnStartingCash = spnStartingCash; } public JCheckBox getChkRandomizeStartingCash() { return chkRandomizeStartingCash; } public void setChkRandomizeStartingCash(final JCheckBox chkRandomizeStartingCash) { this.chkRandomizeStartingCash = chkRandomizeStartingCash; } public JSpinner getSpnRandomStartingCashDiceCount() { return spnRandomStartingCashDiceCount; } public void setSpnRandomStartingCashDiceCount(final JSpinner spnRandomStartingCashDiceCount) { this.spnRandomStartingCashDiceCount = spnRandomStartingCashDiceCount; } public JSpinner getSpnMinimumStartingFloat() { return spnMinimumStartingFloat; } public void setSpnMinimumStartingFloat(final JSpinner spnMinimumStartingFloat) { this.spnMinimumStartingFloat = spnMinimumStartingFloat; } public JCheckBox getChkIncludeInitialContractPayment() { return chkIncludeInitialContractPayment; } public void setChkIncludeInitialContractPayment(final JCheckBox chkIncludeInitialContractPayment) { this.chkIncludeInitialContractPayment = chkIncludeInitialContractPayment; } public JCheckBox getChkStartingLoan() { return chkStartingLoan; } public void setChkStartingLoan(final JCheckBox chkStartingLoan) { this.chkStartingLoan = chkStartingLoan; } public JCheckBox getChkPayForSetup() { return chkPayForSetup; } public void setChkPayForSetup(final JCheckBox chkPayForSetup) { this.chkPayForSetup = chkPayForSetup; } public JCheckBox getChkPayForPersonnel() { return chkPayForPersonnel; } public void setChkPayForPersonnel(final JCheckBox chkPayForPersonnel) { this.chkPayForPersonnel = chkPayForPersonnel; } public JCheckBox getChkPayForUnits() { return chkPayForUnits; } public void setChkPayForUnits(final JCheckBox chkPayForUnits) { this.chkPayForUnits = chkPayForUnits; } public JCheckBox getChkPayForParts() { return chkPayForParts; } public void setChkPayForParts(final JCheckBox chkPayForParts) { this.chkPayForParts = chkPayForParts; } public JCheckBox getChkPayForArmour() { return chkPayForArmour; } public void setChkPayForArmour(final JCheckBox chkPayForArmour) { this.chkPayForArmour = chkPayForArmour; } public JCheckBox getChkPayForAmmunition() { return chkPayForAmmunition; } public void setChkPayForAmmunition(final JCheckBox chkPayForAmmunition) { this.chkPayForAmmunition = chkPayForAmmunition; } //endregion Finances //region Surprises public JCheckBox getChkGenerateSurprises() { return chkGenerateSurprises; } public void setChkGenerateSurprises(final JCheckBox chkGenerateSurprises) { this.chkGenerateSurprises = chkGenerateSurprises; } public JCheckBox getChkGenerateMysteryBoxes() { return chkGenerateMysteryBoxes; } public void setChkGenerateMysteryBoxes(final JCheckBox chkGenerateMysteryBoxes) { this.chkGenerateMysteryBoxes = chkGenerateMysteryBoxes; } public Map<MysteryBoxType, JCheckBox> getChkGenerateMysteryBoxTypes() { return chkGenerateMysteryBoxTypes; } public void setChkGenerateMysteryBoxTypes(final Map<MysteryBoxType, JCheckBox> chkGenerateMysteryBoxTypes) { this.chkGenerateMysteryBoxTypes = chkGenerateMysteryBoxTypes; } //endregion Surprises //endregion Getters/Setters //region Determination Methods public int determineMaximumSupportPersonnel() { return ((getChkGenerateMercenaryCompanyCommandLance().isSelected() ? 1 : 0) + ((int) getSpnCompanyCount().getValue() * (int) getSpnLancesPerCompany().getValue()) + (int) getSpnIndividualLanceCount().getValue()) * (int) getSpnLanceSize().getValue(); } //endregion Determination Methods //region Initialization @Override protected void initialize() { final GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; gbc.anchor = GridBagConstraints.NORTHWEST; gbc.fill = GridBagConstraints.HORIZONTAL; add(createBaseInformationPanel(), gbc); gbc.gridx++; add(createPersonnelPanel(), gbc); gbc.gridx = 0; gbc.gridy++; add(createPersonnelRandomizationPanel(), gbc); gbc.gridx++; add(createStartingSimulationPanel(), gbc); gbc.gridx = 0; gbc.gridy++; add(createUnitsPanel(), gbc); gbc.gridx++; add(createUnitPanel(), gbc); gbc.gridx = 0; gbc.gridy++; add(createSparesPanel(), gbc); gbc.gridx++; add(createContractsPanel(), gbc); gbc.gridx = 0; gbc.gridy++; add(createFinancesPanel(), gbc); gbc.gridx++; add(createSurprisesPanel(), gbc); } private JPanel createBaseInformationPanel() { // Create Panel Components final JLabel lblCompanyGenerationMethod = new JLabel(resources.getString("lblCompanyGenerationMethod.text")); lblCompanyGenerationMethod.setToolTipText(resources.getString("lblCompanyGenerationMethod.toolTipText")); lblCompanyGenerationMethod.setName("lblCompanyGenerationMethod"); setComboCompanyGenerationMethod(new MMComboBox<>("comboCompanyGenerationMethod", CompanyGenerationMethod.values())); getComboCompanyGenerationMethod().setToolTipText(resources.getString("lblCompanyGenerationMethod.toolTipText")); getComboCompanyGenerationMethod().setRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(final JList<?> list, final Object value, final int index, final boolean isSelected, final boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (value instanceof CompanyGenerationMethod) { list.setToolTipText(((CompanyGenerationMethod) value).getToolTipText()); } return this; } }); final JLabel lblSpecifiedFaction = new JLabel(resources.getString("lblSpecifiedFaction.text")); lblSpecifiedFaction.setToolTipText(resources.getString("lblSpecifiedFaction.toolTipText")); lblSpecifiedFaction.setName("lblSpecifiedFaction"); final DefaultComboBoxModel<FactionDisplay> specifiedFactionModel = new DefaultComboBoxModel<>(); specifiedFactionModel.addAll(FactionDisplay .getSortedValidFactionDisplays(Factions.getInstance().getChoosableFactions(), getCampaign().getLocalDate())); setComboSpecifiedFaction(new MMComboBox<>("comboFaction", specifiedFactionModel)); getComboSpecifiedFaction().setToolTipText(resources.getString("lblSpecifiedFaction.toolTipText")); setChkGenerateMercenaryCompanyCommandLance(new JCheckBox(resources.getString("chkGenerateMercenaryCompanyCommandLance.text"))); getChkGenerateMercenaryCompanyCommandLance().setToolTipText(resources.getString("chkGenerateMercenaryCompanyCommandLance.toolTipText")); getChkGenerateMercenaryCompanyCommandLance().setName("chkGenerateMercenaryCompanyCommandLance"); final JLabel lblCompanyCount = new JLabel(resources.getString("lblCompanyCount.text")); lblCompanyCount.setToolTipText(resources.getString("lblCompanyCount.toolTipText")); lblCompanyCount.setName("lblCompanyCount"); setSpnCompanyCount(new JSpinner(new SpinnerNumberModel(0, 0, 5, 1))); getSpnCompanyCount().setToolTipText(resources.getString("lblCompanyCount.toolTipText")); getSpnCompanyCount().setName("spnCompanyCount"); final JLabel lblIndividualLanceCount = new JLabel(resources.getString("lblIndividualLanceCount.text")); lblIndividualLanceCount.setToolTipText(resources.getString("lblIndividualLanceCount.toolTipText")); lblIndividualLanceCount.setName("lblIndividualLanceCount"); setSpnIndividualLanceCount(new JSpinner(new SpinnerNumberModel(0, 0, 2, 1))); getSpnIndividualLanceCount().setToolTipText(resources.getString("lblIndividualLanceCount.toolTipText")); getSpnIndividualLanceCount().setName("spnIndividualLanceCount"); final JLabel lblLancesPerCompany = new JLabel(resources.getString("lblLancesPerCompany.text")); lblLancesPerCompany.setToolTipText(resources.getString("lblLancesPerCompany.toolTipText")); lblLancesPerCompany.setName("lblLancesPerCompany"); setSpnLancesPerCompany(new JSpinner(new SpinnerNumberModel(3, 2, 6, 1))); getSpnLancesPerCompany().setToolTipText(resources.getString("lblLancesPerCompany.toolTipText")); getSpnLancesPerCompany().setName("spnLancesPerCompany"); final JLabel lblLanceSize = new JLabel(resources.getString("lblLanceSize.text")); lblLanceSize.setToolTipText(resources.getString("lblLanceSize.toolTipText")); lblLanceSize.setName("lblLanceSize"); setSpnLanceSize(new JSpinner(new SpinnerNumberModel(4, 3, 6, 1))); getSpnLanceSize().setToolTipText(resources.getString("lblLanceSize.toolTipText")); getSpnLanceSize().setName("spnLanceSize"); final JLabel lblStarLeagueYear = new JLabel(resources.getString("lblStarLeagueYear.text")); lblStarLeagueYear.setToolTipText(resources.getString("lblStarLeagueYear.toolTipText")); lblStarLeagueYear.setName("lblStarLeagueYear"); setSpnStarLeagueYear(new JSpinner(new SpinnerNumberModel(2765, 2571, 2780, 1))); getSpnStarLeagueYear().setToolTipText(resources.getString("lblStarLeagueYear.toolTipText")); getSpnStarLeagueYear().setName("spnStarLeagueYear"); getSpnStarLeagueYear().setEditor(new NumberEditor(getSpnStarLeagueYear(), "#")); // Programmatically Assign Accessibility Labels lblCompanyGenerationMethod.setLabelFor(getComboCompanyGenerationMethod()); lblSpecifiedFaction.setLabelFor(getComboSpecifiedFaction()); lblCompanyCount.setLabelFor(getSpnCompanyCount()); lblIndividualLanceCount.setLabelFor(getSpnIndividualLanceCount()); lblLancesPerCompany.setLabelFor(getSpnLancesPerCompany()); lblLanceSize.setLabelFor(getSpnLanceSize()); lblStarLeagueYear.setLabelFor(getSpnStarLeagueYear()); // Layout the UI final JPanel panel = new JPanel(); panel.setBorder(BorderFactory.createTitledBorder(resources.getString("baseInformationPanel.title"))); panel.setName("baseInformationPanel"); final GroupLayout layout = new GroupLayout(panel); panel.setLayout(layout); layout.setAutoCreateGaps(true); layout.setAutoCreateContainerGaps(true); layout.setVerticalGroup( layout.createSequentialGroup() .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(lblCompanyGenerationMethod) .addComponent(getComboCompanyGenerationMethod(), Alignment.LEADING)) .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(lblSpecifiedFaction) .addComponent(getComboSpecifiedFaction(), Alignment.LEADING)) .addComponent(getChkGenerateMercenaryCompanyCommandLance()) .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(lblCompanyCount) .addComponent(getSpnCompanyCount()) .addComponent(lblIndividualLanceCount) .addComponent(getSpnIndividualLanceCount(), Alignment.LEADING)) .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(lblLancesPerCompany) .addComponent(getSpnLancesPerCompany()) .addComponent(lblLanceSize) .addComponent(getSpnLanceSize(), Alignment.LEADING)) .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(lblStarLeagueYear) .addComponent(getSpnStarLeagueYear(), Alignment.LEADING)) ); layout.setHorizontalGroup( layout.createParallelGroup(Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(lblCompanyGenerationMethod) .addComponent(getComboCompanyGenerationMethod())) .addGroup(layout.createSequentialGroup() .addComponent(lblSpecifiedFaction) .addComponent(getComboSpecifiedFaction())) .addComponent(getChkGenerateMercenaryCompanyCommandLance()) .addGroup(layout.createSequentialGroup() .addComponent(lblCompanyCount) .addComponent(getSpnCompanyCount()) .addComponent(lblIndividualLanceCount) .addComponent(getSpnIndividualLanceCount())) .addGroup(layout.createSequentialGroup() .addComponent(lblLancesPerCompany) .addComponent(getSpnLancesPerCompany()) .addComponent(lblLanceSize) .addComponent(getSpnLanceSize())) .addGroup(layout.createSequentialGroup() .addComponent(lblStarLeagueYear) .addComponent(getSpnStarLeagueYear())) ); return panel; } private JPanel createPersonnelPanel() { // Create Panel Components setLblTotalSupportPersonnel(new JLabel()); updateLblTotalSupportPersonnel(0); getLblTotalSupportPersonnel().setToolTipText(resources.getString("lblTotalSupportPersonnel.toolTipText")); getLblTotalSupportPersonnel().setName("lblTotalSupportPersonnel"); final JPanel supportPersonnelNumbersPanel = createSupportPersonnelNumbersPanel(); setChkPoolAssistants(new JCheckBox(resources.getString("chkPoolAssistants.text"))); getChkPoolAssistants().setToolTipText(resources.getString("chkPoolAssistants.toolTipText")); getChkPoolAssistants().setName("chkPoolAssistants"); setChkGenerateCaptains(new JCheckBox(resources.getString("chkGenerateCaptains.text"))); getChkGenerateCaptains().setToolTipText(resources.getString("chkGenerateCaptains.toolTipText")); getChkGenerateCaptains().setName("chkGenerateCaptains"); setChkAssignCompanyCommanderFlag(new JCheckBox(resources.getString("chkAssignCompanyCommanderFlag.text"))); getChkAssignCompanyCommanderFlag().setToolTipText(resources.getString("chkAssignCompanyCommanderFlag.toolTipText")); getChkAssignCompanyCommanderFlag().setName("chkAssignCompanyCommanderFlag"); setChkApplyOfficerStatBonusToWorstSkill(new JCheckBox(resources.getString("chkApplyOfficerStatBonusToWorstSkill.text"))); getChkApplyOfficerStatBonusToWorstSkill().setToolTipText(resources.getString("chkApplyOfficerStatBonusToWorstSkill.toolTipText")); getChkApplyOfficerStatBonusToWorstSkill().setName("chkApplyOfficerStatBonusToWorstSkill"); setChkAssignBestCompanyCommander(new JCheckBox(resources.getString("chkAssignBestCompanyCommander.text"))); getChkAssignBestCompanyCommander().setToolTipText(resources.getString("chkAssignBestCompanyCommander.toolTipText")); getChkAssignBestCompanyCommander().setName("chkAssignBestCompanyCommander"); getChkAssignBestCompanyCommander().addActionListener(evt -> getChkPrioritizeCompanyCommanderCombatSkills().setEnabled(getChkAssignBestCompanyCommander().isSelected())); setChkPrioritizeCompanyCommanderCombatSkills(new JCheckBox(resources.getString("chkPrioritizeCompanyCommanderCombatSkills.text"))); getChkPrioritizeCompanyCommanderCombatSkills().setToolTipText(resources.getString("chkPrioritizeCompanyCommanderCombatSkills.toolTipText")); getChkPrioritizeCompanyCommanderCombatSkills().setName("chkPrioritizeCompanyCommanderCombatSkills"); setChkAssignBestOfficers(new JCheckBox(resources.getString("chkAssignBestOfficers.text"))); getChkAssignBestOfficers().setToolTipText(resources.getString("chkAssignBestOfficers.toolTipText")); getChkAssignBestOfficers().setName("chkAssignBestOfficers"); getChkAssignBestOfficers().addActionListener(evt -> getChkPrioritizeOfficerCombatSkills().setEnabled(getChkAssignBestOfficers().isSelected())); setChkPrioritizeOfficerCombatSkills(new JCheckBox(resources.getString("chkPrioritizeOfficerCombatSkills.text"))); getChkPrioritizeOfficerCombatSkills().setToolTipText(resources.getString("chkPrioritizeOfficerCombatSkills.toolTipText")); getChkPrioritizeOfficerCombatSkills().setName("chkPrioritizeOfficerCombatSkills"); setChkAssignMostSkilledToPrimaryLances(new JCheckBox(resources.getString("chkAssignMostSkilledToPrimaryLances.text"))); getChkAssignMostSkilledToPrimaryLances().setToolTipText(resources.getString("chkAssignMostSkilledToPrimaryLances.toolTipText")); getChkAssignMostSkilledToPrimaryLances().setName("chkAssignMostSkilledToPrimaryLances"); setChkAutomaticallyAssignRanks(new JCheckBox(resources.getString("chkAutomaticallyAssignRanks.text"))); getChkAutomaticallyAssignRanks().setToolTipText(resources.getString("chkAutomaticallyAssignRanks.toolTipText")); getChkAutomaticallyAssignRanks().setName("chkAutomaticallyAssignRanks"); setChkUseSpecifiedFactionToAssignRanks(new JCheckBox(resources.getString("chkUseSpecifiedFactionToAssignRanks.text"))); getChkUseSpecifiedFactionToAssignRanks().setToolTipText(resources.getString("chkUseSpecifiedFactionToAssignRanks.toolTipText")); getChkUseSpecifiedFactionToAssignRanks().setName("chkUseSpecifiedFactionToAssignRanks"); setChkAssignMechWarriorsCallsigns(new JCheckBox(resources.getString("chkAssignMechWarriorsCallsigns.text"))); getChkAssignMechWarriorsCallsigns().setToolTipText(resources.getString("chkAssignMechWarriorsCallsigns.toolTipText")); getChkAssignMechWarriorsCallsigns().setName("chkAssignMechWarriorsCallsigns"); setChkAssignFounderFlag(new JCheckBox(resources.getString("chkAssignFounderFlag.text"))); getChkAssignFounderFlag().setToolTipText(resources.getString("chkAssignFounderFlag.toolTipText")); getChkAssignFounderFlag().setName("chkAssignFounderFlag"); // Disable Panel Portions by Default getChkAssignBestCompanyCommander().setSelected(true); getChkAssignBestCompanyCommander().doClick(); getChkAssignBestOfficers().setSelected(true); getChkAssignBestOfficers().doClick(); // Layout the UI final JPanel panel = new JPanel(); panel.setBorder(BorderFactory.createTitledBorder(resources.getString("personnelPanel.title"))); panel.setName("personnelPanel"); final GroupLayout layout = new GroupLayout(panel); panel.setLayout(layout); layout.setAutoCreateGaps(true); layout.setAutoCreateContainerGaps(true); layout.setVerticalGroup( layout.createSequentialGroup() .addComponent(getLblTotalSupportPersonnel()) .addComponent(supportPersonnelNumbersPanel) .addComponent(getChkPoolAssistants()) .addComponent(getChkGenerateCaptains()) .addComponent(getChkAssignCompanyCommanderFlag()) .addComponent(getChkApplyOfficerStatBonusToWorstSkill()) .addComponent(getChkAssignBestCompanyCommander()) .addComponent(getChkPrioritizeCompanyCommanderCombatSkills()) .addComponent(getChkAssignBestOfficers()) .addComponent(getChkPrioritizeOfficerCombatSkills()) .addComponent(getChkAssignMostSkilledToPrimaryLances()) .addComponent(getChkAutomaticallyAssignRanks()) .addComponent(getChkUseSpecifiedFactionToAssignRanks()) .addComponent(getChkAssignMechWarriorsCallsigns()) .addComponent(getChkAssignFounderFlag()) ); layout.setHorizontalGroup( layout.createParallelGroup(Alignment.LEADING) .addComponent(getLblTotalSupportPersonnel()) .addComponent(supportPersonnelNumbersPanel) .addComponent(getChkPoolAssistants()) .addComponent(getChkGenerateCaptains()) .addComponent(getChkAssignCompanyCommanderFlag()) .addComponent(getChkApplyOfficerStatBonusToWorstSkill()) .addComponent(getChkAssignBestCompanyCommander()) .addComponent(getChkPrioritizeCompanyCommanderCombatSkills()) .addComponent(getChkAssignBestOfficers()) .addComponent(getChkPrioritizeOfficerCombatSkills()) .addComponent(getChkAssignMostSkilledToPrimaryLances()) .addComponent(getChkAutomaticallyAssignRanks()) .addComponent(getChkUseSpecifiedFactionToAssignRanks()) .addComponent(getChkAssignMechWarriorsCallsigns()) .addComponent(getChkAssignFounderFlag()) ); return panel; } private JPanel createSupportPersonnelNumbersPanel() { final PersonnelRole[] personnelRoles = new PersonnelRole[] { PersonnelRole.MECH_TECH, PersonnelRole.MECHANIC, PersonnelRole.AERO_TECH, PersonnelRole.BA_TECH, PersonnelRole.DOCTOR, PersonnelRole.ADMINISTRATOR_COMMAND, PersonnelRole.ADMINISTRATOR_LOGISTICS, PersonnelRole.ADMINISTRATOR_TRANSPORT, PersonnelRole.ADMINISTRATOR_HR }; // Create Panel Components setSpnSupportPersonnelNumbers(new HashMap<>()); final Map<PersonnelRole, JLabel> labels = new HashMap<>(); for (final PersonnelRole role : personnelRoles) { final String name = role.getName(getCampaign().getFaction().isClan()); final String toolTipText = String.format(resources.getString("supportPersonnelNumber.toolTipText"), name); labels.put(role, new JLabel(name)); labels.get(role).setToolTipText(toolTipText); labels.get(role).setName("lbl" + role.name()); getSpnSupportPersonnelNumbers().put(role, new JSpinner(new SpinnerNumberModel(0, 0, 100, 1))); getSpnSupportPersonnelNumbers().get(role).setToolTipText(toolTipText); getSpnSupportPersonnelNumbers().get(role).setName("spn" + role.name()); // Programmatically Assign Accessibility Labels labels.get(role).setLabelFor(getSpnSupportPersonnelNumbers().get(role)); } // Layout the UI final JPanel panel = new JPanel(new GridLayout(0, 3)); panel.setBorder(BorderFactory.createTitledBorder(resources.getString("supportPersonnelNumbersPanel.title"))); panel.setName("supportPersonnelNumbersPanel"); // This puts the label above the spinner, separated into three columns. From the // personnelRoles array declaration, the i tracks the line and the j tracks the for (int i = 0; i < (personnelRoles.length / 3); i++) { for (int j = 0; j < 3; j++) { panel.add(labels.get(personnelRoles[j + (3 * i)])); } for (int j = 0; j < 3; j++) { panel.add(getSpnSupportPersonnelNumbers().get(personnelRoles[j + (3 * i)])); } } return panel; } private JPanel createPersonnelRandomizationPanel() { setRandomOriginOptionsPanel(new RandomOriginOptionsPanel(getFrame(), getCampaign(), getCampaign().getFaction())); return getRandomOriginOptionsPanel(); } private JPanel createStartingSimulationPanel() { // Initialize Labels Used in ActionListeners final JLabel lblSimulationDuration = new JLabel(); // Create Panel Components setChkRunStartingSimulation(new JCheckBox(resources.getString("chkRunStartingSimulation.text"))); getChkRunStartingSimulation().setToolTipText(resources.getString("chkRunStartingSimulation.toolTipText")); getChkRunStartingSimulation().setName("chkRunStartingSimulation"); getChkRunStartingSimulation().addActionListener(evt -> { final boolean selected = getChkRunStartingSimulation().isSelected(); lblSimulationDuration.setEnabled(selected); getSpnSimulationDuration().setEnabled(selected); getChkSimulateRandomMarriages().setEnabled(selected); getChkSimulateRandomProcreation().setEnabled(selected); }); lblSimulationDuration.setText(resources.getString("lblSimulationDuration.text")); lblSimulationDuration.setToolTipText(resources.getString("lblSimulationDuration.toolTipText")); lblSimulationDuration.setName("lblSimulationDuration"); setSpnSimulationDuration(new JSpinner(new SpinnerNumberModel(0, 0, 25, 1))); getSpnSimulationDuration().setToolTipText(resources.getString("lblSimulationDuration.toolTipText")); getSpnSimulationDuration().setName("spnSimulationDuration"); setChkSimulateRandomMarriages(new JCheckBox(resources.getString("chkSimulateRandomMarriages.text"))); getChkSimulateRandomMarriages().setToolTipText(resources.getString("chkSimulateRandomMarriages.toolTipText")); getChkSimulateRandomMarriages().setName("chkSimulateRandomMarriages"); setChkSimulateRandomProcreation(new JCheckBox(resources.getString("chkSimulateRandomProcreation.text"))); getChkSimulateRandomProcreation().setToolTipText(resources.getString("chkSimulateRandomProcreation.toolTipText")); getChkSimulateRandomProcreation().setName("chkSimulateRandomProcreation"); // Programmatically Assign Accessibility Labels lblSimulationDuration.setLabelFor(getSpnSimulationDuration()); // Disable Panel Portions by Default getChkRunStartingSimulation().setSelected(true); getChkRunStartingSimulation().doClick(); // Layout the UI final JPanel panel = new JPanel(); panel.setBorder(BorderFactory.createTitledBorder(resources.getString("startingSimulationPanel.title"))); panel.setName("startingSimulationPanel"); final GroupLayout layout = new GroupLayout(panel); panel.setLayout(layout); layout.setAutoCreateGaps(true); layout.setAutoCreateContainerGaps(true); layout.setVerticalGroup( layout.createSequentialGroup() .addComponent(getChkRunStartingSimulation()) .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(lblSimulationDuration) .addComponent(getSpnSimulationDuration(), Alignment.LEADING)) .addComponent(getChkSimulateRandomMarriages()) .addComponent(getChkSimulateRandomProcreation()) ); layout.setHorizontalGroup( layout.createParallelGroup(Alignment.LEADING) .addComponent(getChkRunStartingSimulation()) .addGroup(layout.createSequentialGroup() .addComponent(lblSimulationDuration) .addComponent(getSpnSimulationDuration())) .addComponent(getChkSimulateRandomMarriages()) .addComponent(getChkSimulateRandomProcreation()) ); return panel; } private JPanel createUnitsPanel() { // Create Panel Components final JLabel lblBattleMechFactionGenerationMethod = new JLabel(resources.getString("lblBattleMechFactionGenerationMethod.text")); lblBattleMechFactionGenerationMethod.setToolTipText(resources.getString("lblBattleMechFactionGenerationMethod.toolTipText")); lblBattleMechFactionGenerationMethod.setName("lblBattleMechFactionGenerationMethod"); setComboBattleMechFactionGenerationMethod(new MMComboBox<>("comboBattleMechFactionGenerationMethod", BattleMechFactionGenerationMethod.values())); getComboBattleMechFactionGenerationMethod().setToolTipText(resources.getString("lblBattleMechFactionGenerationMethod.toolTipText")); getComboBattleMechFactionGenerationMethod().setRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(final JList<?> list, final Object value, final int index, final boolean isSelected, final boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (value instanceof BattleMechFactionGenerationMethod) { list.setToolTipText(((BattleMechFactionGenerationMethod) value).getToolTipText()); } return this; } }); final JLabel lblBattleMechWeightClassGenerationMethod = new JLabel(resources.getString("lblBattleMechWeightClassGenerationMethod.text")); lblBattleMechWeightClassGenerationMethod.setToolTipText(resources.getString("lblBattleMechWeightClassGenerationMethod.toolTipText")); lblBattleMechWeightClassGenerationMethod.setName("lblBattleMechWeightClassGenerationMethod"); setComboBattleMechWeightClassGenerationMethod(new MMComboBox<>("comboBattleMechWeightClassGenerationMethod", BattleMechWeightClassGenerationMethod.values())); getComboBattleMechWeightClassGenerationMethod().setToolTipText(resources.getString("lblBattleMechWeightClassGenerationMethod.toolTipText")); getComboBattleMechWeightClassGenerationMethod().setRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(final JList<?> list, final Object value, final int index, final boolean isSelected, final boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (value instanceof BattleMechWeightClassGenerationMethod) { list.setToolTipText(((BattleMechWeightClassGenerationMethod) value).getToolTipText()); } return this; } }); final JLabel lblBattleMechQualityGenerationMethod = new JLabel(resources.getString("lblBattleMechQualityGenerationMethod.text")); lblBattleMechQualityGenerationMethod.setToolTipText(resources.getString("lblBattleMechQualityGenerationMethod.toolTipText")); lblBattleMechQualityGenerationMethod.setName("lblBattleMechQualityGenerationMethod"); setComboBattleMechQualityGenerationMethod(new MMComboBox<>("comboBattleMechQualityGenerationMethod", BattleMechQualityGenerationMethod.values())); getComboBattleMechQualityGenerationMethod().setToolTipText(resources.getString("lblBattleMechQualityGenerationMethod.toolTipText")); getComboBattleMechQualityGenerationMethod().setRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(final JList<?> list, final Object value, final int index, final boolean isSelected, final boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (value instanceof BattleMechQualityGenerationMethod) { list.setToolTipText(((BattleMechQualityGenerationMethod) value).getToolTipText()); } return this; } }); setChkNeverGenerateStarLeagueMechs(new JCheckBox(resources.getString("chkNeverGenerateStarLeagueMechs.text"))); getChkNeverGenerateStarLeagueMechs().setToolTipText(resources.getString("chkNeverGenerateStarLeagueMechs.toolTipText")); getChkNeverGenerateStarLeagueMechs().setName("chkNeverGenerateStarLeagueMechs"); getChkNeverGenerateStarLeagueMechs().addActionListener(evt -> getChkOnlyGenerateStarLeagueMechs().setEnabled(!getChkNeverGenerateStarLeagueMechs().isSelected())); setChkOnlyGenerateStarLeagueMechs(new JCheckBox(resources.getString("chkOnlyGenerateStarLeagueMechs.text"))); getChkOnlyGenerateStarLeagueMechs().setToolTipText(resources.getString("chkOnlyGenerateStarLeagueMechs.toolTipText")); getChkOnlyGenerateStarLeagueMechs().setName("chkOnlyGenerateStarLeagueMechs"); getChkOnlyGenerateStarLeagueMechs().addActionListener(evt -> getChkNeverGenerateStarLeagueMechs().setEnabled(!getChkOnlyGenerateStarLeagueMechs().isSelected())); setChkOnlyGenerateOmniMechs(new JCheckBox(resources.getString("chkOnlyGenerateOmniMechs.text"))); getChkOnlyGenerateOmniMechs().setToolTipText(resources.getString("chkOnlyGenerateOmniMechs.toolTipText")); getChkOnlyGenerateOmniMechs().setName("chkOnlyGenerateOmniMechs"); setChkGenerateUnitsAsAttached(new JCheckBox(resources.getString("chkGenerateUnitsAsAttached.text"))); getChkGenerateUnitsAsAttached().setToolTipText(resources.getString("chkGenerateUnitsAsAttached.toolTipText")); getChkGenerateUnitsAsAttached().setName("chkGenerateUnitsAsAttached"); setChkAssignBestRollToCompanyCommander(new JCheckBox(resources.getString("chkAssignBestRollToCompanyCommander.text"))); getChkAssignBestRollToCompanyCommander().setToolTipText(resources.getString("chkAssignBestRollToCompanyCommander.toolTipText")); getChkAssignBestRollToCompanyCommander().setName("chkAssignBestRollToCompanyCommander"); setChkSortStarLeagueUnitsFirst(new JCheckBox(resources.getString("chkSortStarLeagueUnitsFirst.text"))); getChkSortStarLeagueUnitsFirst().setToolTipText(resources.getString("chkSortStarLeagueUnitsFirst.toolTipText")); getChkSortStarLeagueUnitsFirst().setName("chkSortStarLeagueUnitsFirst"); setChkGroupByWeight(new JCheckBox(resources.getString("chkGroupByWeight.text"))); getChkGroupByWeight().setToolTipText(resources.getString("chkGroupByWeight.toolTipText")); getChkGroupByWeight().setName("chkGroupByWeight"); setChkGroupByQuality(new JCheckBox(resources.getString("chkGroupByQuality.text"))); getChkGroupByQuality().setToolTipText(resources.getString("chkGroupByQuality.toolTipText")); getChkGroupByQuality().setName("chkGroupByQuality"); setChkKeepOfficerRollsSeparate(new JCheckBox(resources.getString("chkKeepOfficerRollsSeparate.text"))); getChkKeepOfficerRollsSeparate().setToolTipText(resources.getString("chkKeepOfficerRollsSeparate.toolTipText")); getChkKeepOfficerRollsSeparate().setName("chkKeepOfficerRollsSeparate"); setChkAssignTechsToUnits(new JCheckBox(resources.getString("chkAssignTechsToUnits.text"))); getChkAssignTechsToUnits().setToolTipText(resources.getString("chkAssignTechsToUnits.toolTipText")); getChkAssignTechsToUnits().setName("chkAssignTechsToUnits"); // Programmatically Assign Accessibility Labels lblBattleMechFactionGenerationMethod.setLabelFor(getComboBattleMechFactionGenerationMethod()); lblBattleMechWeightClassGenerationMethod.setLabelFor(getComboBattleMechWeightClassGenerationMethod()); lblBattleMechQualityGenerationMethod.setLabelFor(getComboBattleMechQualityGenerationMethod()); // Layout the UI final JPanel panel = new JPanel(); panel.setBorder(BorderFactory.createTitledBorder(resources.getString("unitsPanel.title"))); panel.setName("unitsPanel"); final GroupLayout layout = new GroupLayout(panel); panel.setLayout(layout); layout.setAutoCreateGaps(true); layout.setAutoCreateContainerGaps(true); layout.setVerticalGroup( layout.createSequentialGroup() .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(lblBattleMechFactionGenerationMethod) .addComponent(getComboBattleMechFactionGenerationMethod(), Alignment.LEADING)) .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(lblBattleMechWeightClassGenerationMethod) .addComponent(getComboBattleMechWeightClassGenerationMethod(), Alignment.LEADING)) .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(lblBattleMechQualityGenerationMethod) .addComponent(getComboBattleMechQualityGenerationMethod(), Alignment.LEADING)) .addComponent(getChkNeverGenerateStarLeagueMechs()) .addComponent(getChkOnlyGenerateStarLeagueMechs()) .addComponent(getChkOnlyGenerateOmniMechs()) .addComponent(getChkGenerateUnitsAsAttached()) .addComponent(getChkAssignBestRollToCompanyCommander()) .addComponent(getChkSortStarLeagueUnitsFirst()) .addComponent(getChkGroupByWeight()) .addComponent(getChkGroupByQuality()) .addComponent(getChkKeepOfficerRollsSeparate()) .addComponent(getChkAssignTechsToUnits()) ); layout.setHorizontalGroup( layout.createParallelGroup(Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(lblBattleMechFactionGenerationMethod) .addComponent(getComboBattleMechFactionGenerationMethod())) .addGroup(layout.createSequentialGroup() .addComponent(lblBattleMechWeightClassGenerationMethod) .addComponent(getComboBattleMechWeightClassGenerationMethod())) .addGroup(layout.createSequentialGroup() .addComponent(lblBattleMechQualityGenerationMethod) .addComponent(getComboBattleMechQualityGenerationMethod())) .addComponent(getChkNeverGenerateStarLeagueMechs()) .addComponent(getChkOnlyGenerateStarLeagueMechs()) .addComponent(getChkOnlyGenerateOmniMechs()) .addComponent(getChkGenerateUnitsAsAttached()) .addComponent(getChkAssignBestRollToCompanyCommander()) .addComponent(getChkSortStarLeagueUnitsFirst()) .addComponent(getChkGroupByWeight()) .addComponent(getChkGroupByQuality()) .addComponent(getChkKeepOfficerRollsSeparate()) .addComponent(getChkAssignTechsToUnits()) ); return panel; } private JPanel createUnitPanel() { // Initialize Components Used in ActionListeners final JPanel forceWeightLimitsPanel = new JDisableablePanel("forceWeightLimitsPanel"); // Create Panel Components final JLabel lblForceNamingMethod = new JLabel(resources.getString("lblForceNamingMethod.text")); lblForceNamingMethod.setToolTipText(resources.getString("lblForceNamingMethod.toolTipText")); lblForceNamingMethod.setName("lblForceNamingMethod"); setComboForceNamingMethod(new MMComboBox<>("comboForceNamingMethod", ForceNamingMethod.values())); getComboForceNamingMethod().setToolTipText(resources.getString("lblForceNamingMethod.toolTipText")); getComboForceNamingMethod().setRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(final JList<?> list, final Object value, final int index, final boolean isSelected, final boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (value instanceof ForceNamingMethod) { list.setToolTipText(((ForceNamingMethod) value).getToolTipText()); } return this; } }); setChkGenerateForceIcons(new JCheckBox(resources.getString("chkGenerateForceIcons.text"))); getChkGenerateForceIcons().setToolTipText(resources.getString("chkGenerateForceIcons.toolTipText")); getChkGenerateForceIcons().setName("chkGenerateForceIcons"); getChkGenerateForceIcons().addActionListener(evt -> { final boolean selected = getChkGenerateForceIcons().isSelected(); getChkUseSpecifiedFactionToGenerateForceIcons().setEnabled(selected); getChkGenerateOriginNodeForceIcon().setEnabled(selected); getChkUseOriginNodeForceIconLogo().setEnabled(selected && getChkGenerateOriginNodeForceIcon().isSelected()); forceWeightLimitsPanel.setEnabled(selected); }); setChkUseSpecifiedFactionToGenerateForceIcons(new JCheckBox(resources.getString("chkUseSpecifiedFactionToGenerateForceIcons.text"))); getChkUseSpecifiedFactionToGenerateForceIcons().setToolTipText(resources.getString("chkUseSpecifiedFactionToGenerateForceIcons.toolTipText")); getChkUseSpecifiedFactionToGenerateForceIcons().setName("chkUseSpecifiedFactionToGenerateForceIcons"); setChkGenerateOriginNodeForceIcon(new JCheckBox(resources.getString("chkGenerateOriginNodeForceIcon.text"))); getChkGenerateOriginNodeForceIcon().setToolTipText(resources.getString("chkGenerateOriginNodeForceIcon.toolTipText")); getChkGenerateOriginNodeForceIcon().setName("chkGenerateOriginNodeForceIcon"); getChkGenerateOriginNodeForceIcon().addActionListener(evt -> getChkUseOriginNodeForceIconLogo() .setEnabled(getChkGenerateOriginNodeForceIcon().isEnabled() && getChkGenerateOriginNodeForceIcon().isSelected())); setChkUseOriginNodeForceIconLogo(new JCheckBox(resources.getString("chkUseOriginNodeForceIconLogo.text"))); getChkUseOriginNodeForceIconLogo().setToolTipText(resources.getString("chkUseOriginNodeForceIconLogo.toolTipText")); getChkUseOriginNodeForceIconLogo().setName("chkUseOriginNodeForceIconLogo"); createForceWeightLimitsPanel(forceWeightLimitsPanel); // Programmatically Assign Accessibility Labels lblForceNamingMethod.setLabelFor(getComboForceNamingMethod()); // Layout the UI final JPanel panel = new JPanel(); panel.setBorder(BorderFactory.createTitledBorder(resources.getString("unitPanel.title"))); panel.setName("unitPanel"); final GroupLayout layout = new GroupLayout(panel); panel.setLayout(layout); layout.setAutoCreateGaps(true); layout.setAutoCreateContainerGaps(true); layout.setVerticalGroup( layout.createSequentialGroup() .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(lblForceNamingMethod) .addComponent(getComboForceNamingMethod(), Alignment.LEADING)) .addComponent(getChkGenerateForceIcons()) .addComponent(getChkUseSpecifiedFactionToGenerateForceIcons()) .addComponent(getChkGenerateOriginNodeForceIcon()) .addComponent(getChkUseOriginNodeForceIconLogo()) .addComponent(forceWeightLimitsPanel) ); layout.setHorizontalGroup( layout.createParallelGroup(Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(lblForceNamingMethod) .addComponent(getComboForceNamingMethod())) .addComponent(getChkGenerateForceIcons()) .addComponent(getChkUseSpecifiedFactionToGenerateForceIcons()) .addComponent(getChkGenerateOriginNodeForceIcon()) .addComponent(getChkUseOriginNodeForceIconLogo()) .addComponent(forceWeightLimitsPanel) ); return panel; } private void createForceWeightLimitsPanel(final JPanel panel) { // Create Panel panel.setBorder(BorderFactory.createTitledBorder(resources.getString("forceWeightLimitsPanel.title"))); panel.setToolTipText(resources.getString("forceWeightLimitsPanel.toolTipText")); panel.setLayout(new GridLayout(0, 2)); // Create Panel Components setSpnForceWeightLimits(new HashMap<>()); for (int i = EntityWeightClass.WEIGHT_ULTRA_LIGHT; i <= EntityWeightClass.WEIGHT_ASSAULT; i++) { final String weightClass = EntityWeightClass.getClassName(i); final JLabel label = new JLabel(weightClass); label.setToolTipText(resources.getString("forceWeightLimitsPanel.toolTipText")); label.setName("lbl" + weightClass); panel.add(label); getSpnForceWeightLimits().put(i, new JSpinner(new SpinnerNumberModel(0, 0, 10000, 10))); getSpnForceWeightLimits().get(i).setToolTipText(resources.getString("forceWeightLimitsPanel.toolTipText")); getSpnForceWeightLimits().get(i).setName("spn" + weightClass); panel.add(getSpnForceWeightLimits().get(i)); } } private JPanel createSparesPanel() { // Initialize Labels Used in ActionListeners final JLabel lblSparesPercentOfActiveUnits = new JLabel(); final JLabel lblNumberReloadsPerWeapon = new JLabel(); // Create Panel Components setChkGenerateMothballedSpareUnits(new JCheckBox(resources.getString("chkGenerateMothballedSpareUnits.text"))); getChkGenerateMothballedSpareUnits().setToolTipText(resources.getString("chkGenerateMothballedSpareUnits.toolTipText")); getChkGenerateMothballedSpareUnits().setName("chkGenerateMothballedSpareUnits"); getChkGenerateMothballedSpareUnits().addActionListener(evt -> { final boolean selected = getChkGenerateMothballedSpareUnits().isSelected(); lblSparesPercentOfActiveUnits.setEnabled(selected); getSpnSparesPercentOfActiveUnits().setEnabled(selected); }); lblSparesPercentOfActiveUnits.setText(resources.getString("lblSparesPercentOfActiveUnits.text")); lblSparesPercentOfActiveUnits.setToolTipText(resources.getString("lblSparesPercentOfActiveUnits.toolTipText")); lblSparesPercentOfActiveUnits.setName("lblSparesPercentOfActiveUnits"); setSpnSparesPercentOfActiveUnits(new JSpinner(new SpinnerNumberModel(0, 0, 100, 1))); getSpnSparesPercentOfActiveUnits().setToolTipText(resources.getString("chkGenerateMothballedSpareUnits.toolTipText")); getSpnSparesPercentOfActiveUnits().setName("spnGenerateMothballedSpareUnits"); final JLabel lblPartGenerationMethod = new JLabel(resources.getString("lblPartGenerationMethod.text")); lblPartGenerationMethod.setToolTipText(resources.getString("lblPartGenerationMethod.toolTipText")); lblPartGenerationMethod.setName("lblPartGenerationMethod"); setComboPartGenerationMethod(new MMComboBox<>("comboPartGenerationMethod", PartGenerationMethod.values())); getComboPartGenerationMethod().setToolTipText(resources.getString("lblPartGenerationMethod.toolTipText")); getComboPartGenerationMethod().setRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(final JList<?> list, final Object value, final int index, final boolean isSelected, final boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (value instanceof PartGenerationMethod) { list.setToolTipText(((PartGenerationMethod) value).getToolTipText()); } return this; } }); final JLabel lblStartingArmourWeight = new JLabel(resources.getString("lblStartingArmourWeight.text")); lblStartingArmourWeight.setToolTipText(resources.getString("lblStartingArmourWeight.toolTipText")); lblStartingArmourWeight.setName("lblStartingArmourWeight"); setSpnStartingArmourWeight(new JSpinner(new SpinnerNumberModel(0, 0, 500, 1))); getSpnStartingArmourWeight().setToolTipText(resources.getString("lblStartingArmourWeight.toolTipText")); getSpnStartingArmourWeight().setName("spnStartingArmourWeight"); setChkGenerateSpareAmmunition(new JCheckBox(resources.getString("chkGenerateSpareAmmunition.text"))); getChkGenerateSpareAmmunition().setToolTipText(resources.getString("chkGenerateSpareAmmunition.toolTipText")); getChkGenerateSpareAmmunition().setName("chkGenerateSpareAmmunition"); getChkGenerateSpareAmmunition().addActionListener(evt -> { final boolean selected = getChkGenerateSpareAmmunition().isSelected(); lblNumberReloadsPerWeapon.setEnabled(selected); getSpnNumberReloadsPerWeapon().setEnabled(selected); getChkGenerateFractionalMachineGunAmmunition().setEnabled(selected); }); lblNumberReloadsPerWeapon.setText(resources.getString("lblNumberReloadsPerWeapon.text")); lblNumberReloadsPerWeapon.setToolTipText(resources.getString("lblNumberReloadsPerWeapon.toolTipText")); lblNumberReloadsPerWeapon.setName("lblNumberReloadsPerWeapon"); setSpnNumberReloadsPerWeapon(new JSpinner(new SpinnerNumberModel(0, 0, 25, 1))); getSpnNumberReloadsPerWeapon().setToolTipText(resources.getString("lblNumberReloadsPerWeapon.toolTipText")); getSpnNumberReloadsPerWeapon().setName("spnNumberReloadsPerWeapon"); setChkGenerateFractionalMachineGunAmmunition(new JCheckBox(resources.getString("chkGenerateFractionalMachineGunAmmunition.text"))); getChkGenerateFractionalMachineGunAmmunition().setToolTipText(resources.getString("chkGenerateFractionalMachineGunAmmunition.toolTipText")); getChkGenerateFractionalMachineGunAmmunition().setName("chkGenerateFractionalMachineGunAmmunition"); // Programmatically Assign Accessibility Labels lblSparesPercentOfActiveUnits.setLabelFor(getSpnSparesPercentOfActiveUnits()); lblPartGenerationMethod.setLabelFor(getComboPartGenerationMethod()); lblStartingArmourWeight.setLabelFor(getSpnStartingArmourWeight()); lblNumberReloadsPerWeapon.setLabelFor(getSpnNumberReloadsPerWeapon()); // Disable Panel Portions by Default getChkGenerateMothballedSpareUnits().setSelected(true); getChkGenerateMothballedSpareUnits().doClick(); getChkGenerateSpareAmmunition().setSelected(true); getChkGenerateSpareAmmunition().doClick(); // Layout the UI final JPanel panel = new JPanel(); panel.setBorder(BorderFactory.createTitledBorder(resources.getString("sparesPanel.title"))); panel.setName("sparesPanel"); final GroupLayout layout = new GroupLayout(panel); panel.setLayout(layout); layout.setAutoCreateGaps(true); layout.setAutoCreateContainerGaps(true); layout.setVerticalGroup( layout.createSequentialGroup() .addComponent(getChkGenerateMothballedSpareUnits()) .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(lblSparesPercentOfActiveUnits) .addComponent(getSpnSparesPercentOfActiveUnits(), Alignment.LEADING)) .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(lblPartGenerationMethod) .addComponent(getComboPartGenerationMethod(), Alignment.LEADING)) .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(lblStartingArmourWeight) .addComponent(getSpnStartingArmourWeight(), Alignment.LEADING)) .addComponent(getChkGenerateSpareAmmunition()) .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(lblNumberReloadsPerWeapon) .addComponent(getSpnNumberReloadsPerWeapon(), Alignment.LEADING)) .addComponent(getChkGenerateFractionalMachineGunAmmunition()) ); layout.setHorizontalGroup( layout.createParallelGroup(Alignment.LEADING) .addComponent(getChkGenerateMothballedSpareUnits()) .addGroup(layout.createSequentialGroup() .addComponent(lblSparesPercentOfActiveUnits) .addComponent(getSpnSparesPercentOfActiveUnits())) .addGroup(layout.createSequentialGroup() .addComponent(lblPartGenerationMethod) .addComponent(getComboPartGenerationMethod())) .addGroup(layout.createSequentialGroup() .addComponent(lblStartingArmourWeight) .addComponent(getSpnStartingArmourWeight())) .addComponent(getChkGenerateSpareAmmunition()) .addGroup(layout.createSequentialGroup() .addComponent(lblNumberReloadsPerWeapon) .addComponent(getSpnNumberReloadsPerWeapon())) .addComponent(getChkGenerateFractionalMachineGunAmmunition()) ); return panel; } private JPanel createContractsPanel() { // Create Panel Components setChkSelectStartingContract(new JCheckBox(resources.getString("chkSelectStartingContract.text"))); getChkSelectStartingContract().setToolTipText(resources.getString("chkSelectStartingContract.toolTipText")); getChkSelectStartingContract().setName("chkSelectStartingContract"); getChkSelectStartingContract().addActionListener(evt -> { final boolean selected = getChkSelectStartingContract().isSelected(); getChkStartCourseToContractPlanet().setEnabled(selected); if (getChkIncludeInitialContractPayment() != null) { getChkIncludeInitialContractPayment().setEnabled(selected); } }); setChkStartCourseToContractPlanet(new JCheckBox(resources.getString("chkStartCourseToContractPlanet.text"))); getChkStartCourseToContractPlanet().setToolTipText(resources.getString("chkStartCourseToContractPlanet.toolTipText")); getChkStartCourseToContractPlanet().setName("chkStartCourseToContractPlanet"); // Disable Panel by Default getChkSelectStartingContract().setSelected(true); getChkSelectStartingContract().doClick(); // Layout the UI final JPanel panel = new JPanel(); panel.setBorder(BorderFactory.createTitledBorder(resources.getString("contractsPanel.title"))); panel.setName("contractsPanel"); final GroupLayout layout = new GroupLayout(panel); panel.setLayout(layout); layout.setAutoCreateGaps(true); layout.setAutoCreateContainerGaps(true); layout.setVerticalGroup( layout.createSequentialGroup() .addComponent(getChkSelectStartingContract()) .addComponent(getChkStartCourseToContractPlanet()) ); layout.setHorizontalGroup( layout.createParallelGroup(Alignment.LEADING) .addComponent(getChkSelectStartingContract()) .addComponent(getChkStartCourseToContractPlanet()) ); // TODO : Wave 5 : Company Generation GUI panel.setEnabled(false); getChkSelectStartingContract().setEnabled(false); getChkStartCourseToContractPlanet().setEnabled(false); return panel; } private JPanel createFinancesPanel() { // Initialize Components Used in ActionListeners final JPanel financialCreditsPanel = new JDisableablePanel("financialCreditsPanel"); final JPanel financialDebitsPanel = new JDisableablePanel("financialDebitsPanel"); // Create Panel Components setChkProcessFinances(new JCheckBox(resources.getString("chkProcessFinances.text"))); getChkProcessFinances().setToolTipText(resources.getString("chkProcessFinances.toolTipText")); getChkProcessFinances().setName("chkProcessFinances"); getChkProcessFinances().addActionListener(evt -> { final boolean selected = getChkProcessFinances().isSelected(); financialCreditsPanel.setEnabled(selected); financialDebitsPanel.setEnabled(selected); if (selected) { getChkRandomizeStartingCash().setSelected(!getChkRandomizeStartingCash().isSelected()); getChkRandomizeStartingCash().doClick(); getChkIncludeInitialContractPayment().setEnabled(getChkSelectStartingContract().isSelected()); getChkPayForSetup().setSelected(!getChkPayForSetup().isSelected()); getChkPayForSetup().doClick(); } }); createFinancialCreditsPanel(financialCreditsPanel); createFinancialDebitsPanel(financialDebitsPanel); // Disable Panel Portions by Default getChkProcessFinances().setSelected(true); getChkProcessFinances().doClick(); // Layout the UI final JPanel panel = new JPanel(); panel.setBorder(BorderFactory.createTitledBorder(resources.getString("financesPanel.title"))); panel.setName("financesPanel"); final GroupLayout layout = new GroupLayout(panel); panel.setLayout(layout); layout.setAutoCreateGaps(true); layout.setAutoCreateContainerGaps(true); layout.setVerticalGroup( layout.createSequentialGroup() .addComponent(getChkProcessFinances()) .addComponent(financialCreditsPanel) .addComponent(financialDebitsPanel) ); layout.setHorizontalGroup( layout.createParallelGroup(Alignment.LEADING) .addComponent(getChkProcessFinances()) .addComponent(financialCreditsPanel) .addComponent(financialDebitsPanel) ); return panel; } private void createFinancialCreditsPanel(final JPanel panel) { // Initialize Components Used in ActionListeners final JLabel lblRandomStartingCashDiceCount = new JLabel(); // Create Panel Components final JLabel lblStartingCash = new JLabel(resources.getString("lblStartingCash.text")); lblStartingCash.setToolTipText(resources.getString("lblStartingCash.toolTipText")); lblStartingCash.setName("lblStartingCash"); setSpnStartingCash(new JSpinner(new SpinnerNumberModel(0, 0, 200000000, 100000))); getSpnStartingCash().setToolTipText(resources.getString("lblStartingCash.toolTipText")); getSpnStartingCash().setName("spnStartingCash"); setChkRandomizeStartingCash(new JCheckBox(resources.getString("chkRandomizeStartingCash.text"))); getChkRandomizeStartingCash().setToolTipText(resources.getString("chkRandomizeStartingCash.toolTipText")); getChkRandomizeStartingCash().setName("chkRandomizeStartingCash"); getChkRandomizeStartingCash().addActionListener(evt -> { final boolean selected = getChkRandomizeStartingCash().isSelected(); lblStartingCash.setEnabled(!selected); getSpnStartingCash().setEnabled(!selected); lblRandomStartingCashDiceCount.setEnabled(selected); getSpnRandomStartingCashDiceCount().setEnabled(selected); }); lblRandomStartingCashDiceCount.setText(resources.getString("lblRandomStartingCashDiceCount.text")); lblRandomStartingCashDiceCount.setToolTipText(resources.getString("lblRandomStartingCashDiceCount.toolTipText")); lblRandomStartingCashDiceCount.setName("lblRandomStartingCashDiceCount"); setSpnRandomStartingCashDiceCount(new JSpinner(new SpinnerNumberModel(8, 1, 100, 1))); getSpnRandomStartingCashDiceCount().setToolTipText(resources.getString("lblRandomStartingCashDiceCount.toolTipText")); getSpnRandomStartingCashDiceCount().setName("spnRandomStartingCashDiceCount"); final JLabel lblMinimumStartingFloat = new JLabel(resources.getString("lblMinimumStartingFloat.text")); lblMinimumStartingFloat.setToolTipText(resources.getString("lblMinimumStartingFloat.toolTipText")); lblMinimumStartingFloat.setName("lblMinimumStartingFloat"); setSpnMinimumStartingFloat(new JSpinner(new SpinnerNumberModel(0, 0, 10000000, 100000))); getSpnMinimumStartingFloat().setToolTipText(resources.getString("lblMinimumStartingFloat.toolTipText")); getSpnMinimumStartingFloat().setName("spnMinimumStartingFloat"); setChkIncludeInitialContractPayment(new JCheckBox(resources.getString("chkIncludeInitialContractPayment.text"))); getChkIncludeInitialContractPayment().setToolTipText(resources.getString("chkIncludeInitialContractPayment.toolTipText")); getChkIncludeInitialContractPayment().setName("chkIncludeInitialContractPayment"); setChkStartingLoan(new JCheckBox(resources.getString("chkStartingLoan.text"))); getChkStartingLoan().setToolTipText(resources.getString("chkStartingLoan.toolTipText")); getChkStartingLoan().setName("chkStartingLoan"); // Programmatically Assign Accessibility Labels lblStartingCash.setLabelFor(getSpnStartingCash()); lblRandomStartingCashDiceCount.setLabelFor(getSpnRandomStartingCashDiceCount()); lblMinimumStartingFloat.setLabelFor(getSpnMinimumStartingFloat()); // Disable Panel Portions by Default // This is handled by createFinancesPanel // Layout the UI panel.setBorder(BorderFactory.createTitledBorder(resources.getString("financialCreditsPanel.title"))); final GroupLayout layout = new GroupLayout(panel); panel.setLayout(layout); layout.setAutoCreateGaps(true); layout.setAutoCreateContainerGaps(true); layout.setVerticalGroup( layout.createSequentialGroup() .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(lblStartingCash) .addComponent(getSpnStartingCash(), Alignment.LEADING)) .addComponent(getChkRandomizeStartingCash()) .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(lblRandomStartingCashDiceCount) .addComponent(getSpnRandomStartingCashDiceCount(), Alignment.LEADING)) .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(lblMinimumStartingFloat) .addComponent(getSpnMinimumStartingFloat(), Alignment.LEADING)) .addComponent(getChkIncludeInitialContractPayment()) .addComponent(getChkStartingLoan()) ); layout.setHorizontalGroup( layout.createParallelGroup(Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(lblStartingCash) .addComponent(getSpnStartingCash())) .addComponent(getChkRandomizeStartingCash()) .addGroup(layout.createSequentialGroup() .addComponent(lblRandomStartingCashDiceCount) .addComponent(getSpnRandomStartingCashDiceCount())) .addGroup(layout.createSequentialGroup() .addComponent(lblMinimumStartingFloat) .addComponent(getSpnMinimumStartingFloat())) .addComponent(getChkIncludeInitialContractPayment()) .addComponent(getChkStartingLoan()) ); } private void createFinancialDebitsPanel(final JPanel panel) { // Create Panel Components setChkPayForSetup(new JCheckBox(resources.getString("chkPayForSetup.text"))); getChkPayForSetup().setToolTipText(resources.getString("chkPayForSetup.toolTipText")); getChkPayForSetup().setName("chkPayForSetup"); getChkPayForSetup().addActionListener(evt -> { final boolean enabled = getChkPayForSetup().isEnabled() && getChkPayForSetup().isSelected(); getChkPayForPersonnel().setEnabled(enabled); getChkPayForUnits().setEnabled(enabled); getChkPayForParts().setEnabled(enabled); getChkPayForArmour().setEnabled(enabled); getChkPayForAmmunition().setEnabled(enabled); }); setChkPayForPersonnel(new JCheckBox(resources.getString("chkPayForPersonnel.text"))); getChkPayForPersonnel().setToolTipText(resources.getString("chkPayForPersonnel.toolTipText")); getChkPayForPersonnel().setName("chkPayForPersonnel"); setChkPayForUnits(new JCheckBox(resources.getString("chkPayForUnits.text"))); getChkPayForUnits().setToolTipText(resources.getString("chkPayForUnits.toolTipText")); getChkPayForUnits().setName("chkPayForUnits"); setChkPayForParts(new JCheckBox(resources.getString("chkPayForParts.text"))); getChkPayForParts().setToolTipText(resources.getString("chkPayForParts.toolTipText")); getChkPayForParts().setName("chkPayForParts"); setChkPayForArmour(new JCheckBox(resources.getString("chkPayForArmour.text"))); getChkPayForArmour().setToolTipText(resources.getString("chkPayForArmour.toolTipText")); getChkPayForArmour().setName("chkPayForArmour"); setChkPayForAmmunition(new JCheckBox(resources.getString("chkPayForAmmunition.text"))); getChkPayForAmmunition().setToolTipText(resources.getString("chkPayForAmmunition.toolTipText")); getChkPayForAmmunition().setName("chkPayForAmmunition"); // Disable Panel Portions by Default // This is handled by createFinancesPanel // Layout the UI panel.setBorder(BorderFactory.createTitledBorder(resources.getString("financialDebitsPanel.title"))); final GroupLayout layout = new GroupLayout(panel); panel.setLayout(layout); layout.setAutoCreateGaps(true); layout.setAutoCreateContainerGaps(true); layout.setVerticalGroup( layout.createSequentialGroup() .addComponent(getChkPayForSetup()) .addComponent(getChkPayForPersonnel()) .addComponent(getChkPayForUnits()) .addComponent(getChkPayForParts()) .addComponent(getChkPayForArmour()) .addComponent(getChkPayForAmmunition()) ); layout.setHorizontalGroup( layout.createParallelGroup(Alignment.LEADING) .addComponent(getChkPayForSetup()) .addComponent(getChkPayForPersonnel()) .addComponent(getChkPayForUnits()) .addComponent(getChkPayForParts()) .addComponent(getChkPayForArmour()) .addComponent(getChkPayForAmmunition()) ); } private JPanel createSurprisesPanel() { // Initialize Components Used in ActionListeners final JPanel mysteryBoxPanel = new JDisableablePanel("mysteryBoxPanel"); // Create Panel Components setChkGenerateSurprises(new JCheckBox(resources.getString("chkGenerateSurprises.text"))); getChkGenerateSurprises().setToolTipText(resources.getString("chkGenerateSurprises.toolTipText")); getChkGenerateSurprises().setName("chkGenerateSurprises"); getChkGenerateSurprises().addActionListener(evt -> { final boolean selected = getChkGenerateSurprises().isSelected(); getChkGenerateMysteryBoxes().setEnabled(selected); mysteryBoxPanel.setEnabled(selected && getChkGenerateMysteryBoxes().isSelected()); }); setChkGenerateMysteryBoxes(new JCheckBox(resources.getString("chkGenerateMysteryBoxes.text"))); getChkGenerateMysteryBoxes().setToolTipText(resources.getString("chkGenerateMysteryBoxes.toolTipText")); getChkGenerateMysteryBoxes().setName("chkGenerateMysteryBoxes"); getChkGenerateMysteryBoxes().addActionListener(evt -> mysteryBoxPanel.setEnabled( getChkGenerateMysteryBoxes().isSelected())); createMysteryBoxPanel(mysteryBoxPanel); // Disable Panel by Default getChkGenerateSurprises().setSelected(true); getChkGenerateSurprises().doClick(); // Layout the UI final JPanel panel = new JPanel(); panel.setBorder(BorderFactory.createTitledBorder(resources.getString("surprisesPanel.title"))); panel.setToolTipText(resources.getString("surprisesPanel.toolTipText")); panel.setName("surprisesPanel"); final GroupLayout layout = new GroupLayout(panel); panel.setLayout(layout); layout.setAutoCreateGaps(true); layout.setAutoCreateContainerGaps(true); layout.setVerticalGroup( layout.createSequentialGroup() .addComponent(getChkGenerateSurprises()) .addComponent(getChkGenerateMysteryBoxes()) .addComponent(mysteryBoxPanel) ); layout.setHorizontalGroup( layout.createParallelGroup(Alignment.LEADING) .addComponent(getChkGenerateSurprises()) .addComponent(getChkGenerateMysteryBoxes()) .addComponent(mysteryBoxPanel) ); // TODO : Wave 7 : Surprises panel.setEnabled(false); getChkGenerateSurprises().setEnabled(false); getChkGenerateMysteryBoxes().setEnabled(false); mysteryBoxPanel.setEnabled(false); return panel; } private void createMysteryBoxPanel(final JPanel panel) { // Create Panel panel.setBorder(BorderFactory.createTitledBorder(resources.getString("mysteryBoxPanel.title"))); panel.setToolTipText(resources.getString("mysteryBoxPanel.toolTipText")); panel.setLayout(new GridLayout(0, 1)); // Create Panel Components setChkGenerateMysteryBoxTypes(new HashMap<>()); for (final MysteryBoxType type : MysteryBoxType.values()) { getChkGenerateMysteryBoxTypes().put(type, new JCheckBox(type.toString())); getChkGenerateMysteryBoxTypes().get(type).setToolTipText(type.getToolTipText()); getChkGenerateMysteryBoxTypes().get(type).setName("chk" + type.name()); panel.add(getChkGenerateMysteryBoxTypes().get(type)); } } //endregion Initialization //region Options /** * Sets the options for this panel to the default for the selected CompanyGenerationMethod */ public void setOptions() { setOptions(getComboCompanyGenerationMethod().getSelectedItem()); } /** * Sets the options for this panel to the default for the provided CompanyGenerationMethod * @param method the CompanyGenerationOptions to create the CompanyGenerationOptions from */ public void setOptions(final CompanyGenerationMethod method) { setOptions(new CompanyGenerationOptions(method)); } /** * Sets the options for this panel based on the provided CompanyGenerationOptions * @param options the CompanyGenerationOptions to use */ public void setOptions(final CompanyGenerationOptions options) { // Base Information getComboCompanyGenerationMethod().setSelectedItem(options.getMethod()); getComboSpecifiedFaction().setSelectedItem(new FactionDisplay(options.getSpecifiedFaction(), getCampaign().getLocalDate())); getChkGenerateMercenaryCompanyCommandLance().setSelected(options.isGenerateMercenaryCompanyCommandLance()); getSpnCompanyCount().setValue(options.getCompanyCount()); getSpnIndividualLanceCount().setValue(options.getIndividualLanceCount()); getSpnLancesPerCompany().setValue(options.getLancesPerCompany()); getSpnLanceSize().setValue(options.getLanceSize()); getSpnStarLeagueYear().setValue(options.getStarLeagueYear()); // Personnel updateLblTotalSupportPersonnel(determineMaximumSupportPersonnel()); for (final Entry<PersonnelRole, JSpinner> entry : getSpnSupportPersonnelNumbers().entrySet()) { entry.getValue().setValue(options.getSupportPersonnel().getOrDefault(entry.getKey(), 0)); } getChkPoolAssistants().setSelected(options.isPoolAssistants()); getChkGenerateCaptains().setSelected(options.isGenerateCaptains()); getChkAssignCompanyCommanderFlag().setSelected(options.isAssignCompanyCommanderFlag()); getChkApplyOfficerStatBonusToWorstSkill().setSelected(options.isApplyOfficerStatBonusToWorstSkill()); if (getChkAssignBestCompanyCommander().isSelected() != options.isAssignBestCompanyCommander()) { getChkAssignBestCompanyCommander().doClick(); } getChkPrioritizeCompanyCommanderCombatSkills().setSelected(options.isPrioritizeCompanyCommanderCombatSkills()); if (getChkAssignBestOfficers().isSelected() != options.isAssignBestOfficers()) { getChkAssignBestOfficers().doClick(); } getChkPrioritizeOfficerCombatSkills().setSelected(options.isPrioritizeOfficerCombatSkills()); getChkAssignMostSkilledToPrimaryLances().setSelected(options.isAssignMostSkilledToPrimaryLances()); getChkAutomaticallyAssignRanks().setSelected(options.isAutomaticallyAssignRanks()); getChkUseSpecifiedFactionToAssignRanks().setSelected(options.isUseSpecifiedFactionToAssignRanks()); getChkAssignMechWarriorsCallsigns().setSelected(options.isAssignMechWarriorsCallsigns()); getChkAssignFounderFlag().setSelected(options.isAssignFounderFlag()); // Personnel Randomization getRandomOriginOptionsPanel().setOptions(options.getRandomOriginOptions()); // Starting Simulation if (getChkRunStartingSimulation().isSelected() != options.isRunStartingSimulation()) { getChkRunStartingSimulation().doClick(); } getSpnSimulationDuration().setValue(options.getSimulationDuration()); getChkSimulateRandomMarriages().setSelected(options.isSimulateRandomMarriages()); getChkSimulateRandomProcreation().setSelected(options.isSimulateRandomProcreation()); // Units getComboBattleMechFactionGenerationMethod().setSelectedItem(options.getBattleMechFactionGenerationMethod()); getComboBattleMechWeightClassGenerationMethod().setSelectedItem(options.getBattleMechWeightClassGenerationMethod()); getComboBattleMechQualityGenerationMethod().setSelectedItem(options.getBattleMechQualityGenerationMethod()); getChkNeverGenerateStarLeagueMechs().setSelected(options.isNeverGenerateStarLeagueMechs()); getChkOnlyGenerateStarLeagueMechs().setSelected(options.isOnlyGenerateStarLeagueMechs()); getChkOnlyGenerateOmniMechs().setSelected(options.isOnlyGenerateOmniMechs()); getChkGenerateUnitsAsAttached().setSelected(options.isGenerateUnitsAsAttached()); getChkAssignBestRollToCompanyCommander().setSelected(options.isAssignBestRollToCompanyCommander()); getChkSortStarLeagueUnitsFirst().setSelected(options.isSortStarLeagueUnitsFirst()); getChkGroupByWeight().setSelected(options.isGroupByWeight()); getChkGroupByQuality().setSelected(options.isGroupByQuality()); getChkKeepOfficerRollsSeparate().setSelected(options.isKeepOfficerRollsSeparate()); getChkAssignTechsToUnits().setSelected(options.isAssignTechsToUnits()); // Unit getComboForceNamingMethod().setSelectedItem(options.getForceNamingMethod()); if (getChkGenerateForceIcons().isSelected() != options.isGenerateForceIcons()) { getChkGenerateForceIcons().doClick(); } getChkUseSpecifiedFactionToGenerateForceIcons().setSelected(options.isUseSpecifiedFactionToGenerateForceIcons()); if (getChkGenerateOriginNodeForceIcon().isSelected() != options.isGenerateOriginNodeForceIcon()) { getChkGenerateOriginNodeForceIcon().doClick(); } getChkUseOriginNodeForceIconLogo().setSelected(options.isUseOriginNodeForceIconLogo()); for (final Entry<Integer, Integer> entry : options.getForceWeightLimits().entrySet()) { getSpnForceWeightLimits().get(entry.getValue()).setValue(entry.getKey()); } // Spares if (getChkGenerateMothballedSpareUnits().isSelected() != options.isGenerateMothballedSpareUnits()) { getChkGenerateMothballedSpareUnits().doClick(); } getSpnSparesPercentOfActiveUnits().setValue(options.getSparesPercentOfActiveUnits()); getComboPartGenerationMethod().setSelectedItem(options.getPartGenerationMethod()); getSpnStartingArmourWeight().setValue(options.getStartingArmourWeight()); if (getChkGenerateSpareAmmunition().isSelected() != options.isGenerateSpareAmmunition()) { getChkGenerateSpareAmmunition().doClick(); } getSpnNumberReloadsPerWeapon().setValue(options.getNumberReloadsPerWeapon()); getChkGenerateFractionalMachineGunAmmunition().setSelected(options.isGenerateFractionalMachineGunAmmunition()); // Contracts if (getChkSelectStartingContract().isSelected() != options.isSelectStartingContract()) { getChkSelectStartingContract().doClick(); } getChkStartCourseToContractPlanet().setSelected(options.isStartCourseToContractPlanet()); // Finances if (getChkProcessFinances().isSelected() != options.isProcessFinances()) { getChkProcessFinances().doClick(); } getSpnStartingCash().setValue(options.getStartingCash()); if (getChkRandomizeStartingCash().isSelected() != options.isRandomizeStartingCash()) { getChkRandomizeStartingCash().doClick(); } getSpnRandomStartingCashDiceCount().setValue(options.getRandomStartingCashDiceCount()); getSpnMinimumStartingFloat().setValue(options.getMinimumStartingFloat()); getChkIncludeInitialContractPayment().setSelected(options.isIncludeInitialContractPayment()); getChkStartingLoan().setSelected(options.isStartingLoan()); if (getChkPayForSetup().isSelected() != options.isPayForSetup()) { getChkPayForSetup().doClick(); } getChkPayForPersonnel().setSelected(options.isPayForPersonnel()); getChkPayForUnits().setSelected(options.isPayForUnits()); getChkPayForParts().setSelected(options.isPayForParts()); getChkPayForArmour().setSelected(options.isPayForArmour()); getChkPayForAmmunition().setSelected(options.isPayForAmmunition()); // Surprises if (getChkGenerateSurprises().isSelected() != options.isGenerateSurprises()) { getChkGenerateSurprises().doClick(); } if (getChkGenerateMysteryBoxes().isSelected() != options.isGenerateMysteryBoxes()) { getChkGenerateMysteryBoxes().doClick(); } for (final Entry<MysteryBoxType, JCheckBox> entry : getChkGenerateMysteryBoxTypes().entrySet()) { entry.getValue().setSelected(options.getGenerateMysteryBoxTypes().getOrDefault(entry.getKey(), false)); } } /** * @return the CompanyGenerationOptions created from the current panel */ public CompanyGenerationOptions createOptionsFromPanel() { final CompanyGenerationOptions options = new CompanyGenerationOptions( getComboCompanyGenerationMethod().getSelectedItem()); // Base Information options.setSpecifiedFaction(Objects.requireNonNull(getComboSpecifiedFaction().getSelectedItem()).getFaction()); options.setGenerateMercenaryCompanyCommandLance(getChkGenerateMercenaryCompanyCommandLance().isSelected()); options.setCompanyCount((Integer) getSpnCompanyCount().getValue()); options.setIndividualLanceCount((Integer) getSpnIndividualLanceCount().getValue()); options.setLancesPerCompany((Integer) getSpnLancesPerCompany().getValue()); options.setLanceSize((Integer) getSpnLanceSize().getValue()); options.setStarLeagueYear((Integer) getSpnStarLeagueYear().getValue()); // Personnel options.setSupportPersonnel(new HashMap<>()); for (final Entry<PersonnelRole, JSpinner> entry : getSpnSupportPersonnelNumbers().entrySet()) { final int value = (int) entry.getValue().getValue(); if (value <= 0) { continue; } options.getSupportPersonnel().put(entry.getKey(), value); } options.setPoolAssistants(getChkPoolAssistants().isSelected()); options.setGenerateCaptains(getChkGenerateCaptains().isSelected()); options.setAssignCompanyCommanderFlag(getChkAssignCompanyCommanderFlag().isSelected()); options.setApplyOfficerStatBonusToWorstSkill(getChkApplyOfficerStatBonusToWorstSkill().isSelected()); options.setAssignBestCompanyCommander(getChkAssignBestCompanyCommander().isSelected()); options.setPrioritizeCompanyCommanderCombatSkills(getChkPrioritizeCompanyCommanderCombatSkills().isSelected()); options.setAssignBestOfficers(getChkAssignBestOfficers().isSelected()); options.setPrioritizeOfficerCombatSkills(getChkPrioritizeOfficerCombatSkills().isSelected()); options.setAssignMostSkilledToPrimaryLances(getChkAssignMostSkilledToPrimaryLances().isSelected()); options.setAutomaticallyAssignRanks(getChkAutomaticallyAssignRanks().isSelected()); options.setUseSpecifiedFactionToAssignRanks(getChkUseSpecifiedFactionToAssignRanks().isSelected()); options.setAssignMechWarriorsCallsigns(getChkAssignMechWarriorsCallsigns().isSelected()); options.setAssignFounderFlag(getChkAssignFounderFlag().isSelected()); // Personnel Randomization options.setRandomOriginOptions(getRandomOriginOptionsPanel().createOptionsFromPanel()); // Starting Simulation options.setRunStartingSimulation(getChkRunStartingSimulation().isSelected()); options.setSimulationDuration((Integer) getSpnSimulationDuration().getValue()); options.setSimulateRandomMarriages(getChkSimulateRandomMarriages().isSelected()); options.setSimulateRandomProcreation(getChkSimulateRandomProcreation().isSelected()); // Units options.setBattleMechFactionGenerationMethod(getComboBattleMechFactionGenerationMethod().getSelectedItem()); options.setBattleMechWeightClassGenerationMethod(getComboBattleMechWeightClassGenerationMethod().getSelectedItem()); options.setBattleMechQualityGenerationMethod(getComboBattleMechQualityGenerationMethod().getSelectedItem()); options.setNeverGenerateStarLeagueMechs(getChkNeverGenerateStarLeagueMechs().isSelected()); options.setOnlyGenerateStarLeagueMechs(getChkOnlyGenerateStarLeagueMechs().isSelected()); options.setOnlyGenerateOmniMechs(getChkOnlyGenerateOmniMechs().isSelected()); options.setGenerateUnitsAsAttached(getChkGenerateUnitsAsAttached().isSelected()); options.setAssignBestRollToCompanyCommander(getChkAssignBestRollToCompanyCommander().isSelected()); options.setSortStarLeagueUnitsFirst(getChkSortStarLeagueUnitsFirst().isSelected()); options.setGroupByWeight(getChkGroupByWeight().isSelected()); options.setGroupByQuality(getChkGroupByQuality().isSelected()); options.setKeepOfficerRollsSeparate(getChkKeepOfficerRollsSeparate().isSelected()); options.setAssignTechsToUnits(getChkAssignTechsToUnits().isSelected()); // Unit options.setForceNamingMethod(getComboForceNamingMethod().getSelectedItem()); options.setGenerateForceIcons(getChkGenerateForceIcons().isSelected()); options.setUseSpecifiedFactionToGenerateForceIcons(getChkUseSpecifiedFactionToGenerateForceIcons().isSelected()); options.setGenerateOriginNodeForceIcon(getChkGenerateOriginNodeForceIcon().isSelected()); options.setUseOriginNodeForceIconLogo(getChkUseOriginNodeForceIconLogo().isSelected()); options.setForceWeightLimits(new TreeMap<>()); for (final Entry<Integer, JSpinner> entry : getSpnForceWeightLimits().entrySet()) { options.getForceWeightLimits().put((int) entry.getValue().getValue(), entry.getKey()); } // Spares options.setGenerateMothballedSpareUnits(getChkGenerateMothballedSpareUnits().isSelected()); options.setSparesPercentOfActiveUnits((Integer) getSpnSparesPercentOfActiveUnits().getValue()); options.setPartGenerationMethod(getComboPartGenerationMethod().getSelectedItem()); options.setStartingArmourWeight((Integer) getSpnStartingArmourWeight().getValue()); options.setGenerateSpareAmmunition(getChkGenerateSpareAmmunition().isSelected()); options.setNumberReloadsPerWeapon((Integer) getSpnNumberReloadsPerWeapon().getValue()); options.setGenerateFractionalMachineGunAmmunition(getChkGenerateFractionalMachineGunAmmunition().isSelected()); // Contracts options.setSelectStartingContract(getChkSelectStartingContract().isSelected()); options.setStartCourseToContractPlanet(getChkStartCourseToContractPlanet().isSelected()); // Finances options.setProcessFinances(getChkProcessFinances().isSelected()); options.setStartingCash((Integer) getSpnStartingCash().getValue()); options.setRandomizeStartingCash(getChkRandomizeStartingCash().isSelected()); options.setRandomStartingCashDiceCount((Integer) getSpnRandomStartingCashDiceCount().getValue()); options.setMinimumStartingFloat((Integer) getSpnMinimumStartingFloat().getValue()); options.setIncludeInitialContractPayment(getChkIncludeInitialContractPayment().isSelected()); options.setStartingLoan(getChkStartingLoan().isSelected()); options.setPayForSetup(getChkPayForSetup().isSelected()); options.setPayForPersonnel(getChkPayForPersonnel().isSelected()); options.setPayForUnits(getChkPayForUnits().isSelected()); options.setPayForParts(getChkPayForParts().isSelected()); options.setPayForArmour(getChkPayForArmour().isSelected()); options.setPayForAmmunition(getChkPayForAmmunition().isSelected()); // Surprises options.setGenerateSurprises(getChkGenerateSurprises().isSelected()); options.setGenerateMysteryBoxes(getChkGenerateMysteryBoxes().isSelected()); options.setGenerateMysteryBoxTypes(new HashMap<>()); for (final Entry<MysteryBoxType, JCheckBox> entry : getChkGenerateMysteryBoxTypes().entrySet()) { options.getGenerateMysteryBoxTypes().put(entry.getKey(), entry.getValue().isSelected()); } return options; } /** * Validates the data contained in this panel, returning the current state of validation. * @param display to display dialogs containing the messages or not * @return true if the data validates successfully, otherwise false */ public ValidationState validateOptions(final boolean display) { //region Errors // Minimum Generation Size Validation // Minimum Generation Parameter of 1 Company or Lance, the Company Command Lance Doesn't Count if (((int) getSpnCompanyCount().getValue() <= 0) && ((int) getSpnIndividualLanceCount().getValue() <= 0)) { if (display) { JOptionPane.showMessageDialog(getFrame(), resources.getString("CompanyGenerationOptionsPanel.InvalidGenerationSize.text"), resources.getString("InvalidOptions.title"), JOptionPane.ERROR_MESSAGE); } return ValidationState.FAILURE; } // Random Origin Options Validation if (getRandomOriginOptionsPanel().validateOptions(display).isFailure()) { return ValidationState.FAILURE; } //endregion Errors //region Warnings // Only need to check these if they are to be displayed if (display) { // Support Personnel Count: // 1) Above Recommended Maximum Support Personnel Count // 2) Below Half of Recommended Maximum Support Personnel Count final int maximumSupportPersonnelCount = determineMaximumSupportPersonnel(); final int currentSupportPersonnelCount = getSpnSupportPersonnelNumbers().values().stream() .mapToInt(spinner -> (int) spinner.getValue()).sum(); if ((maximumSupportPersonnelCount < currentSupportPersonnelCount) && (JOptionPane.showConfirmDialog(getFrame(), resources.getString("CompanyGenerationOptionsPanel.OverMaximumSupportPersonnel.text"), resources.getString("CompanyGenerationOptionsPanel.OverMaximumSupportPersonnel.title"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.NO_OPTION)) { return ValidationState.WARNING; } else if ((currentSupportPersonnelCount < (maximumSupportPersonnelCount / 2.0)) && (JOptionPane.showConfirmDialog(getFrame(), resources.getString("CompanyGenerationOptionsPanel.UnderHalfMaximumSupportPersonnel.text"), resources.getString("CompanyGenerationOptionsPanel.UnderHalfMaximumSupportPersonnel.title"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.NO_OPTION)) { return ValidationState.WARNING; } } //endregion Warnings // The options specified are correct, and thus can be saved return ValidationState.SUCCESS; } //endregion Options //region File I/O /** * Imports CompanyGenerationOptions from an XML file */ public void importOptionsFromXML() { FileDialogs.openCompanyGenerationOptions(getFrame()) .ifPresent(file -> setOptions(CompanyGenerationOptions.parseFromXML(file))); } /** * Exports the CompanyGenerationOptions displayed on this panel to an XML file. */ public void exportOptionsToXML() { FileDialogs.saveCompanyGenerationOptions(getFrame()) .ifPresent(file -> createOptionsFromPanel().writeToFile(file)); } //endregion File I/O }
MegaMek/mekhq
MekHQ/src/mekhq/gui/panels/CompanyGenerationOptionsPanel.java
46,032
package com.elifut.models; import com.google.auto.value.AutoValue; import com.google.common.collect.FluentIterable; import android.content.ContentValues; import android.database.Cursor; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.elifut.services.ClubDataStore; import com.gabrielittner.auto.value.cursor.ColumnAdapter; import com.squareup.moshi.JsonAdapter; import com.squareup.moshi.Moshi; import java.util.ArrayList; import java.util.List; import static com.google.common.base.Predicates.in; import static com.google.common.base.Predicates.not; @AutoValue public abstract class Club extends Model implements Persistable { // @formatter:off public abstract String name(); public abstract String small_image(); public abstract String large_image(); public abstract int league_id(); @Nullable public abstract String abbrev_name(); @ColumnAdapter(ClubStats.Adapter.class) @Nullable public abstract ClubStats stats(); // @formatter:on public static Club create(Cursor cursor) { return AutoValue_Club.createFromCursor(cursor); } public abstract ContentValues toContentValues(); @Override public String toString() { return shortName(); } /** * Returns a list of all the players on this team who are substitutes, that is, who are not on the * main squad of 11 players. */ public List<? extends Player> substitutes(ClubDataStore dataStore) { List<? extends Player> players = dataStore.allPlayers(this); ClubSquad clubSquad = dataStore.squad(this); // Exclude the players who are already on the team players from the list of all players, so we // get a list with only the subs. return FluentIterable.from(players) .filter(not(in(clubSquad.players()))) .toList(); } /** Replaces an existing player on this Club's players with a new one and saves the changes. */ public void replacePlayer(Player oldPlayer, Player newPlayer, ClubDataStore dataStore) { ClubSquad clubSquad = dataStore.squad(this); List<Player> squad = new ArrayList<>(clubSquad.players()); squad.remove(oldPlayer); squad.add(newPlayer); dataStore.updateSquad(clubSquad, clubSquad.toBuilder().players(squad).build()); } public static Builder builder() { return new AutoValue_Club.Builder() .stats(ClubStats.builder().build()) .small_image("") .large_image("") .base_id(0) .league_id(0); } public static Club create(int id, String name) { return Club.builder().id(id).name(name).build(); } public String tinyName() { //noinspection ConstantConditions return abbrev_name() != null ? abbrev_name().length() > 3 ? abbrev_name().substring(0, 3) : abbrev_name() : name().length() > 3 ? name().substring(0, 3) : name(); } // @formatter:off @AutoValue.Builder public abstract static class Builder { public abstract Builder id(int i); public abstract Builder base_id(int i); public abstract Builder name(String s); public abstract Builder abbrev_name(String s); public abstract Builder small_image(String s); public abstract Builder large_image(String s); public abstract Builder league_id(int i); public abstract Builder stats(ClubStats s); public abstract Club build(); } // @formatter:on public abstract Builder toBuilder(); public Club newWithWin(int goalsDifferential) { if (goalsDifferential <= 0) { throw new IllegalArgumentException("Goals difference must be bigger than zero for wins."); } return toBuilder() .stats(nonNullStats() .newWithWin(goalsDifferential)) .build(); } public boolean nameEquals(Club otherTeam) { return name().equals(otherTeam.name()); } public Club newWithDraw() { return toBuilder() .stats(nonNullStats().newWithDraw()) .build(); } public Club newWithLoss(int goalsDifferential) { if (goalsDifferential >= 0) { throw new IllegalArgumentException("Goals difference must be less than zero for losses."); } return toBuilder() .stats(nonNullStats() .newWithLoss(goalsDifferential)) .build(); } @NonNull public ClubStats nonNullStats() { //noinspection ConstantConditions return stats() == null ? ClubStats.create() : stats(); } public String shortName() { return abbrev_name() != null ? abbrev_name() : name(); } public static JsonAdapter<Club> jsonAdapter(Moshi moshi) { return new AutoValue_Club.MoshiJsonAdapter(moshi); } @Override public int describeContents() { return 0; } }
EliFUT/android
app/src/main/java/com/elifut/models/Club.java
46,033
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. /* * This is adapted from the kstemmer code base which is Copyright 2003, CIIR University of Massachusetts * Amherst (http://ciir.cs.umass.edu) and Licensed under the terms of a modified old-style BSD license. */ package com.yahoo.language.simple.kstem; /** A list of words used by Kstem */ class KStemData2 { private KStemData2() { } static String[] data = { "cash","cashew","cashier","cashmere","casing", "casino","cask","casket","casque","cassava", "casserole","cassette","cassock","cassowary","cast", "castanets","castaway","castellated","caster","castigate", "casting","castle","castor","castrate","casual", "casualty","casuist","casuistry","cat","cataclysm", "catacomb","catafalque","catalepsy","catalog","catalogue", "catalpa","catalysis","catalyst","catamaran","catapult", "cataract","catarrh","catastrophe","catatonic","catcall", "catch","catcher","catching","catchpenny","catchphrase", "catchword","catchy","catechise","catechism","catechize", "categorical","categorise","categorize","category","cater", "caterer","caterpillar","caterwaul","catfish","catgut", "catharsis","cathartic","cathedral","catheter","cathode", "catholic","catholicism","catholicity","catkin","catnap", "catnip","catsup","cattle","catty","catwalk", "caucus","caudal","caught","caul","cauldron", "cauliflower","caulk","causal","causality","causation", "causative","cause","causeless","causeway","caustic", "cauterise","cauterize","caution","cautionary","cautious", "cavalcade","cavalier","cavalry","cavalryman","cave", "caveat","caveman","cavern","cavernous","caviar", "caviare","cavil","cavity","cavort","cavy", "caw","cay","cayman","cease","ceaseless", "cedar","cede","cedilla","ceiling","celandine", "celebrant","celebrate","celebrated","celebration","celebrity", "celerity","celery","celestial","celibacy","celibate", "cell","cellar","cellarage","cellist","cello", "cellophane","cellular","celluloid","cellulose","celsius", "celtic","cement","cemetery","cenotaph","censor", "censorious","censorship","censure","census","cent", "centaur","centavo","centenarian","centenary","centennial", "center","centerboard","centerpiece","centigrade","centigram", "centigramme","centime","centimeter","centimetre","centipede", "central","centralise","centralism","centralize","centre", "centreboard","centrepiece","centrifugal","centrifuge","centripetal", "centrist","centurion","century","cephalic","ceramic", "ceramics","cereal","cerebellum","cerebral","cerebration", "cerebrum","ceremonial","ceremonious","ceremony","cerise", "cert","certain","certainly","certainty","certifiable", "certificate","certificated","certify","certitude","cerulean", "cervical","cervix","cessation","cession","cesspit", "cetacean","chablis","chaconne","chafe","chaff", "chaffinch","chagrin","chain","chair","chairman", "chairmanship","chairperson","chairwoman","chaise","chalet", "chalice","chalk","chalky","challenge","challenging", "chamber","chamberlain","chambermaid","chambers","chameleon", "chamiomile","chamois","chamomile","champ","champagne", "champaign","champion","championship","chance","chancel", "chancellery","chancellor","chancery","chancy","chandelier", "chandler","change","changeable","changeless","changeling", "changeover","channel","chant","chanterelle","chanticleer", "chantry","chanty","chaos","chaotic","chap", "chapel","chapelgoer","chaperon","chaperone","chapfallen", "chaplain","chaplaincy","chaplet","chaps","chapter", "char","charabanc","character","characterise","characteristic", "characterization","characterize","characterless","charade","charades", "charcoal","chard","charge","chargeable","charged", "charger","chariot","charioteer","charisma","charismatic", "charitable","charity","charlady","charlatan","charleston", "charlock","charlotte","charm","charmer","charming", "chart","charter","chartreuse","charwoman","chary", "charybdis","chase","chaser","chasm","chassis", "chaste","chasten","chastise","chastisement","chastity", "chasuble","chat","chatelaine","chattel","chatter", "chatterbox","chatty","chauffeur","chauvinism","chauvinist", "cheap","cheapen","cheapskate","cheat","check", "checkbook","checked","checker","checkerboard","checkers", "checklist","checkmate","checkoff","checkout","checkpoint", "checkrail","checkrein","checkroom","checkup","cheddar", "cheek","cheekbone","cheeky","cheep","cheer", "cheerful","cheering","cheerio","cheerleader","cheerless", "cheers","cheery","cheese","cheesecake","cheesecloth", "cheeseparing","cheetah","chef","chem","chemical", "chemise","chemist","chemistry","chemotherapy","chenille", "cheque","chequebook","chequer","cherish","cheroot", "cherry","cherub","chervil","chess","chessboard", "chessman","chest","chesterfield","chestnut","chesty", "chevalier","chevron","chevvy","chevy","chew", "chi","chianti","chiaroscuro","chic","chicanery", "chicano","chichi","chick","chicken","chickenfeed", "chickenhearted","chickpea","chickweed","chicle","chicory", "chide","chief","chiefly","chieftain","chieftainship", "chiffon","chiffonier","chiffonnier","chigger","chignon", "chihuahua","chilblain","child","childbearing","childbirth", "childhood","childish","childlike","chile","chill", "chiller","chilli","chilly","chimaera","chime", "chimera","chimerical","chimney","chimneybreast","chimneypiece", "chimneypot","chimneystack","chimneysweep","chimpanzee","chin", "china","chinatown","chinaware","chinchilla","chine", "chink","chinless","chinook","chinstrap","chintz", "chinwag","chip","chipboard","chipmunk","chippendale", "chipping","chippy","chiromancy","chiropody","chiropractic", "chirp","chirpy","chisel","chiseler","chiseller", "chit","chitchat","chivalrous","chivalry","chive", "chivvy","chivy","chloride","chlorinate","chlorine", "chloroform","chlorophyll","chock","chocolate","choice", "choir","choirboy","choirmaster","choke","choker", "chokey","choky","choler","cholera","choleric", "cholesterol","chomp","choose","choosey","choosy", "chop","chopfallen","chophouse","chopper","choppers", "choppy","chopstick","choral","chorale","chord", "chore","choreographer","choreography","chorine","chorister", "chortle","chorus","chose","chosen","chow", "chowder","christ","christen","christendom","christening", "christian","christianity","christlike","christmastime","chromatic", "chrome","chromium","chromosome","chronic","chronicle", "chronograph","chronological","chronology","chronometer","chrysalis", "chrysanthemum","chub","chubby","chuck","chuckle", "chug","chukker","chum","chummy","chump", "chunk","chunky","church","churchgoer","churching", "churchwarden","churchyard","churl","churlish","churn", "chute","chutney","cia","cicada","cicatrice", "cicerone","cid","cider","cif","cigar", "cigaret","cigarette","cinch","cincture","cinder", "cinderella","cinders","cine","cinema","cinematograph", "cinematography","cinnamon","cinquefoil","cipher","circa", "circadian","circle","circlet","circuit","circuitous", "circular","circularise","circularize","circulate","circulation", "circumcise","circumcision","circumference","circumflex","circumlocution", "circumnavigate","circumscribe","circumscription","circumspect","circumstance", "circumstances","circumstantial","circumvent","circus","cirque", "cirrhosis","cirrus","cissy","cistern","citadel", "citation","cite","citizen","citizenry","citizenship", "citron","citrous","citrus","city","civet", "civic","civics","civies","civil","civilian", "civilisation","civilise","civility","civilization","civilize", "civilly","civvies","clack","clad","claim", "claimant","clairvoyance","clairvoyant","clam","clambake", "clamber","clammy","clamor","clamorous","clamour", "clamp","clampdown","clamshell","clan","clandestine", "clang","clanger","clangor","clangour","clank", "clannish","clansman","clap","clapboard","clapper", "clapperboard","clappers","claptrap","claque","claret", "clarification","clarify","clarinet","clarinetist","clarinettist", "clarion","clarity","clarts","clash","clasp", "class","classic","classical","classicism","classicist", "classics","classification","classified","classify","classless", "classmate","classroom","classy","clatter","clause", "claustrophobia","claustrophobic","clavichord","clavicle","claw", "clay","claymore","clean","cleaner","cleanliness", "cleanly","cleanse","cleanser","cleanup","clear", "clearance","clearing","clearinghouse","clearly","clearout", "clearway","cleat","cleavage","cleave","cleaver", "clef","cleft","clematis","clemency","clement", "clench","clerestory","clergy","clergyman","clerical", "clerihew","clerk","clever","clew","click", "client","clientele","cliff","cliffhanger","climacteric", "climactic","climate","climatic","climatology","climax", "climb","climber","clime","clinch","clincher", "cline","cling","clinging","clingy","clinic", "clinical","clink","clinker","clip","clipboard", "clipper","clippers","clippie","clipping","clique", "cliquey","cliquish","clitoris","cloaca","cloak", "cloakroom","clobber","cloche","clock","clockwise", "clockwork","clod","cloddish","clodhopper","clog", "cloggy","cloister","clone","clop","close", "closed","closedown","closefisted","closet","closure", "clot","cloth","clothe","clothes","clothesbasket", "clotheshorse","clothesline","clothier","clothing","cloture", "cloud","cloudbank","cloudburst","cloudless","cloudy", "clout","clove","cloven","clover","cloverleaf", "clown","clownish","cloy","club","clubbable", "clubfoot","clubhouse","cluck","clue","clueless", "clump","clumsy","clung","cluster","clutch", "clutches","clutter","coach","coachbuilder","coachman", "coachwork","coadjutor","coagulant","coagulate","coal", "coalbunker","coalesce","coalface","coalfield","coalhole", "coalhouse","coalition","coalmine","coalscuttle","coarse", "coarsen","coast","coastal","coaster","coastguard", "coastguardsman","coastline","coastwise","coat","coating", "coax","cob","cobalt","cobber","cobble", "cobbler","cobblers","cobblestone","cobra","cobweb", "cocaine","coccyx","cochineal","cochlea","cock", "cockade","cockatoo","cockchafer","cockcrow","cockerel", "cockeyed","cockfight","cockhorse","cockle","cockleshell", "cockney","cockpit","cockroach","cockscomb","cocksure", "cocktail","cocky","coco","cocoa","coconut", "cocoon","cod","coda","coddle","code", "codeine","codex","codger","codicil","codify", "codling","codpiece","codswallop","coed","coeducation", "coefficient","coelacanth","coequal","coerce","coercion", "coercive","coeternal","coeval","coexist","coexistence", "coffee","coffeepot","coffer","cofferdam","coffers", "coffin","cog","cogency","cogent","cogitate", "cogitation","cognac","cognate","cognition","cognitive", "cognizance","cognizant","cognomen","cognoscenti","cogwheel", "cohabit","cohere","coherence","coherent","cohesion", "cohesive","cohort","coif","coiffeur","coiffure", "coil","coin","coinage","coincide","coincidence", "coincident","coincidental","coir","coitus","coke", "col","cola","colander","cold","coleslaw", "coley","colic","colicky","colitis","collaborate", "collaboration","collaborationist","collage","collapse","collapsible", "collar","collarbone","collate","collateral","collation", "colleague","collect","collected","collection","collective", "collectivise","collectivism","collectivize","collector","colleen", "college","collegiate","collide","collie","collier", "colliery","collision","collocate","collocation","colloquial", "colloquialism","colloquy","collude","collusion","collywobbles", "cologne","colon","colonel","colonial","colonialism", "colonialist","colonies","colonise","colonist","colonize", "colonnade","colony","color","coloration","coloratura", "colored","colorfast","colorful","coloring","colorless", "colors","colossal","colossally","colossus","colostrum", "colour","coloured","colourfast","colourful","colouring", "colourless","colours","colt","colter","coltish", "columbine","column","columnist","coma","comatose", "comb","combat","combatant","combative","comber", "combination","combinations","combinatorial","combine","combo", "combustible","combustion","come","comeback","comecon", "comedian","comedienne","comedown","comedy","comely", "comer","comestible","comet","comfit","comfort", "comfortable","comforter","comfrey","comfy","comic", "comical","comics","cominform","coming","comintern", "comity","comma","command","commandant","commandeer", "commander","commanding","commandment","commando","commemorate", "commemoration","commemorative","commence","commencement","commend", "commendable","commendation","commendatory","commensurable","commensurate", "comment","commentary","commentate","commentator","commerce", "commercial","commercialise","commercialism","commercialize","commie", "commiserate","commiseration","commissar","commissariat","commissary", "commission","commissionaire","commissioner","commit","commitment", "committal","committed","committee","committeeman","commode", "commodious","commodity","commodore","common","commonage", "commonalty","commoner","commonly","commonplace","commons", "commonweal","commonwealth","commotion","communal","commune", "communicable","communicant","communicate","communication","communications", "communicative","communion","communism","communist","community", "commutable","commutation","commutative","commutator","commute", "commuter","compact","compacted","companion","companionable", "companionship","companionway","company","comparable","comparative", "comparatively","compare","comparison","compartment","compartmentalise", "compartmentalize","compass","compassion","compassionate","compatibility", "compatible","compatriot","compeer","compel","compendious", "compendium","compensate","compensation","compensatory","compere", "compete","competence","competent","competition","competitive", "competitor","compilation","compile","complacency","complacent", "complain","complainant","complaint","complaisance","complaisant", "complement","complementary","complete","completely","completion", "complex","complexion","complexity","compliance","compliant", "complicate","complicated","complication","complicity","compliment", "complimentary","compliments","complin","compline","comply", "compo","component","comport","comportment","compose", "composer","composite","composition","compositor","compost", "composure","compote","compound","comprehend","comprehensible", "comprehension","comprehensive","compress","compressible","compression", "compressor","comprise","compromise","comptometer","comptroller", "compulsion","compulsive","compulsory","compunction","computation", "compute","computer","computerize","comrade","comradeship", "coms","con","concatenate","concatenation","concave", "concavity","conceal","concealment","concede","conceit", "conceited","conceivable","conceive","concentrate","concentrated", "concentration","concentric","concept","conception","conceptual", "conceptualise","conceptualize","concern","concerned","concernedly", "concerning","concert","concerted","concertgoer","concertina", "concertmaster","concerto","concession","concessionaire","concessive", "conch","conchology","concierge","conciliate","conciliation", "conciliatory","concise","concision","conclave","conclude", "conclusion","conclusive","concoct","concoction","concomitance", "concomitant","concord","concordance","concordant","concordat", "concourse","concrete","concubinage","concubine","concupiscence", "concur","concurrence","concurrent","concuss","concussion", "condemn","condemnation","condensation","condense","condenser", "condescend","condescension","condign","condiment","condition", "conditional","conditions","condole","condolence","condom", "condominium","condone","condor","conduce","conducive", "conduct","conduction","conductive","conductivity","conductor", "conduit","cone","coney","confabulate","confabulation", "confection","confectioner","confectionery","confederacy","confederate", "confederation","confer","conference","confess","confessed", "confession","confessional","confessor","confetti","confidant", "confide","confidence","confident","confidential","confiding", "configuration","confine","confinement","confines","confirm", "confirmation","confirmed","confiscate","confiscatory","conflagration", "conflate","conflict","confluence","conform","conformable", "conformation","conformist","conformity","confound","confounded", "confraternity","confront","confrontation","confucian","confucianism", "confuse","confusion","confute","conga","congeal", "congenial","congenital","congest","congestion","conglomerate", "conglomeration","congrats","congratulate","congratulations","congratulatory", "congregate","congregation","congregational","congregationalism","congress", "congressional","congressman","congruent","congruity","congruous", "conic","conical","conifer","coniferous","conj", "conjectural","conjecture","conjoin","conjoint","conjugal", "conjugate","conjugation","conjunction","conjunctiva","conjunctive", "conjunctivitis","conjuncture","conjure","conjurer","conjuror", "conk","conker","conkers","connect","connected", "connection","connective","connexion","connivance","connive", "connoisseur","connotation","connotative","connote","connubial", "conquer","conquest","conquistador","consanguineous","consanguinity", "conscience","conscientious","conscious","consciousness","conscript", "conscription","consecrate","consecration","consecutive","consensus", "consent","consequence","consequent","consequential","consequently", "conservancy","conservation","conservationist","conservatism","conservative", "conservatoire","conservatory","conserve","consider","considerable", "considerably","considerate","consideration","considered","considering", "consign","consignee","consigner","consignment","consignor", "consist","consistency","consistent","consistory","consolation", "consolatory","console","consolidate","consols","consonance", "consonant","consort","consortium","conspectus","conspicuous", "conspiracy","conspirator","conspiratorial","conspire","constable", "constabulary","constancy","constant","constellation","consternation", "constipate","constipation","constituency","constituent","constitute", "constitution","constitutional","constitutionalism","constitutionally","constitutive", "constrain","constrained","constraint","constrict","constriction", "constrictor","construct","construction","constructive","constructor", "construe","consubstantiation","consul","consular","consulate", "consult","consultancy","consultant","consultation","consultative", "consulting","consume","consumer","consummate","consummation", "consumption","consumptive","contact","contagion","contagious", "contain","contained","container","containerise","containerize", "containment","contaminate","contamination","contemplate","contemplation", "contemplative","contemporaneous","contemporary","contempt","contemptible", "contemptuous","contend","contender","content","contented", "contention","contentious","contentment","contents","contest", "contestant","context","contextual","contiguity","contiguous", "continence","continent","continental","contingency","contingent", "continual","continuance","continuation","continue","continuity", "continuo","continuous","continuum","contort","contortion", "contortionist","contour","contraband","contrabass","contraception", "contraceptive","contract","contractile","contraction","contractor", "contractual","contradict","contradiction","contradictory","contradistinction", "contrail","contraindication","contralto","contraption","contrapuntal", "contrariety","contrariwise","contrary","contrast","contravene", "contravention","contretemps","contribute","contribution","contributor", "contributory","contrite","contrition","contrivance","contrive", "contrived","control","controller","controversial","controversy", "controvert","contumacious","contumacy","contumelious","contumely", "contuse","contusion","conundrum","conurbation","convalesce", "convalescence","convalescent","convection","convector","convene", "convener","convenience","convenient","convenor","convent", "conventicle","convention","conventional","conventionality","converge", "conversant","conversation","conversational","conversationalist","conversazione", "converse","conversion","convert","converter","convertible", "convex","convexity","convey","conveyance","conveyancer", "conveyancing","conveyer","conveyor","convict","conviction", "convince","convinced","convincing","convivial","convocation", "convoke","convoluted","convolution","convolvulus","convoy", "convulse","convulsion","convulsive","cony","coo", "cook","cooker","cookery","cookhouse","cookie", "cooking","cookout","cool","coolant","cooler", "coolie","coon","coop","cooper","cooperate", "cooperation","cooperative","coordinate","coordinates","coordination", "coot","cop","cope","copeck","copier", "copilot","coping","copingstone","copious","copper", "copperhead","copperplate","coppersmith","coppice","copra", "coptic","copula","copulate","copulative","copy", "copybook","copyboy","copycat","copydesk","copyhold", "copyist","copyright","copywriter","coquetry","coquette", "cor","coracle","coral","corbel","cord", "cordage","cordial","cordiality","cordially","cordillera", "cordite","cordon","cords","corduroy","core", "corelate","coreligionist","corer","corespondent","corgi", "coriander","corinthian","cork","corkage","corked", "corker","corkscrew","corm","cormorant","corn", "corncob","corncrake","cornea","cornelian","corner", "cornerstone","cornet","cornfield","cornflakes","cornflower", "cornice","cornish","cornucopia","corny","corolla", "corollary","corona","coronary","coronation","coroner", "coronet","corpora","corporal","corporate","corporation", "corporeal","corps","corpse","corpulence","corpulent", "corpus","corpuscle","corral","correct","correction", "correctitude","corrective","correlate","correlation","correlative", "correspond","correspondence","correspondent","corresponding","corridor", "corrie","corrigendum","corroborate","corroboration","corroborative", "corroboree","corrode","corrosion","corrosive","corrugate", "corrugation","corrupt","corruption","corsage","corsair", "corse","corselet","corset","cortex","cortisone", "corundum","coruscate","corvette","cos","cosh", "cosignatory","cosine","cosmetic","cosmetician","cosmic", "cosmogony","cosmology","cosmonaut","cosmopolitan","cosmos", "cosset","cost","costermonger","costive","costly", "costs","costume","costumier","cosy","cot", "cotangent","cote","coterie","coterminous","cotillion", "cottage","cottager","cottar","cotter","cotton", "cottonseed","cottontail","cotyledon","couch","couchant", "couchette","cougar","cough","could","couldst", "coulter","council","councillor","counsel","counsellor", "counselor","count","countable","countdown","countenance", "counter","counteract","counterattack","counterattraction","counterbalance", "counterblast","counterclaim","counterclockwise","counterespionage","counterfeit", "counterfoil","counterintelligence","counterirritant","countermand","countermarch", "countermeasure","counteroffensive","counterpane","counterpart","counterpoint", "counterpoise","countersign","countersink","countertenor","countervail", "countess","countinghouse","countless","countrified","country", "countryman","countryside","county","coup","couple", "couplet","coupling","coupon","courage","courageous", "courgette","courier","course","courser","coursing", "court","courteous","courtesan","courtesy","courthouse", "courtier","courting","courtly","courtroom","courtship", "courtyard","couscous","cousin","couture","cove", "coven","covenant","coventry","cover","coverage", "covering","coverlet","covert","covet","covetous", "covey","cow","coward","cowardice","cowardly", "cowbell","cowboy","cowcatcher","cower","cowgirl", "cowhand","cowheel","cowherd","cowhide","cowl", "cowlick","cowling","cowman","cowpat","cowpox", "cowrie","cowry","cowshed","cowslip","cox", "coxcomb","coy","coyote","coypu","cozen", "cozy","cpa","crab","crabbed","crabby", "crabgrass","crabwise","crack","crackbrained","crackdown", "cracked","cracker","crackers","crackle","crackleware", "crackling","crackpot","cracksman","crackup","cradle", "craft","craftsman","crafty","crag","craggy", "crake","cram","crammer","cramp","cramped", "crampon","cramps","cranberry","crane","cranial", "cranium","crank","crankshaft","cranky","cranny", "crap","crape","crappy","craps","crash", "crashing","crass","crate","crater","cravat", "crave","craven","craving","crawl","crawler", "crawlers","crayfish","crayon","craze","crazy", "creak","creaky","cream","creamer","creamery", "creamy","crease","create","creation","creative", "creativity","creator","creature","credence","credentials", "credibility","credible","credit","creditable","creditor", "credo","credulous","creed","creek","creel", "creep","creeper","creepers","creeps","creepy", "cremate","crematorium","crenelated","crenellated","creole", "creosote","crept","crepuscular","crescendo","crescent", "cress","crest","crested","crestfallen","cretaceous", "cretin","cretonne","crevasse","crevice","crew", "crewman","crib","cribbage","crick","cricket", "cricketer","crier","cries","crikey","crime", "criminal","criminology","crimp","crimplene","crimson", "cringe","crinkle","crinkly","crinoid","crinoline", "cripes","cripple","crisis","crisp","crispy", "crisscross","criterion","critic","critical","criticise", "criticism","criticize","critique","critter","croak", "crochet","crock","crockery","crocodile","crocus", "croft","crofter","croissant","cromlech","crone", "crony","crook","crooked","croon","crooner", "crop","cropper","croquet","croquette","crore", "crosier","cross","crossbar","crossbeam","crossbenches", "crossbones","crossbow","crossbred","crossbreed","crosscheck", "crosscurrent","crosscut","crossfire","crossing","crossover", "crosspatch","crosspiece","crossply","crossroad","crossroads", "crosstree","crosswalk","crosswind","crosswise","crossword", "crotch","crotchet","crotchety","crouch","croup", "croupier","crouton","crow","crowbar","crowd", "crowded","crowfoot","crown","crozier","crucial", "crucible","crucifix","crucifixion","cruciform","crucify", "crude","crudity","cruel","cruelty","cruet", "cruise","cruiser","crumb","crumble","crumbly", "crummy","crumpet","crumple","crunch","crupper", "crusade","cruse","crush","crust","crustacean", "crusty","crutch","crux","cry","crybaby", "crying","crypt","cryptic","cryptogram","cryptography", "crystal","crystalline","crystallise","crystallize","cub", "cubbyhole","cube","cubic","cubical","cubicle", "cubism","cubit","cubs","cuckold","cuckoldry", "cuckoo","cucumber","cud","cuddle","cuddlesome", "cuddly","cudgel","cue","cuff","cuffs", "cuirass","cuisine","culinary","cull","cullender", "culminate","culmination","culotte","culottes","culpable", "culprit","cult","cultivable","cultivate","cultivated", "cultivation","cultivator","cultural","culture","cultured", "culvert","cumber","cumbersome","cumin","cummerbund", "cumulative","cumulonimbus","cumulus","cuneiform","cunnilingus", "cunning","cunt","cup","cupbearer","cupboard", "cupid","cupidity","cupola","cuppa","cupping", "cupric","cur","curable","curacy","curate", "curative","curator","curb","curd","curdle", "cure","curettage","curfew","curia","curio", "curiosity","curious","curl","curler","curlew", "curlicue","curling","curly","curlycue","curmudgeon", "currant","currency","current","curriculum","currish", "curry","curse","cursed","cursive","cursory", "curt","curtail","curtain","curtains","curtsey", "curtsy","curvaceous","curvacious","curvature","curve", "cushion","cushy","cusp","cuspidor","cuss", "cussed","custard","custodial","custodian","custody", "custom","customary","customer","customs","cut", "cutaway","cutback","cuticle","cutlass","cutler", "cutlery","cutlet","cutoff","cutout","cutpurse", "cutter","cutthroat","cutting","cuttlefish","cutworm", "cwm","cwt","cyanide","cybernetics","cyclamate", "cyclamen","cycle","cyclic","cyclist","cyclone", "cyclopaedia","cyclopedia","cyclostyle","cyclotron","cyder", "cygnet","cylinder","cymbal","cynic","cynical", "cynicism","cynosure","cypher","cypress","cyrillic", "cyst","cystitis","cytology","czar","czarina", "czech","dab","dabble","dabchick","dabs", "dace","dachshund","dactyl","dad","daddy", "dado","daemon","daffodil","daft","dagger", "dago","daguerreotype","dahlia","daily","dainty", "daiquiri","dairy","dairying","dairymaid","dairyman", "dais","daisy","dale","dalliance","dally", "dalmation","dam","damage","damages","damascene", "damask","damn","damnable","damnation","damnedest", "damning","damocles","damp","dampen","damper", "dampish","damsel","damson","dance","dandelion", "dander","dandified","dandle","dandruff","dandy", "danger","dangerous","dangle","dank","dapper", "dappled","dare","daredevil","daresay","daring", "dark","darken","darkey","darkroom","darky", "darling","darn","darning","dart","dartboard", "dartmoor","darts","dash","dashboard","dashed", "dashing","data","date","dated","dateless", "dateline","dates","dative","daub","daughter", "daunt","dauntless","dauphin","davit","dawdle", "dawn","day","dayboy","daybreak","daydream", "daylight","dayroom","days","daytime","daze", "dazzle","ddt","deacon","dead","deaden", "deadline","deadlock","deadly","deadpan","deadweight", "deaf","deafen","deal","dealer","dealing", "dealings","dean","deanery","dear","dearest", "dearie","dearly","dearth","deary","death", "deathbed","deathblow","deathless","deathlike","deathly", "deathwatch","deb","debar","debark","debase", "debatable","debate","debater","debauch","debauchee", "debauchery","debenture","debilitate","debility","debit", "debonair","debone","debouch","debrief","debris", "debt","debtor","debug","debunk","debut", "debutante","decade","decadence","decadent","decalogue", "decamp","decant","decanter","decapitate","decathlon", "decay","decease","deceased","deceit","deceitful", "deceive","decelerate","december","decencies","decency", "decent","decentralise","decentralize","deception","deceptive", "decibel","decide","decided","decidedly","deciduous", "decimal","decimalise","decimalize","decimate","decipher", "decision","decisive","deck","deckchair","deckhand", "declaim","declamation","declaration","declare","declared", "declassify","declension","declination","decline","declivity", "declutch","decoction","decode","decolonise","decolonize", "decompose","decompress","decongestant","decontaminate","decontrol", "decorate","decoration","decorative","decorator","decorous", "decorum","decoy","decrease","decree","decrepit", "decrepitude","decry","dedicate","dedicated","dedication", "deduce","deduct","deduction","deductive","deed", "deem","deep","deepen","deer","deerstalker", "def","deface","defame","default","defeat", "defeatism","defecate","defect","defection","defective", "defence","defend","defendant","defense","defensible", "defensive","defer","deference","defiance","defiant", "deficiency","deficient","deficit","defile","define", "definite","definitely","definition","definitive","deflate", "deflation","deflationary","deflect","deflection","deflower", "defoliant","defoliate","deforest","deform","deformation", "deformity","defraud","defray","defrock","defrost", "deft","defunct","defuse","defy","degauss", "degeneracy","degenerate","degeneration","degenerative","degrade", "degree","dehorn","dehumanise","dehumanize","dehydrate", "deice","deification","deify","deign","deism", "deity","dejected","dejection","dekko","delay", "delectable","delectation","delegacy","delegate","delegation", "delete","deleterious","deletion","delft","deliberate", "deliberation","deliberative","delicacy","delicate","delicatessen", "delicious","delight","delightful","delimit","delineate", "delinquency","delinquent","deliquescent","delirious","delirium", "deliver","deliverance","delivery","deliveryman","dell", "delouse","delphic","delphinium","delta","delude", "deluge","delusion","delusive","delve","demagnetise", "demagnetize","demagogic","demagogue","demagoguery","demand", "demanding","demarcate","demarcation","demean","demeanor", "demeanour","demented","demerit","demesne","demigod", "demijohn","demilitarise","demilitarize","demise","demist", "demister","demo","demob","demobilise","demobilize", "democracy","democrat","democratic","democratise","democratize", "demography","demolish","demolition","demon","demonetise", "demonetize","demoniacal","demonic","demonstrable","demonstrate", "demonstration","demonstrative","demonstrator","demoralise","demoralize", "demote","demotic","demur","demure","demystify", "den","denationalise","denationalize","denial","denier", "denigrate","denim","denims","denizen","denominate", "denomination","denominational","denominator","denotation","denote", "denouement","denounce","dense","density","dent", "dental","dentifrice","dentist","dentistry","denture", "dentures","denude","denunciation","deny","deodorant", "deodorise","deodorize","depart","departed","department", "departure","depend","dependable","dependant","dependence", "dependency","dependent","depict","depilatory","deplete", "deplorable","deplore","deploy","deponent","depopulate", "deport","deportee","deportment","depose","deposit", "deposition","depositor","depository","depot","deprave", "depravity","deprecate","deprecatory","depreciate","depreciatory", "depredation","depress","depressed","depression","deprivation", "deprive","deprived","depth","depths","deputation", "depute","deputise","deputize","deputy","derail", "derange","derby","derelict","dereliction","deride", "derision","derisive","derisory","derivative","derive", "dermatitis","dermatology","derogate","derogatory","derrick", "derv","dervish","des","desalinise","desalinize", "descale","descant","descend","descendant","descended", "descent","describe","description","descriptive","descry", "desecrate","desegregate","desensitise","desensitize","desert", "deserter","desertion","deserts","deserve","deservedly", "deserving","desiccant","desiccate","desideratum","design", "designate","designation","designedly","designer","designing", "designs","desirable","desire","desirous","desist", "desk","deskwork","desolate","despair","despairing", "despatch","despatches","desperado","desperate","desperation", "despicable","despise","despite","despoil","despondent", "despot","despotic","despotism","dessert","dessertspoon", "dessertspoonful","destination","destined","destiny","destitute", "destroy","destroyer","destruction","destructive","desuetude", "desultory","detach","detached","detachedly","detachment", "detail","detailed","detain","detainee","detect", "detection","detective","detector","detention","deter", "detergent","deteriorate","determinant","determination","determine", "determined","determiner","determinism","deterrent","detest", "dethrone","detonate","detonation","detonator","detour", "detract","detractor","detrain","detriment","detritus", "deuce","deuced","deuteronomy","devaluation","devalue", "devastate","devastating","develop","developer","development", "developmental","deviance","deviant","deviate","deviation", "deviationist","device","devil","devilish","devilishly", "devilment","devious","devise","devitalise","devitalize", "devoid","devolution","devolve","devote","devoted", "devotee","devotion","devotional","devotions","devour", "devout","devoutly","dew","dewdrop","dewlap", "dewpond","dewy","dexterity","dexterous","dextrose", "dhoti","dhow","diabetes","diabetic","diabolic", "diabolical","diacritic","diacritical","diadem","diaeresis", "diagnose","diagnosis","diagnostic","diagonal","diagram", "dial","dialect","dialectic","dialectician","dialog", "dialogue","diameter","diametrically","diamond","diaper", "diaphanous","diaphragm","diarist","diarrhea","diarrhoea", "diary","diaspora","diatom","diatribe","dibble", "dice","dicey","dichotomy","dick","dicker", "dickie","dicky","dickybird","dictaphone","dictate", "dictation","dictator","dictatorial","dictatorship","diction", "dictionary","dictum","did","didactic","diddle", "didst","die","diehard","dieresis","diet", "dietary","dietetic","dietetics","dietician","dietitian", "differ","difference","different","differential","differentiate", "difficult","difficulty","diffident","diffract","diffuse", "diffusion","dig","digest","digestion","digestive", "digger","digging","diggings","digit","digital", "dignified","dignify","dignitary","dignity","digraph", "digress","digression","digs","dike","dilapidated", "dilapidation","dilapidations","dilate","dilatory","dildo", "dilemma","dilettante","diligence","diligent","dill", "dillydally","dilute","dilution","dim","dimension", "dimensions","diminish","diminuendo","diminution","diminutive", "dimity","dimple","dimwit","din","dinar", "dine","diner","dingdong","dinghy","dingle", "dingo","dingy","dink","dinkum","dinky", "dinner","dinosaur","dint","diocese","dioxide", "dip","diphtheria","diphthong","diploma","diplomacy", "diplomat","diplomatic","diplomatically","diplomatist","dipper", "dipsomania","dipsomaniac","dipstick","dipswitch","diptych", "dire","direct","direction","directional","directions", "directive","directly","director","directorate","directorship", "directory","direful","dirge","dirigible","dirk", "dirndl","dirt","dirty","disability","disable", "disabled","disabuse","disadvantage","disadvantageous","disaffected", "disaffection","disaffiliate","disafforest","disagree","disagreeable", "disagreement","disallow","disappear","disappearance","disappoint", "disappointed","disappointing","disappointment","disapprobation","disapproval", "disapprove","disarm","disarmament","disarrange","disarray", "disassociate","disaster","disastrous","disavow","disband", "disbar","disbelief","disbelieve","disburden","disburse", "disbursement","disc","discard","discern","discerning", "discernment","discharge","disciple","discipleship","disciplinarian", "disciplinary","discipline","disclaim","disclaimer","disclose", "disclosure","disco","discolor","discoloration","discolour", "discolouration","discomfit","discomfiture","discomfort","discommode", "discompose","disconcert","disconnect","disconnected","disconnection", "disconsolate","discontent","discontented","discontinue","discontinuity", "discontinuous","discord","discordance","discordant","discotheque", "discount","discountenance","discourage","discouragement","discourse", "discourteous","discourtesy","discover","discovery","discredit", "discreditable","discreet","discrepancy","discrete","discretion", "discretionary","discriminate","discriminating","discrimination","discriminatory", "discursive","discus","discuss","discussion","disdain", "disdainful","disease","disembark","disembarrass","disembodied", "disembowel","disembroil","disenchant","disencumber","disendow", "disengage","disengaged","disentangle","disequilibrium","disestablish", "disfavor","disfavour","disfigure","disforest","disfranchise", "disfrock","disgorge","disgrace","disgraceful","disgruntled", "disguise","disgust","dish","dishabille","disharmony", "dishcloth","dishearten","dishes","dishevelled","dishful", "dishonest","dishonesty","dishonor","dishonorable","dishonour", "dishonourable","dishwasher","dishwater","dishy","disillusion", "disillusioned","disillusionment","disincentive","disinclination","disinclined", "disinfect","disinfectant","disinfest","disingenuous","disinherit", "disintegrate","disinter","disinterested","disjoint","disjointed", "disjunctive","disk","dislike","dislocate","dislocation", "dislodge","disloyal","dismal","dismantle","dismast", "dismay","dismember","dismiss","dismissal","dismount", "disobedient","disobey","disoblige","disorder","disorderly", "disorganise","disorganize","disorientate","disown","disparage", "disparate","disparity","dispassionate","dispatch","dispatches", "dispel","dispensable","dispensary","dispensation","dispense", "dispenser","dispersal","disperse","dispersion","dispirit", "displace","displacement","display","displease","displeasure", "disport","disposable","disposal","dispose","disposed", "disposition","dispossess","dispossessed","disproof","disproportion", "disproportionate","disprove","disputable","disputant","disputation", "disputatious","dispute","disqualification","disqualify","disquiet", "disquietude","disquisition","disregard","disrelish","disremember", "disrepair","disreputable","disrepute","disrespect","disrobe", "disrupt","dissatisfaction","dissatisfy","dissect","dissection", "dissemble","disseminate","dissension","dissent","dissenter", "dissenting","dissertation","disservice","dissever","dissident", "dissimilar","dissimilarity","dissimulate","dissipate","dissipated", "dissipation","dissociate","dissoluble","dissolute","dissolution", "dissolve","dissonance","dissonant","dissuade","distaff", "distal","distance","distant","distantly","distaste", }; }
vespa-engine/vespa
linguistics/src/main/java/com/yahoo/language/simple/kstem/KStemData2.java
46,034
package net.dean.jraw.docs.samples; import net.dean.jraw.RedditClient; import net.dean.jraw.docs.CodeSample; import net.dean.jraw.models.Flair; import net.dean.jraw.models.Subreddit; import net.dean.jraw.references.SubredditReference; import java.util.List; @SuppressWarnings("unused") final class Basics { @CodeSample void updateFlair(RedditClient redditClient) { // "Navigate" to the subreddit SubredditReference subreddit = redditClient.subreddit("RocketLeague"); // Request available user flair List<Flair> userFlairOptions = subreddit.userFlairOptions(); if (!userFlairOptions.isEmpty()) { // Arbitrarily choose a new Flair Flair newFlair = userFlairOptions.get(0); // Update the flair on the website subreddit.selfUserFlair().updateToTemplate(newFlair.getId(), ""); } } @CodeSample void referenceChain(RedditClient redditClient) { Subreddit sr = redditClient.subreddit("RocketLeague").about(); } }
mattbdean/JRAW
docs/src/main/java/net/dean/jraw/docs/samples/Basics.java
46,035
package eu.faircode.email; /* This file is part of FairEmail. FairEmail is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. FairEmail is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with FairEmail. If not, see <http://www.gnu.org/licenses/>. Copyright 2018-2024 by Marcel Bokhorst (M66B) */ import android.content.Context; import android.content.SharedPreferences; import android.net.Uri; import android.text.TextUtils; import android.util.Base64; import android.webkit.URLUtil; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.net.MailTo; import androidx.core.util.PatternsCompat; import androidx.preference.PreferenceManager; import org.json.JSONArray; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.IDN; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; public class UriHelper { // https://publicsuffix.org/ private static final HashSet<String> suffixList = new HashSet<>(); // https://raw.githubusercontent.com/publicsuffix/list/master/public_suffix_list.dat private static final String SUFFIX_LIST_NAME = "public_suffix_list.dat"; // https://github.com/svenjacobs/leon // https://github.com/newhouse/url-tracking-stripper // https://maxchadwick.xyz/tracking-query-params-registry/ private static final List<String> PARANOID_QUERY = Collections.unmodifiableList(Arrays.asList( // https://en.wikipedia.org/wiki/UTM_parameters "awt_a", // AWeber "awt_l", // AWeber "awt_m", // AWeber "icid", // Adobe "ef_id", // https://experienceleague.adobe.com/docs/advertising-cloud/integrations/analytics/mc/mc-ids.html "_ga", // Google Analytics "gclid", // Google "gclsrc", // Google ads "dclid", // DoubleClick (Google) "fbclid", // Facebook "igshid", // Instagram "msclkid", // https://help.ads.microsoft.com/apex/index/3/en/60000 "mc_cid", // MailChimp "mc_eid", // MailChimp "zanpid", // Zanox (Awin) "kclickid", // https://support.freespee.com/hc/en-us/articles/202577831-Kenshoo-integration "oly_anon_id", "oly_enc_id", // https://training.omeda.com/knowledge-base/olytics-product-outline/ "_openstat", // https://yandex.com/support/direct/statistics/url-tags.html "vero_conv", "vero_id", // https://help.getvero.com/cloud/articles/what-is-vero_id/ "wickedid", // https://help.wickedreports.com/how-to-manually-tag-a-facebook-ad-with-wickedid "yclid", // https://ads-help.yahoo.co.jp/yahooads/ss/articledetail?lan=en&aid=20442 "__s", // https://ads-help.yahoo.co.jp/yahooads/ss/articledetail?lan=en&aid=20442 "guccounter", "guce_referrer", "guce_referrer_sig", // Yahoo "rb_clickid", // Russian "s_cid", // https://help.goacoustic.com/hc/en-us/articles/360043311613-Track-lead-sources "ml_subscriber", "ml_subscriber_hash", // https://www.mailerlite.com/help/how-to-integrate-your-forms-to-a-wix-website "twclid", // https://business.twitter.com/en/blog/performance-advertising-on-twitter.html "gbraid", "wbraid", // https://support.google.com/google-ads/answer/10417364 "_hsenc", "__hssc", "__hstc", "__hsfp", "hsCtaTracking" // https://knowledge.hubspot.com/reports/what-cookies-does-hubspot-set-in-a-visitor-s-browser )); // https://github.com/snarfed/granary/blob/master/granary/facebook.py#L1789 private static final List<String> FACEBOOK_WHITELIST_PATH = Collections.unmodifiableList(Arrays.asList( "/nd/", "/n/", "/story.php" )); private static final List<String> FACEBOOK_WHITELIST_QUERY = Collections.unmodifiableList(Arrays.asList( "story_fbid", "fbid", "id", "comment_id" )); static String getParentDomain(Context context, String host) { if (host == null) return null; int dot = host.indexOf('.'); if (dot < 0) return null; String parent = host.substring(dot + 1); String tld = getTld(context, host); if (tld == null || tld.equals(parent) || parent.length() < tld.length()) return null; return parent; } static String getRootDomain(Context context, String host) { if (host == null) return null; String tld = getTld(context, host); if (tld == null) return null; if (tld.equalsIgnoreCase(host)) return null; int len = host.length() - tld.length() - 1; if (len < 0) { Log.e("getRootDomain host=" + host + " tld=" + tld); return null; } int dot = host.substring(0, len).lastIndexOf('.'); if (dot < 0) return host; return host.substring(dot + 1); } static boolean isTld(Context context, String host) { if (host == null) return false; String tld = getTld(context, host); return (tld != null && tld.equals(host)); } static boolean hasTld(Context context, String host) { return (host != null && getTld(context, host) != null); } static String getTld(Context context, @NonNull String host) { ensureSuffixList(context); String eval = host.toLowerCase(Locale.ROOT); while (true) { int d = eval.indexOf('.'); String w = (d < 0 ? null : '*' + eval.substring(d)); synchronized (suffixList) { if (suffixList.contains(eval)) return eval; if (suffixList.contains(w)) if (suffixList.contains('!' + eval)) return eval.substring(d + 1); else return eval; } int dot = eval.indexOf('.'); if (dot < 0) return null; eval = eval.substring(dot + 1); } } static String getEmailUser(String address) { if (address == null) return null; int at = address.indexOf('@'); if (at > 0) return address.substring(0, at); return null; } static String getEmailDomain(String address) { if (address == null) return null; int at = address.indexOf('@'); if (at > 0) return address.substring(at + 1); return null; } static @NonNull Uri guessScheme(@NonNull Uri uri) { if (uri.getScheme() != null) return uri; String url = uri.toString(); if (Helper.EMAIL_ADDRESS.matcher(url).matches()) return Uri.parse("mailto:" + url); else if (PatternsCompat.IP_ADDRESS.matcher(url).matches()) return Uri.parse("https://" + url); else if (android.util.Patterns.PHONE.matcher(url).matches()) // Patterns.PHONE (\+[0-9]+[\- \.]*)?(\([0-9]+\)[\- \.]*)?([0-9][0-9\- \.]+[0-9]) // PhoneNumberUtils.isGlobalPhoneNumber() [\+]?[0-9.-]+ return Uri.parse("tel:" + url); else { Uri g = Uri.parse(URLUtil.guessUrl(url)); String scheme = g.getScheme(); if (scheme == null) return uri; else if ("http".equals(scheme)) scheme = "https"; return Uri.parse(scheme + "://" + url); } } static int getSuffixCount(Context context) { ensureSuffixList(context); synchronized (suffixList) { return suffixList.size(); } } private static void ensureSuffixList(Context context) { synchronized (suffixList) { if (suffixList.size() > 0) return; Log.i("Reading " + SUFFIX_LIST_NAME); try (InputStream is = context.getAssets().open(SUFFIX_LIST_NAME)) { BufferedReader br = new BufferedReader(new InputStreamReader((is))); String line; while ((line = br.readLine()) != null) { line = line.trim(); if (TextUtils.isEmpty(line)) continue; if (line.startsWith("//")) continue; suffixList.add(line); try { String ascii = IDN.toASCII(line, IDN.ALLOW_UNASSIGNED); if (!line.equals(ascii)) suffixList.add(line); } catch (Throwable ex) { Log.e(ex); } } Log.i(SUFFIX_LIST_NAME + "=" + suffixList.size()); } catch (Throwable ex) { Log.e(ex); } } } static Uri sanitize(Context context, Uri uri) { if (uri.isOpaque()) return uri; Uri url; boolean changed = false; if (uri.getHost() != null && uri.getHost().endsWith("safelinks.protection.outlook.com") && !TextUtils.isEmpty(uri.getQueryParameter("url"))) { Uri result = Uri.parse(uri.getQueryParameter("url")); changed = (result != null && isHyperLink(result)); url = (changed ? result : uri); } else if ("https".equals(uri.getScheme()) && "smex-ctp.trendmicro.com".equals(uri.getHost()) && "/wis/clicktime/v1/query".equals(uri.getPath()) && !TextUtils.isEmpty(uri.getQueryParameter("url"))) { Uri result = Uri.parse(uri.getQueryParameter("url")); changed = (result != null && isHyperLink(result)); url = (changed ? result : uri); } else if ("https".equals(uri.getScheme()) && "www.google.com".equals(uri.getHost()) && uri.getPath() != null && uri.getPath().startsWith("/amp/")) { // https://blog.amp.dev/2017/02/06/whats-in-an-amp-url/ Uri result = null; String u = uri.toString(); u = u.replace("https://www.google.com/amp/", ""); int p = u.indexOf("/"); while (p > 0) { String segment = u.substring(0, p); if (segment.contains(".")) { result = Uri.parse("https://" + u); break; } u = u.substring(p + 1); p = u.indexOf("/"); } changed = (result != null && isHyperLink(result)); url = (changed ? result : uri); } else if ("https".equals(uri.getScheme()) && uri.getHost() != null && uri.getHost().startsWith("www.google.") && uri.getQueryParameter("url") != null) { // Google non-com redirects Uri result = Uri.parse(uri.getQueryParameter("url")); changed = (result != null && isHyperLink(result)); url = (changed ? result : uri); } else if (uri.getPath() != null && uri.getPath().startsWith("/track/click") && uri.getQueryParameter("p") != null) { Uri result = null; try { // Mandrill String p = new String(Base64.decode(uri.getQueryParameter("p"), Base64.URL_SAFE)); JSONObject json = new JSONObject(p); json = new JSONObject(json.getString("p")); result = Uri.parse(json.getString("url")); } catch (Throwable ex) { Log.i(ex); } changed = (result != null && isHyperLink(result)); url = (changed ? result : uri); } else if (uri.getHost() != null && uri.getHost().endsWith(".awstrack.me")) { // https://docs.aws.amazon.com/ses/latest/dg/configure-custom-open-click-domains.html String path = uri.getPath(); int s = (path == null ? -1 : path.indexOf('/', 1)); Uri result = (s > 0 ? Uri.parse(path.substring(s + 1)) : null); changed = (result != null && isHyperLink(result)); url = (changed ? result : uri); } else { Uri result = getBraveDebounce(context, uri); if (result == null && uri.getQueryParameter("redirectUrl") != null) // https://.../link-tracker?redirectUrl=<base64>&sig=...&iat=...&a=...&account=...&email=...&s=...&i=... try { byte[] bytes = Base64.decode(uri.getQueryParameter("redirectUrl"), Base64.URL_SAFE); String u = URLDecoder.decode(new String(bytes), StandardCharsets.UTF_8.name()); result = Uri.parse(u); } catch (Throwable ex) { Log.i(ex); } changed = (result != null && isHyperLink(result)); url = (changed ? result : uri); } if (!changed) { // Sophos Email Appliance // http://<host>/?<base64> Uri result = null; try { if (uri.getQueryParameterNames().size() == 1) { String key = uri.getQueryParameterNames().iterator().next(); if (TextUtils.isEmpty(uri.getQueryParameter(key))) { String data = new String(Base64.decode(key, Base64.URL_SAFE)); int v = data.indexOf("ver="); int u = data.indexOf("&&url="); if (v == 0 && u > 0) result = Uri.parse(URLDecoder.decode(data.substring(u + 6), StandardCharsets.UTF_8.name())); } } } catch (Throwable ex) { Log.i(ex); } changed = (result != null && isHyperLink(result)); url = (changed ? result : uri); } if (!changed) { // go.dhlparcel.nl and others // Try base64 last path segment Uri result = null; String path = uri.getPath(); try { if (path != null) { int s = path.lastIndexOf('/'); if (s > 0) { String b = new String(Base64.decode(path.substring(s + 1), Base64.URL_SAFE)); result = Uri.parse(b); } } } catch (Throwable ex) { Log.i(ex); } changed = (result != null && isHyperLink(result)); url = (changed ? result : uri); } if (url.isOpaque() || !isHyperLink(url)) return uri; SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); boolean adguard = prefs.getBoolean("adguard", false); if (adguard) { Uri result = Adguard.filter(context, url); return (result == null ? url : result); } Uri.Builder builder = url.buildUpon(); builder.clearQuery(); String host = uri.getHost(); String path = uri.getPath(); if (host != null) host = host.toLowerCase(Locale.ROOT); if (path != null) path = path.toLowerCase(Locale.ROOT); boolean first = "www.facebook.com".equals(host); for (String key : url.getQueryParameterNames()) { // https://en.wikipedia.org/wiki/UTM_parameters // https://docs.oracle.com/en/cloud/saas/marketing/eloqua-user/Help/EloquaAsynchronousTrackingScripts/EloquaTrackingParameters.htm String lkey = key.toLowerCase(Locale.ROOT); if (PARANOID_QUERY.contains(lkey) || lkey.startsWith("utm_") || lkey.startsWith("elq") || ((host != null && host.endsWith("facebook.com")) && !first && FACEBOOK_WHITELIST_PATH.contains(path) && !FACEBOOK_WHITELIST_QUERY.contains(lkey)) || ("store.steampowered.com".equals(host) && "snr".equals(lkey))) changed = true; else if (!TextUtils.isEmpty(key)) for (String value : url.getQueryParameters(key)) { Log.i("Query " + key + "=" + value); Uri suri = Uri.parse(value); if (suri != null && isHyperLink(suri)) { Uri s = sanitize(context, suri); return (s == null ? suri : s); } builder.appendQueryParameter(key, value); } first = false; } return (changed ? builder.build() : null); } @Nullable private static Uri getBraveDebounce(Context context, Uri uri) { // https://github.com/brave/adblock-lists/blob/master/brave-lists/debounce.json try (InputStream is = context.getAssets().open("debounce.json")) { String json = Helper.readStream(is); JSONArray jbounce = new JSONArray(json); for (int i = 0; i < jbounce.length(); i++) { JSONObject jitem = jbounce.getJSONObject(i); JSONArray jinclude = jitem.getJSONArray("include"); JSONArray jexclude = jitem.getJSONArray("exclude"); boolean include = false; for (int j = 0; j < jinclude.length(); j++) if (Pattern.matches(escapeStar(jinclude.getString(j)), uri.toString())) { include = true; break; } if (include) for (int j = 0; j < jexclude.length(); j++) if (Pattern.matches(escapeStar(jexclude.getString(j)), uri.toString())) { include = false; break; } if (include) { String action = jitem.getString("action"); if ("redirect".equals(action) || "base64,redirect".equals(action)) { String name = jitem.getString("param"); String param = uri.getQueryParameter(name); if (!TextUtils.isEmpty(param)) try { if ("base64,redirect".equals(action)) param = new String(Base64.decode(param, Base64.NO_PADDING)); return Uri.parse(param); } catch (Throwable ex) { Log.w(ex); } } else if ("regex-path".equals(action)) { String regex = jitem.getString("param"); String prepend = jitem.optString("prepend_scheme"); String path = uri.getPath(); if (!TextUtils.isEmpty(path)) { Matcher m = Pattern.compile(regex).matcher(path); if (m.matches()) { String param = m.group(1); if (!TextUtils.isEmpty(prepend)) param = prepend + "://" + param; return Uri.parse(param); } } } } } } catch (Throwable ex) { Log.e(ex); } return null; } private static String escapeStar(String regex) { for (char kar : "\\.?![]{}()<>*+-=^$|".toCharArray()) if (kar != '*') regex = regex.replace("" + kar, "\\" + kar); return regex.replace("*", ".*"); } static Uri secure(Uri uri, boolean https) { String scheme = uri.getScheme(); if (https ? "http".equals(scheme) : "https".equals(scheme)) { Uri.Builder builder = uri.buildUpon(); builder.scheme(https ? "https" : "http"); String authority = uri.getEncodedAuthority(); if (authority != null) { authority = authority.replace(https ? ":80" : ":443", https ? ":443" : ":80"); builder.encodedAuthority(authority); } return builder.build(); } else return uri; } static boolean isSecure(Uri uri) { return (!uri.isOpaque() && "https".equalsIgnoreCase(uri.getScheme())); } static boolean isHyperLink(Uri uri) { return (!uri.isOpaque() && ("http".equalsIgnoreCase(uri.getScheme()) || "https".equalsIgnoreCase(uri.getScheme()))); } static boolean isMail(Uri uri) { return (uri.isOpaque() && "mailto".equalsIgnoreCase(uri.getScheme())); } static boolean isPhoneNumber(Uri uri) { return (uri.isOpaque() && "tel".equalsIgnoreCase(uri.getScheme())); } static boolean isGeo(Uri uri) { return (uri.isOpaque() && "geo".equalsIgnoreCase(uri.getScheme())); } static Uri fix(Uri uri) { if ((!"http".equals(uri.getScheme()) && "http".equalsIgnoreCase(uri.getScheme())) || (!"https".equals(uri.getScheme()) && "https".equalsIgnoreCase(uri.getScheme()))) { String u = uri.toString(); int semi = u.indexOf(':'); if (semi > 0) return Uri.parse(u.substring(0, semi).toLowerCase(Locale.ROOT) + u.substring(semi)); } return uri; } static String getHost(Uri uri) { if ("mailto".equalsIgnoreCase(uri.getScheme())) { MailTo email = MailTo.parse(uri.toString()); return getEmailDomain(email.getTo()); } else return uri.getHost(); } static void test(Context context) { String[] hosts = new String[]{ "child.parent.example.com", "parent.example.com", "example.com", "com", "child.parent.co.uk", "parent.co.uk", "co.uk", "uk", "child.parent.aaa.ck", "parent.aaa.ck", "aaa.ck", "ck", "child.parent.www.ck", "parent.www.ck", "www.ck", "ck" }; for (String host : hosts) Log.i("PSL " + host + ":" + " tld=" + getTld(context, host) + " root=" + getRootDomain(context, host) + " parent=" + getParentDomain(context, host)); } }
M66B/FairEmail
app/src/main/java/eu/faircode/email/UriHelper.java
46,036
/* * Copyright (c) 2018. Aberic - All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.aberic.fabric.bean; import cn.aberic.fabric.dao.entity.Channel; import lombok.Getter; import lombok.Setter; import java.util.List; /** * 作者:Aberic on 2018/8/10 21:29 * 邮箱:[email protected] */ @Setter @Getter public class Home { int leagueCount; int orgCount; int ordererCount; int peerCount; int caCount; int channelCount; int chaincodeCount; int appCount; List<Channel> channels; List<Block> blocks; List<ChannelPercent> channelPercents; List<ChannelBlockList> channelBlockLists; List<cn.aberic.fabric.dao.entity.Block> blockDaos; DayStatistics dayStatistics; Platform platform; Curve dayBlocks; Curve dayTxs; Curve dayRWs; }
aberic/fabric-net-server
fabric-edge/src/main/java/cn/aberic/fabric/bean/Home.java
46,037
/** * Copyright (C) 2024 Patrice Brend'amour <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.brendamour.jpasskit; import java.util.Collections; import java.util.Date; import java.util.List; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import de.brendamour.jpasskit.enums.PKEventType; import de.brendamour.jpasskit.semantics.PKCurrencyAmount; import de.brendamour.jpasskit.semantics.PKPersonNameComponents; import de.brendamour.jpasskit.semantics.PKSeat; import de.brendamour.jpasskit.semantics.PKSemanticLocation; /** * Allows constructing and validating {@link PKSemantics} entities. * * @author Patrice Brend'amour */ @JsonPOJOBuilder(withPrefix = "") public class PKSemanticsBuilder implements IPKValidateable, IPKBuilder<PKSemantics> { private PKSemantics semantics; protected PKSemanticsBuilder() { this.semantics = new PKSemantics(); } @Override public PKSemanticsBuilder of(final PKSemantics source) { if (source != null) { this.semantics = source.clone(); } return this; } public PKSemanticsBuilder totalPrice(PKCurrencyAmount totalPrice) { this.semantics.totalPrice = totalPrice; return this; } public PKSemanticsBuilder duration(Number duration) { this.semantics.duration = duration; return this; } public PKSemanticsBuilder seats(List<PKSeat> seats) { this.semantics.seats = seats; return this; } public PKSemanticsBuilder silenceRequested(Boolean silenceRequested) { this.semantics.silenceRequested = silenceRequested; return this; } public PKSemanticsBuilder departureLocation(PKSemanticLocation departureLocation) { this.semantics.departureLocation = departureLocation; return this; } public PKSemanticsBuilder departureLocationDescription(String departureLocationDescription) { this.semantics.departureLocationDescription = departureLocationDescription; return this; } public PKSemanticsBuilder destinationLocation(PKSemanticLocation destinationLocation) { this.semantics.destinationLocation = destinationLocation; return this; } public PKSemanticsBuilder destinationLocationDescription(String destinationLocationDescription) { this.semantics.destinationLocationDescription = destinationLocationDescription; return this; } public PKSemanticsBuilder transitProvider(String transitProvider) { this.semantics.transitProvider = transitProvider; return this; } public PKSemanticsBuilder vehicleName(String vehicleName) { this.semantics.vehicleName = vehicleName; return this; } public PKSemanticsBuilder vehicleNumber(String vehicleNumber) { this.semantics.vehicleNumber = vehicleNumber; return this; } public PKSemanticsBuilder vehicleType(String vehicleType) { this.semantics.vehicleType = vehicleType; return this; } public PKSemanticsBuilder originalDepartureDate(Date originalDepartureDate) { this.semantics.originalDepartureDate = originalDepartureDate; return this; } public PKSemanticsBuilder currentDepartureDate(Date currentDepartureDate) { this.semantics.currentDepartureDate = currentDepartureDate; return this; } public PKSemanticsBuilder originalArrivalDate(Date originalArrivalDate) { this.semantics.originalArrivalDate = originalArrivalDate; return this; } public PKSemanticsBuilder currentArrivalDate(Date currentArrivalDate) { this.semantics.currentArrivalDate = currentArrivalDate; return this; } public PKSemanticsBuilder originalBoardingDate(Date originalBoardingDate) { this.semantics.originalBoardingDate = originalBoardingDate; return this; } public PKSemanticsBuilder currentBoardingDate(Date currentBoardingDate) { this.semantics.currentBoardingDate = currentBoardingDate; return this; } public PKSemanticsBuilder boardingGroup(String boardingGroup) { this.semantics.boardingGroup = boardingGroup; return this; } public PKSemanticsBuilder boardingSequenceNumber(String boardingSequenceNumber) { this.semantics.boardingSequenceNumber = boardingSequenceNumber; return this; } public PKSemanticsBuilder confirmationNumber(String confirmationNumber) { this.semantics.confirmationNumber = confirmationNumber; return this; } public PKSemanticsBuilder transitStatus(String transitStatus) { this.semantics.transitStatus = transitStatus; return this; } public PKSemanticsBuilder transitStatusReason(String transitStatusReason) { this.semantics.transitStatusReason = transitStatusReason; return this; } public PKSemanticsBuilder passengerName(PKPersonNameComponents passengerName) { this.semantics.passengerName = passengerName; return this; } public PKSemanticsBuilder membershipProgramName(String membershipProgramName) { this.semantics.membershipProgramName = membershipProgramName; return this; } public PKSemanticsBuilder membershipProgramNumber(String membershipProgramNumber) { this.semantics.membershipProgramNumber = membershipProgramNumber; return this; } public PKSemanticsBuilder priorityStatus(String priorityStatus) { this.semantics.priorityStatus = priorityStatus; return this; } public PKSemanticsBuilder securityScreening(String securityScreening) { this.semantics.securityScreening = securityScreening; return this; } public PKSemanticsBuilder flightCode(String flightCode) { this.semantics.flightCode = flightCode; return this; } public PKSemanticsBuilder airlineCode(String airlineCode) { this.semantics.airlineCode = airlineCode; return this; } public PKSemanticsBuilder flightNumber(Number flightNumber) { this.semantics.flightNumber = flightNumber; return this; } public PKSemanticsBuilder departureAirportCode(String departureAirportCode) { this.semantics.departureAirportCode = departureAirportCode; return this; } public PKSemanticsBuilder departureAirportName(String departureAirportName) { this.semantics.departureAirportName = departureAirportName; return this; } public PKSemanticsBuilder departureTerminal(String departureTerminal) { this.semantics.departureTerminal = departureTerminal; return this; } public PKSemanticsBuilder departureGate(String departureGate) { this.semantics.departureGate = departureGate; return this; } public PKSemanticsBuilder destinationAirportCode(String destinationAirportCode) { this.semantics.destinationAirportCode = destinationAirportCode; return this; } public PKSemanticsBuilder destinationAirportName(String destinationAirportName) { this.semantics.destinationAirportName = destinationAirportName; return this; } public PKSemanticsBuilder destinationTerminal(String destinationTerminal) { this.semantics.destinationTerminal = destinationTerminal; return this; } public PKSemanticsBuilder destinationGate(String destinationGate) { this.semantics.destinationGate = destinationGate; return this; } public PKSemanticsBuilder departurePlatform(String departurePlatform) { this.semantics.departurePlatform = departurePlatform; return this; } public PKSemanticsBuilder departureStationName(String departureStationName) { this.semantics.departureStationName = departureStationName; return this; } public PKSemanticsBuilder destinationPlatform(String destinationPlatform) { this.semantics.destinationPlatform = destinationPlatform; return this; } public PKSemanticsBuilder destinationStationName(String destinationStationName) { this.semantics.destinationStationName = destinationStationName; return this; } public PKSemanticsBuilder carNumber(String carNumber) { this.semantics.carNumber = carNumber; return this; } public PKSemanticsBuilder eventName(String eventName) { this.semantics.eventName = eventName; return this; } public PKSemanticsBuilder venueName(String venueName) { this.semantics.venueName = venueName; return this; } public PKSemanticsBuilder venueLocation(PKSemanticLocation venueLocation) { this.semantics.venueLocation = venueLocation; return this; } public PKSemanticsBuilder venueEntrance(String venueEntrance) { this.semantics.venueEntrance = venueEntrance; return this; } public PKSemanticsBuilder venuePhoneNumber(String venuePhoneNumber) { this.semantics.venuePhoneNumber = venuePhoneNumber; return this; } public PKSemanticsBuilder venueRoom(String venueRoom) { this.semantics.venueRoom = venueRoom; return this; } public PKSemanticsBuilder eventType(PKEventType eventType) { this.semantics.eventType = eventType; return this; } public PKSemanticsBuilder eventStartDate(Date eventStartDate) { this.semantics.eventStartDate = eventStartDate; return this; } public PKSemanticsBuilder eventEndDate(Date eventEndDate) { this.semantics.eventEndDate = eventEndDate; return this; } public PKSemanticsBuilder artistIDs(List<String> artistIDs) { this.semantics.artistIDs = artistIDs; return this; } public PKSemanticsBuilder performerNames(List<String> performerNames) { this.semantics.performerNames = performerNames; return this; } public PKSemanticsBuilder genre(String genre) { this.semantics.genre = genre; return this; } public PKSemanticsBuilder leagueName(String leagueName) { this.semantics.leagueName = leagueName; return this; } public PKSemanticsBuilder leagueAbbreviation(String leagueAbbreviation) { this.semantics.leagueAbbreviation = leagueAbbreviation; return this; } public PKSemanticsBuilder homeTeamLocation(String homeTeamLocation) { this.semantics.homeTeamLocation = homeTeamLocation; return this; } public PKSemanticsBuilder homeTeamName(String homeTeamName) { this.semantics.homeTeamName = homeTeamName; return this; } public PKSemanticsBuilder homeTeamAbbreviation(String homeTeamAbbreviation) { this.semantics.homeTeamAbbreviation = homeTeamAbbreviation; return this; } public PKSemanticsBuilder awayTeamLocation(String awayTeamLocation) { this.semantics.awayTeamLocation = awayTeamLocation; return this; } public PKSemanticsBuilder awayTeamName(String awayTeamName) { this.semantics.awayTeamName = awayTeamName; return this; } public PKSemanticsBuilder awayTeamAbbreviation(String awayTeamAbbreviation) { this.semantics.awayTeamAbbreviation = awayTeamAbbreviation; return this; } public PKSemanticsBuilder sportName(String sportName) { this.semantics.sportName = sportName; return this; } public PKSemanticsBuilder balance(PKCurrencyAmount balance) { this.semantics.balance = balance; return this; } @Override public boolean isValid() { return getValidationErrors().isEmpty(); } @Override public List<String> getValidationErrors() { return Collections.emptyList(); } @Override public PKSemantics build() { return this.semantics; } }
drallgood/jpasskit
jpasskit/src/main/java/de/brendamour/jpasskit/PKSemanticsBuilder.java
46,038
import java.util.*; import java.util.stream.Collectors; import java.io.*; import java.math.*; class Player { static final int TYPE_MONSTER = 0; static final int TYPE_MY_HERO = 1; static final int TYPE_OP_HERO = 2; static class Entity { int id; int type; int x, y; int shieldLife; int isControlled; int health; int vx, vy; int nearBase; int threatFor; Entity(int id, int type, int x, int y, int shieldLife, int isControlled, int health, int vx, int vy, int nearBase, int threatFor) { this.id = id; this.type = type; this.x = x; this.y = y; this.shieldLife = shieldLife; this.isControlled = isControlled; this.health = health; this.vx = vx; this.vy = vy; this.nearBase = nearBase; this.threatFor = threatFor; } } public static void main(String args[]) { Scanner in = new Scanner(System.in); // base_x,base_y: The corner of the map representing your base int baseX = in.nextInt(); int baseY = in.nextInt(); // heroesPerPlayer: Always 3 int heroesPerPlayer = in.nextInt(); // game loop while (true) { int myHealth = in.nextInt(); // Your base health int myMana = in.nextInt(); // Ignore in the first league; Spend ten mana to cast a spell int oppHealth = in.nextInt(); int oppMana = in.nextInt(); int entityCount = in.nextInt(); // Amount of heros and monsters you can see List<Entity> myHeroes = new ArrayList<>(entityCount); List<Entity> oppHeroes = new ArrayList<>(entityCount); List<Entity> monsters = new ArrayList<>(entityCount); for (int i = 0; i < entityCount; i++) { int id = in.nextInt(); // Unique identifier int type = in.nextInt(); // 0=monster, 1=your hero, 2=opponent hero int x = in.nextInt(); // Position of this entity int y = in.nextInt(); int shieldLife = in.nextInt(); // Ignore for this league; Count down until shield spell fades int isControlled = in.nextInt(); // Ignore for this league; Equals 1 when this entity is under a control spell int health = in.nextInt(); // Remaining health of this monster int vx = in.nextInt(); // Trajectory of this monster int vy = in.nextInt(); int nearBase = in.nextInt(); // 0=monster with no target yet, 1=monster targeting a base int threatFor = in.nextInt(); // Given this monster's trajectory, is it a threat to 1=your base, 2=your opponent's base, 0=neither Entity entity = new Entity( id, type, x, y, shieldLife, isControlled, health, vx, vy, nearBase, threatFor ); switch (type) { case TYPE_MONSTER: monsters.add(entity); break; case TYPE_MY_HERO: myHeroes.add(entity); break; case TYPE_OP_HERO: oppHeroes.add(entity); break; } } for (int i = 0; i < heroesPerPlayer; i++) { Entity target = null; if (!monsters.isEmpty()) { target = monsters.get(i % monsters.size()); } if (target != null) { System.out.println(String.format("MOVE %d %d", target.x , target.y)); } else { System.out.println("WAIT"); } } } } }
DracoBlue/SpringChallenge2022
starterAIs/Starter.java
46,039
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.opensymphony.xwork2.validator.validators; import com.opensymphony.xwork2.validator.ValidationException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /** * <!-- START SNIPPET: javadoc --> * The ConditionalVisitorFieldValidator will forward validation to the VisitorFieldValidator * only if the expression will evaluate to true. * <!-- END SNIPPET: javadoc --> * * <!-- START SNIPPET: parameters --> * <ul> * <li>expression - an OGNL expression which should evaluate to true to pass validation to the VisitorFieldValidator</li> * </ul> * <!-- END SNIPPET: parameters --> * * <pre> * <!-- START SNIPPET: example --> * &lt;field name="colleaguePosition"&gt; * &lt;field-validator type="conditionalvisitor"&gt; * &lt;param name="expression"&gt;reason == 'colleague' and colleaguePositionID == 'OTHER'&lt;/param&gt; * &lt;message&gt;You must select reason Colleague and position Other&lt;/message&gt; * &lt;/field-validator&gt; * &lt;/field&gt; * <!-- END SNIPPET: example --> * </pre> * * @author Matt Raible */ public class ConditionalVisitorFieldValidator extends VisitorFieldValidator { private static final Logger LOG = LogManager.getLogger(ConditionalVisitorFieldValidator.class); private String expression; public void setExpression(String expression) { this.expression = expression; } public String getExpression() { return expression; } /** * If expression evaluates to true, invoke visitor validation. * * @param object the object being validated * @throws ValidationException in case of validation problems */ @Override public void validate(Object object) throws ValidationException { if (validateExpression(object)) { super.validate(object); } } /** * Validate the expression contained in the "expression" paramter. * * @param object the object you're validating * @return true if expression evaluates to true (implying a validation * failure) * @throws ValidationException if anything goes wrong */ public boolean validateExpression(Object object) throws ValidationException { Boolean answer = Boolean.FALSE; Object obj = null; try { obj = getFieldValue(expression, object); } catch (ValidationException e) { throw e; } catch (Exception e) { // let this pass, but it will be logged right below } if ((obj != null) && (obj instanceof Boolean)) { answer = (Boolean) obj; } else { LOG.warn("Got result of {} when trying to get Boolean.", obj); } return answer; } }
apache/struts
core/src/main/java/com/opensymphony/xwork2/validator/validators/ConditionalVisitorFieldValidator.java
46,040
package java.mediator; import java.awt.Button; public class ColleagueButton extends Button implements Colleague { private Mediator mediator; public ColleagueButton(String caption) { super(caption); } @Override public void setMediator(Mediator mediator) { this.mediator = mediator; } @Override public void setColleagueEnabled(boolean enabled) { setEnabled(enabled); } }
hyunnnn98/IT-Note
chapter06-디자인패턴/java/mediator/ColleagueButton.java
46,041
package com.github.guang19.designpattern.mediator; import java.util.ArrayList; import java.util.List; /** * @author guang19 * @date 2020/5/30 * @description 具体中介者 * @since 1.0.0 */ public class ConcreteMediator extends Mediator { //已注册的同事 private List<Colleague> registerColleagues = new ArrayList<>(); @Override public void registerColleague(Colleague colleague) { if (colleague != null && !this.registerColleagues.contains(colleague)) { this.registerColleagues.add(colleague); colleague.setMediator(this); } } @Override public void forwardMessage(Colleague colleague,String message) { for (Colleague c : registerColleagues) { if (!c.equals(colleague)) { c.receive(message); } } } }
imlhx/framework-learning
design_pattern/src/main/java/com/github/guang19/designpattern/mediator/ConcreteMediator.java
46,042
package poe.poeapi; import org.json.JSONArray; import org.json.JSONObject; import poe.level.data.CharacterInfo; import poe.level.data.Util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; public class POEAPIHelper { public static ArrayList<String> getPOEActiveLeagues() { Util.HttpResponse response = Util.httpToString("http://api.pathofexile.com/leagues?compact=1"); ArrayList<String> result = new ArrayList<>(); if (response.responseCode == 200) { JSONArray arr = new JSONArray(response.responseString); for (int i = 0; i < arr.length(); i++) { result.add(arr.getJSONObject(i).getString("id")); } } return result; } public static long getCharacterExperience(String account, String character, String league) { Util.HttpResponse response = Util.httpToString("https://www.pathofexile.com/character-window/get-characters?accountName=" + account); long result = -1; if (response.responseCode == 200) { JSONArray arr = new JSONArray(response.responseString); for (int i = 0; i < arr.length(); i++) { if (arr.getJSONObject(i).getString("league").equalsIgnoreCase(league) && arr.getJSONObject(i).getString("name").equalsIgnoreCase(character)) { result = arr.getJSONObject(i).getLong("experience"); break; } } } return result; } public static ArrayList<CharacterInfo> getCharacters(String account) { Util.HttpResponse response = Util.httpToString("https://www.pathofexile.com/character-window/get-characters?accountName=" + account); ArrayList<CharacterInfo> result = new ArrayList<>(); if (response.responseCode == 200) { JSONArray arr = new JSONArray(response.responseString); for (int i = 0; i < arr.length(); i++) { CharacterInfo ci = new CharacterInfo(); ci.loadedFromPOEAPI = true; JSONObject charObj = arr.getJSONObject(i); ci.characterName = charObj.getString("name"); ci.experience = charObj.getLong("experience"); ci.level = charObj.getInt("level"); ci.ascendancyName = charObj.getString("class"); ci.setClassNameFromInt(charObj.getInt("classId")); ci.league = charObj.getString("league"); result.add(ci); } } result.sort(new CharacterInfo.CharacterLeagueComparator()); return result; } public static void main(String[] args) { /*ArrayList<String> result = getPOEActiveLeagues(); System.out.println(result);*/ long experience = getCharacterExperience("protuhj", "FlashBadmanners", "SSF Standard"); //System.out.println("Experience: " + experience); } }
karakasis/Path-of-Leveling
src/poe/poeapi/POEAPIHelper.java
46,043
package day64; import java.util.*; public class MapPractice { public static void main(String[] args) { // What if we want to have multiple value for one key ?? // for example groupCode (bugHunter) -- group member names (abc, efg , htj , knl) // String List<String> // key data type is String , value data type is List<String> Map<String, List<String>> groupMap = new HashMap<>(); groupMap.put("PowerOf4", Arrays.asList("Furkan", "Daria", "Serife", "Muge")); groupMap.put("Achievers", Arrays.asList("Maiia", "Anastasia", "Zaki", "Toyly", "Like")); groupMap.put("BugHunter", Arrays.asList("Ayse", "Rabiyam", "Gulzina")); groupMap.put("BugBusters", Arrays.asList("Rukhshona", "Fariza", "Seyma", "Sumeyyra", "Huvayda")); //System.out.println("groupMap = " + groupMap); groupMap.forEach((groupCode, allMembers) -> System.out.println("groupCode = " + groupCode + "\n\t members : " + allMembers)); // get Toyly , he is at index 3 System.out.println(groupMap.get("Achievers").get(3)); // check whether this map has Gulzina or not in BugHunter ? // get method from Map | contains method is coming from list // because the values are List<String> get method will return the entire List System.out.println(groupMap.get("BugHunter").contains("Gulzina")); // we want to add a group entry so we can add or remove members from the group groupMap.put("Justice League", new ArrayList<>(Arrays.asList("Superman", "Batman", "WonderWoman"))); groupMap.get("Justice League").add("Flash"); System.out.println("groupMap.get(\"Justice League\") = " + groupMap.get("Justice League")); // the key for the Map should be a type Immutable } }
raksanao/JavaProgrammingB15Online
src/day64/MapPractice.java