answer
stringlengths
17
10.2M
package com.github.behaim.builder; import com.github.behaim.Behaim; import com.github.behaim.builder.config.Config; import com.github.behaim.domain.Person; import org.assertj.core.api.SoftAssertions; import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collection; import static org.assertj.core.api.Assertions.assertThat; public class BuilderTest { private final static Logger logger = LoggerFactory.getLogger(BuilderTest.class); private static final Config CONFIG = new Config(0, 1); @Test public void testBuild_1Param_oneInstance() { Person person = Behaim.build(Person.class); SoftAssertions assertions = new SoftAssertions(); assertFullyPopulated(assertions, person, "person", CONFIG.getRecursionDepth()); assertions.assertAll(); } @Test public void testBuild_2Params_oneInstance() { Collection<Person> persons = Behaim.build(Person.class, 1); assertResult(persons, 1); } @Test @Ignore(value = "broken test") //TODO fix the bug public void testBuild_2Params_twoInstances() { Collection<Person> persons = Behaim.build(Person.class, 2); assertResult(persons, 2); } private void assertResult(Collection<Person> persons, int expectedNumberOfInstances) { assertThat(persons).as("persons").hasSize(expectedNumberOfInstances); SoftAssertions assertions = new SoftAssertions(); int index = 0; for (Person person : persons) { assertFullyPopulated(assertions, person, "person[" + index++ + "]", CONFIG.getRecursionDepth()); } assertions.assertAll(); } private void assertFullyPopulated(SoftAssertions assertions, Person person, String breadcrumb, int level) { logger.trace("[{}] Checking {}", level, breadcrumb); assertions.assertThat(person).as(breadcrumb + " at level " + level).isNotNull(); if (person == null) { return; } assertions.assertThat(person.getAnnualSalary()).as(breadcrumb + ".annualSalary at level " + level).isNotNull(); assertions.assertThat(person.getBirthday()).as(breadcrumb + ".birthday at level " + level).isNotNull(); assertions.assertThat(person.getName()).as(breadcrumb + ".name at level " + level).isNotNull(); if (level > 0) { assertFullyPopulated(assertions, person.getManager(), breadcrumb + ".manager", level - 1); String teamProperty = breadcrumb + ".team at level " + level; assertions.assertThat(person.getTeam()).as(teamProperty).isNotNull(); if (person.getTeam() != null) { for (Person teamMember : person.getTeam()) { assertFullyPopulated(assertions, teamMember, teamProperty, level - 1); } } } } }
package com.graph.db.file.term; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.collection.IsEmptyCollection.empty; import static org.junit.Assert.assertThat; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.List; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import com.graph.db.domain.input.term.RawTerm; public class TermParserTest { @Rule public TemporaryFolder testFolder = new TemporaryFolder(); private TermParser termParser; @Before public void before() throws IOException { File tempFolder = testFolder.newFolder(getClass().getSimpleName()); termParser = new TermParser("file") { @Override protected String getOutputFolder() { return tempFolder.toString(); } }; } @Test public void termProducedFromListOfStrings() { List<String> linesForTerm = Arrays.asList("[Term]", "id: HP:0000001", "name: All", "comment: Root of all terms in the Human Phenotype Ontology."); RawTerm rawTerm = termParser.createRawTermFromLines(linesForTerm); assertThat(rawTerm.getIsA(), is(empty())); assertThat(rawTerm.getName(), is("All")); assertThat(rawTerm.getTermId(), is("HP:0000001")); } }
package com.levelup.java.number; import static org.hamcrest.CoreMatchers.hasItems; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.math.BigInteger; import java.util.List; import java.util.Random; import org.apache.commons.math3.primes.Primes; import org.junit.Ignore; import org.junit.Test; public class NumberIsPrime { /** * Method will determine if n is prime * * @param n * @return boolean */ boolean isPrime(int n) { if (n % 2 == 0) { return false; } else { for(int i=3; i*i <=n; i+=2) { if(n % i == 0) { return false; } } } return true; } @Test public void determine_if_number_is_prime_java () { boolean isPrimeNumber = isPrime(5779); assertTrue(isPrimeNumber); } @Ignore("due to inconsistencies b/t 5 and 7") @Test public void determine_if_number_is_prime_java_big_integer () { Random rnd = new Random(); BigInteger isPrimeNumber = BigInteger.probablePrime(3, rnd); assertEquals(5, isPrimeNumber.intValue()); } @Test public void determine_if_number_is_prime_java_regular_expresison () { char n = 5779; boolean isPrimeNumber = false; if (!new String(new char[n]).matches(".?|(..+?)\\1+")) { isPrimeNumber = true; } assertTrue(isPrimeNumber); } @Test public void determine_if_number_prime_with_apache_commons () { boolean isPrimeNumber = Primes.isPrime(5779); assertTrue(isPrimeNumber); } @Test public void find_next_prime_number_with_apache_commons () { int nextPrimeNumber = Primes.nextPrime(5780); assertEquals(5783, nextPrimeNumber); } @Test public void determine_prime_factors_of_a_number_with_apache_commons () { List<Integer> primeFactors = Primes.primeFactors(5782); assertThat(primeFactors, hasItems(2, 7, 7, 59)); } }
// Depot library - a Java relational persistence library // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.samskivert.depot; import java.util.List; import com.google.common.collect.Lists; import com.samskivert.depot.Tuple2; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; /** * Tests individual field selection. */ public class SelectFieldsTest extends TestBase { @Before public void createRecords () { for (int ii = 0; ii < 10; ii++) { _repo.insert(createTestRecord(ii)); } _repo.insert(new EnumKeyRecord(EnumKeyRecord.Type.A, "Elvis")); _repo.insert(new EnumKeyRecord(EnumKeyRecord.Type.B, "Moses")); _repo.insert(new EnumKeyRecord(EnumKeyRecord.Type.C, "Abraham")); _repo.insert(new EnumKeyRecord(EnumKeyRecord.Type.D, "Elvis")); } @After public void cleanup () { _repo.from(TestRecord.class).whereTrue().delete(); _repo.from(EnumKeyRecord.class).whereTrue().delete(); } @Test public void testProjection () { // test some basic one and two column selects List<Integer> allKeys = _repo.from(TestRecord.class).select(TestRecord.RECORD_ID); assertEquals(allKeys, Lists.newArrayList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)); List<Integer> someKeys = _repo.from(TestRecord.class).where( TestRecord.RECORD_ID.greaterThan(5)).select(TestRecord.RECORD_ID); assertEquals(someKeys, Lists.newArrayList(6, 7, 8, 9)); List<Tuple2<Integer,String>> data = _repo.from(TestRecord.class).where( TestRecord.RECORD_ID.greaterThan(7)).select(TestRecord.RECORD_ID, TestRecord.NAME); List<Tuple2<Integer,String>> want = Lists.newArrayList(); want.add(Tuple2.create(8, "Elvis")); want.add(Tuple2.create(9, "Elvis")); assertEquals(data, want); } @Test public void testProjectedJoin () { // test a basic join List<Tuple2<Integer,EnumKeyRecord.Type>> jdata = _repo.from(TestRecord.class).join( TestRecord.NAME, EnumKeyRecord.NAME).select(TestRecord.RECORD_ID, EnumKeyRecord.TYPE); assertEquals(20, jdata.size()); } @Test public void testAggregates () { // test computed expressions on the RHS (the casts are just to cope with JUnit's overloads) assertEquals(9, (int)_repo.from(TestRecord.class).load(Funcs.max(TestRecord.RECORD_ID))); assertEquals(10, (int)_repo.from(TestRecord.class).load(Funcs.count(TestRecord.RECORD_ID))); assertEquals(0, (int)_repo.from(TestRecord.class).load(Funcs.min(TestRecord.RECORD_ID))); assertEquals(Tuple2.create(9, 0), _repo.from(TestRecord.class).load( Funcs.max(TestRecord.RECORD_ID), Funcs.min(TestRecord.RECORD_ID))); List<Tuple2<String, Integer>> ewant = Lists.newArrayList(); ewant.add(Tuple2.create("Abraham", 1)); ewant.add(Tuple2.create("Elvis", 2)); ewant.add(Tuple2.create("Moses", 1)); assertEquals(ewant, _repo.from(EnumKeyRecord.class). groupBy(EnumKeyRecord.NAME).ascending(EnumKeyRecord.NAME). select(EnumKeyRecord.NAME, Funcs.count(EnumKeyRecord.TYPE))); } // the HSQL in-memory database persists for the lifetime of the VM, which means we have to // clean up after ourselves in every test; thus we go ahead and share a repository protected TestRepository _repo = createTestRepository(); }
package de.tototec.utils.functional; import static de.tototec.utils.functional.FList.foldLeft; import static de.tototec.utils.functional.FList.mkString; import static org.testng.Assert.assertEquals; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedList; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class FListTest { @DataProvider public Iterator<Object[]> dataFoldLeft() { @SuppressWarnings("serial") class Data extends LinkedList<Object[]> { <T> void data(final T expected, final T left, final F2<T, T, T> function, final T... list) { add(new Object[] { expected, left, function, list }); } } ; final Data data = new Data(); final F2<Integer, Integer, Integer> add = new F2<Integer, Integer, Integer>() { public Integer apply(final Integer p1, final Integer p2) { return p1 + p2; } }; final F2<Integer, Integer, Integer> multiply = new F2<Integer, Integer, Integer>() { public Integer apply(final Integer p1, final Integer p2) { return p1 * p2; } }; data.data(6, 0, add, 1, 2, 3); data.data(6, 1, multiply, 1, 2, 3); return data.iterator(); } @Test(dataProvider = "dataFoldLeft") public <T> void testFoldLeft(final T expected, final T left, final F2<T, T, T> function, final T[] list) { assertEquals(foldLeft(list, left, function), expected); assertEquals(foldLeft(Arrays.asList(list), left, function), expected); } @DataProvider public Iterator<Object[]> dataMkString() { @SuppressWarnings("serial") class Data extends LinkedList<Object[]> { void data(final String expected, final String prefix, final String sep, final String suffix, final Object... elements) { add(new Object[] { expected, null, prefix, sep, suffix, elements }); } void dataConvert(final String expected, final F1<?, String> convert, final String prefix, final String sep, final String suffix, final Object... elements) { add(new Object[] { expected, convert, prefix, sep, suffix, elements }); } } ; final Data data = new Data(); data.data("ABC", null, null, null, "A", "B", "C"); data.data("ABC", null, "", null, "A", "B", "C"); data.data("ABC", "", null, null, "A", "B", "C"); data.data("ABC", null, null, "", "A", "B", "C"); data.data("ABC", "", "", "", "A", "B", "C"); data.data("A,B,C", null, ",", "", "A", "B", "C"); data.data("[A,B,C]", "[", ",", "]", "A", "B", "C"); data.data("[A,B,null]", "[", ",", "]", "A", "B", null); final F1<String, String> convert = new F1<String, String>() { public String apply(final String param) { return param == null ? "" : param; } }; data.dataConvert("[A,B,]", convert, "[", ",", "]", "A", "B", null); return data.iterator(); } @Test(dataProvider = "dataMkString") public <T> void testMkString(final String expected, final F1<T, String> convert, final String prefix, final String sep, final String suffix, final T[] elements) { assertEquals(mkString(Arrays.asList(elements), prefix, sep, suffix, convert), expected); assertEquals(mkString(elements, prefix, sep, suffix, convert), expected); if (convert == null) { assertEquals(mkString(Arrays.asList(elements), prefix, sep, suffix), expected); assertEquals(mkString(elements, prefix, sep, suffix), expected); } } }
package hudson.plugins.git.util; import hudson.model.Api; import hudson.model.Result; import hudson.plugins.git.Branch; import hudson.plugins.git.Revision; import hudson.plugins.git.UserRemoteConfig; import java.util.ArrayList; import java.util.Collection; import java.util.Random; import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import org.eclipse.jgit.lib.ObjectId; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.jvnet.hudson.test.Issue; /** * @author Mark Waite */ public class BuildDataTest { private BuildData data; private final ObjectId sha1 = ObjectId.fromString("929e92e3adaff2e6e1d752a8168c1598890fe84c"); private final String remoteUrl = "https://github.com/jenkinsci/git-plugin"; @Before public void setUp() throws Exception { data = new BuildData(); } @Test public void testGetDisplayName() throws Exception { assertThat(data.getDisplayName(), is("Git Build Data")); } @Test public void testGetDisplayNameEmptyString() throws Exception { String scmName = ""; BuildData dataWithSCM = new BuildData(scmName); assertThat(dataWithSCM.getDisplayName(), is("Git Build Data")); } @Test public void testGetDisplayNameNullSCMName() throws Exception { BuildData dataWithNullSCM = new BuildData(null); assertThat(dataWithNullSCM.getDisplayName(), is("Git Build Data")); } @Test public void testGetDisplayNameWithSCM() throws Exception { final String scmName = "testSCM"; final BuildData dataWithSCM = new BuildData(scmName); assertThat("Git Build Data:" + scmName, is(dataWithSCM.getDisplayName())); } @Test public void testGetIconFileName() { assertThat(data.getIconFileName(), endsWith("/plugin/git/icons/git-32x32.png")); } @Test public void testGetUrlName() { assertThat(data.getUrlName(), is("git")); } @Test public void testGetUrlNameMultipleEntries() { Random random = new Random(); int randomIndex = random.nextInt(1234) + 1; data.setIndex(randomIndex); assertThat(data.getUrlName(), is("git-" + randomIndex)); } @Test public void testHasBeenBuilt() { assertFalse(data.hasBeenBuilt(sha1)); } @Test public void testGetLastBuild() { assertEquals(null, data.getLastBuild(sha1)); } @Test public void testGetLastBuildSingleBranch() { String branchName = "origin/master"; Collection<Branch> branches = new ArrayList<>(); Branch branch = new Branch(branchName, sha1); branches.add(branch); Revision revision = new Revision(sha1, branches); Build build = new Build(revision, 13, Result.FAILURE); data.saveBuild(build); assertThat(data.getLastBuild(sha1), is(build)); ObjectId newSha1 = ObjectId.fromString("31a987bc9fc0b08d1ad297cac8584d5871a21581"); Revision newRevision = new Revision(newSha1, branches); Revision marked = revision; Build newBuild = new Build(marked, newRevision, 17, Result.SUCCESS); data.saveBuild(newBuild); assertThat(data.getLastBuild(newSha1), is(newBuild)); assertThat(data.getLastBuild(sha1), is(newBuild)); ObjectId unbuiltSha1 = ObjectId.fromString("da99ce34121292bc887e91fc0a9d60cf8a701662"); assertThat(data.getLastBuild(unbuiltSha1), is(nullValue())); } @Test public void testGetLastBuildMultipleBranches() { String branchName = "origin/master"; Collection<Branch> branches = new ArrayList<>(); Branch branch = new Branch(branchName, sha1); branches.add(branch); Revision revision = new Revision(sha1, branches); Build build = new Build(revision, 13, Result.FAILURE); data.saveBuild(build); assertThat(data.getLastBuild(sha1), is(build)); ObjectId newSha1 = ObjectId.fromString("31a987bc9fc0b08d1ad297cac8584d5871a21581"); Branch newBranch = new Branch("origin/stable-3.x", newSha1); branches.add(newBranch); Revision newRevision = new Revision(newSha1, branches); Revision marked = revision; Build newBuild = new Build(marked, newRevision, 17, Result.SUCCESS); data.saveBuild(newBuild); assertThat(data.getLastBuild(newSha1), is(newBuild)); assertThat(data.getLastBuild(sha1), is(newBuild)); ObjectId unbuiltSha1 = ObjectId.fromString("da99ce34121292bc887e91fc0a9d60cf8a701662"); assertThat(data.getLastBuild(unbuiltSha1), is(nullValue())); } @Test public void testGetLastBuildWithNullSha1() { assertThat(data.getLastBuild(null), is(nullValue())); String branchName = "origin/master"; Collection<Branch> branches = new ArrayList<>(); Branch branch = new Branch(branchName, sha1); branches.add(branch); Revision revision = new Revision(null, branches); // A revision with a null sha1 (unexpected) Build build = new Build(revision, 29, Result.FAILURE); data.saveBuild(build); assertThat(data.getLastBuild(sha1), is(nullValue())); ObjectId unbuiltSha1 = ObjectId.fromString("da99ce34121292bc887e91fc0a9d60cf8a701662"); assertThat(data.getLastBuild(unbuiltSha1), is(nullValue())); } @Test public void testSaveBuild() { Revision revision = new Revision(sha1); Build build = new Build(revision, 1, Result.SUCCESS); data.saveBuild(build); assertThat(data.getLastBuild(sha1), is(build)); Revision nullRevision = new Revision(null); Build newBuild = new Build(revision, nullRevision, 2, Result.SUCCESS); data.saveBuild(newBuild); assertThat(data.getLastBuild(sha1), is(newBuild)); Build anotherBuild = new Build(nullRevision, revision, 3, Result.SUCCESS); data.saveBuild(anotherBuild); assertThat(data.getLastBuild(sha1), is(anotherBuild)); } @Test public void testGetLastBuildOfBranch() { String branchName = "origin/master"; assertEquals(null, data.getLastBuildOfBranch(branchName)); Collection<Branch> branches = new ArrayList<>(); Branch branch = new Branch(branchName, sha1); branches.add(branch); Revision revision = new Revision(sha1, branches); Build build = new Build(revision, 13, Result.FAILURE); data.saveBuild(build); assertThat(data.getLastBuildOfBranch(branchName), is(build)); } @Test public void testGetLastBuiltRevision() { Revision revision = new Revision(sha1); Build build = new Build(revision, 1, Result.SUCCESS); data.saveBuild(build); assertThat(data.getLastBuiltRevision(), is(revision)); } @Test public void testGetBuildsByBranchName() { assertTrue(data.getBuildsByBranchName().isEmpty()); } @Test public void testGetScmName() { assertThat(data.getScmName(), is("")); } @Test public void testSetScmName() { final String scmName = "Some SCM name"; data.setScmName(scmName); assertThat(data.getScmName(), is(scmName)); } @Test public void testAddRemoteUrl() { data.addRemoteUrl(remoteUrl); assertEquals(1, data.getRemoteUrls().size()); String remoteUrl2 = "https://github.com/jenkinsci/git-plugin.git/"; data.addRemoteUrl(remoteUrl2); assertFalse(data.getRemoteUrls().isEmpty()); assertTrue("Second URL not found in remote URLs", data.getRemoteUrls().contains(remoteUrl2)); assertEquals(2, data.getRemoteUrls().size()); } @Test public void testHasBeenReferenced() { assertFalse(data.hasBeenReferenced(remoteUrl)); data.addRemoteUrl(remoteUrl); assertTrue(data.hasBeenReferenced(remoteUrl)); assertFalse(data.hasBeenReferenced(remoteUrl + "/")); } @Test public void testGetApi() { Api api = data.getApi(); Api apiClone = data.clone().getApi(); assertEquals(api, api); assertEquals(api.getSearchUrl(), apiClone.getSearchUrl()); } @Test public void testToString() { assertEquals(data.toString(), data.clone().toString()); } @Test public void testToStringEmptyBuildData() { BuildData empty = new BuildData(); assertThat(empty.toString(), endsWith("[scmName=<null>,remoteUrls=[],buildsByBranchName={},lastBuild=null]")); } @Test public void testToStringNullSCMBuildData() { BuildData nullSCM = new BuildData(null); assertThat(nullSCM.toString(), endsWith("[scmName=<null>,remoteUrls=[],buildsByBranchName={},lastBuild=null]")); } @Test public void testToStringNonNullSCMBuildData() { BuildData nonNullSCM = new BuildData("gitless"); assertThat(nonNullSCM.toString(), endsWith("[scmName=gitless,remoteUrls=[],buildsByBranchName={},lastBuild=null]")); } @Test public void testEquals() { // Null object not equal non-null BuildData nullData = null; assertFalse("Null object not equal non-null", data.equals(nullData)); // Object should equal itself assertEquals("Object not equal itself", data, data); assertTrue("Object not equal itself", data.equals(data)); assertEquals("Object hashCode not equal itself", data.hashCode(), data.hashCode()); // Cloned object equals original object BuildData data1 = data.clone(); assertEquals("Cloned objects not equal", data1, data); assertTrue("Cloned objects not equal", data1.equals(data)); assertTrue("Cloned objects not equal", data.equals(data1)); assertEquals("Cloned object hashCodes not equal", data.hashCode(), data1.hashCode()); // Saved build makes object unequal Revision revision1 = new Revision(sha1); Build build1 = new Build(revision1, 1, Result.SUCCESS); data1.saveBuild(build1); assertFalse("Distinct objects shouldn't be equal", data.equals(data1)); assertFalse("Distinct objects shouldn't be equal", data1.equals(data)); // Same saved build makes objects equal BuildData data2 = data.clone(); data2.saveBuild(build1); assertTrue("Objects with same saved build not equal", data2.equals(data1)); assertTrue("Objects with same saved build not equal", data1.equals(data2)); assertEquals("Objects with same saved build not equal hashCodes", data2.hashCode(), data1.hashCode()); // Add remote URL makes objects unequal final String remoteUrl2 = "git://github.com/jenkinsci/git-plugin.git"; data1.addRemoteUrl(remoteUrl2); assertFalse("Distinct objects shouldn't be equal", data.equals(data1)); assertFalse("Distinct objects shouldn't be equal", data1.equals(data)); // Add same remote URL makes objects equal data2.addRemoteUrl(remoteUrl2); assertTrue("Objects with same remote URL not equal", data2.equals(data1)); assertTrue("Objects with same remote URL not equal", data1.equals(data2)); assertEquals("Objects with same remote URL not equal hashCodes", data2.hashCode(), data1.hashCode()); // Another saved build still keeps objects equal String branchName = "origin/master"; Collection<Branch> branches = new ArrayList<>(); Branch branch = new Branch(branchName, sha1); branches.add(branch); Revision revision2 = new Revision(sha1, branches); Build build2 = new Build(revision2, 1, Result.FAILURE); assertEquals(build1, build2); // Surprising, since build1 result is SUCCESS, build2 result is FAILURE data1.saveBuild(build2); data2.saveBuild(build2); assertTrue(data1.equals(data2)); assertEquals(data1.hashCode(), data2.hashCode()); // Saving different build results still equal BuildData, // because the different build results are equal data1.saveBuild(build1); data2.saveBuild(build2); assertTrue(data1.equals(data2)); assertEquals(data1.hashCode(), data2.hashCode()); // Set SCM name doesn't change equality or hashCode data1.setScmName("scm 1"); assertTrue(data1.equals(data2)); assertEquals(data1.hashCode(), data2.hashCode()); data2.setScmName("scm 2"); assertTrue(data1.equals(data2)); assertEquals(data1.hashCode(), data2.hashCode()); BuildData emptyData = new BuildData(); emptyData.remoteUrls = null; assertNotEquals("Non-empty object equal empty", data, emptyData); assertNotEquals("Empty object similar to non-empty", emptyData, data); } @Test public void equalsContract() { EqualsVerifier.forClass(BuildData.class) .usingGetClass() .suppress(Warning.NONFINAL_FIELDS) .withIgnoredFields("index", "scmName") .verify(); } @Test public void testSetIndex() { data.setIndex(null); assertEquals(null, data.getIndex()); data.setIndex(-1); assertEquals(null, data.getIndex()); data.setIndex(0); assertEquals(null, data.getIndex()); data.setIndex(13); assertEquals(13, data.getIndex().intValue()); data.setIndex(-1); assertEquals(null, data.getIndex()); } @Test public void testSimilarToHttpsRemoteURL() { final String SIMPLE_URL = "https://github.com/jenkinsci/git-plugin"; BuildData simple = new BuildData("git-" + SIMPLE_URL); simple.addRemoteUrl(SIMPLE_URL); permuteBaseURL(SIMPLE_URL, simple); } @Test public void testSimilarToScpRemoteURL() { final String SIMPLE_URL = "git@github.com:jenkinsci/git-plugin"; BuildData simple = new BuildData("git-" + SIMPLE_URL); simple.addRemoteUrl(SIMPLE_URL); permuteBaseURL(SIMPLE_URL, simple); } @Test public void testSimilarToSshRemoteURL() { final String SIMPLE_URL = "ssh://git@github.com/jenkinsci/git-plugin"; BuildData simple = new BuildData("git-" + SIMPLE_URL); simple.addRemoteUrl(SIMPLE_URL); permuteBaseURL(SIMPLE_URL, simple); } private void permuteBaseURL(String simpleURL, BuildData simple) { final String TRAILING_SLASH_URL = simpleURL + "/"; BuildData trailingSlash = new BuildData("git-" + TRAILING_SLASH_URL); trailingSlash.addRemoteUrl(TRAILING_SLASH_URL); assertTrue("Trailing slash not similar to simple URL " + TRAILING_SLASH_URL, trailingSlash.similarTo(simple)); final String TRAILING_SLASHES_URL = TRAILING_SLASH_URL + " BuildData trailingSlashes = new BuildData("git-" + TRAILING_SLASHES_URL); trailingSlashes.addRemoteUrl(TRAILING_SLASHES_URL); assertTrue("Trailing slashes not similar to simple URL " + TRAILING_SLASHES_URL, trailingSlashes.similarTo(simple)); final String DOT_GIT_URL = simpleURL + ".git"; BuildData dotGit = new BuildData("git-" + DOT_GIT_URL); dotGit.addRemoteUrl(DOT_GIT_URL); assertTrue("Dot git not similar to simple URL " + DOT_GIT_URL, dotGit.similarTo(simple)); final String DOT_GIT_TRAILING_SLASH_URL = DOT_GIT_URL + "/"; BuildData dotGitTrailingSlash = new BuildData("git-" + DOT_GIT_TRAILING_SLASH_URL); dotGitTrailingSlash.addRemoteUrl(DOT_GIT_TRAILING_SLASH_URL); assertTrue("Dot git trailing slash not similar to dot git URL " + DOT_GIT_TRAILING_SLASH_URL, dotGitTrailingSlash.similarTo(dotGit)); final String DOT_GIT_TRAILING_SLASHES_URL = DOT_GIT_TRAILING_SLASH_URL + " BuildData dotGitTrailingSlashes = new BuildData("git-" + DOT_GIT_TRAILING_SLASHES_URL); dotGitTrailingSlashes.addRemoteUrl(DOT_GIT_TRAILING_SLASHES_URL); assertTrue("Dot git trailing slashes not similar to dot git URL " + DOT_GIT_TRAILING_SLASHES_URL, dotGitTrailingSlashes.similarTo(dotGit)); } @Test @Issue("JENKINS-43630") public void testSimilarToContainsNullURL() { final String SIMPLE_URL = "ssh://git@github.com/jenkinsci/git-plugin"; BuildData simple = new BuildData("git-" + SIMPLE_URL); simple.addRemoteUrl(SIMPLE_URL); simple.addRemoteUrl(null); simple.addRemoteUrl(SIMPLE_URL); BuildData simple2 = simple.clone(); assertTrue(simple.similarTo(simple2)); BuildData simple3 = new BuildData("git-" + SIMPLE_URL); simple3.addRemoteUrl(SIMPLE_URL); simple3.addRemoteUrl(null); simple3.addRemoteUrl(SIMPLE_URL); assertTrue(simple.similarTo(simple3)); } @Test public void testGetIndex() { assertEquals(null, data.getIndex()); } @Test public void testGetRemoteUrls() { assertTrue(data.getRemoteUrls().isEmpty()); } @Test public void testClone() { // Tested in testSimilarTo and testEquals } @Test public void testSimilarTo() { data.addRemoteUrl(remoteUrl); // Null object not similar to non-null BuildData dataNull = null; assertFalse("Null object similar to non-null", data.similarTo(dataNull)); BuildData emptyData = new BuildData(); assertFalse("Non-empty object similar to empty", data.similarTo(emptyData)); assertFalse("Empty object similar to non-empty", emptyData.similarTo(data)); emptyData.remoteUrls = null; assertFalse("Non-empty object similar to empty", data.similarTo(emptyData)); assertFalse("Empty object similar to non-empty", emptyData.similarTo(data)); // Object should be similar to itself assertTrue("Object not similar to itself", data.similarTo(data)); // Object should not be similar to constructed variants Collection<UserRemoteConfig> emptyList = new ArrayList<>(); assertFalse("Object similar to data with SCM name", data.similarTo(new BuildData("abc"))); assertFalse("Object similar to data with SCM name & empty", data.similarTo(new BuildData("abc", emptyList))); BuildData dataSCM = new BuildData("scm"); assertFalse("Object similar to data with SCM name", dataSCM.similarTo(data)); assertTrue("Object with SCM name not similar to data with SCM name", dataSCM.similarTo(new BuildData("abc"))); assertTrue("Object with SCM name not similar to data with SCM name & empty", dataSCM.similarTo(new BuildData("abc", emptyList))); // Cloned object equals original object BuildData dataClone = data.clone(); assertTrue("Clone not similar to origin", dataClone.similarTo(data)); assertTrue("Origin not similar to clone", data.similarTo(dataClone)); // Saved build makes objects dissimilar Revision revision1 = new Revision(sha1); Build build1 = new Build(revision1, 1, Result.SUCCESS); dataClone.saveBuild(build1); assertFalse("Unmodified origin similar to modified clone", data.similarTo(dataClone)); assertFalse("Modified clone similar to unmodified origin", dataClone.similarTo(data)); assertTrue("Modified clone not similar to itself", dataClone.similarTo(dataClone)); // Same saved build makes objects similar BuildData data2 = data.clone(); data2.saveBuild(build1); assertFalse("Unmodified origin similar to modified clone", data.similarTo(data2)); assertTrue("Objects with same saved build not similar (1)", data2.similarTo(dataClone)); assertTrue("Objects with same saved build not similar (2)", dataClone.similarTo(data2)); // Add remote URL makes objects dissimilar final String remoteUrl = "git://github.com/jenkinsci/git-client-plugin.git"; dataClone.addRemoteUrl(remoteUrl); assertFalse("Distinct objects shouldn't be similar (1)", data.similarTo(dataClone)); assertFalse("Distinct objects shouldn't be similar (2)", dataClone.similarTo(data)); // Add same remote URL makes objects similar data2.addRemoteUrl(remoteUrl); assertTrue("Objects with same remote URL dissimilar", data2.similarTo(dataClone)); assertTrue("Objects with same remote URL dissimilar", dataClone.similarTo(data2)); // Add different remote URL objects similar final String trailingSlash = "git-client-plugin.git/"; // Unlikely as remote URL dataClone.addRemoteUrl(trailingSlash); assertFalse("Distinct objects shouldn't be similar", data.similarTo(dataClone)); assertFalse("Distinct objects shouldn't be similar", dataClone.similarTo(data)); data2.addRemoteUrl(trailingSlash); assertTrue("Objects with same remote URL dissimilar", data2.similarTo(dataClone)); assertTrue("Objects with same remote URL dissimilar", dataClone.similarTo(data2)); // Add different remote URL objects final String noSlash = "git-client-plugin"; // Unlikely as remote URL dataClone.addRemoteUrl(noSlash); assertFalse("Distinct objects shouldn't be similar", data.similarTo(dataClone)); assertFalse("Distinct objects shouldn't be similar", dataClone.similarTo(data)); data2.addRemoteUrl(noSlash); assertTrue("Objects with same remote URL dissimilar", data2.similarTo(dataClone)); assertTrue("Objects with same remote URL dissimilar", dataClone.similarTo(data2)); // Another saved build still keeps objects similar String branchName = "origin/master"; Collection<Branch> branches = new ArrayList<>(); Branch branch = new Branch(branchName, sha1); branches.add(branch); Revision revision2 = new Revision(sha1, branches); Build build2 = new Build(revision2, 1, Result.FAILURE); dataClone.saveBuild(build2); assertTrue("Another saved build, still similar (1)", dataClone.similarTo(data2)); assertTrue("Another saved build, still similar (2)", data2.similarTo(dataClone)); data2.saveBuild(build2); assertTrue("Another saved build, still similar (3)", dataClone.similarTo(data2)); assertTrue("Another saved build, still similar (4)", data2.similarTo(dataClone)); // Saving different build results still similar BuildData dataClone.saveBuild(build1); assertTrue("Saved build with different results, similar (5)", dataClone.similarTo(data2)); assertTrue("Saved build with different results, similar (6)", data2.similarTo(dataClone)); data2.saveBuild(build2); assertTrue("Saved build with different results, similar (7)", dataClone.similarTo(data2)); assertTrue("Saved build with different results, similar (8)", data2.similarTo(dataClone)); // Set SCM name doesn't change similarity dataClone.setScmName("scm 1"); assertTrue(dataClone.similarTo(data2)); data2.setScmName("scm 2"); assertTrue(dataClone.similarTo(data2)); } @Test public void testHashCode() { // Tested in testEquals } @Test public void testHashCodeEmptyData() { BuildData emptyData = new BuildData(); assertEquals(emptyData.hashCode(), emptyData.hashCode()); emptyData.remoteUrls = null; assertEquals(emptyData.hashCode(), emptyData.hashCode()); } }
package net.imagej.ops.math; import net.imagej.ops.AbstractNamespaceTest; import net.imagej.ops.MathOps.Abs; import net.imagej.ops.MathOps.Add; import net.imagej.ops.MathOps.AddNoise; import net.imagej.ops.MathOps.And; import net.imagej.ops.MathOps.Arccos; import net.imagej.ops.MathOps.Arccosh; import net.imagej.ops.MathOps.Arccot; import net.imagej.ops.MathOps.Arccoth; import net.imagej.ops.MathOps.Arccsc; import net.imagej.ops.MathOps.Arccsch; import net.imagej.ops.MathOps.Arcsec; import net.imagej.ops.MathOps.Arcsech; import net.imagej.ops.MathOps.Arcsin; import net.imagej.ops.MathOps.Arcsinh; import net.imagej.ops.MathOps.Arctan; import net.imagej.ops.MathOps.Arctanh; import net.imagej.ops.MathOps.Ceil; import net.imagej.ops.MathOps.Complement; import net.imagej.ops.MathOps.Copy; import net.imagej.ops.MathOps.Cos; import net.imagej.ops.MathOps.Cosh; import net.imagej.ops.MathOps.Cot; import net.imagej.ops.MathOps.Coth; import net.imagej.ops.MathOps.Csc; import net.imagej.ops.MathOps.Csch; import net.imagej.ops.MathOps.CubeRoot; import net.imagej.ops.MathOps.Divide; import net.imagej.ops.MathOps.Exp; import net.imagej.ops.MathOps.ExpMinusOne; import org.junit.Test; /** * Tests that the ops of the math namespace have corresponding type-safe Java * method signatures declared in the {@link MathNamespace} class. * * @author Curtis Rueden */ public class MathNamespaceTest extends AbstractNamespaceTest { /** Tests for {@link Abs} method convergence. */ @Test public void testAbs() { assertComplete("math", MathNamespace.class, Abs.NAME); } /** Tests for {@link Add} method convergence. */ @Test public void testAdd() { assertComplete("math", MathNamespace.class, Add.NAME); } /** Tests for {@link AddNoise} method convergence. */ @Test public void testAddNoise() { assertComplete("math", MathNamespace.class, AddNoise.NAME); } /** Tests for {@link And} method convergence. */ @Test public void testAnd() { assertComplete("math", MathNamespace.class, And.NAME); } /** Tests for {@link Arccos} method convergence. */ @Test public void testArccos() { assertComplete("math", MathNamespace.class, Arccos.NAME); } /** Tests for {@link Arccosh} method convergence. */ @Test public void testArccosh() { assertComplete("math", MathNamespace.class, Arccosh.NAME); } /** Tests for {@link Arccot} method convergence. */ @Test public void testArccot() { assertComplete("math", MathNamespace.class, Arccot.NAME); } /** Tests for {@link Arccoth} method convergence. */ @Test public void testArccoth() { assertComplete("math", MathNamespace.class, Arccoth.NAME); } /** Tests for {@link Arccsc} method convergence. */ @Test public void testArccsc() { assertComplete("math", MathNamespace.class, Arccsc.NAME); } /** Tests for {@link Arccsch} method convergence. */ @Test public void testArccsch() { assertComplete("math", MathNamespace.class, Arccsch.NAME); } /** Tests for {@link Arcsec} method convergence. */ @Test public void testArcsec() { assertComplete("math", MathNamespace.class, Arcsec.NAME); } /** Tests for {@link Arcsech} method convergence. */ @Test public void testArcsech() { assertComplete("math", MathNamespace.class, Arcsech.NAME); } /** Tests for {@link Arcsin} method convergence. */ @Test public void testArcsin() { assertComplete("math", MathNamespace.class, Arcsin.NAME); } /** Tests for {@link Arcsinh} method convergence. */ @Test public void testArcsinh() { assertComplete("math", MathNamespace.class, Arcsinh.NAME); } /** Tests for {@link Arctan} method convergence. */ @Test public void testArctan() { assertComplete("math", MathNamespace.class, Arctan.NAME); } /** Tests for {@link Arctanh} method convergence. */ @Test public void testArctanh() { assertComplete("math", MathNamespace.class, Arctanh.NAME); } /** Tests for {@link Ceil} method convergence. */ @Test public void testCeil() { assertComplete("math", MathNamespace.class, Ceil.NAME); } /** Tests for {@link Complement} method convergence. */ @Test public void testComplement() { assertComplete("math", MathNamespace.class, Complement.NAME); } /** Tests for {@link Copy} method convergence. */ @Test public void testCopy() { assertComplete("math", MathNamespace.class, Copy.NAME); } /** Tests for {@link Cos} method convergence. */ @Test public void testCos() { assertComplete("math", MathNamespace.class, Cos.NAME); } /** Tests for {@link Cosh} method convergence. */ @Test public void testCosh() { assertComplete("math", MathNamespace.class, Cosh.NAME); } /** Tests for {@link Cot} method convergence. */ @Test public void testCot() { assertComplete("math", MathNamespace.class, Cot.NAME); } /** Tests for {@link Coth} method convergence. */ @Test public void testCoth() { assertComplete("math", MathNamespace.class, Coth.NAME); } /** Tests for {@link Csc} method convergence. */ @Test public void testCsc() { assertComplete("math", MathNamespace.class, Csc.NAME); } /** Tests for {@link Csch} method convergence. */ @Test public void testCsch() { assertComplete("math", MathNamespace.class, Csch.NAME); } /** Tests for {@link CubeRoot} method convergence. */ @Test public void testCubeRoot() { assertComplete("math", MathNamespace.class, CubeRoot.NAME); } /** Tests for {@link Divide} method convergence. */ @Test public void testDivide() { assertComplete("math", MathNamespace.class, Divide.NAME); } /** Tests for {@link Exp} method convergence. */ @Test public void testExp() { assertComplete("math", MathNamespace.class, Exp.NAME); } /** Tests for {@link ExpMinusOne} method convergence. */ @Test public void testExpMinusOne() { assertComplete("math", MathNamespace.class, ExpMinusOne.NAME); } }
package org.animotron.games.tetris; import java.util.LinkedHashMap; import java.util.Map; import javax.xml.stream.XMLStreamException; import org.animotron.ATest; import org.junit.Ignore; import org.junit.Test; /** * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a> * */ public class TetrisTest extends ATest { //players private static final String THE_PLAYER = "<the:player "+ANIMO_NSs+">" + " <have:keyboard/>" + "</the:player>"; private static final String KEY = "key"; private static final String KEY_UP = "key-up"; private static final String KEY_DOWN = "key-down"; private static final String KEY_LEFT = "key-left"; private static final String KEY_RIGHT = "key-right"; private static final String KEY_SPACE = "key-space"; //keyboard private static final String THE_KEYBOARD = "<the:keyboard "+ANIMO_NSs+">" + " <have:key>" + " <an:"+KEY_UP+"/>" + " <an:"+KEY_DOWN+"/>" + " <an:"+KEY_LEFT+"/>" + " <an:"+KEY_RIGHT+"/>" + " <an:"+KEY_SPACE+"/>" + " </have:key>" + "</the:keyboard>"; private static final String[] PLAYER_IDs = {"player1", "player2"}; private static final String[] KEYBOARD_IDs = {"keyboard1", "keyboard2"}; private static void playerAndKeyboard(Map<String, String> map, String payerID, String keyboardID) { map.put(keyboardID+".xml", "<the:"+keyboardID+" "+ANIMO_NSs+">" + " <is:keyboard/>" + "</the:"+keyboardID+">"); map.put(payerID+".xml", "<the:"+payerID+" "+ANIMO_NSs+">" + " <is:player/>" + " <have:keyboard>" + " <an:"+keyboardID+"/>" + " </have:keyboard>" + "</the:"+payerID+">"); } //action private static final String ACTION = "action"; private static final String LEFT = "left"; private static final String RIGHT = "right"; private static final String ROTATE = "rotate"; private static final String SPEED_UP = "speed-up"; private static final String DROP = "drop"; //shapes private static final String SHAPE = "shape"; //tetrominoes (shapes) private static final String TETROMINOES = "tetrominoes"; private static final String I = "I-tetrominoes"; private static final String J = "J-tetrominoes"; private static final String L = "L-tetrominoes"; private static final String O = "O-tetrominoes"; private static final String S = "S-tetrominoes"; private static final String T = "T-tetrominoes"; private static final String Z = "Z-tetrominoes"; //game private static final String GAME = "game"; private static final String TETRIS = "tetris"; private static final String GAME_FIELD = "game-field"; private static final String THE_TETRIS = "<the:tetris "+ANIMO_NSs+">" + //shapes " <have:"+TETROMINOES+">" + " <an:"+I+"/>" + " <an:"+J+"/>" + " <an:"+L+"/>" + " <an:"+O+"/>" + " <an:"+S+"/>" + " <an:"+T+"/>" + " <an:"+Z+"/>" + " </have:"+TETROMINOES+">" + //game field " <have:gamefield>" + " <have:"+TETROMINOES+"/>" + " <have:shape>" + " <the:floor-shape/>" + " </have:shape>" + " <have:speed/>" + " <have:tic>" + " <have:seconds>" + " <get:speed>" + " <any:gamefield/>" + " </get:speed>" + " </have:seconds>" + " <an:down/>" + " </have:tic>" + " </have:gamefield>" + //actions " <have:action>" + " <the:left>" + " <op:enlarge>" + " <get:X>" + " <any:"+TETROMINOES+"/>" + " </get:X>" + " <Q:N-1/>" + " </op:enlarge>" + " </the:left>" + " <the:right>" + " <op:enlarge>" + " <get:X>" + " <any:"+TETROMINOES+"/>" + " </get:X>" + " <Q:N1/>" + " </op:enlarge>" + " </the:right>" + " <the:down>" + " <op:enlarge>" + " <get:Y>" + " <any:"+TETROMINOES+"/>" + " </get:Y>" + " <Q:N1/>" + " </op:enlarge>" + " </the:down>" + " </have:action>" + "</the:tetris>"; //@Test public void game() throws XMLStreamException { if (true) { Map<String, String> data = new LinkedHashMap<String, String>(); //keyboard data.put("keyboard.xml", THE_KEYBOARD); Utils.the(data, KEY); for (String key : new String[] {KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT, KEY_SPACE} ) { Utils.the(data, key, KEY); } //player data.put("player.xml", THE_PLAYER); for (int i = 0; i < 2; i++) { playerAndKeyboard(data, PLAYER_IDs[i], KEYBOARD_IDs[i]); } //game Utils.the(data, GAME); data.put(TETRIS+".xml", THE_TETRIS); Utils.the(data, GAME_FIELD, TETRIS); //action Utils.the(data, ACTION); Utils.the(data, LEFT, ACTION); Utils.the(data, RIGHT, ACTION); Utils.the(data, ROTATE, ACTION); Utils.the(data, SPEED_UP, ACTION); Utils.the(data, DROP, ACTION); //shape Utils.the(data, SHAPE); //tetrominoes Utils.the(data, TETROMINOES); Utils.the(data, I, TETROMINOES); Utils.the(data, J, TETROMINOES); Utils.the(data, L, TETROMINOES); Utils.the(data, O, TETROMINOES); Utils.the(data, S, TETROMINOES); Utils.the(data, T, TETROMINOES); Utils.the(data, Z, TETROMINOES); store(data); } //degrees = random.choice([0,90,180,270]) //BOARD_WIDTH = 10; //BOARD_HEIGHT = 20 //ScoringRows Score // 1 10 // 2 25 // 3 40 // 4 55 // <table border="0"> // <tr><td valign="top"> // <div style="width:240px; height:480px; background-color:Black; padding: 0px; border: solid 1px red; position:relative" id="divBoard"> // <div class="row"></div> // <div class="row"></div> // <div class="row"></div> // <div class="row"></div> // <div class="row"></div> // <div class="row"></div> // <div class="row"></div> // <div class="row"></div> // <div class="row"></div> // <div class="row"></div> // <div class="row"></div> // <div class="row"></div> // <div class="row"></div> // <div class="row"></div> // <div class="row"></div> // <div class="row"></div> // <div class="row"></div> // <div class="row"></div> // <div class="row"></div> // <div class="row"></div> // </div> // <img src="/static/l.png"/> // <img src="/static/j.png"/> // <img src="/static/o.png"/> // <img src="/static/i.png"/> // <img src="/static/t.png"/> // <img src="/static/s.png"/> // <img src="/static/z.png"/> } }
package org.mitre.synthea.export; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.mitre.synthea.helpers.Config; import org.mitre.synthea.helpers.Utilities; import org.mitre.synthea.modules.DeathModule; import org.mitre.synthea.world.agents.Person; import org.mitre.synthea.world.agents.Provider; import org.mitre.synthea.world.concepts.HealthRecord; import org.mitre.synthea.world.concepts.HealthRecord.Encounter; import org.mitre.synthea.world.concepts.HealthRecord.EncounterType; import org.mitre.synthea.world.geography.Location; public class ExporterTest { private long time; private long endTime; private int yearsToKeep; private Person patient; private HealthRecord record; private static final HealthRecord.Code DUMMY_CODE = new HealthRecord.Code("", "", ""); /** * Setup test data. */ @Before public void setup() { Config.set("exporter.split_records", "false"); endTime = time = System.currentTimeMillis(); yearsToKeep = 5; patient = new Person(12345L); Location location = new Location("Massachusetts", null); location.assignPoint(patient, location.randomCityName(patient.random)); Provider.loadProviders(location); record = patient.record; } @Test public void test_export_filter_simple_cutoff() { record.encounterStart(time - years(8), EncounterType.AMBULATORY); record.observation(time - years(8), "height", 64); record.encounterStart(time - years(4), EncounterType.AMBULATORY); record.observation(time - years(4), "weight", 128); // observations should be filtered to the cutoff date Person filtered = Exporter.filterForExport(patient, yearsToKeep, endTime); Encounter encounter = filtered.record.currentEncounter(time); assertEquals(1, encounter.observations.size()); assertEquals("weight", encounter.observations.get(0).type); assertEquals(time - years(4), encounter.observations.get(0).start); assertEquals(128, encounter.observations.get(0).value); } @Test public void test_export_filter_should_keep_old_active_medication() { record.encounterStart(time - years(10), EncounterType.AMBULATORY); record.medicationStart(time - years(10), "fakeitol"); record.encounterStart(time - years(8), EncounterType.AMBULATORY); record.medicationStart(time - years(8), "placebitol"); record.medicationEnd(time - years(6), "placebitol", DUMMY_CODE); Person filtered = Exporter.filterForExport(patient, yearsToKeep, endTime); Encounter encounter = filtered.record.currentEncounter(time); assertEquals(1, encounter.medications.size()); assertEquals("fakeitol", encounter.medications.get(0).type); assertEquals(time - years(10), encounter.medications.get(0).start); } @Test public void test_export_filter_should_keep_medication_that_ended_during_target() { record.encounterStart(time - years(10), EncounterType.AMBULATORY); record.medicationStart(time - years(10), "dimoxinil"); record.medicationEnd(time - years(9), "dimoxinil", DUMMY_CODE); record.encounterStart(time - years(8), EncounterType.AMBULATORY); record.medicationStart(time - years(8), "placebitol"); record.medicationEnd(time - years(4), "placebitol", DUMMY_CODE); Person filtered = Exporter.filterForExport(patient, yearsToKeep, endTime); Encounter encounter = filtered.record.currentEncounter(time); assertEquals(1, encounter.medications.size()); assertEquals("placebitol", encounter.medications.get(0).type); assertEquals(time - years(8), encounter.medications.get(0).start); assertEquals(time - years(4), encounter.medications.get(0).stop); } @Test public void test_export_filter_should_keep_old_active_careplan() { record.encounterStart(time - years(10), EncounterType.AMBULATORY); record.careplanStart(time - years(10), "stop_smoking"); record.careplanEnd(time - years(8), "stop_smoking", DUMMY_CODE); record.encounterStart(time - years(12), EncounterType.AMBULATORY); record.careplanStart(time - years(12), "healthy_diet"); Person filtered = Exporter.filterForExport(patient, yearsToKeep, endTime); Encounter encounter = filtered.record.currentEncounter(time); assertEquals(1, encounter.careplans.size()); assertEquals("healthy_diet", encounter.careplans.get(0).type); assertEquals(time - years(12), encounter.careplans.get(0).start); } @Test public void test_export_filter_should_keep_careplan_that_ended_during_target() { record.encounterStart(time - years(10), EncounterType.AMBULATORY); record.careplanStart(time - years(10), "stop_smoking"); record.careplanEnd(time - years(1), "stop_smoking", DUMMY_CODE); Person filtered = Exporter.filterForExport(patient, yearsToKeep, endTime); Encounter encounter = filtered.record.currentEncounter(time); assertEquals(1, encounter.careplans.size()); assertEquals("stop_smoking", encounter.careplans.get(0).type); assertEquals(time - years(10), encounter.careplans.get(0).start); assertEquals(time - years(1), encounter.careplans.get(0).stop); } @Test public void test_export_filter_should_keep_old_active_conditions() { record.encounterStart(time - years(10), EncounterType.AMBULATORY); record.conditionStart(time - years(10), "fakitis"); record.conditionEnd(time - years(8), "fakitis"); record.encounterStart(time - years(10), EncounterType.AMBULATORY); record.conditionStart(time - years(10), "fakosis"); Person filtered = Exporter.filterForExport(patient, yearsToKeep, endTime); Encounter encounter = filtered.record.currentEncounter(time); assertEquals(1, encounter.conditions.size()); assertEquals("fakosis", encounter.conditions.get(0).type); assertEquals(time - years(10), encounter.conditions.get(0).start); } @Test public void test_export_filter_should_keep_condition_that_ended_during_target() { record.encounterStart(time - years(10), EncounterType.AMBULATORY); record.conditionStart(time - years(10), "boneitis"); record.conditionEnd(time - years(2), "boneitis"); record.encounterStart(time - years(10), EncounterType.AMBULATORY); record.conditionStart(time - years(10), "smallpox"); record.conditionEnd(time - years(9), "smallpox"); Person filtered = Exporter.filterForExport(patient, yearsToKeep, endTime); Encounter encounter = filtered.record.currentEncounter(time); assertEquals(1, encounter.conditions.size()); assertEquals("boneitis", encounter.conditions.get(0).type); assertEquals(time - years(10), encounter.conditions.get(0).start); } @Test public void test_export_filter_should_keep_cause_of_death() { HealthRecord.Code causeOfDeath = new HealthRecord.Code("SNOMED-CT", "Todo-lookup-code", "Rabies"); patient.recordDeath(time - years(20), causeOfDeath, "death"); DeathModule.process(patient, time - years(20)); Person filtered = Exporter.filterForExport(patient, yearsToKeep, endTime); assertEquals(1, filtered.record.encounters.size()); Encounter encounter = filtered.record.encounters.get(0); assertEquals(DeathModule.DEATH_CERTIFICATION, encounter.codes.get(0)); assertEquals(time - years(20), encounter.start); assertEquals(1, encounter.observations.size()); assertEquals(DeathModule.CAUSE_OF_DEATH_CODE.code, encounter.observations.get(0).type); assertEquals(time - years(20), encounter.observations.get(0).start); assertEquals(1, encounter.reports.size()); assertEquals(DeathModule.DEATH_CERTIFICATE.code, encounter.reports.get(0).type); assertEquals(time - years(20), encounter.reports.get(0).start); } @Test public void test_export_filter_should_not_keep_old_stuff() { record.encounterStart(time - years(18), EncounterType.EMERGENCY); record.procedure(time - years(20), "appendectomy"); record.immunization(time - years(12), "flu_shot"); record.observation(time - years(10), "weight", 123); Person filtered = Exporter.filterForExport(patient, yearsToKeep, endTime); assertTrue(filtered.record.encounters.isEmpty()); } @Test public void test_export_filter_should_keep_old_active_stuff() { // create an old encounter with a diagnosis that isn't ended record.encounterStart(time - years(18), EncounterType.EMERGENCY); record.conditionStart(time - years(18), "diabetes"); Person filtered = Exporter.filterForExport(patient, yearsToKeep, endTime); assertEquals(1, filtered.record.encounters.size()); assertEquals(1, filtered.record.encounters.get(0).conditions.size()); assertEquals("diabetes", filtered.record.encounters.get(0).conditions.get(0).type); } @Test public void test_export_filter_should_filter_claim_items() { record.encounterStart(time - years(10), EncounterType.EMERGENCY); record.conditionStart(time - years(10), "something_permanent"); record.procedure(time - years(10), "xray"); assertEquals(1, record.encounters.size()); assertEquals(2, record.encounters.get(0).claim.items.size()); // 1 condition, 1 procedure Person filtered = Exporter.filterForExport(patient, yearsToKeep, endTime); // filter removes the procedure but keeps the open condition assertEquals(1, filtered.record.encounters.size()); assertEquals(1, filtered.record.encounters.get(0).conditions.size()); assertEquals("something_permanent", filtered.record.encounters.get(0).conditions.get(0).type); assertEquals(1, record.encounters.get(0).claim.items.size()); assertEquals("something_permanent", record.encounters.get(0).claim.items.get(0).type); } private static long years(long numYears) { return Utilities.convertTime("years", numYears); } }
package org.osiam.client; import com.github.tomakehurst.wiremock.client.MappingBuilder; import com.github.tomakehurst.wiremock.junit.WireMockRule; import org.codehaus.jackson.map.ObjectMapper; import org.junit.Before; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.osiam.client.exception.NoResultException; import org.osiam.client.exception.UnauthorizedException; import org.osiam.client.oauth.AccessToken; import org.osiam.client.query.Query; import org.osiam.client.query.QueryResult; import org.osiam.resources.scim.*; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.net.URI; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.UUID; import static com.github.tomakehurst.wiremock.client.WireMock.*; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static org.apache.http.HttpStatus.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; public class OsiamUserServiceTest { private static final String URL_BASE = "/osiam-server//Users"; @Rule public WireMockRule wireMockRule = new WireMockRule(9090); // No-args constructor defaults to port 8080 final static private String COUNTRY = "Germany"; final static private String userUuidString = "94bbe688-4b1e-4e4e-80e7-e5ba5c4d6db4"; final static private String INVALID_USER_UUID_STRING = "55bbe688-4b1e-4e4e-80e7-e5ba5c4d"; final static private String endpoint = "http://localhost:9090/osiam-server/"; final static private String SIMPLE_QUERY_STRING = "filter=displayName eq BarbaraJ."; private UUID searchedUUID; private AccessToken accessToken; private AccessTokenMockProvider tokenProvider; private User singleUserResult; private Query query; private QueryResult<User> queryResult; OsiamUserService service; @Before public void setUp() throws Exception { service = new OsiamUserService.Builder(endpoint).build(); tokenProvider = new AccessTokenMockProvider("/__files/valid_accesstoken.json"); // use happy path for default givenAnUserUUID(); givenAnAccessToken(); } @Test public void service_returns_correct_uri() throws Exception { assertEquals(new URI(endpoint + "/Users"), service.getUri()); } @Test public void existing_user_is_returned() throws Exception { givenUUIDcanBeFound(); whenSingleUUIDisLookedUp(); thenReturnedUserHasUUID(searchedUUID); thenMetaDataWasDeserializedCorrectly(); thenAddressIsDeserializedCorrectly(); thenPhoneNumbersAreDeserializedCorrectly(); thenBasicValuesAreDeserializedCorrectly(); } @Test public void user_has_valid_values() throws Exception { givenUUIDcanBeFound(); whenSingleUUIDisLookedUp(); thenReturnedUserMatchesExpectations(); } @Test(expected = IllegalArgumentException.class) public void uuid_is_null_by_getting_single_user_raises_exception() throws Exception { givenUUIDisEmpty(); searchedUUID = null; whenSingleUUIDisLookedUp(); fail("Exception expected"); } @Test(expected = IllegalArgumentException.class) public void accessToken_is_null_by_getting_single_user_raises_exception() throws Exception { givenUUIDisEmpty(); accessToken = null; whenSingleUUIDisLookedUp(); fail("Exception expected"); } @Test(expected = IllegalArgumentException.class) public void accessToken_is_null_by_getting_all_group_raises_exception() throws Exception { givenUUIDisEmpty(); accessToken = null; whenAllUsersAreLookedUp(); fail("Exception expected"); } @Test(expected = IllegalArgumentException.class) public void accessToken_is_null_by_searching_for_group_by_string_raises_exception() throws Exception { givenUUIDisEmpty(); accessToken = null; whenSearchIsUsedByString("meta.version=3"); fail("Exception expected"); } @Test(expected = NoResultException.class) public void user_does_not_exist() throws IOException { givenUUIDcanNotBeFound(); whenSingleUUIDisLookedUp(); fail("Exception expected"); } @Test(expected = UnauthorizedException.class) public void expired_access_token() throws Exception { givenExpiredAccessTokenIsUsedForLookup(); whenSingleUUIDisLookedUp(); fail("Exception expected"); } @Test(expected = UnauthorizedException.class) public void invalid_access_token() throws Exception { givenInvalidAccessTokenIsUsedForLookup(); whenSingleUUIDisLookedUp(); fail("Exception expected"); } @Test(expected = NoResultException.class) public void invalid_UUID_search() throws IOException { givenUUIDisInvalid(); whenSingleUUIDisLookedUp(); fail("Exception expected"); } @Test(expected = NoResultException.class) public void invalid_UUID_is_star() throws IOException { givenUUIDisSpecial("*"); whenSingleUUIDisLookedUp(); fail("Exception expected"); } @Test(expected = NoResultException.class) public void invalid_UUID_is_dot() throws IOException { givenUUIDisSpecial("."); whenSingleUUIDisLookedUp(); fail("Exception expected"); } @Test public void all_users_are_looked_up() { givenAllUsersAreLookedUpSuccessfully(); whenAllUsersAreLookedUp(); thenNumberOfReturnedUsersIs(1); } @Test public void search_for_single_user_is_successful() { givenASingleUserCanBeSearchedByQuery(); whenSearchIsUsedByString(SIMPLE_QUERY_STRING); thenQueryWasValid(); thenNumberOfReturnedUsersIs(1); thenReturnedListOfSearchedUsersIsAsExpected(); } @Test public void query_string_is_split_correctly() { givenAQueryContainingDifficultCharacters(); givenAUserCanBeSearchedByQuery(); whenSearchIsUsedByQuery(); thenQueryStringIsSplitCorrectly(); } @Test @Ignore public void sort_order_is_split_correctly(){ givenAQueryContainingDifficultCharactersAndSortBy(); givenAUserCanBeSearchedByQuery(); whenSearchIsUsedByQuery(); thenSortedQueryStringIsSplitCorrectly(); } private void givenAnAccessToken() throws IOException { this.accessToken = tokenProvider.valid_access_token(); } private void givenAnUserUUID() { this.searchedUUID = UUID.fromString(userUuidString); } private void givenAQueryContainingDifficultCharacters() { query = new Query.Builder(User.class).filter("name.formatted").contains("Schulz & Schulz Industries").build(); } private void givenAQueryContainingDifficultCharactersAndSortBy() { query = new Query.Builder(User.class).filter("name.formatted").contains("Schulz & Schulz Industries").sortBy("userName").build(); } private void givenAUserCanBeSearchedByQuery() { stubFor(get(urlMatching(URL_BASE + "\\?access_token=.+")) .withHeader("Content-Type", equalTo(APPLICATION_JSON)) .willReturn(aResponse() .withStatus(SC_OK) .withHeader("Content-Type", APPLICATION_JSON) .withBodyFile("query_user_by_name.json"))); } private void givenExpiredAccessTokenIsUsedForLookup() { stubFor(givenUUIDisLookedUp(userUuidString, accessToken) .willReturn(aResponse() .withStatus(SC_UNAUTHORIZED))); } private void givenInvalidAccessTokenIsUsedForLookup() { stubFor(givenUUIDisLookedUp(userUuidString, accessToken) .willReturn(aResponse() .withStatus(SC_UNAUTHORIZED))); } private void givenUUIDcanNotBeFound() { stubFor(givenUUIDisLookedUp(userUuidString, accessToken) .willReturn(aResponse() .withStatus(SC_NOT_FOUND))); } private void givenUUIDcanBeFound() { stubFor(givenUUIDisLookedUp(userUuidString, accessToken) .willReturn(aResponse() .withStatus(SC_OK) .withHeader("Content-Type", APPLICATION_JSON) .withBodyFile("user_" + userUuidString + ".json"))); } private void givenUUIDisEmpty() { stubFor(givenUUIDisLookedUp("", accessToken) .willReturn(aResponse() .withStatus(SC_OK) .withHeader("Content-Type", APPLICATION_JSON) .withBodyFile("query_all_users.json"))); } private void givenUUIDisInvalid() { stubFor(givenUUIDisLookedUp(INVALID_USER_UUID_STRING, accessToken) .willReturn(aResponse() .withStatus(SC_NOT_FOUND))); } private void givenUUIDisSpecial(String wildcard) { stubFor(givenUUIDisLookedUp(wildcard, accessToken) .willReturn(aResponse() .withStatus(SC_CONFLICT))); } private MappingBuilder givenUUIDisLookedUp(String uuidString, AccessToken accessToken) { return get(urlEqualTo(URL_BASE + "/" + uuidString)) .withHeader("Content-Type", equalTo(APPLICATION_JSON)) .withHeader("Authorization", equalTo("Bearer " + accessToken.getToken())); } private void givenAllUsersAreLookedUpSuccessfully() { stubFor(get(urlEqualTo(URL_BASE)) .withHeader("Content-Type", equalTo(APPLICATION_JSON)) .withHeader("Authorization", equalTo("Bearer " + accessToken.getToken())) .willReturn(aResponse() .withStatus(SC_OK) .withHeader("Content-Type", APPLICATION_JSON) .withBodyFile("query_all_users.json"))); } private void givenASingleUserCanBeSearchedByQuery() { stubFor(get(urlEqualTo(URL_BASE + "?access_token=" + accessToken.getToken() + "&filter=displayName+eq+BarbaraJ.")) .withHeader("Content-Type", equalTo(APPLICATION_JSON)) .willReturn(aResponse() .withStatus(SC_OK) .withHeader("Content-Type", APPLICATION_JSON) .withBodyFile("query_user_by_name.json"))); } private void whenSingleUUIDisLookedUp() { singleUserResult = service.getUserByUUID(searchedUUID, accessToken); } private void whenAllUsersAreLookedUp() { queryResult = service.getAllUsers(accessToken); } private void whenSearchIsUsedByQuery() { queryResult = service.searchUsers(query, accessToken); } private void whenSearchIsUsedByString(String queryString) { queryResult = service.searchUsers(queryString, accessToken); } private void thenQueryStringIsSplitCorrectly() { verify(getRequestedFor(urlEqualTo(URL_BASE + "?access_token=" + accessToken.getToken() + "&filter=name.formatted+co+%22Schulz+%26+Schulz+Industries%22")) .withHeader("Content-Type", equalTo(APPLICATION_JSON))); } private void thenSortedQueryStringIsSplitCorrectly() { verify(getRequestedFor(urlEqualTo(URL_BASE + "?access_token=" + accessToken.getToken() + "&filter=name.formatted+co+%22Schulz+%26+Schulz+Industries%22&sortBy=userName")) .withHeader("Content-Type", equalTo(APPLICATION_JSON))); } private void thenReturnedUserHasUUID(UUID uuid) { assertEquals(uuid.toString(), singleUserResult.getId()); } private void thenQueryWasValid() { verify(getRequestedFor(urlEqualTo(URL_BASE + "?access_token=" + accessToken.getToken() + "&filter=displayName+eq+BarbaraJ.")) .withHeader("Content-Type", equalTo(APPLICATION_JSON))); } private void thenReturnedListOfSearchedUsersIsAsExpected() { assertEquals(1, queryResult.getTotalResults()); assertEquals("BarbaraJ.", queryResult.getResources().iterator().next().getDisplayName()); } private void thenNumberOfReturnedUsersIs(int numberOfUsers) { assertEquals(numberOfUsers, queryResult.getTotalResults()); assertEquals(numberOfUsers, queryResult.getResources().size()); } private void thenMetaDataWasDeserializedCorrectly() throws ParseException { Meta deserializedMeta = singleUserResult.getMeta(); Date expectedCreated = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2011-08-01 20:29:49"); assertEquals(expectedCreated, deserializedMeta.getCreated()); assertEquals(expectedCreated, deserializedMeta.getLastModified()); assertEquals("https://example.com/v1/Users/2819c223...", deserializedMeta.getLocation()); assertEquals(null, deserializedMeta.getVersion()); assertEquals("User", deserializedMeta.getResourceType()); } public void thenAddressIsDeserializedCorrectly() throws Exception { List<Address> addresses = singleUserResult.getAddresses(); assertEquals(1, addresses.size()); Address address = addresses.get(0); assertEquals("example street 42", address.getStreetAddress()); assertEquals("11111", address.getPostalCode()); assertEquals(COUNTRY, address.getCountry()); assertEquals(COUNTRY, address.getRegion()); assertEquals(COUNTRY, address.getLocality()); } public void thenPhoneNumbersAreDeserializedCorrectly() { List<MultiValuedAttribute> phonenumbers = singleUserResult.getPhoneNumbers(); assertEquals(1, phonenumbers.size()); MultiValuedAttribute phonenumber = phonenumbers.get(0); assertEquals("555-555-8377", phonenumber.getValue().toString()); assertEquals("work", phonenumber.getType()); } public void thenBasicValuesAreDeserializedCorrectly() throws Exception { assertEquals("bjensen", singleUserResult.getExternalId()); assertEquals(null, singleUserResult.isActive()); assertEquals("BarbaraJ.", singleUserResult.getDisplayName()); assertEquals("de", singleUserResult.getLocale()); assertEquals("Barbara", singleUserResult.getNickName()); assertEquals("Dr.", singleUserResult.getTitle()); assertEquals("bjensen", singleUserResult.getUserName()); } private void thenReturnedUserMatchesExpectations() throws Exception { User expectedUser = get_expected_user(); assertEquals(expectedUser.getDisplayName(), singleUserResult.getDisplayName()); assertEqualsMultiValueList(expectedUser.getEmails(), singleUserResult.getEmails()); assertEquals(expectedUser.getExternalId(), singleUserResult.getExternalId()); assertEquals(expectedUser.getLocale(), singleUserResult.getLocale()); assertEqualsName(expectedUser.getName(), singleUserResult.getName()); assertEquals(expectedUser.getNickName(), singleUserResult.getNickName()); assertEquals(expectedUser.getPassword(), singleUserResult.getPassword()); assertEquals(expectedUser.getPhotos(), singleUserResult.getPhotos()); assertEquals(expectedUser.getPreferredLanguage(), singleUserResult.getPreferredLanguage()); assertEquals(expectedUser.getProfileUrl(), singleUserResult.getProfileUrl()); assertEquals(expectedUser.getTimezone(), singleUserResult.getTimezone()); assertEquals(expectedUser.getTitle(), singleUserResult.getTitle()); assertEquals(expectedUser.getUserName(), singleUserResult.getUserName()); assertEquals(expectedUser.getUserType(), singleUserResult.getUserType()); assertEquals(expectedUser.isActive(), singleUserResult.isActive()); } private void assertEqualsMultiValueList(List<MultiValuedAttribute> expected, List<MultiValuedAttribute> actual) { if (expected == null && actual == null) { return; } if (expected.size() != actual.size()) { fail("The expected List has not the same number of values like the actual list"); } for (int count = 0; count < expected.size(); count++) { MultiValuedAttribute expectedAttribute = expected.get(count); MultiValuedAttribute actualAttribute = actual.get(count); assertEquals(expectedAttribute.getValue().toString(), actualAttribute.getValue().toString()); } } private void assertEqualsName(Name expected, Name actual) { if (expected == null && actual == null) { return; } assertEquals(expected.getFamilyName(), actual.getFamilyName()); assertEquals(expected.getGivenName(), actual.getGivenName()); assertEquals(expected.getMiddleName(), actual.getMiddleName()); assertEquals(expected.getHonorificPrefix(), actual.getHonorificPrefix()); assertEquals(expected.getHonorificSuffix(), actual.getHonorificSuffix()); } private User get_expected_user() throws Exception { Reader reader = null; StringBuilder jsonUser = null; User expectedUser; try { reader = new FileReader("src/test/resources/__files/user_" + userUuidString + ".json"); jsonUser = new StringBuilder(); for (int c; (c = reader.read()) != -1; ) jsonUser.append((char) c); } finally { try { reader.close(); } catch (Exception e) { } } expectedUser = new ObjectMapper().readValue(jsonUser.toString(), User.class); return expectedUser; } }
package org.shmztko.model; import java.sql.SQLException; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; public class DatabaseManagerTest { @BeforeClass public static void setUpBeforeClass() throws Exception { } @AfterClass public static void tearDownAfterClass() throws Exception { } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void test() throws SQLException { } }
package picocli; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.contrib.java.lang.system.RestoreSystemProperties; import org.junit.contrib.java.lang.system.SystemErrRule; import org.junit.rules.TestRule; import picocli.CommandLine.ArgGroup; import picocli.CommandLine.Command; import picocli.CommandLine.Model.OptionSpec; import picocli.CommandLine.Option; import picocli.CommandLine.Parameters; import picocli.CommandLine.PropertiesDefaultProvider; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.util.Properties; import static org.junit.Assert.*; public class PropertiesDefaultProviderTest { @Rule public final TestRule restoreSystemProperties = new RestoreSystemProperties(); @Rule public final SystemErrRule systemErrRule = new SystemErrRule().enableLog().muteForSuccessfulTests(); @Command(name = "providertest", subcommands = Subcommand.class, defaultValueProvider = PropertiesDefaultProvider.class) static class MyApp { @Option(names = "--aaa") int aaa; @Option(names = "-b", descriptionKey = "bbb") int bbb; @Parameters(index = "1", paramLabel = "ppp") int ppp; @Parameters(index = "0", paramLabel = "qqq", descriptionKey = "xxx") int xxx; } @Command(name = "providersub", defaultValueProvider = PropertiesDefaultProvider.class) static class Subcommand { @Option(names = "--aaa") int aaa; @Option(names = "-b", descriptionKey = "bbb") int bbb; @Parameters(index = "1", paramLabel = "ppp") int ppp; @Parameters(index = "0", paramLabel = "qqq", descriptionKey = "xxx") int xxx; } @Test public void testLoadFromUserHomeCommandNameByDefault() throws IOException { File f = new File(System.getProperty("user.home"), ".providertest.properties"); if (f.exists()) { f.delete(); } Properties expected = new Properties(); expected.setProperty("aaa", "111"); expected.setProperty("bbb", "222"); expected.setProperty("ppp", "333"); expected.setProperty("xxx", "444"); expected.store(new FileOutputStream(f), "exported from test"); MyApp myApp = new MyApp(); assertEquals(myApp.aaa, 0); assertEquals(myApp.bbb, 0); assertEquals(myApp.ppp, 0); assertEquals(myApp.xxx, 0); new CommandLine(myApp).parseArgs(); f.delete(); assertEquals(myApp.aaa, 111); assertEquals(myApp.bbb, 222); assertEquals(myApp.ppp, 333); assertEquals(myApp.xxx, 444); } @Test public void testLoadFromDifferentLocationIfPropertySpecified() throws IOException { File tempFile = File.createTempFile("providertest", "properties"); System.setProperty("picocli.defaults.providertest.path", tempFile.getAbsolutePath()); if (tempFile.exists()) { tempFile.delete(); } Properties expected = new Properties(); expected.setProperty("aaa", "123"); expected.setProperty("bbb", "234"); expected.setProperty("ppp", "345"); expected.setProperty("xxx", "456"); expected.store(new FileOutputStream(tempFile), "exported from test to specific location"); MyApp myApp = new MyApp(); assertEquals(myApp.aaa, 0); assertEquals(myApp.bbb, 0); assertEquals(myApp.ppp, 0); assertEquals(myApp.xxx, 0); new CommandLine(myApp).parseArgs(); tempFile.delete(); assertEquals(myApp.aaa, 123); assertEquals(myApp.bbb, 234); assertEquals(myApp.ppp, 345); assertEquals(myApp.xxx, 456); } @Test public void testDefaultsForNestedSubcommandsCanBeLoadedFromTheirOwnFile() throws IOException { File parent = new File(System.getProperty("user.home"), ".providertest.properties"); parent.delete(); File f = new File(System.getProperty("user.home"), ".providersub.properties"); if (f.exists()) { f.delete(); } Properties expected = new Properties(); expected.setProperty("aaa", "111"); expected.setProperty("bbb", "222"); expected.setProperty("ppp", "333"); expected.setProperty("xxx", "444"); expected.store(new FileOutputStream(f), "exported from test"); MyApp myApp = new MyApp(); //TestUtil.setTraceLevel("DEBUG"); CommandLine.ParseResult parseResult = new CommandLine(myApp).parseArgs("999", "888", "providersub"); f.delete(); assertEquals(myApp.aaa, 0); assertEquals(myApp.bbb, 0); assertEquals(myApp.ppp, 888); assertEquals(myApp.xxx, 999); Subcommand sub = (Subcommand) parseResult.subcommand().commandSpec().userObject(); assertEquals(sub.aaa, 111); assertEquals(sub.bbb, 222); assertEquals(sub.ppp, 333); assertEquals(sub.xxx, 444); } @Test public void testDefaultsForNestedSubcommandsCanBeLoadedFromParentFile() throws IOException { File parent = new File(System.getProperty("user.home"), ".providertest.properties"); parent.delete(); File f = new File(System.getProperty("user.home"), ".providersub.properties"); if (f.exists()) { f.delete(); } Properties expected = new Properties(); expected.setProperty("providertest.providersub.aaa", "111"); expected.setProperty("providertest.providersub.bbb", "222"); expected.setProperty("providertest.providersub.ppp", "333"); expected.setProperty("providertest.providersub.xxx", "444"); expected.store(new FileOutputStream(parent), "exported from test"); MyApp myApp = new MyApp(); //TestUtil.setTraceLevel("DEBUG"); CommandLine.ParseResult parseResult = null; try { parseResult = new CommandLine(myApp).parseArgs("999", "888", "providersub"); } finally { f.delete(); } assertEquals(myApp.aaa, 0); assertEquals(myApp.bbb, 0); assertEquals(myApp.ppp, 888); assertEquals(myApp.xxx, 999); Subcommand sub = (Subcommand) parseResult.subcommand().commandSpec().userObject(); assertEquals(sub.aaa, 111); assertEquals(sub.bbb, 222); assertEquals(sub.ppp, 333); assertEquals(sub.xxx, 444); } @Command( name="myCommand") static class CommandIssue876 implements Runnable { @Option(names = "-x") int x; @ArgGroup() MyArgGroup anArgGroup; //MyArgGroup anArgGroup = new MyArgGroup(); // this does work! static class MyArgGroup { @Option(names = { "-y" }, descriptionKey= "myOption") int y; } public void run() { System.out.println("Option x is picked up: " + x); System.out.println("Option y inside arg group is not picked up (static class!): " + anArgGroup.y); } } @Ignore @Test public void testArgGroups() throws IOException { File temp = File.createTempFile("MyCommand", ".properties"); FileWriter fw = new FileWriter(temp); fw.write("myCommand.x=6\n" + "myCommand.y=9\n" + "myCommand.myOption=9\n"); fw.flush(); fw.close(); CommandLine cmd = new CommandLine(new CommandIssue876()); cmd.setDefaultValueProvider(new PropertiesDefaultProvider(temp)); cmd.execute(); } @Test(expected = NullPointerException.class) public void testNullFile() { new PropertiesDefaultProvider((File) null); } @Test public void testNonExistingFile() { TestUtil.setTraceLevel("DEBUG"); new PropertiesDefaultProvider(new File("nosuchfile")); assertTrue(systemErrRule.getLog().startsWith("[picocli WARN] defaults configuration file ")); assertTrue(systemErrRule.getLog().endsWith(String.format("nosuchfile does not exist or is not readable%n"))); } @Test public void testEmptyFile() throws Exception { File temp = File.createTempFile("MyCommand", ".properties"); FileWriter fw = new FileWriter(temp); fw.flush(); fw.close(); PropertiesDefaultProvider provider = new PropertiesDefaultProvider(temp); String actual = provider.defaultValue(OptionSpec.builder("-x").build()); assertNull(actual); } @Test public void testExistingFile() throws Exception { File temp = File.createTempFile("MyCommand", ".properties"); FileWriter fw = new FileWriter(temp); fw.write(" fw.flush(); fw.close(); PropertiesDefaultProvider provider = new PropertiesDefaultProvider(temp); String actual = provider.defaultValue(OptionSpec.builder("---").build()); assertEquals("9", actual); } }
package seedu.taskboss.logic; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static seedu.taskboss.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.taskboss.commons.core.Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX; import static seedu.taskboss.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import com.google.common.eventbus.Subscribe; import seedu.taskboss.commons.core.EventsCenter; import seedu.taskboss.commons.events.model.TaskBossChangedEvent; import seedu.taskboss.commons.events.ui.JumpToListRequestEvent; import seedu.taskboss.commons.events.ui.ShowHelpRequestEvent; import seedu.taskboss.commons.exceptions.BuiltInCategoryException; import seedu.taskboss.commons.exceptions.IllegalValueException; import seedu.taskboss.logic.commands.AddCommand; import seedu.taskboss.logic.commands.ClearCommand; import seedu.taskboss.logic.commands.Command; import seedu.taskboss.logic.commands.CommandResult; import seedu.taskboss.logic.commands.ExitCommand; import seedu.taskboss.logic.commands.FindCommand; import seedu.taskboss.logic.commands.HelpCommand; import seedu.taskboss.logic.commands.ListByCategoryCommand; import seedu.taskboss.logic.commands.ViewCommand; import seedu.taskboss.logic.commands.exceptions.CommandException; import seedu.taskboss.logic.commands.exceptions.InvalidDatesException; import seedu.taskboss.logic.parser.DateTimeParser; import seedu.taskboss.model.Model; import seedu.taskboss.model.ModelManager; import seedu.taskboss.model.ReadOnlyTaskBoss; import seedu.taskboss.model.TaskBoss; import seedu.taskboss.model.category.Category; import seedu.taskboss.model.category.UniqueCategoryList; import seedu.taskboss.model.task.DateTime; import seedu.taskboss.model.task.Information; import seedu.taskboss.model.task.Name; import seedu.taskboss.model.task.PriorityLevel; import seedu.taskboss.model.task.ReadOnlyTask; import seedu.taskboss.model.task.Recurrence; import seedu.taskboss.model.task.Recurrence.Frequency; import seedu.taskboss.model.task.Task; import seedu.taskboss.storage.StorageManager; public class LogicManagerTest { @Rule public TemporaryFolder saveFolder = new TemporaryFolder(); private Model model; private Logic logic; // These are for checking the correctness of the events raised private ReadOnlyTaskBoss latestSavedTaskBoss; private boolean helpShown; private int targetedJumpIndex; @Subscribe private void handleLocalModelChangedEvent(TaskBossChangedEvent abce) throws IllegalValueException { latestSavedTaskBoss = new TaskBoss(abce.data); } @Subscribe private void handleShowHelpRequestEvent(ShowHelpRequestEvent she) { helpShown = true; } @Subscribe private void handleJumpToListRequestEvent(JumpToListRequestEvent je) { targetedJumpIndex = je.targetIndex; } @Before public void setUp() throws IllegalValueException { model = new ModelManager(); String tempTaskBossFile = saveFolder.getRoot().getPath() + "TempTaskBoss.xml"; String tempPreferencesFile = saveFolder.getRoot().getPath() + "TempPreferences.json"; logic = new LogicManager(model, new StorageManager(tempTaskBossFile, tempPreferencesFile)); EventsCenter.getInstance().registerHandler(this); latestSavedTaskBoss = new TaskBoss(model.getTaskBoss()); // last saved // assumed to be up to date helpShown = false; targetedJumpIndex = -1; // non yet } @After public void tearDown() { EventsCenter.clearSubscribers(); } @Test public void execute_invalid() throws IllegalValueException, InvalidDatesException, BuiltInCategoryException { String invalidCommand = " "; assertCommandFailure(invalidCommand, String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE)); } private void assertCommandSuccess(String inputCommand, String expectedMessage, ReadOnlyTaskBoss expectedTaskBoss, List<? extends ReadOnlyTask> expectedShownList) throws IllegalValueException, InvalidDatesException, BuiltInCategoryException { assertCommandBehavior(false, inputCommand, expectedMessage, expectedTaskBoss, expectedShownList); } private void assertCommandFailure(String inputCommand, String expectedMessage) throws IllegalValueException, InvalidDatesException, BuiltInCategoryException { TaskBoss expectedTaskBoss = new TaskBoss(model.getTaskBoss()); List<ReadOnlyTask> expectedShownList = new ArrayList<>(model.getFilteredTaskList()); assertCommandBehavior(true, inputCommand, expectedMessage, expectedTaskBoss, expectedShownList); } private void assertCommandBehavior(boolean isCommandExceptionExpected, String inputCommand, String expectedMessage, ReadOnlyTaskBoss expectedTaskBoss, List<? extends ReadOnlyTask> expectedShownList) throws IllegalValueException, InvalidDatesException, BuiltInCategoryException { try { CommandResult result = logic.execute(inputCommand); assertFalse("CommandException expected but was not thrown.", isCommandExceptionExpected); assertEquals(expectedMessage, result.feedbackToUser); } catch (CommandException e) { assertTrue("CommandException not expected but was thrown.", isCommandExceptionExpected); assertEquals(expectedMessage, e.getMessage()); } // Confirm the ui display elements should contain the right data assertEquals(expectedShownList, model.getFilteredTaskList()); // Confirm the state of data (saved and in-memory) is as expected assertEquals(expectedTaskBoss, model.getTaskBoss()); assertEquals(expectedTaskBoss, latestSavedTaskBoss); } @Test public void execute_unknownCommandWord() throws IllegalValueException, InvalidDatesException, BuiltInCategoryException { String unknownCommand = "uicfhmowqewca"; assertCommandFailure(unknownCommand, MESSAGE_UNKNOWN_COMMAND); } @Test public void execute_help() throws IllegalValueException, InvalidDatesException, BuiltInCategoryException { assertCommandSuccess("help", HelpCommand.SHOWING_HELP_MESSAGE, new TaskBoss(), Collections.emptyList()); assertTrue(helpShown); } @Test public void execute_helpShortCommand() throws IllegalValueException, InvalidDatesException, BuiltInCategoryException { assertCommandSuccess("h", HelpCommand.SHOWING_HELP_MESSAGE, new TaskBoss(), Collections.emptyList()); assertTrue(helpShown); } @Test public void execute_exit() throws IllegalValueException, InvalidDatesException, BuiltInCategoryException { assertCommandSuccess("exit", ExitCommand.MESSAGE_EXIT_ACKNOWLEDGEMENT, new TaskBoss(), Collections.emptyList()); } @Test public void execute_exitShortCommand() throws IllegalValueException, InvalidDatesException, BuiltInCategoryException { assertCommandSuccess("x", ExitCommand.MESSAGE_EXIT_ACKNOWLEDGEMENT, new TaskBoss(), Collections.emptyList()); } @Test public void execute_clear() throws Exception { TestDataHelper helper = new TestDataHelper(); model.addTask(helper.generateTask(1)); model.addTask(helper.generateTask(2)); model.addTask(helper.generateTask(3)); assertCommandSuccess("clear", ClearCommand.MESSAGE_SUCCESS, new TaskBoss(), Collections.emptyList()); } @Test public void execute_add_invalidTaskData() throws IllegalValueException, InvalidDatesException, BuiltInCategoryException { //invalid empty task name assertCommandFailure("add sd/today ed/tomorrow " + "i/valid, information c/valid", Name.MESSAGE_NAME_CONSTRAINTS); //invalid name which longer than 45 characters assertCommandFailure("add longggggggggggggggggggggggggggggggggggTaskName sd/today ed/tomorrow " + "i/valid, information c/valid", Name.MESSAGE_NAME_CONSTRAINTS); assertCommandFailure("add Valid Name! sd/today ed/tomorrow " + "i/valid, information c/invalid_-[.category", Category.MESSAGE_CATEGORY_CONSTRAINTS); assertCommandFailure("add Valid Name sd/today to next week ed/tomorrow i/valid, information", DateTimeParser.getMultipleDatesError()); assertCommandFailure("add Valid Name sd/invalid date ed/tomorrow i/valid, information", DateTime.MESSAGE_DATE_CONSTRAINTS); assertCommandFailure("add n/Valid Name sd/today ed/invalid i/valid, information", DateTime.MESSAGE_DATE_CONSTRAINTS); assertCommandFailure("add n/Valid Name sd/tomorrow ed/next friday i/valid info r/invalid recurrence", Recurrence.MESSAGE_RECURRENCE_CONSTRAINTS); assertCommandFailure("add n/Valid Name r/weekly monthly", Recurrence.MESSAGE_RECURRENCE_CONSTRAINTS); } @Test public void execute_add_successful() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); Task toBeAdded = helper.adam(); TaskBoss expectedAB = new TaskBoss(); expectedAB.addTask(toBeAdded); // execute command and verify result assertCommandSuccess(helper.generateAddCommand(toBeAdded), String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded), expectedAB, expectedAB.getTaskList()); } @Test public void execute_addDuplicate_notAllowed() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); Task toBeAdded = helper.adam(); // setup starting state model.addTask(toBeAdded); // task already in internal TaskBoss // execute command and verify result assertCommandFailure(helper.generateAddCommand(toBeAdded), AddCommand.MESSAGE_DUPLICATE_TASK); } @Test public void execute_list_showsAllTasks() throws Exception { // prepare expectations TestDataHelper helper = new TestDataHelper(); TaskBoss expectedTB = helper.generateTaskBoss(2); List<? extends ReadOnlyTask> expectedList = expectedTB.getTaskList(); // prepare TaskBoss state helper.addToModel(model, 2); assertCommandSuccess("list", String.format(ListByCategoryCommand.MESSAGE_SUCCESS, new Category("Alltasks")), expectedTB, expectedList); } @Test public void execute_listShortCommand_showsAllTasks() throws Exception { // prepare expectations TestDataHelper helper = new TestDataHelper(); TaskBoss expectedTB = helper.generateTaskBoss(2); List<? extends ReadOnlyTask> expectedList = expectedTB.getTaskList(); // prepare TaskBoss state helper.addToModel(model, 2); assertCommandSuccess("l", String.format(ListByCategoryCommand.MESSAGE_SUCCESS, new Category("Alltasks")), expectedTB, expectedList); } /** * Confirms the 'invalid argument index number behaviour' for the given * command targeting a single task in the shown list, using visible index. * * @param commandWord to test assuming it targets a single task in the last shown * list based on visible index. */ private void assertIncorrectIndexFormatBehaviorForCommand(String commandWord, String expectedMessage) throws Exception { assertCommandFailure(commandWord, expectedMessage); // index missing assertCommandFailure(commandWord + " +1", expectedMessage); // index should be unsigned assertCommandFailure(commandWord + " -1", expectedMessage); // index should be unsigned assertCommandFailure(commandWord + " 0", expectedMessage); assertCommandFailure(commandWord + " not_a_number", expectedMessage); } /** * Confirms the 'invalid argument index number behaviour' for the given * command targeting a single task in the shown list, using visible index. * * @param commandWord * to test assuming it targets a single task in the last shown * list based on visible index. */ private void assertIndexNotFoundBehaviorForCommand(String commandWord) throws Exception { String expectedMessage = MESSAGE_INVALID_TASK_DISPLAYED_INDEX; TestDataHelper helper = new TestDataHelper(); List<Task> taskList = helper.generateTaskList(2); // set AB state to 2 tasks model.resetData(new TaskBoss()); for (Task p : taskList) { model.addTask(p); } assertCommandFailure(commandWord + " 3", expectedMessage); } @Test public void execute_viewInvalidArgsFormat_errorMessageShown() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, ViewCommand.MESSAGE_USAGE); assertIncorrectIndexFormatBehaviorForCommand("view", expectedMessage); } @Test public void execute_viewIndexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("view"); } @Test public void execute_view_jumpsToCorrectTask() throws Exception { TestDataHelper helper = new TestDataHelper(); List<Task> threeTasks = helper.generateTaskList(3); TaskBoss expectedAB = helper.generateTaskBoss(threeTasks); helper.addToModel(model, threeTasks); assertCommandSuccess("view 2", String.format(ViewCommand.MESSAGE_VIEW_TASK_SUCCESS, 2), expectedAB, expectedAB.getTaskList()); assertEquals(1, targetedJumpIndex); assertEquals(model.getFilteredTaskList().get(1), threeTasks.get(1)); } @Test public void execute_deleteIndexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("delete"); } @Test public void execute_find_invalidArgsFormat() throws IllegalValueException, InvalidDatesException, BuiltInCategoryException { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE); assertCommandFailure("find ", expectedMessage); } /* * Valid equivalence partitions: * - Find the tasks only when full words in name or information match the keywords * - Is not case sensitive * - Find the tasks when any of the keywords match the name * The three test cases below test valid input as a name. */ @Test public void execute_findKeyword_onlyMatchesFullWordsInNames() throws Exception { TestDataHelper helper = new TestDataHelper(); Task pTarget1 = helper.generateTaskWithName("bla bla KEY bla"); Task pTarget2 = helper.generateTaskWithName("bla KEY bla bceofeia"); Task p1 = helper.generateTaskWithName("KE Y"); Task p2 = helper.generateTaskWithName("KEYKEYKEY sduauo"); List<Task> fourTasks = helper.generateTaskList(p1, pTarget1, p2, pTarget2); TaskBoss expectedAB = helper.generateTaskBoss(fourTasks); List<Task> expectedList = helper.generateTaskList(pTarget1, pTarget2); helper.addToModel(model, fourTasks); assertCommandSuccess("find KEY", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); } @Test public void execute_findKeyword_isNotCaseSensitive() throws Exception { TestDataHelper helper = new TestDataHelper(); Task p1 = helper.generateTaskWithName("bla bla KEY bla"); Task p2 = helper.generateTaskWithName("bla KEY bla bceofeia"); Task p3 = helper.generateTaskWithName("key key"); Task p4 = helper.generateTaskWithName("KEy sduauo"); List<Task> fourTasks = helper.generateTaskList(p3, p1, p4, p2); TaskBoss expectedAB = helper.generateTaskBoss(fourTasks); List<Task> expectedList = fourTasks; helper.addToModel(model, fourTasks); assertCommandSuccess("find KEY", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); } @Test public void execute_findKeyword_matchesIfAnyKeywordPresent() throws Exception { TestDataHelper helper = new TestDataHelper(); Task pTarget1 = helper.generateTaskWithName("bla bla KEY bla"); Task pTarget2 = helper.generateTaskWithName("bla rAnDoM bla bceofeia"); Task pTarget3 = helper.generateTaskWithName("key key"); Task p1 = helper.generateTaskWithName("sduauo"); List<Task> fourTasks = helper.generateTaskList(pTarget1, p1, pTarget2, pTarget3); TaskBoss expectedAB = helper.generateTaskBoss(fourTasks); List<Task> expectedList = helper.generateTaskList(pTarget1, pTarget2, pTarget3); helper.addToModel(model, fourTasks); assertCommandSuccess("find key rAnDoM", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); } /* * Valid equivalence partitions: * - Find the tasks only when the keywords present in order * - Do not need match full words * The two test cases below test valid input as datetime. */ //@@author A0147990R @Test public void execute_findStartDatetime_matchesOnlyIfKeywordPresentInOrder() throws Exception { TestDataHelper helper = new TestDataHelper(); Task pTarget1 = helper.generateTaskWithStartDateTime("Monday, 13 March, 2017"); Task p1 = helper.generateTaskWithStartDateTime("16 March, 2017"); Task p2 = helper.generateTaskWithStartDateTime("Monday, 1 May, 2017"); Task p3 = helper.generateTaskWithStartDateTime("2 July, 2017"); List<Task> fourTasks = helper.generateTaskList(pTarget1, p1, p2, p3); TaskBoss expectedTB = helper.generateTaskBoss(fourTasks); List<Task> expectedList = helper.generateTaskList(pTarget1, p1); helper.addToModel(model, fourTasks); assertCommandSuccess("find sd/Mar", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedTB, expectedList); } //@@author A0147990R @Test public void execute_findEndDatetime_matchesOnlyIfKeywordPresentInOrder() throws Exception { TestDataHelper helper = new TestDataHelper(); Task pTarget1 = helper.generateTaskWithEndDateTime("Monday, 13 March, 2017"); Task p1 = helper.generateTaskWithEndDateTime("16 March, 2017"); Task p2 = helper.generateTaskWithEndDateTime("Monday, 1 May, 2017"); Task p3 = helper.generateTaskWithEndDateTime("2 July, 2017"); List<Task> fourTasks = helper.generateTaskList(pTarget1, p1, p2, p3); TaskBoss expectedAB = helper.generateTaskBoss(fourTasks); List<Task> expectedList = helper.generateTaskList(pTarget1, p1); helper.addToModel(model, fourTasks); assertCommandSuccess("find ed/Mar", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); } /** * A utility class to generate test data. */ class TestDataHelper { Task adam() throws Exception { Name name = new Name("Adam Brown"); PriorityLevel priorityLevel = new PriorityLevel("Yes"); DateTime startDateTime = new DateTime("today 5pm"); DateTime endDateTime = new DateTime("tomorrow 8pm"); Information information = new Information("111, alpha street"); Recurrence recurrence = new Recurrence(Frequency.NONE); Category category1 = new Category("Category1"); Category category2 = new Category("Longercategory2"); UniqueCategoryList categories = new UniqueCategoryList(category2, new Category("Alltasks"), category1); return new Task(name, priorityLevel, startDateTime, endDateTime, information, recurrence, categories); } /** * Generates a valid task using the given seed. Running this function * with the same parameter values guarantees the returned task will have * the same state. Each unique seed will generate a unique Task object. * * @param seed * used to generate the task data field values */ Task generateTask(int seed) throws Exception { return new Task( new Name("Task " + seed), new PriorityLevel("Yes"), new DateTime("Feb 19 10am 2017"), new DateTime("Feb 20 10am 2017"), new Information("House of " + seed), new Recurrence(Frequency.NONE), new UniqueCategoryList(new Category("Alltasks")) ); } private String generateAddCommand(Task p) throws IllegalValueException { StringBuffer cmd = new StringBuffer(); cmd.append("add "); //@@author A0144904H cmd.append(p.getName().toString()); cmd.append(" p/").append(p.getPriorityLevel().input); cmd.append(" sd/").append(p.getStartDateTime().toString()); cmd.append(" ed/").append(p.getEndDateTime().toString()); cmd.append(" i/").append(p.getInformation()); cmd.append(" r/").append(p.getRecurrence().toString()); UniqueCategoryList categories = p.getCategories(); for (Category t : categories) { cmd.append(" c/").append(t.categoryName); } return cmd.toString(); } /** * Generates an TaskBoss with auto-generated tasks. */ TaskBoss generateTaskBoss(int numGenerated) throws Exception { TaskBoss taskBoss = new TaskBoss(); addToTaskBoss(taskBoss, numGenerated); return taskBoss; } /** * Generates TaskBoss based on the list of Tasks given. */ TaskBoss generateTaskBoss(List<Task> tasks) throws Exception { TaskBoss taskBoss = new TaskBoss(); addToTaskBoss(taskBoss, tasks); return taskBoss; } /** * Adds auto-generated Task objects to the given TaskBoss * * @param taskBoss * The TaskBoss to which the Tasks will be added */ void addToTaskBoss(TaskBoss taskBoss, int numGenerated) throws Exception { addToTaskBoss(taskBoss, generateTaskList(numGenerated)); } /** * Adds the given list of Tasks to the given TaskBoss */ void addToTaskBoss(TaskBoss taskBoss, List<Task> tasksToAdd) throws Exception { for (Task t : tasksToAdd) { taskBoss.addTask(t); } } /** * Adds auto-generated Task objects to the given model * * @param model * The model to which the Tasks will be added */ void addToModel(Model model, int numGenerated) throws Exception { addToModel(model, generateTaskList(numGenerated)); } /** * Adds the given list of Tasks to the given model */ void addToModel(Model model, List<Task> tasksToAdd) throws Exception { for (Task t : tasksToAdd) { model.addTask(t); } } /** * Generates a list of Tasks based on the flags. */ List<Task> generateTaskList(int numGenerated) throws Exception { List<Task> tasks = new ArrayList<>(); for (int i = 1; i <= numGenerated; i++) { tasks.add(generateTask(i)); } return tasks; } List<Task> generateTaskList(Task... tasks) { return Arrays.asList(tasks); } /** * Generates a Task object with given name. Other fields will have some * dummy values. */ Task generateTaskWithName(String name) throws Exception { return new Task( new Name(name), new PriorityLevel("Yes"), new DateTime("Feb 19 10am 2017"), new DateTime("Feb 20 10am 2017"), new Information("House of 1"), new Recurrence(Frequency.NONE), new UniqueCategoryList(new Category("category")) ); } //@@author A0147990R /** * Generates a Task object with given startDatetime. Other fields will have some * dummy values. */ Task generateTaskWithStartDateTime(String startDatetime) throws Exception { return new Task( new Name("testTask"), new PriorityLevel("Yes"), new DateTime(startDatetime), new DateTime("Feb 20 10am 2018"), new Information("House of 1"), new Recurrence(Frequency.NONE), new UniqueCategoryList(new Category("category")) ); } /** * Generates a Task object with given endDatetime. Other fields will have some * dummy values. */ Task generateTaskWithEndDateTime(String endDatetime) throws Exception { return new Task( new Name("testTask"), new PriorityLevel("Yes"), new DateTime("Feb 20 10am 2017"), new DateTime(endDatetime), new Information("House of 1"), new Recurrence(Frequency.NONE), new UniqueCategoryList(new Category("category")) ); } } }
package org.jdesktop.swingx; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.net.MalformedURLException; import java.net.URL; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.Box; import javax.swing.DefaultListModel; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ListModel; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import org.jdesktop.swingx.action.LinkAction; import org.jdesktop.swingx.action.LinkModelAction; import org.jdesktop.swingx.decorator.HighlighterFactory; import org.jdesktop.swingx.decorator.SortOrder; import org.jdesktop.swingx.renderer.DefaultListRenderer; import org.jdesktop.swingx.renderer.DefaultTableRenderer; import org.jdesktop.swingx.renderer.DefaultTreeRenderer; import org.jdesktop.swingx.renderer.HyperlinkProvider; import org.jdesktop.swingx.treetable.FileSystemModel; /** * Test of JXHyperlink visuals. Raw usage and as hyperlinkRenderer. * <p> * * @author Jeanette Winzenburg */ public class JXHyperlinkVisualCheck extends InteractiveTestCase { private static final Logger LOG = Logger.getLogger(JXHyperlinkVisualCheck.class .getName()); public JXHyperlinkVisualCheck() { super("JXHyperlinkLabel Test"); } public static void main(String[] args) throws Exception { // setSystemLF(true); JXHyperlinkVisualCheck test = new JXHyperlinkVisualCheck(); try { // test.runInteractiveTests(); test.runInteractiveTests("interactive.*Table.*"); // test.runInteractiveTests("interactive.*List.*"); // test.runInteractiveTests("interactive.*Tree.*"); test.runInteractiveTests("interactive.*Underline.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * Issue #441-swingx: underline not showing for html text. * While text wrapping as such is working with html text the * underline is only under the last line. */ public void interactiveHtmlUnderlineWrapping() { Action action = new AbstractAction("<html><b><i>Bold Italic Link and another loong way way out part of the text</i></b></html>") { public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub } }; JXHyperlink hyperlink = new JXHyperlink(action ); JFrame frame = wrapInFrame(hyperlink, "show html underline "); frame.setSize(200, 200); frame.setVisible(true); } /** * Issue #441-swingx: underline not showing for html text. * */ public void interactiveHtmlUnderlineButton() { Action action = new AbstractAction("<html><b><i>Bold Italic Link</i></b></html>") { public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub } }; JXHyperlink hyperlink = new JXHyperlink(action ); JFrame frame = wrapInFrame(hyperlink, "show html underline "); frame.setSize(200, 200); frame.setVisible(true); } /** * visually check how differently configured buttons behave on * clicked. * */ public void interactiveCompareClicked() { JComponent box = Box.createVerticalBox(); JXHyperlink noActionHyperlink = new JXHyperlink(); noActionHyperlink.setText("have no action - auto-click"); box.add(noActionHyperlink); LinkAction doNothingAction = createEmptyLinkAction("have do nothing action - follow action"); JXHyperlink doNothingActionHyperlink = new JXHyperlink(doNothingAction); box.add(doNothingActionHyperlink); LinkAction doNothingAction2 = createEmptyLinkAction("have do nothing action - overrule"); JXHyperlink overruleActionHyperlink = new JXHyperlink(doNothingAction2); overruleActionHyperlink.setOverrulesActionOnClick(true); box.add(overruleActionHyperlink); JXFrame frame = wrapInFrame(box, "compare clicked control"); frame.setVisible(true); } public void interactiveUnderlineButton() { Action action = new AbstractAction("LinkModel@somewhere") { public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub } }; JXHyperlink hyperlink = new JXHyperlink(action ); JFrame frame = wrapInFrame(hyperlink, "show underline - no link action"); frame.setSize(200, 200); frame.setVisible(true); } public void interactiveLink() throws Exception { EditorPaneLinkVisitor visitor = new EditorPaneLinkVisitor(); LinkModel link = new LinkModel("Click me!", null, JXEditorPaneTest.class.getResource("resources/test.html")); LinkModelAction linkAction = new LinkModelAction<LinkModel>(link, visitor); // linkAction.setVisitingDelegate(visitor); JXHyperlink hyperlink = new JXHyperlink(linkAction); JPanel panel = new JPanel(new BorderLayout()); panel.add(new JScrollPane(visitor.getOutputComponent())); panel.add(hyperlink, BorderLayout.SOUTH); JFrame frame = wrapInFrame(panel, "simple hyperlink"); frame.setSize(200, 200); frame.setVisible(true); } public void interactiveTreeLinkRendererSimpleText() { LinkAction simpleAction = new LinkAction<Object>(null) { public void actionPerformed(ActionEvent e) { LOG.info("hit: " + getTarget()); } }; JXTree tree = new JXTree(new FileSystemModel()); tree.setRolloverEnabled(true); HyperlinkProvider provider = new HyperlinkProvider(simpleAction); tree.setCellRenderer(new DefaultTreeRenderer(provider)); // tree.setCellRenderer(new LinkRenderer(simpleAction)); tree.setHighlighters(HighlighterFactory.createSimpleStriping()); JFrame frame = wrapWithScrollingInFrame(tree, "tree and simple links"); frame.setVisible(true); } /** * Table url activation, disabled tooltips. */ public void interactiveTableHyperlinkNoTooltip() { JXTable table = new JXTable(createModelWithLinks()); EditorPaneLinkVisitor visitor = new EditorPaneLinkVisitor(); LinkModelAction action = new LinkModelAction<LinkModel>(visitor) { @Override protected void updateFromTarget() { super.updateFromTarget(); putValue(Action.SHORT_DESCRIPTION, null); } }; // set the default renderer for LinkModel - which is basically // a bean wrapped around an URL table.setDefaultRenderer(LinkModel.class, new DefaultTableRenderer (new HyperlinkProvider(action, LinkModel.class))); JXFrame frame = wrapWithScrollingInFrame(table, visitor.getOutputComponent(), "table and simple links"); frame.setVisible(true); } /** * Table with both simple "hyperlinks" targets and url activation. */ public void interactiveTableHyperlinkSimpleText() { JXTable table = new JXTable(createModelWithLinks()); EditorPaneLinkVisitor visitor = new EditorPaneLinkVisitor(); LinkModelAction action = new LinkModelAction<LinkModel>(visitor); // set the default renderer for LinkModel - which is basically // a bean wrapped around an URL table.setDefaultRenderer(LinkModel.class, new DefaultTableRenderer (new HyperlinkProvider(action, LinkModel.class))); // JW: editor mis-use is not recommended but possible... // the LinkRenderer in its role as editor is not yet deprecated but should // soon. Without registering a specialized editor the column should // not editable - otherwise the "normal" default editor would jump in // LinkModelAction action2 = new LinkModelAction<LinkModel>(visitor); // table.setDefaultEditor(LinkModel.class, new LinkRenderer(action2, LinkModel.class)); // simple activatable action on the target in the first column LinkAction simpleAction = new LinkAction<Object>(null) { public void actionPerformed(ActionEvent e) { LOG.info("hit: " + getTarget()); } }; // the action will be activated only if the column is not-editable // here that's done in the model // TODO JW: revisit table.getColumn(0).setCellRenderer(new DefaultTableRenderer( new HyperlinkProvider(simpleAction))); JXFrame frame = wrapWithScrollingInFrame(table, visitor.getOutputComponent(), "table and simple links"); frame.setVisible(true); } /** * Check visuals of hyperlink and highlighter. * Issue #513-swingx: no rollover effect for disabled table. * Hyperlink is disabled automatically by DefaultVisuals, no need * to disable the xxRolloverController. * */ public void interactiveTableHyperlinkLFStripingHighlighter() { EditorPaneLinkVisitor visitor = new EditorPaneLinkVisitor(); final JXTable table = new JXTable(createModelWithLinks()); LinkModelAction action = new LinkModelAction(visitor); table.setDefaultRenderer(LinkModel.class, new DefaultTableRenderer (new HyperlinkProvider(action, LinkModel.class))); table.setHighlighters(HighlighterFactory.createSimpleStriping()); Action enabled = new AbstractAction("toggle table enabled") { public void actionPerformed(ActionEvent e) { table.setEnabled(!table.isEnabled()); } }; JXFrame frame = wrapWithScrollingInFrame(table, visitor.getOutputComponent(), "show link renderer in table with LF striping highlighter"); addAction(frame, enabled); frame.setVisible(true); } /** * Custom link target action in JXList. */ public void interactiveListHyperlikPlayer() { LinkAction<Player> linkAction = new LinkAction<Player>() { public void actionPerformed(ActionEvent e) { LOG.info("hit: " + getTarget()); } protected void installTarget() { setName(getTarget() != null ? getTarget().name : ""); } }; JXList list = new JXList(createPlayerModel()); list.setRolloverEnabled(true); // descending order - check if the action is performed for the // correct value list.setFilterEnabled(true); list.setSortOrder(SortOrder.DESCENDING); list.setCellRenderer(new DefaultListRenderer( new HyperlinkProvider(linkAction, Player.class))); JFrame frame = wrapWithScrollingInFrame(list, "show simple bean link renderer in list"); frame.setVisible(true); } private ListModel createPlayerModel() { DefaultListModel model = new DefaultListModel(); model.addElement(new Player("Henry", 10)); model.addElement(new Player("Berta", 112)); model.addElement(new Player("Dave", 20)); return model; } public static class Player { String name; int score; public Player(String name, int score) { this.name = name; this.score = score; } @Override public String toString() { return name + " has score: " + score; } } /** * Simple target action. * */ public void interactiveListHyperlinkSimpleText() { LinkAction linkAction = new LinkAction<Object>(null) { public void actionPerformed(ActionEvent e) { LOG.info("hit: " + getTarget()); } }; JXList list = new JXList(createTextOnlyListModel(20)); list.setRolloverEnabled(true); list.setCellRenderer(new DefaultListRenderer( new HyperlinkProvider(linkAction))); JFrame frame = wrapWithScrollingInFrame(list, "show simple link renderer in list"); frame.setVisible(true); } /** * ListModel with LinkModel. * */ public void interactiveListHyperlink() { EditorPaneLinkVisitor visitor = new EditorPaneLinkVisitor(); JXList list = new JXList(createListModelWithLinks(20)); list.setRolloverEnabled(true); LinkModelAction action = new LinkModelAction(visitor); list.setCellRenderer(new DefaultListRenderer( new HyperlinkProvider(action, LinkModel.class))); JFrame frame = wrapWithScrollingInFrame(list, visitor.getOutputComponent(), "show link renderer in list"); frame.setVisible(true); } /** * Visuals of Hyperlink/Highlighter interaction. * */ public void interactiveListHyperlinkLFStripingHighlighter() { EditorPaneLinkVisitor visitor = new EditorPaneLinkVisitor(); JXList list = new JXList(createListModelWithLinks(20)); LinkModelAction action = new LinkModelAction<LinkModel>(visitor); list.setCellRenderer(new DefaultListRenderer( new HyperlinkProvider(action, LinkModel.class))); list.setRolloverEnabled(true); list.setHighlighters(HighlighterFactory.createSimpleStriping()); JFrame frame = wrapWithScrollingInFrame(list, visitor.getOutputComponent(), "show link renderer in list with LFStriping highlighter"); frame.setVisible(true); } private ListModel createTextOnlyListModel(int count) { DefaultListModel model = new DefaultListModel(); for (int i = 0; i < count; i++) { model.addElement("text } return model; } private ListModel createListModelWithLinks(int count) { DefaultListModel model = new DefaultListModel(); for (int i = 0; i < count; i++) { try { LinkModel link = new LinkModel("a link text " + i, null, new URL("http://some.dummy.url" + i)); if (i == 1) { URL url = JXEditorPaneTest.class.getResource("resources/test.html"); link = new LinkModel("a link text " + i, null, url); } model.addElement(link); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return model; } private TableModel createModelWithLinks() { String[] columnNames = { "text - not-editable", "Link not-editable", "Bool editable", "Bool not-editable" }; DefaultTableModel model = new DefaultTableModel(columnNames, 0) { @Override public Class<?> getColumnClass(int column) { return getValueAt(0, column).getClass(); } @Override public boolean isCellEditable(int row, int column) { return !getColumnName(column).contains("not"); } }; for (int i = 0; i < 4; i++) { try { LinkModel link = new LinkModel("a link text " + i, null, new URL("http://some.dummy.url" + i)); if (i == 1) { URL url = JXEditorPaneTest.class.getResource("resources/test.html"); link = new LinkModel("a link text " + i, null, url); } model.addRow(new Object[] {"text only " + i, link, Boolean.TRUE, Boolean.TRUE }); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return model; } protected LinkAction<Object> createEmptyLinkAction() { LinkAction<Object> linkAction = new LinkAction<Object>(null) { public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub } }; return linkAction; } protected LinkAction createEmptyLinkAction(String name) { LinkAction linkAction = createEmptyLinkAction(); linkAction.setName(name); return linkAction; } /** * make auto-run happy in the absence of real test methods. * */ public void testDummy() { } }
package com.valkryst.VTerminal.samples; import com.valkryst.VTerminal.AsciiString; import com.valkryst.VTerminal.Panel; import com.valkryst.VTerminal.builder.PanelBuilder; import com.valkryst.VTerminal.font.Font; import com.valkryst.VTerminal.font.FontLoader; import java.io.IOException; import java.net.URISyntaxException; public class SampleTileSheet { public static void main(final String[] args) throws IOException, URISyntaxException, InterruptedException { final Font font = FontLoader.loadFontFromJar("Tiles/Nevanda Nethack/bitmap.png", "Tiles/Nevanda Nethack/data.fnt", 1); final PanelBuilder builder = new PanelBuilder(); builder.setFont(font); builder.setWidthInCharacters(50); builder.setHeightInCharacters(22); final Panel panel = builder.build(); Thread.sleep(50); char counter = 32; for (int y = 0 ; y < panel.getHeightInCharacters() ; y++) { final AsciiString string = panel.getScreen().getString(y); for (int x = 0 ; x < panel.getWidthInCharacters() ; x++) { string.setCharacter(x, counter); counter++; } } panel.getScreen().convertAsciiCharactersToAsciiTiles(); panel.draw(); } }
package uk.ac.ox.oucs.vle; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.Map; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.StreamingOutput; import javax.ws.rs.ext.ContextResolver; import org.codehaus.jackson.JsonEncoding; import org.codehaus.jackson.JsonFactory; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig; import org.codehaus.jackson.map.annotate.JsonSerialize; import org.codehaus.jackson.map.type.TypeFactory; import org.sakaiproject.user.cover.UserDirectoryService; import uk.ac.ox.oucs.vle.CourseSignupService.Range; @Path("/course/") public class CourseResource { private CourseSignupService courseService; private JsonFactory jsonFactory; private ObjectMapper objectMapper; public CourseResource(@Context ContextResolver<Object> resolver) { this.courseService = (CourseSignupService) resolver.getContext(CourseSignupService.class); jsonFactory = new JsonFactory(); objectMapper = new ObjectMapper(); objectMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); objectMapper.configure(SerializationConfig.Feature.USE_STATIC_TYPING, true); objectMapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); } @Path("/{id}") @GET @Produces(MediaType.APPLICATION_JSON) public StreamingOutput getCourse(@PathParam("id") final String courseId, @QueryParam("range") final Range range) { final CourseGroup course = courseService.getCourseGroup(courseId, range); if (course == null) { throw new WebApplicationException(Response.Status.NOT_FOUND); } return new GroupStreamingOutput(course); /* return new StreamingOutput() { public void write(OutputStream output) throws IOException, WebApplicationException { objectMapper.writeValue(output, course); } }; */ } @Path("/all") @GET @Produces(MediaType.APPLICATION_JSON) public StreamingOutput getCourses(@QueryParam("range") final Range range) { boolean externalUser = false; if (UserDirectoryService.getAnonymousUser().equals(UserDirectoryService.getCurrentUser())) { externalUser = true; } final Map<String, String> departments = courseService.getDepartments(); final List<CourseGroup> groups = courseService.search("", range, externalUser); if (groups == null) { throw new WebApplicationException(Response.Status.NOT_FOUND); } return new AllGroupsStreamingOutput(departments, groups); } /** * This gets all the courses for a department that have upcoming * parts. * @param deptId The department to load the courses for. * @return An array of jsTree nodes. */ @Path("/dept/{deptId}") @Produces(MediaType.APPLICATION_JSON) @GET public StreamingOutput getCoursesUpcoming(@PathParam("deptId") final String deptId, @QueryParam("components") final Range range) { boolean externalUser = false; if (UserDirectoryService.getAnonymousUser().equals(UserDirectoryService.getCurrentUser())) { externalUser = true; } if (deptId.length() == 4) { if (range.equals(Range.PREVIOUS)) { List<CourseGroup> courses = courseService.getCourseGroupsByDept(deptId, range, externalUser); return new GroupsStreamingOutput(Collections.<SubUnit>emptyList(), courses, deptId, range.name(), false); } else { List<SubUnit> subUnits = courseService.getSubUnitsByDept(deptId); List<CourseGroup> courses = courseService.getCourseGroupsByDept(deptId, range, externalUser); List<CourseGroup> previous = courseService.getCourseGroupsByDept(deptId, Range.PREVIOUS, externalUser); return new GroupsStreamingOutput(subUnits, courses, deptId, range.name(), !previous.isEmpty()); } } else { if (range.equals(Range.PREVIOUS)) { List<CourseGroup> courses = courseService.getCourseGroupsBySubUnit(deptId, range, externalUser); return new GroupsStreamingOutput(Collections.<SubUnit>emptyList(), courses, deptId, range.name(), false); } else { List<CourseGroup> courses = courseService.getCourseGroupsBySubUnit(deptId, range, externalUser); List<CourseGroup> previous = courseService.getCourseGroupsBySubUnit(deptId, Range.PREVIOUS, externalUser); return new GroupsStreamingOutput(Collections.<SubUnit>emptyList(), courses, deptId, range.name(), !previous.isEmpty()); } } } @Path("/admin") @GET @Produces(MediaType.APPLICATION_JSON) public Response getAdminCourse() throws JsonGenerationException, JsonMappingException, IOException { if (UserDirectoryService.getAnonymousUser().equals(UserDirectoryService.getCurrentUser())) { throw new WebApplicationException(Response.Status.FORBIDDEN); } List <CourseGroup> groups = courseService.getAdministering(); // TODO Just return the coursegroups (no nested objects). return Response.ok(objectMapper.typedWriter(TypeFactory.collectionType(List.class, CourseGroup.class)).writeValueAsString(groups)).build(); } @Path("/search") @GET @Produces(MediaType.APPLICATION_JSON) public Response setCourses(@QueryParam("terms") String terms) throws JsonGenerationException, JsonMappingException, IOException { if (UserDirectoryService.getAnonymousUser().equals(UserDirectoryService.getCurrentUser())) { throw new WebApplicationException(Response.Status.FORBIDDEN); } if (terms == null) { throw new WebApplicationException(); } List<CourseGroup> groups = courseService.search(terms, Range.UPCOMING, false); return Response.ok(objectMapper.typedWriter(TypeFactory.collectionType(List.class, CourseGroup.class)).writeValueAsString(groups)).build(); } @Path("/calendar") @GET @Produces(MediaType.APPLICATION_JSON) public Response getCourseCalendar() throws JsonGenerationException, JsonMappingException, IOException { List <CourseGroup> groups = courseService.getCourseCalendar(null); // TODO Just return the coursegroups (no nested objects). return Response.ok(objectMapper.typedWriter(TypeFactory.collectionType(List.class, CourseGroup.class)).writeValueAsString(groups)).build(); } @Path("/nodates") @GET @Produces(MediaType.APPLICATION_JSON) public Response getCourseNoDates() throws JsonGenerationException, JsonMappingException, IOException { List <CourseGroup> groups = courseService.getCourseNoDates(null); // TODO Just return the coursegroups (no nested objects). return Response.ok(objectMapper.typedWriter(TypeFactory.collectionType(List.class, CourseGroup.class)).writeValueAsString(groups)).build(); } @Path("/url/{id}") @GET @Produces(MediaType.APPLICATION_JSON) public StreamingOutput getCourseURL(@PathParam("id") final String courseId) throws JsonGenerationException, JsonMappingException, IOException { if (UserDirectoryService.getAnonymousUser().equals(UserDirectoryService.getCurrentUser())) { throw new WebApplicationException(Response.Status.FORBIDDEN); } final String url = courseService.getDirectUrl(courseId); return new StreamingOutput() { public void write(OutputStream output) throws IOException, WebApplicationException { objectMapper.typedWriter(TypeFactory.fromClass(String.class)).writeValue(output, url); } }; } @Path("/hide") @POST public Response hide(@FormParam("courseId")String courseId, @FormParam("hideCourse")String hideCourse) { if (UserDirectoryService.getAnonymousUser().equals(UserDirectoryService.getCurrentUser())) { throw new WebApplicationException(Response.Status.FORBIDDEN); } courseService.setHideCourse(courseId, Boolean.parseBoolean(hideCourse)); return Response.ok().build(); } /** * Formats a duration sensibly. * @param remaining Time remaining in milliseconds. * @return a String roughly representing the duration. */ private String formatDuration(long remaining) { if (remaining < 1000) { return "< 1 second"; } else if (remaining < 60000) { return remaining / 1000 + " seconds"; } else if (remaining < 3600000) { return remaining / 60000 + " minutes"; } else if (remaining < 86400000) { return remaining / 3600000 + " hours"; } else { return remaining / 86400000 + " days"; } } private CourseSummary summary(Date now, CourseGroup courseGroup) { // Calculate the summary based on the available components. if (courseGroup.getComponents().isEmpty()) { return new CourseSummary("none available", Collections.singletonList(CourseState.UNKNOWN)); } Integer recentDays = courseService.getRecentDays(); Collection<CourseState> states = new ArrayList<CourseState>(); //CourseState state = CourseState.UNKNOWN; Date nextOpen = new Date(Long.MAX_VALUE); Date willClose = new Date(0); boolean isOneOpen = false; boolean isOneBookable = false; boolean areSomePlaces = false; boolean isNew = false; for (CourseComponent component: courseGroup.getComponents()) { if (!isOneBookable) { isOneBookable = component.getBookable(); } // Check if component is the earliest one opening in the future. boolean isGoingToOpen = component.getOpens().after(now) && component.getOpens().before(nextOpen); if (isGoingToOpen) { nextOpen = component.getOpens(); } // Check if the component is open and is open for the longest. if (component.getOpens().before(now) && component.getCloses().after(willClose)) { willClose = component.getCloses(); } boolean isOpen = component.getOpens().before(now) && component.getCloses().after(now); if (!isOneOpen && isOpen) { isOneOpen = true; } if (isOpen) { if (component.getPlaces() > 0) { areSomePlaces = true; } } Calendar recent = new GregorianCalendar(); recent.setTime(component.getCreated()); recent.add(Calendar.DATE, (recentDays)); if (now.before(recent.getTime())) { isNew = true; } } String detail = null; if (isNew) { states.add(CourseState.NEW); } //String newCourse = isNew ? "*NEW*" : ""; if (!isOneBookable) { states.add(CourseState.UNBOOKABLE); return new CourseSummary(null, states); } if (isOneOpen) { if (areSomePlaces) { long remaining = willClose.getTime() - now.getTime(); detail = "close in "+ formatDuration(remaining); states.add(CourseState.OPEN); } else { detail = "full"; states.add(CourseState.FULL); } } else { if (nextOpen.getTime() == Long.MAX_VALUE) { states.add(CourseState.UNBOOKABLE); } else { long until = nextOpen.getTime() - now.getTime(); detail = "open in "+ formatDuration(until); } } return new CourseSummary(detail, states); } // Maybe I should have just implemented a tuple. static enum CourseState {OPEN, FULL, UNBOOKABLE, UNKNOWN, NEW} class CourseSummary { private String detail; private Collection<CourseState> states; CourseSummary(String detail, Collection<CourseState> states) { this.detail = detail; this.states = states; } String getDetail() { return this.detail; } String getCourseState() { StringBuffer sb = new StringBuffer(); for (CourseState state : states) { sb.append(state.toString().toLowerCase()); sb.append(" "); } return sb.toString(); } } private class GroupsStreamingOutput implements StreamingOutput { private final List<SubUnit> subUnits; private final List<CourseGroup> courses; private final String deptId; private final String range; private final boolean previous; private GroupsStreamingOutput(List<SubUnit> subUnits, List<CourseGroup> courses, String deptId, String range, boolean previous) { this.subUnits = subUnits; this.courses = courses; this.deptId = deptId; this.range = range; this.previous = previous; } public void write(OutputStream out) throws IOException { Date now = courseService.getNow(); JsonGenerator gen = jsonFactory.createJsonGenerator(out, JsonEncoding.UTF8); gen.writeStartObject(); gen.writeObjectField("dept", deptId); gen.writeObjectField("range", range); gen.writeArrayFieldStart("tree"); for (SubUnit subUnit : subUnits) { gen.writeStartObject(); gen.writeObjectFieldStart("attr"); gen.writeStringField("id", subUnit.getCode()); gen.writeEndObject(); gen.writeStringField("data", (String)subUnit.getName()); gen.writeStringField("state", "closed"); gen.writeArrayFieldStart("children"); gen.writeEndArray(); gen.writeEndObject(); } for (CourseGroup courseGroup : courses) { gen.writeStartObject(); CourseSummary state = summary(now, courseGroup); gen.writeObjectFieldStart("attr"); gen.writeObjectField("id", courseGroup.getId()); gen.writeObjectField("class", state.getCourseState().toString().toLowerCase()); gen.writeEndObject(); gen.writeObjectField("data", courseGroup.getTitle() + (state.getDetail() == null ? "" : (" ("+state.getDetail()+")")) //(state.getNew() == null ? "" : " " + (state.getNew())) ); gen.writeEndObject(); } if (previous) { gen.writeStartObject(); gen.writeObjectFieldStart("attr"); gen.writeStringField("id", deptId+"-PREVIOUS"); gen.writeEndObject(); gen.writeStringField("data", "Previous"); gen.writeStringField("state", "closed"); //gen.writeArrayFieldStart("children"); //gen.writeEndArray(); gen.writeEndObject(); } gen.writeEndArray(); gen.writeEndObject(); gen.close(); } } private class AllGroupsStreamingOutput implements StreamingOutput { private final Map<String, String> departments; private final List<CourseGroup> courses; private AllGroupsStreamingOutput(Map<String, String> departments, List<CourseGroup> courses) { this.departments = departments; this.courses = courses; } public void write(OutputStream out) throws IOException { JsonGenerator gen = jsonFactory.createJsonGenerator(out, JsonEncoding.UTF8); gen.writeStartArray(); for (CourseGroup courseGroup : courses) { gen.writeStartObject(); gen.writeObjectField("id", courseGroup.getId()); gen.writeObjectField("description", courseGroup.getDescription()); gen.writeObjectField("title", courseGroup.getTitle()); //gen.writeObjectField("supervisorApproval", courseGroup.getSupervisorApproval()); //gen.writeObjectField("administratorApproval", courseGroup.getAdministratorApproval()); //gen.writeObjectField("publicView", courseGroup.getPublicView()); //gen.writeObjectField("homeApproval", courseGroup.getHomeApproval()); //gen.writeObjectField("isAdmin", courseGroup.getIsAdmin()); gen.writeArrayFieldStart("components"); for (CourseComponent component : courseGroup.getComponents()) { gen.writeStartObject(); gen.writeObjectField("id", component.getId()); gen.writeObjectField("location", component.getLocation()); gen.writeObjectField("slot", component.getSlot()); gen.writeObjectField("size", component.getSize()); gen.writeObjectField("subject", component.getSubject()); gen.writeObjectField("opens", component.getOpens().getTime()); gen.writeObjectField("closes", component.getCloses().getTime()); gen.writeObjectField("title", component.getTitle()); gen.writeObjectField("sessions", component.getSessions()); gen.writeObjectField("when", component.getWhen()); gen.writeObjectField("bookable", component.getBookable()); gen.writeObjectField("places", component.getPlaces()); gen.writeObjectField("created", component.getCreated().getTime()); gen.writeObjectField("componentSet", component.getComponentSet()); if (null != component.getPresenter()) { gen.writeObjectFieldStart("presenter"); gen.writeObjectField("name", component.getPresenter().getName()); gen.writeObjectField("email", component.getPresenter().getEmail()); //gen.writeObjectField("units", component.getPresenter().getUnits()); gen.writeEndObject(); } gen.writeEndObject(); } gen.writeEndArray(); gen.writeArrayFieldStart("administrators"); for (Person administrator : courseGroup.getAdministrators()) { gen.writeStartObject(); gen.writeObjectField("id", administrator.getId()); gen.writeObjectField("name", administrator.getName()); gen.writeObjectField("type", administrator.getType()); gen.writeObjectField("email", administrator.getEmail()); //gen.writeObjectField("units", administrator.getUnits()); gen.writeEndObject(); } gen.writeEndArray(); gen.writeArrayFieldStart("superusers"); for (Person superuser : courseGroup.getSuperusers()) { gen.writeStartObject(); gen.writeObjectField("id", superuser.getId()); gen.writeObjectField("name", superuser.getName()); gen.writeObjectField("type", superuser.getType()); gen.writeObjectField("email", superuser.getEmail()); //gen.writeObjectField("units", superuser.getUnits()); gen.writeEndObject(); } gen.writeEndArray(); gen.writeArrayFieldStart("department"); gen.writeObject(departments.get(courseGroup.getDepartmentCode())); for (String code : courseGroup.getOtherDepartments()) { gen.writeObject(departments.get(code)); } gen.writeEndArray(); gen.writeArrayFieldStart("categories_rdf"); for (CourseCategory category : courseGroup.getCategories(CourseGroup.Category_Type.RDF)) { gen.writeObject(category.getName()); } gen.writeEndArray(); gen.writeArrayFieldStart("categories_jacs"); for (CourseCategory category : courseGroup.getCategories(CourseGroup.Category_Type.JACS)) { gen.writeObject(category.getName()); } gen.writeEndArray(); gen.writeArrayFieldStart("categories_rm"); for (CourseCategory category : courseGroup.getCategories(CourseGroup.Category_Type.RM)) { gen.writeObject(category.getName()); } gen.writeEndArray(); gen.writeEndObject(); } gen.writeEndArray(); gen.close(); } } private class GroupStreamingOutput implements StreamingOutput { private final CourseGroup course; private GroupStreamingOutput(CourseGroup course) { this.course = course; } public void write(OutputStream out) throws IOException { JsonGenerator gen = jsonFactory.createJsonGenerator(out, JsonEncoding.UTF8); gen.writeStartObject(); gen.writeObjectField("id", course.getId()); gen.writeObjectField("description", course.getDescription()); gen.writeObjectField("title", course.getTitle()); gen.writeObjectField("supervisorApproval", course.getSupervisorApproval()); gen.writeObjectField("administratorApproval", course.getAdministratorApproval()); gen.writeObjectField("publicView", course.getPublicView()); //gen.writeObjectField("homeApproval", courseGroup.getHomeApproval()); gen.writeObjectField("isAdmin", course.getIsAdmin()); gen.writeObjectField("isSuperuser", course.getIsSuperuser()); gen.writeObjectField("department", course.getDepartment()); gen.writeObjectField("departmentCode", course.getDepartmentCode()); gen.writeObjectField("subUnit", course.getSubUnit()); gen.writeObjectField("subUnitCode", course.getSubUnitCode()); gen.writeArrayFieldStart("components"); for (CourseComponent component : course.getComponents()) { gen.writeStartObject(); gen.writeObjectField("id", component.getId()); gen.writeObjectField("location", component.getLocation()); gen.writeObjectField("slot", component.getSlot()); gen.writeObjectField("size", component.getSize()); gen.writeObjectField("subject", component.getSubject()); gen.writeObjectField("opens", component.getOpens().getTime()); gen.writeObjectField("closes", component.getCloses().getTime()); gen.writeObjectField("title", component.getTitle()); gen.writeObjectField("sessions", component.getSessions()); gen.writeObjectField("when", component.getWhen()); gen.writeObjectField("bookable", component.getBookable()); if (null != component.getStarts()) { gen.writeObjectField("starts", component.getStarts().getTime()); } if (null != component.getEnds()) { gen.writeObjectField("ends", component.getEnds().getTime()); } gen.writeObjectField("places", component.getPlaces()); gen.writeObjectField("componentSet", component.getComponentSet()); if (null != component.getPresenter()) { gen.writeObjectFieldStart("presenter"); gen.writeObjectField("name", component.getPresenter().getName()); gen.writeObjectField("email", component.getPresenter().getEmail()); //gen.writeObjectField("units", component.getPresenter().getUnits()); gen.writeEndObject(); } gen.writeEndObject(); } gen.writeEndArray(); gen.writeArrayFieldStart("administrators"); for (Person administrator : course.getAdministrators()) { gen.writeStartObject(); gen.writeObjectField("id", administrator.getId()); gen.writeObjectField("name", administrator.getName()); gen.writeObjectField("type", administrator.getType()); gen.writeObjectField("email", administrator.getEmail()); gen.writeObjectField("firstName", administrator.getFirstName()); gen.writeObjectField("lastName", administrator.getLastName()); gen.writeObjectField("departmentName", administrator.getDepartmentName()); //gen.writeObjectField("units", administrator.getUnits()); gen.writeObjectField("webauthId", administrator.getWebauthId()); gen.writeEndObject(); } gen.writeEndArray(); gen.writeArrayFieldStart("superusers"); for (Person superuser : course.getSuperusers()) { gen.writeStartObject(); gen.writeObjectField("id", superuser.getId()); gen.writeObjectField("name", superuser.getName()); gen.writeObjectField("type", superuser.getType()); gen.writeObjectField("email", superuser.getEmail()); gen.writeObjectField("firstName", superuser.getFirstName()); gen.writeObjectField("lastName", superuser.getLastName()); gen.writeObjectField("departmentName", superuser.getDepartmentName()); //gen.writeObjectField("units", superuser.getUnits()); gen.writeObjectField("webauthId", superuser.getWebauthId()); gen.writeEndObject(); } gen.writeEndArray(); gen.writeArrayFieldStart("otherDepartments"); for (String code : course.getOtherDepartments()) { gen.writeObject(code); } gen.writeEndArray(); gen.writeArrayFieldStart("categories_rdf"); for (CourseCategory category : course.getCategories(CourseGroup.Category_Type.RDF)) { gen.writeObject(category.getName()); } gen.writeEndArray(); gen.writeArrayFieldStart("categories_jacs"); for (CourseCategory category : course.getCategories(CourseGroup.Category_Type.JACS)) { gen.writeObject(category.getName()); } gen.writeEndArray(); gen.writeArrayFieldStart("categories_rm"); for (CourseCategory category : course.getCategories(CourseGroup.Category_Type.RM)) { gen.writeObject(category.getName()); } gen.writeEndArray(); gen.writeEndObject(); gen.close(); } } }
package uk.ac.ox.oucs.vle; import java.io.IOException; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.StreamingOutput; import javax.ws.rs.ext.ContextResolver; import org.codehaus.jackson.JsonEncoding; import org.codehaus.jackson.JsonFactory; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig; import org.codehaus.jackson.map.annotate.JsonSerialize; import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion; import org.codehaus.jackson.map.type.TypeFactory; import uk.ac.ox.oucs.vle.CourseSignupService.Range; @Path("/course/") public class CourseResource { private CourseSignupService courseService; private JsonFactory jsonFactory; private ObjectMapper objectMapper; public CourseResource(@Context ContextResolver<Object> resolver) { this.courseService = (CourseSignupService) resolver.getContext(CourseSignupService.class); jsonFactory = new JsonFactory(); objectMapper = new ObjectMapper(); objectMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); objectMapper.configure(SerializationConfig.Feature.USE_STATIC_TYPING, true); objectMapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); } @Path("/{id}") @GET @Produces(MediaType.APPLICATION_JSON) public StreamingOutput getCourse(@PathParam("id") final String courseId, @QueryParam("range") final Range range) { final CourseGroup course = courseService.getCourseGroup(courseId, range); if (course == null) { throw new WebApplicationException(Response.Status.NOT_FOUND); } return new StreamingOutput() { public void write(OutputStream output) throws IOException, WebApplicationException { objectMapper.writeValue(output, course); } }; } /** * This gets all the courses for a department that have upcoming * parts. * @param deptId The department to load the courses for. * @return An array of jsTree nodes. */ @Path("/dept/{deptId}") @Produces(MediaType.APPLICATION_JSON) @GET public StreamingOutput getCoursesUpcoming(@PathParam("deptId") final String deptId, @QueryParam("components") final Range range) { final List<CourseGroup> courses = courseService.getCourseGroups(deptId, range); return new GroupsStreamingOutput(courses, deptId, range.name()); } @Path("/admin") @GET @Produces(MediaType.APPLICATION_JSON) public Response getAdminCourse() throws JsonGenerationException, JsonMappingException, IOException { List <CourseGroup> groups = courseService.getAdministering(); // TODO Just return the coursegroups (no nested objects). return Response.ok(objectMapper.typedWriter(TypeFactory.collectionType(List.class, CourseGroup.class)).writeValueAsString(groups)).build(); } @Path("/search") @GET @Produces(MediaType.APPLICATION_JSON) public Response setCourses(@QueryParam("terms") String terms) throws JsonGenerationException, JsonMappingException, IOException { if (terms == null) { throw new WebApplicationException(); } List<CourseGroup> groups = courseService.search(terms); return Response.ok(objectMapper.typedWriter(TypeFactory.collectionType(List.class, CourseGroup.class)).writeValueAsString(groups)).build(); } /** * Formats a duration sensibly. * @param remaining Time remaining in milliseconds. * @return a String roughly representing the durnation. */ private String formatDuration(long remaining) { if (remaining < 1000) { return "< 1 second"; } else if (remaining < 60000) { return remaining / 1000 + " seconds"; } else if (remaining < 3600000) { return remaining / 60000 + " minutes"; } else if (remaining < 86400000) { return remaining / 3600000 + " hours"; } else { return remaining / 86400000 + " days"; } } private String summary(Date now, CourseGroup courseGroup) { // Calculate the summary based on the available components. if (courseGroup.getComponents().isEmpty()) { return "none available"; } Date nextOpen = new Date(Long.MAX_VALUE); Date willClose = new Date(0); boolean isOneOpen = false; boolean isOneBookable = false; boolean areSomePlaces = false; for (CourseComponent component: courseGroup.getComponents()) { if (!isOneBookable) { isOneBookable = component.getBookable(); } // Check if component is the earliest one opening in the future. boolean isGoingToOpen = component.getOpens().after(now) && component.getOpens().before(nextOpen); if (isGoingToOpen) { nextOpen = component.getOpens(); } // Check if the component is open and is open for the longest. if (component.getOpens().before(now) && component.getCloses().after(willClose)) { willClose = component.getCloses(); } boolean isOpen = component.getOpens().before(now) && component.getCloses().after(now); if (!isOneOpen && isOpen) { isOneOpen = true; } if (isOpen) { if (component.getPlaces() > 0) { areSomePlaces = true; } } } String detail = null; if (!isOneBookable) { return null; // No signup available. } if (isOneOpen) { if (areSomePlaces) { long remaining = willClose.getTime() - now.getTime(); detail = "close in "+ formatDuration(remaining); } else { detail = "full"; } } else { if (nextOpen.getTime() == Long.MAX_VALUE) { return null; // Didn't find one open } long until = nextOpen.getTime() - now.getTime(); detail = "open in "+ formatDuration(until); } return detail; } private class GroupsStreamingOutput implements StreamingOutput { private final List<CourseGroup> courses; private final String deptId; private final String range; private GroupsStreamingOutput(List<CourseGroup> courses, String deptId, String range) { this.courses = courses; this.deptId = deptId; this.range = range; } public void write(OutputStream out) throws IOException { Date now = courseService.getNow(); JsonGenerator gen = jsonFactory.createJsonGenerator(out, JsonEncoding.UTF8); gen.writeStartObject(); gen.writeObjectField("dept", deptId); gen.writeObjectField("range", range); gen.writeArrayFieldStart("tree"); for (CourseGroup courseGroup : courses) { gen.writeStartObject(); gen.writeObjectFieldStart("attr"); gen.writeObjectField("id", courseGroup.getId()); gen.writeEndObject(); String detail = summary(now, courseGroup); gen.writeObjectField("data", courseGroup.getTitle() + (detail == null?"":(" ("+detail+")")) ); gen.writeEndObject(); } gen.writeEndArray(); gen.writeEndObject(); gen.close(); } } }
import drafts.com.sun.star.accessibility.XAccessible; import drafts.com.sun.star.accessibility.XAccessibleContext; import drafts.com.sun.star.accessibility.XAccessibleStateSet; import com.sun.star.uno.UnoRuntime; import com.sun.star.container.XIndexAccess; class AccessibleContextHandler extends NodeHandler { protected int nChildrenCount; private static String maStateNames[] = { "INVALID", "ACTIVE", "ARMED", "BUSY", "CHECKED", "COLLAPSED", "DEFUNC", "EDITABLE", "ENABLED", "EXPANDABLE", "EXPANDED", "FOCUSABLE", "FOCUSED", "HORIZONTAL", "ICONIFIED", "MODAL", "MULTILINE", "MULTISELECTABLE", "OPAQUE", "PRESSED", "RESIZABLE", "SELECTABLE", "SELECTED", "SENSITIVE", "SHOWING", "SINGLE_LINE", "STALE", "TRANSIENT", "VERTICAL", "VISIBLE", }; public NodeHandler createHandler (XAccessibleContext xContext) { if (xContext != null) return new AccessibleContextHandler (xContext); else return null; } public AccessibleContextHandler () { super (); } public AccessibleContextHandler (XAccessibleContext xContext) { super(); if (xContext != null) maChildList.setSize (4); } public AccessibleTreeNode createChild (AccessibleTreeNode aParent, int nIndex) { XAccessibleContext xContext = null; if (aParent instanceof AccTreeNode) xContext = ((AccTreeNode)aParent).getContext(); String sChild = new String(); if (xContext != null) { switch( nIndex ) { case 0: sChild = "Description: " + xContext.getAccessibleDescription(); break; case 1: sChild = "Role: " + xContext.getAccessibleRole(); break; case 2: XAccessible xParent = xContext.getAccessibleParent(); sChild = "Has parent: " + (xParent!=null ? "yes" : "no"); /* if (xParent != ((AccTreeNode)aParent).getAccessible()) { sChild += " but that is inconsistent" + "#" + xParent + " # " + ((AccTreeNode)aParent).getAccessible(); } */ break; case 3: sChild = ""; XAccessibleStateSet xStateSet = xContext.getAccessibleStateSet(); if (xStateSet != null) { for (short i=0; i<=29; i++) { if (xStateSet.contains (i)) { if (sChild.compareTo ("") != 0) sChild += ", "; sChild += maStateNames[i]; } } } else sChild += "no state set"; sChild = "State set: " + sChild; /* case 3: sChild = "Child count: " + xContext.getAccessibleChildCount(); break;*/ } } return new StringNode (sChild, aParent); } }
public class InsecureBasicAuth { /** * Test basic authentication with Apache HTTP request. */ public void testApacheHttpRequest(String username, String password) { // BAD: basic authentication over HTTP String url = "http: // GOOD: basic authentication over HTTPS url = "https: HttpPost post = new HttpPost(url); post.setHeader("Accept", "application/json"); post.setHeader("Content-type", "application/json"); String authString = username + ":" + password; byte[] authEncBytes = Base64.getEncoder().encode(authString.getBytes()); String authStringEnc = new String(authEncBytes); post.addHeader("Authorization", "Basic " + authStringEnc); } /** * Test basic authentication with Java HTTP URL connection. */ public void testHttpUrlConnection(String username, String password) { // BAD: basic authentication over HTTP String urlStr = "http: // GOOD: basic authentication over HTTPS urlStr = "https: String authString = username + ":" + password; String encoding = Base64.getEncoder().encodeToString(authString.getBytes("UTF-8")); URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Authorization", "Basic " + encoding); } }
package org.flymine.web.logic; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import org.intermine.objectstore.query.BagConstraint; import org.intermine.objectstore.query.ConstraintOp; import org.intermine.objectstore.query.ConstraintSet; import org.intermine.objectstore.query.ContainsConstraint; import org.intermine.objectstore.query.Query; import org.intermine.objectstore.query.QueryClass; import org.intermine.objectstore.query.QueryField; import org.intermine.objectstore.query.QueryObjectReference; import org.intermine.objectstore.query.QueryValue; import org.intermine.objectstore.query.Results; import org.intermine.objectstore.query.ResultsRow; import org.intermine.objectstore.query.SimpleConstraint; import org.intermine.objectstore.ObjectStore; import org.intermine.web.logic.bag.InterMineBag; import org.flymine.model.genomic.Chromosome; import org.flymine.model.genomic.Gene; import org.flymine.model.genomic.Organism; /** * Utility methods for the flymine package. * @author Julie Sullivan */ public abstract class FlymineUtil { /** * For a bag of genes, returns a list of organisms * @param os ObjectStore * @param bag InterMineBag * @return collection of organism names */ public static Collection getOrganisms(ObjectStore os, InterMineBag bag) { Query q = new Query(); QueryClass qcGene = new QueryClass(Gene.class); QueryClass qcOrganism = new QueryClass(Organism.class); QueryField qfOrganismName = new QueryField(qcOrganism, "name"); QueryField qfGeneId = new QueryField(qcGene, "id"); q.addFrom(qcGene); q.addFrom(qcOrganism); q.addToSelect(qfOrganismName); ConstraintSet cs = new ConstraintSet(ConstraintOp.AND); if (bag != null) { BagConstraint bc = new BagConstraint(qfGeneId, ConstraintOp.IN, bag.getOsb()); cs.addConstraint(bc); } QueryObjectReference qr = new QueryObjectReference(qcGene, "organism"); ContainsConstraint cc = new ContainsConstraint(qr, ConstraintOp.CONTAINS, qcOrganism); cs.addConstraint(cc); q.setConstraint(cs); q.addToOrderBy(qfOrganismName); Results r = new Results(q, os, os.getSequence()); Iterator it = r.iterator(); Collection organismNames = new ArrayList(); while (it.hasNext()) { ResultsRow rr = (ResultsRow) it.next(); organismNames.add(rr.get(0)); } return organismNames; } /** * Return a list of chromosomes for specified organism * @param os ObjectStore * @param organism Organism name * @return collection of chromosome names */ public static Collection getChromosomes(ObjectStore os, String organism) { // SELECT DISTINCT o // FROM org.flymine.model.genomic.Chromosome AS c, // org.flymine.model.genomic.Organism AS o // WHERE c.organism CONTAINS o /* TODO put this in a config file */ if (organism.equals("Drosophila melanogaster")) { ArrayList<String> chromosomes = new ArrayList<String>(); chromosomes.add("2L"); chromosomes.add("2R"); chromosomes.add("3L"); chromosomes.add("3R"); chromosomes.add("U"); chromosomes.add("X"); return chromosomes; } Query q = new Query(); QueryClass qcChromosome = new QueryClass(Chromosome.class); QueryClass qcOrganism = new QueryClass(Organism.class); QueryField qfChromosome = new QueryField(qcChromosome, "identifier"); QueryField organismNameQF = new QueryField(qcOrganism, "name"); q.addFrom(qcChromosome); q.addFrom(qcOrganism); q.addToSelect(qfChromosome); ConstraintSet cs = new ConstraintSet(ConstraintOp.AND); QueryObjectReference qr = new QueryObjectReference(qcChromosome, "organism"); ContainsConstraint cc = new ContainsConstraint(qr, ConstraintOp.CONTAINS, qcOrganism); cs.addConstraint(cc); SimpleConstraint sc = new SimpleConstraint(organismNameQF, ConstraintOp.EQUALS, new QueryValue(organism)); cs.addConstraint(sc); q.setConstraint(cs); q.addToOrderBy(qfChromosome); Results r = new Results(q, os, os.getSequence()); Iterator it = r.iterator(); Collection<String> chromosomes = new ArrayList<String>(); while (it.hasNext()) { ResultsRow rr = (ResultsRow) it.next(); chromosomes.add((String) rr.get(0)); } return chromosomes; } }
package com.marcusmccurdy.trie; import java.util.Collection; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; /** * * @author Marcus McCurdy <marcus.mccurdy@gmail.com> */ public class TrieTest { private Trie root; @Before public void setUp() { root = new Trie(); } @Test public void testAdd() { root.add('z'); assertEquals(1, root.children.size()); Trie child = root.children.get('z'); assertNotNull(child); assertEquals("z", child.value); } /** * Test of insert method, of class Trie. */ @Test public void testInsert() { root.insert("test"); assertEquals(1, root.children.size()); root.insert("basic"); assertEquals(2, root.children.size()); assertEquals(1, root.children.get('b').children.size()); assertEquals(1, root.children.get('t').children.size()); } @Test(expected = IllegalArgumentException.class) public void testInsertNull() { root.insert(null); } @Test public void testFind() { root.insert("hello"); root.insert("test"); root.insert("tea"); root.insert("bravo"); assertEquals("", root.find("missing")); assertEquals("test", root.find("test")); } @Test public void testAutoComplete() { root.insert("test"); root.insert("tea"); root.insert("tell"); root.insert("zebra"); Collection<String> results = root.autoComplete("te"); assertTrue(results.contains("test")); assertTrue(results.contains("tea")); assertTrue(results.contains("tell")); assertFalse(results.contains("zebra")); } }
package co.aikar.commands; import com.google.common.collect.HashMultimap; import com.google.common.collect.SetMultimap; import java.util.ArrayList; import java.util.List; public class JDARootCommand implements RootCommand { private JDACommandManager manager; private final String name; private BaseCommand defCommand; private SetMultimap<String, RegisteredCommand> subCommands = HashMultimap.create(); private List<BaseCommand> children = new ArrayList<>(); boolean isRegistered = false; JDARootCommand(JDACommandManager manager, String name) { this.manager = manager; this.name = name; } @Override public void addChild(BaseCommand command) { if (this.defCommand == null || !command.subCommands.get(BaseCommand.DEFAULT).isEmpty()) { this.defCommand = command; } addChildShared(this.children, this.subCommands, command); } @Override public CommandManager getManager() { return this.manager; } @Override public SetMultimap<String, RegisteredCommand> getSubCommands() { return this.subCommands; } @Override public List<BaseCommand> getChildren() { return this.children; } @Override public String getCommandName() { return this.name; } @Override public BaseCommand getDefCommand() { return defCommand; } }
package org.jpos.util; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.sameInstance; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import org.junit.After; import org.junit.Before; import org.junit.Test; public class NameRegistrarTest { private static final boolean WITH_DETAIL = true; @Before public void onSetup() { NameRegistrar.register("test1", "testValue1"); NameRegistrar.register("test2", "testValue2"); } @After public void tearDown() { NameRegistrar.unregister("test1"); NameRegistrar.unregister("test2"); } @Test public void testDumpWithoutDetail() throws Throwable { ByteArrayOutputStream out = new ByteArrayOutputStream(); NameRegistrar.getInstance().dump(new PrintStream(out), ">"); assertThat( out.toString(), allOf(containsString("name-registrar:" + System.getProperty("line.separator")), containsString("test1"), containsString("test2"))); } @Test public void testDumpWithDetail() throws Throwable { ByteArrayOutputStream out = new ByteArrayOutputStream(); NameRegistrar.getInstance().dump(new PrintStream(out), "+", WITH_DETAIL); assertThat( out.toString(), allOf(containsString("name-registrar:" + System.getProperty("line.separator")), containsString("test1"), containsString("test2"))); } @Test public void testGetInstance() throws Throwable { NameRegistrar result = NameRegistrar.getInstance(); assertThat(result, is(sameInstance(NameRegistrar.getInstance()))); } @Test public void testGet() throws Exception { String value = (String) NameRegistrar.get("test1"); assertThat(value, is("testValue1")); } @Test(expected = NameRegistrar.NotFoundException.class) public void testGetThrowsNotFoundException() throws Throwable { NameRegistrar.get("NonexistentKey"); } @Test public void testGetIfExists() throws Throwable { String value = (String) NameRegistrar.getIfExists("test2"); assertThat(value, is("testValue2")); } @Test public void testGetIfExistsWithNotFoundKey() throws Exception { String value = (String) NameRegistrar.getIfExists("NonexistentKey"); assertThat(value, is(nullValue())); } @Test(expected = NameRegistrar.NotFoundException.class) public void testUnregister() throws Exception { NameRegistrar.register("test3", "someTest3Value"); assertThat((String) NameRegistrar.get("test3"), is("someTest3Value")); NameRegistrar.unregister("test3"); NameRegistrar.get("test3"); } @Test public void testUnregisterUnknownKeyDoesNotThrowException() throws Exception { NameRegistrar.unregister("unknownKey"); } @Test public void testNotFoundExceptionConstructor1() throws Throwable { NameRegistrar.NotFoundException notFoundException = new NameRegistrar.NotFoundException("testNotFoundExceptionDetail"); assertEquals("notFoundException.getMessage()", "testNotFoundExceptionDetail", notFoundException.getMessage()); } }
package xdroid.widget; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.database.Cursor; import android.net.Uri; import android.os.Parcel; import android.os.Parcelable; import android.util.AttributeSet; import android.view.View; import android.widget.Adapter; import android.widget.ListView; import android.widget.WrapperListAdapter; import java.io.Serializable; import xdroid.adapter.AdapterExt; import xdroid.adapter.CursorAdapterExt; import xdroid.adapter.IAdapter; import xdroid.adapter.ViewBinder; import xdroid.adapter.ViewTypeResolver; import xdroid.collections.Indexed; import xdroid.collections.Prototypes; import xdroid.core.ParcelUtils; import xdroid.core.ReflectUtils; import xdroid.core.Strings; public class ListViewExt extends ListView { public static final int ADAPTER_DATA_NONE = 0; public static final int ADAPTER_DATA_ARRAY_LIST = 1; public static final int ADAPTER_DATA_LINKED_LIST = 2; public static final int ADAPTER_DATA_CURSOR = 3; private boolean mKeepData; public boolean isKeepData() { return mKeepData; } public void setKeepData(boolean keepData) { mKeepData = keepData; } public ListViewExt(Context context) { super(context); init(context, null, 0); } public ListViewExt(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs, 0); } public ListViewExt(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context, attrs, defStyle); } private void init(Context context, AttributeSet attrs, @SuppressWarnings("unused") int defStyle) { mKeepData = true; if (attrs == null) { return; } if (context == null) { return; } Resources resources = context.getResources(); if (resources == null) { return; } TypedArray a = resources.obtainAttributes(attrs, R.styleable.ListViewExt); if (a == null) { return; } try { switch (a.getInt(R.styleable.ListViewExt_adapterData, ADAPTER_DATA_NONE)) { case ADAPTER_DATA_ARRAY_LIST: initAdapter(context, a, new AdapterExt(), Prototypes.newArrayList()); break; case ADAPTER_DATA_LINKED_LIST: initAdapter(context, a, new AdapterExt(), Prototypes.newLinkedList()); break; case ADAPTER_DATA_CURSOR: initCursorAdapter(context, a); break; } } finally { a.recycle(); } } private void initAdapter(Context context, TypedArray a, IAdapter adapter) { int layoutId = a.getResourceId(R.styleable.ListViewExt_adapterLayoutId, 0); if (layoutId != 0) { adapter.setLayoutId(layoutId); } int layoutIdsArray = a.getResourceId(R.styleable.ListViewExt_adapterLayoutIdsArray, 0); if (layoutIdsArray != 0) { TypedArray layouts = context.getResources().obtainTypedArray(layoutIdsArray); try { int count = layouts.length(); for (int i = 0; i < count; ++i) { adapter.putLayoutId(i, layouts.getResourceId(i, 0)); } } finally { layouts.recycle(); } } String binderClass = a.getString(R.styleable.ListViewExt_adapterBinderClass); if (Strings.isNotEmpty(binderClass)) { //noinspection unchecked adapter.setBinder(ReflectUtils.<ViewBinder>newInstanceByClassName(ReflectUtils.fullClassName(context, binderClass))); } String viewTypeResolverClass = a.getString(R.styleable.ListViewExt_adapterViewTypeResolverClass); if (Strings.isNotEmpty(viewTypeResolverClass)) { //noinspection unchecked adapter.setViewTypeResolver(ReflectUtils.<ViewTypeResolver>newInstanceByClassName(ReflectUtils.fullClassName(context, viewTypeResolverClass))); } } @SuppressWarnings("unchecked") private void initAdapter(Context context, TypedArray a, AdapterExt adapter, Indexed data) { adapter.setData(data); initAdapter(context, a, adapter); setAdapter(adapter); } @SuppressWarnings("unchecked") private void initCursorAdapter(Context context, TypedArray a) { String uri = a.getString(R.styleable.ListViewExt_adapterCursorQuery); if (Strings.isEmpty(uri)) { return; } Cursor cursor = context.getContentResolver().query(Uri.parse(uri), null, null, null, null); if (cursor == null) { return; } CursorAdapterExt adapter = new CursorAdapterExt(context, cursor, a.getBoolean(R.styleable.ListViewExt_adapterCursorAutoRequery, true)); initAdapter(context, a, adapter); setAdapter(adapter); } @Override public Parcelable onSaveInstanceState() { return new SavedState(super.onSaveInstanceState(), this); } @Override public void onRestoreInstanceState(Parcelable state) { SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); ss.onRestoreInstanceState(this); } public AdapterExt getRawAdapter() { Adapter adapter = getAdapter(); if (adapter instanceof WrapperListAdapter) { adapter = ((WrapperListAdapter) adapter).getWrappedAdapter(); } if (adapter instanceof AdapterExt) { return (AdapterExt) adapter; } return null; } static class SavedState extends BaseSavedState { final int firstVisiblePosition; final int topItemPosition; final boolean keepData; final Object data; public static int getTopItemPosition(ListView listView) { View topItem = listView.getChildAt(listView.getHeaderViewsCount()); return topItem == null ? 0 : topItem.getTop(); } public static Object getData(ListViewExt listView) { AdapterExt adapter = listView.getRawAdapter(); if (adapter != null) { Indexed data = adapter.getData(); if (data instanceof Parcelable || data instanceof Serializable) { return data; } } return null; } public SavedState(Parcelable superState, ListViewExt listView) { super(superState); firstVisiblePosition = listView.getFirstVisiblePosition(); topItemPosition = getTopItemPosition(listView); keepData = listView.isKeepData(); data = keepData ? getData(listView) : null; } @SuppressWarnings("unchecked") public void onRestoreInstanceState(ListViewExt listView) { listView.setSelectionFromTop(firstVisiblePosition, topItemPosition); listView.setKeepData(keepData); AdapterExt adapter = listView.getRawAdapter(); if (adapter != null && data instanceof Indexed) { adapter.setData((Indexed) data); } } @Override public void writeToParcel(@SuppressWarnings("NullableProblems") Parcel out, int flags) { out.writeInt(firstVisiblePosition); out.writeInt(topItemPosition); out.writeInt(keepData ? 1 : 0); ParcelUtils.writeParcelableOrSerializable(out, flags, data); } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel in) { return new SavedState(in); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; private SavedState(Parcel in) { super(in); ClassLoader cl = ((Object) this).getClass().getClassLoader(); firstVisiblePosition = in.readInt(); topItemPosition = in.readInt(); keepData = in.readInt() == 1; data = ParcelUtils.readParcelableOrSerializable(in, cl); } } }
package com.google.common.base; import com.google.common.annotations.GwtCompatible; /** * Action callback with possibility of exception throw. */ @GwtCompatible public interface ThrowableAction { /** * Calls action. * * @throws Throwable when exception occurs */ void call() throws Throwable; }
package whelk; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.Set; public class PortableScript implements Serializable { final String scriptText; final Set<String> ids; final public String comment; public PortableScript(String scriptText, Set<String> ids, String comment) { this.scriptText = scriptText; if (ids != null) this.ids = Collections.unmodifiableSet(ids); else this.ids = null; this.comment = comment; } public Path execute() throws IOException { Path scriptWorkingDir = Files.createTempDirectory("xl_script"); Path scriptFilePath = scriptWorkingDir.resolve("script.groovy"); Path inputFilePath = scriptWorkingDir.resolve("input"); Path reportPath = scriptWorkingDir.resolve("report"); Files.createDirectories(reportPath); String flattenedScriptText = scriptText; if (ids != null) { Files.write(inputFilePath, ids); // On windows inputFilePath.toString() produces backslashes, but the groovy script allows only forwardslashes. flattenedScriptText = scriptText.replace("£INPUT", inputFilePath.toString().replace("\\", "/")); } Files.write(scriptFilePath, flattenedScriptText.getBytes()); String[] args = { "--allow-loud", "--report", reportPath.toString(), scriptFilePath.toString(), }; whelk.datatool.WhelkTool.main(args); return reportPath; } }
package com.psddev.dari.util; import java.io.IOException; import java.io.Writer; import java.lang.reflect.Array; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Deque; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.UUID; /** Writer implementation that adds basic HTML formatting. */ public class HtmlWriter extends Writer { private static final String GRID_PADDING; static { StringBuilder gp = new StringBuilder(); for (int i = 0; i < 500; ++ i) { gp.append(" ."); } GRID_PADDING = gp.toString(); } private final Writer writer; private final Map<Class<?>, HtmlFormatter<Object>> defaultFormatters = new HashMap<Class<?>, HtmlFormatter<Object>>(); private final Map<Class<?>, HtmlFormatter<Object>> overrideFormatters = new HashMap<Class<?>, HtmlFormatter<Object>>(); private final Deque<String> tags = new ArrayDeque<String>(); /** Creates an instance that writes to the given {@code writer}. */ public HtmlWriter(Writer writer) { this.writer = writer; } @SuppressWarnings("unchecked") public <T> void putDefault(Class<T> objectClass, HtmlFormatter<? super T> formatter) { defaultFormatters.put(objectClass, (HtmlFormatter<Object>) formatter); } @SuppressWarnings("unchecked") public <T> void putOverride(Class<T> objectClass, HtmlFormatter<? super T> formatter) { overrideFormatters.put(objectClass, (HtmlFormatter<Object>) formatter); } public void putAllStandardDefaults() { putDefault(null, HtmlFormatter.NULL); putDefault(Class.class, HtmlFormatter.CLASS); putDefault(Collection.class, HtmlFormatter.COLLECTION); putDefault(Date.class, HtmlFormatter.DATE); putDefault(Double.class, HtmlFormatter.FLOATING_POINT); putDefault(Enum.class, HtmlFormatter.ENUM); putDefault(Float.class, HtmlFormatter.FLOATING_POINT); putDefault(Map.class, HtmlFormatter.MAP); putDefault(Number.class, HtmlFormatter.NUMBER); putDefault(PaginatedResult.class, HtmlFormatter.PAGINATED_RESULT); putDefault(StackTraceElement.class, HtmlFormatter.STACK_TRACE_ELEMENT); putDefault(Throwable.class, HtmlFormatter.THROWABLE); // Optional. if (HtmlFormatter.JASPER_EXCEPTION_CLASS != null) { putDefault(HtmlFormatter.JASPER_EXCEPTION_CLASS, HtmlFormatter.JASPER_EXCEPTION); } } public void removeDefault(Class<?> objectClass) { defaultFormatters.remove(objectClass); } public void removeOverride(Class<?> objectClass) { overrideFormatters.remove(objectClass); } /** * Escapes the given {@code string} so that it's safe to use in * an HTML page. */ protected String escapeHtml(String string) { return StringUtils.escapeHtml(string); } private void writeAttribute(Object name, Object value) throws IOException { if (!(ObjectUtils.isBlank(name) || value == null)) { writer.write(' '); writer.write(escapeHtml(name.toString())); writer.write("=\""); writer.write(escapeHtml(value.toString())); writer.write('"'); } } /** * Writes the given {@code tag} with the given {@code attributes}. * * <p>This method doesn't keep state, so it should be used with doctype * declaration and self-closing tags like {@code img}.</p> */ public HtmlWriter tag(String tag, Object... attributes) throws IOException { if (tag == null) { throw new IllegalArgumentException("Tag can't be null!"); } writer.write('<'); writer.write(tag); if (attributes != null) { for (int i = 0, length = attributes.length; i < length; ++ i) { Object name = attributes[i]; if (name instanceof Map) { for (Map.Entry<?, ?> entry : ((Map<?, ?>) name).entrySet()) { writeAttribute(entry.getKey(), entry.getValue()); } } else { ++ i; Object value = i < length ? attributes[i] : null; writeAttribute(name, value); } } } writer.write('>'); return this; } /** * Writes the given start {@code tag} with the given {@code attributes}. * * <p>This method keeps state, so there should be a matching {@link #end} * call afterwards.</p> */ public HtmlWriter start(String tag, Object... attributes) throws IOException { tag(tag, attributes); tags.addFirst(tag); return this; } /** Writes the end tag previously started with {@link #start}. */ public HtmlWriter end() throws IOException { String tag = tags.removeFirst(); if (tag == null) { throw new IllegalStateException("No more tags!"); } writer.write("</"); writer.write(tag); writer.write('>'); return this; } /** * Escapes and writes the given {@code unescapedHtml}, or if it's * {@code null}, the given {@code defaultUnescapedHtml}. */ public HtmlWriter htmlOrDefault(Object unescapedHtml, String defaultUnescapedHtml) throws IOException { writer.write(escapeHtml(unescapedHtml == null ? defaultUnescapedHtml : unescapedHtml.toString())); return this; } /** * Escapes and writes the given {@code unescapedHtml}, or if it's * {@code null}, nothing. */ public HtmlWriter html(Object unescapedHtml) throws IOException { htmlOrDefault(unescapedHtml, ""); return this; } /** Formats and writes the given {@code object}. */ public HtmlWriter object(Object object) throws IOException { HtmlFormatter<Object> formatter; if (object == null) { formatter = overrideFormatters.get(null); if (formatter == null) { formatter = defaultFormatters.get(null); } if (formatter != null) { formatter.format(this, null); return this; } } else { if (formatWithMap(overrideFormatters, object)) { return this; } if (object instanceof HtmlObject) { ((HtmlObject) object).format(this); return this; } if (formatWithMap(defaultFormatters, object)) { return this; } } if (object != null && object.getClass().isArray()) { start("ul"); for (int i = 0, length = Array.getLength(object); i < length; ++ i) { start("li").object(Array.get(object, i)).end(); } end(); return this; } return html(object); } private boolean formatWithMap( Map<Class<?>, HtmlFormatter<Object>> formatters, Object object) throws IOException { HtmlFormatter<Object> formatter; for (Class<?> objectClass = object.getClass(); objectClass != null; objectClass = objectClass.getSuperclass()) { formatter = formatters.get(objectClass); if (formatter != null) { formatter.format(this, object); return true; } for (Class<?> interfaceClass : objectClass.getInterfaces()) { formatter = formatters.get(interfaceClass); if (formatter != null) { formatter.format(this, object); return true; } } } return false; } /** Returns a CSS string based on the given {@code properties}. */ public String cssString(Object... properties) { return Static.cssString(properties); } /** Writes a CSS rule based on the given parameters. */ public HtmlWriter css(String selector, Object... properties) throws IOException { write(selector); write('{'); write(cssString(properties)); write("}\n"); return this; } public HtmlWriter grid(Object object, HtmlGrid grid, boolean inlineCss) throws IOException { Map<String, Area> areas = createAreas(grid); boolean debug; try { debug = !Settings.isProduction() && ObjectUtils.to(boolean.class, PageContextFilter.Static.getRequest().getParameter("_grid")); } catch (Exception error) { debug = false; } if (!inlineCss) { start("style", "type", "text/css"); css(".dari-grid-area", "-moz-box-sizing", "content-box", "-webkit-box-sizing", "content-box", "box-sizing", "content-box", "float", "left", "margin", "0 -100% 0 -30000px"); css(".dari-grid-adj", "float", "left"); for (Area area : areas.values()) { String selector = area.id != null ? "#" + area.id : ".dari-grid-area[data-grid-area=\"" + area.getName() + "\"]"; css(selector, "clear", area.clear ? "left" : null, "padding-left", area.frPaddingLeft + "%", "width", area.frWidth + "%"); for (Map.Entry<String, Adjustment> entry : area.adjustments.entrySet()) { String unit = entry.getKey(); Adjustment adjustment = entry.getValue(); css(selector + "-" + unit, "height", adjustment.height, "margin", adjustment.getMargin(unit), "width", adjustment.width); } } end(); } if (object == null) { object = areas; } for (Map.Entry<String, Area> entry : areas.entrySet()) { String areaName = entry.getKey(); Area area = entry.getValue(); // The main wrapping DIV around the area. Initially shifted // left 30000px so that it's off-screen as not to overlap // other elements that come before. start("div", "class", "dari-grid-area", "id", area.id, "data-grid-area", areaName, "style", !inlineCss ? null : cssString( "-moz-box-sizing", "content-box", "-webkit-box-sizing", "content-box", "box-sizing", "content-box", "clear", area.clear ? "left" : null, "float", "left", "margin", "0 -100% 0 -30000px", "padding-left", area.frPaddingLeft + "%", "width", area.frWidth + "%")); int adjustments = 0; for (Map.Entry<String, Adjustment> adjustmentEntry : area.adjustments.entrySet()) { ++ adjustments; String unit = adjustmentEntry.getKey(); Adjustment adjustment = adjustmentEntry.getValue(); start("div", "class", "dari-grid-adj", "id", area.id + "-" + unit, "style", !inlineCss ? null : cssString( "float", "left", "height", adjustment.height, "margin", adjustment.getMargin(unit), "width", adjustment.width)); } start("div", "style", cssString( "height", 0, "overflow", "hidden", "visibility", "hidden")); write(GRID_PADDING); end(); if (debug) { start("div", "style", cssString( "border", "3px dashed red", "padding", "3px")); } // Minimum width with multiple units. if (area.singleWidth == null) { int i = 0; for (CssUnit column : area.width.getAll()) { if (!"fr".equals(column.getUnit())) { ++ i; start("div", "style", cssString( "padding-left", column, "height", 0)); } } for (; i > 0; end(); } } // Minimum height with multiple units. if (area.singleHeight == null) { start("div", "style", cssString( "float", "left", "width", 0)); int i = 0; for (CssUnit row : area.height.getAll()) { ++ i; start("div", "style", cssString( "padding-top", row, "width", 0)); } for (; i > 0; end(); } end(); } object(CollectionUtils.getByPath(object, entry.getKey())); if (area.singleHeight == null) { start("div", "style", cssString("clear", "left")); end(); } if (debug) { end(); } for (; adjustments > 0; -- adjustments) { end(); } end(); } start("div", "style", cssString("clear", "left")); end(); return this; } private Map<String, Area> createAreas(HtmlGrid grid) { List<CssUnit> columns = grid.getColumns(); List<CssUnit> rows = grid.getRows(); List<List<String>> template = new ArrayList<List<String>>(grid.getTemplate()); // Clone the template so that the original isn't changed. for (ListIterator<List<String>> i = template.listIterator(); i.hasNext(); ) { i.set(new ArrayList<String>(i.next())); } Map<String, Area> areaInstances = new LinkedHashMap<String, Area>(); int clearAt = -1; for (int rowStart = 0, rowSize = rows.size(); rowStart < rowSize; ++ rowStart) { List<String> areas = template.get(rowStart); for (int columnStart = 0, columnSize = columns.size(); columnStart < columnSize; ++ columnStart) { String area = areas.get(columnStart); // Already processed or padding. if (area == null || ".".equals(area)) { continue; } int rowStop = rowStart + 1; int columnStop = columnStart + 1; // Figure out the "width" of the area. for (; columnStop < columnSize; ++ columnStop) { if (!ObjectUtils.equals(areas.get(columnStop), area)) { break; } else { areas.set(columnStop, null); } } // Figure out the "height" of the area. for (; rowStop < rowSize; ++ rowStop) { if (columnStart < template.get(rowStop).size() && !ObjectUtils.equals(template.get(rowStop).get(columnStart), area)) { break; } else { for (int i = columnStart; i < columnStop; ++ i) { if (i < template.get(rowStop).size()) { template.get(rowStop).set(i, null); } } } } // Figure out the rough initial position and size using // percentages. Area areaInstance = new Area(area); areaInstances.put(area, areaInstance); double frMax = 0; double frBefore = 0; double frAfter = 0; for (int i = 0; i < columnSize; ++ i) { CssUnit column = columns.get(i); if ("fr".equals(column.getUnit())) { double fr = column.getNumber(); frMax += fr; if (i < columnStart) { frBefore += fr; } else if (i >= columnStop) { frAfter += fr; } } } if (frMax == 0) { frMax = 1; frAfter = 1; } double frBeforeRatio = frBefore / frMax; double frAfterRatio = frAfter / frMax; areaInstance.frPaddingLeft = frBeforeRatio * 100.0; areaInstance.frWidth = (frMax - frBefore - frAfter) * 100.0 / frMax; // Adjust left and width. for (int i = 0; i < columnSize; ++ i) { CssUnit column = columns.get(i); String columnUnit = column.getUnit(); if (!"fr".equals(columnUnit)) { double columnNumber = column.getNumber(); double left = columnNumber * ((i < columnStart ? 1 : 0) - frBeforeRatio); double right = columnNumber * ((i >= columnStop ? 1 : 0) - frAfterRatio); if (left != 0.0 || right != 0.0) { Adjustment adjustment = areaInstance.getOrCreateAdjustment(columnUnit); adjustment.left += left; adjustment.right += right; } } } // Adjust top. for (int i = rowSize - 1; i >= 0; CssUnit row = rows.get(i); String rowUnit = row.getUnit(); if (i < rowStart && "auto".equals(rowUnit)) { break; } else if (!"fr".equals(rowUnit)) { double top = row.getNumber() * (i < rowStart ? 1 : 0); if (top != 0.0) { Adjustment adjustment = areaInstance.getOrCreateAdjustment(rowUnit); adjustment.top += top; } } } // Make sure there's always "px" adjustment layer so that // we can shift right 30000px to cancel out the positioning // from the main wrapping DIV. Adjustment pxAdjustment = areaInstance.adjustments.remove("px"); if (pxAdjustment == null) { pxAdjustment = new Adjustment(); } pxAdjustment.left += 30000; pxAdjustment.right -= 30000; areaInstance.adjustments.put("px", pxAdjustment); // Set width explicitly if there's only one unit. CombinedCssUnit width = areaInstance.width = new CombinedCssUnit(columns.subList(columnStart, columnStop)); CssUnit singleWidth = areaInstance.singleWidth = width.getSingle(); if (singleWidth != null) { pxAdjustment.width = singleWidth; } // Set height explicitly if there's only one unit. CombinedCssUnit height = areaInstance.height = new CombinedCssUnit(rows.subList(rowStart, rowStop)); CssUnit singleHeight = areaInstance.singleHeight = height.getSingle(); if (singleHeight != null) { pxAdjustment.height = singleHeight; } // Clear because of "auto" height? if (clearAt >= 0 && clearAt <= rowStart) { clearAt = -1; areaInstance.clear = true; } if (height.hasAuto() && rowStop > clearAt) { clearAt = rowStop; } } } return areaInstances; } public HtmlWriter grid(Object object, HtmlGrid grid) throws IOException { return grid(object, grid, false); } /** * Writes the given {@code object} and positions it according to the * grid rules as specified by the given parameters. * * @see #grid(Object, HtmlGrid) */ public HtmlWriter grid(Object object, String columns, String rows, String... template) throws IOException { return grid(object, new HtmlGrid(columns, rows, template)); } public static class Area { private final String name; protected final String id = "i" + UUID.randomUUID().toString().replaceAll("-", ""); protected boolean clear; protected double frPaddingLeft; protected double frWidth; protected CombinedCssUnit width; protected CssUnit singleWidth; protected CombinedCssUnit height; protected CssUnit singleHeight; protected final Map<String, Adjustment> adjustments = new LinkedHashMap<String, Adjustment>(); public Area(String name) { this.name = name; } public String getName() { return name; } protected Adjustment getOrCreateAdjustment(String unit) { Adjustment adjustment = adjustments.get(unit); if (adjustment == null) { adjustment = new Adjustment(); adjustments.put(unit, adjustment); } return adjustment; } } private class CombinedCssUnit { private final Map<String, CssUnit> combined = new HashMap<String, CssUnit>(); public CombinedCssUnit(Iterable<CssUnit> values) { for (CssUnit value : values) { String unit = value.getUnit(); CssUnit old = combined.get(unit); if (old == null) { combined.put(unit, value); } else { combined.put(unit, new CssUnit(old.getNumber() + value.getNumber(), unit)); } } for (Iterator<Map.Entry<String, CssUnit>> i = combined.entrySet().iterator(); i.hasNext(); ) { CssUnit value = i.next().getValue(); if (!"auto".equals(value.getUnit()) && value.getNumber() == 0.0) { i.remove(); } } } public Collection<CssUnit> getAll() { return combined.values(); } public CssUnit getSingle() { if (combined.size() != 1) { return null; } else { CssUnit value = combined.values().iterator().next(); return "fr".equals(value.getUnit()) ? null : value; } } public boolean hasAuto() { return combined.keySet().contains("auto"); } } private static class Adjustment { public double left; public double right; public double top; public CssUnit width; public CssUnit height; public String getMargin(String unit) { return new CssUnit(top, unit) + " " + new CssUnit(right, unit) + " 0 " + new CssUnit(left, unit); } } @Override public Writer append(char letter) throws IOException { writer.write(letter); return this; } @Override public Writer append(CharSequence text) throws IOException { writer.append(text); return this; } @Override public Writer append(CharSequence text, int start, int end) throws IOException { writer.append(text, start, end); return this; } @Override public void close() throws IOException { writer.close(); } @Override public void flush() throws IOException { writer.flush(); } @Override public void write(char[] buffer) throws IOException { writer.write(buffer); } @Override public void write(char[] buffer, int offset, int length) throws IOException { writer.write(buffer, offset, length); } @Override public void write(int letter) throws IOException { writer.write(letter); } @Override public void write(String text) throws IOException { writer.write(text); } @Override public void write(String text, int offset, int length) throws IOException { writer.write(text, offset, length); } /** {@link HtmlWriter} utility methods. */ public static final class Static { /** Returns a CSS string based on the given {@code properties}. */ public static String cssString(Object... properties) { StringBuilder css = new StringBuilder(); if (properties != null) { for (int i = 1, length = properties.length; i < length; i += 2) { Object property = properties[i - 1]; if (property != null) { Object value = properties[i]; if (value != null) { css.append(property); css.append(':'); css.append(value); css.append(';'); } } } } return css.toString(); } } /** @deprecated Use {@link #htmlOrDefault} instead. */ @Deprecated public HtmlWriter stringOrDefault(Object string, String defaultString) throws IOException { return htmlOrDefault(string, defaultString); } /** @deprecated Use {@link #html} instead. */ @Deprecated public HtmlWriter string(Object string) throws IOException { return html(string); } }
package com.gaiagps.iburn; import android.app.Activity; import android.content.Intent; import android.support.annotation.NonNull; import android.widget.Toast; import com.gaiagps.iburn.activity.PlayaItemViewActivity; public class IntentUtil { public static void viewItemDetail(@NonNull Activity host, int modelId, Constants.PlayaItemType type) { // Launch detail activity? if (type == Constants.PlayaItemType.POI) { Toast.makeText(host.getApplicationContext(), "MAYBE NEXT YEAR\n ¯\\_()_/¯", Toast.LENGTH_SHORT).show(); } else { Intent i = new Intent(host, PlayaItemViewActivity.class); i.putExtra(PlayaItemViewActivity.EXTRA_MODEL_ID, modelId); i.putExtra(PlayaItemViewActivity.EXTRA_MODEL_TYPE, type); host.startActivity(i); } } }
package edu.pdx.cs410J.grader; import com.google.common.collect.Sets; import com.google.common.io.ByteStreams; import java.io.*; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import java.util.stream.Collectors; class JarMaker { private final Map<Attributes.Name, String> manifestEntries; private final Map<File, String> sourceFilesAndNames; private final File jarFile; public JarMaker(Map<File, String> sourceFilesAndNames, File jarFile, Map<Attributes.Name, String> manifestEntries) { this.sourceFilesAndNames = sourceFilesAndNames; this.jarFile = jarFile; this.manifestEntries = manifestEntries; } public File makeJar() throws IOException { // Create a Manifest for the Jar file containing the name of the // author (userName) and a version that is based on the current // date/time. Manifest manifest = new Manifest(); addEntriesToMainManifest(manifest); // Create a JarOutputStream around the jar file JarOutputStream jos = new JarOutputStream(new FileOutputStream(jarFile), manifest); jos.setMethod(JarOutputStream.DEFLATED); // Add the source files to the Jar for (Map.Entry<File, String> fileEntry : sourceFilesAndNames.entrySet()) { File file = fileEntry.getKey(); String fileName = fileEntry.getValue(); System.out.println("Adding " + fileName + " to jar"); JarEntry entry = new JarEntry(fileName); entry.setTime(file.lastModified()); entry.setSize(file.length()); entry.setMethod(JarEntry.DEFLATED); // Add the entry to the JAR file jos.putNextEntry(entry); ByteStreams.copy(new FileInputStream(file), jos); jos.closeEntry(); } jos.close(); return jarFile; } private void addEntriesToMainManifest(Manifest manifest) { Attributes attrs = manifest.getMainAttributes(); // If a manifest doesn't have a version, the other attributes won't get written out. Lame. attrs.put(Attributes.Name.MANIFEST_VERSION, new Date().toString()); for (Map.Entry<Attributes.Name, String> entry : this.manifestEntries.entrySet()) { attrs.put(entry.getKey(), entry.getValue()); } } public static void main(String[] args) throws IOException { String jarFileName = null; Set<File> files = Sets.newHashSet(); for (String arg : args) { if (jarFileName == null) { jarFileName = arg; } else { File file = new File(arg); if (file.exists()) { files.add(file); } } } if (jarFileName == null) { usage("Missing jar file name"); } if (files.isEmpty()) { usage("Missing files"); } Map<File, String> sourceFilesAndNames = files.stream().collect(Collectors.toMap(file -> file, File::getPath)); assert jarFileName != null; File jarFile = new File(jarFileName); Map<Attributes.Name, String> manifestEntries = new HashMap<>(); manifestEntries.put(new Attributes.Name("Created-By"), System.getProperty("user.name")); manifestEntries.put(Attributes.Name.MANIFEST_VERSION, new Date().toString()); new JarMaker(sourceFilesAndNames, jarFile, manifestEntries).makeJar(); } private static void usage(String message) { PrintStream err = System.err; err.println("** " + message); err.println("java JarMaker jarFileName files+"); err.println(" jarFileName The name of the jar file to create"); err.println(" files+ One or more files to include in the jar"); err.println(); System.exit(1); } }
package com.vip.saturn.job.basic; import com.vip.saturn.job.exception.SaturnJobException; import com.vip.saturn.job.internal.config.ConfigurationService; import com.vip.saturn.job.utils.AlarmUtils; import com.vip.saturn.job.utils.UpdateJobCronUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; /** * Provide the hook for client job callback. */ public class SaturnApi { private static Logger logger = LoggerFactory.getLogger(SaturnApi.class); private String namespace; private String executorName; public SaturnApi(String namespace, String executorName) { this.namespace = namespace; this.executorName = executorName; } // Make sure that only SaturnApi(String namespace) will be called. private SaturnApi() { } public void updateJobCron(String jobName, String cron, Map<String, String> customContext) throws SaturnJobException { try { UpdateJobCronUtils.updateJobCron(namespace, jobName, cron, customContext); } catch (SaturnJobException se) { logger.error("SaturnJobException throws: {}", se.getMessage()); throw se; } catch (Exception e) { logger.error("Other exception throws: {}", e.getMessage()); throw new SaturnJobException(SaturnJobException.SYSTEM_ERROR, e.getMessage(), e); } } /** * The hook for client job raise alarm. * * @param alarmInfo The alarm information. */ public void raiseAlarm(Map<String, Object> alarmInfo) throws SaturnJobException { // set executorName into the alarmInfo alarmInfo.put("executorName", executorName); AlarmUtils.raiseAlarm(alarmInfo, namespace); } }
package com.digi.xbee.api; import java.io.IOException; import java.util.Arrays; import com.digi.xbee.api.connection.DataReader; import com.digi.xbee.api.connection.IConnectionInterface; import com.digi.xbee.api.connection.serial.SerialPortParameters; import com.digi.xbee.api.exceptions.InterfaceAlreadyOpenException; import com.digi.xbee.api.exceptions.InterfaceNotOpenException; import com.digi.xbee.api.exceptions.InvalidOperatingModeException; import com.digi.xbee.api.exceptions.OperationNotSupportedException; import com.digi.xbee.api.exceptions.TimeoutException; import com.digi.xbee.api.exceptions.XBeeException; import com.digi.xbee.api.listeners.IIOSampleReceiveListener; import com.digi.xbee.api.listeners.IModemStatusReceiveListener; import com.digi.xbee.api.listeners.IPacketReceiveListener; import com.digi.xbee.api.listeners.IDataReceiveListener; import com.digi.xbee.api.models.ATCommand; import com.digi.xbee.api.models.ATCommandResponse; import com.digi.xbee.api.models.OperatingMode; import com.digi.xbee.api.models.XBee16BitAddress; import com.digi.xbee.api.models.XBee64BitAddress; import com.digi.xbee.api.models.XBeeMessage; import com.digi.xbee.api.models.XBeePacketsQueue; import com.digi.xbee.api.models.XBeeTransmitOptions; import com.digi.xbee.api.packet.APIFrameType; import com.digi.xbee.api.packet.XBeeAPIPacket; import com.digi.xbee.api.packet.XBeePacket; import com.digi.xbee.api.packet.common.ReceivePacket; import com.digi.xbee.api.packet.common.TransmitPacket; import com.digi.xbee.api.packet.raw.RX16Packet; import com.digi.xbee.api.packet.raw.RX64Packet; import com.digi.xbee.api.packet.raw.TX64Packet; import com.digi.xbee.api.utils.HexUtils; /** * This class represents a local XBee device. * * @see DigiMeshDevice * @see DigiPointDevice * @see Raw802Device * @see ZigBeeDevice */ public class XBeeDevice extends AbstractXBeeDevice { // Constants. private static int TIMEOUT_RESET = 5000; private static int TIMEOUT_READ_PACKET = 3000; private static String COMMAND_MODE_CHAR = "+"; private static String COMMAND_MODE_OK = "OK\r"; // Variables. protected XBeeNetwork network; private Object resetLock = new Object(); private boolean modemStatusReceived = false; public XBeeDevice(String port, int baudRate) { super(port, baudRate); } public XBeeDevice(String port, int baudRate, int dataBits, int stopBits, int parity, int flowControl) { super(port, baudRate, dataBits, stopBits, parity, flowControl); } /** * Class constructor. Instantiates a new {@code XBeeDevice} object in the * given serial port name and parameters. * * @param port Serial port name where XBee device is attached to. * @param serialPortParameters Object containing the serial port parameters. * * @throws NullPointerException if {@code port == null} or * if {@code serialPortParameters == null}. * * @see SerialPortParameters */ public XBeeDevice(String port, SerialPortParameters serialPortParameters) { super(port, serialPortParameters); } /** * Class constructor. Instantiates a new {@code XBeeDevice} object with the * given connection interface. * * @param connectionInterface The connection interface with the physical * XBee device. * * @throws NullPointerException if {@code connectionInterface == null}. * * @see IConnectionInterface */ public XBeeDevice(IConnectionInterface connectionInterface) { super(connectionInterface); } /** * Opens the connection interface associated with this XBee device. * * @throws XBeeException if there is any problem opening the device. * @throws InterfaceAlreadyOpenException if the device is already open. * * @see #isOpen() * @see #close() */ public void open() throws XBeeException { logger.info(toString() + "Opening the connection interface..."); // First, verify that the connection is not already open. if (connectionInterface.isOpen()) throw new InterfaceAlreadyOpenException(); // Connect the interface. connectionInterface.open(); logger.info(toString() + "Connection interface open."); // Initialize the data reader. dataReader = new DataReader(connectionInterface, operatingMode, this); dataReader.start(); // Wait 10 milliseconds until the dataReader thread is started. // This is because when the connection is opened immediately after // closing it, there is sometimes a concurrency problem and the // dataReader thread never dies. try { Thread.sleep(10); } catch (InterruptedException e) {} // Determine the operating mode of the XBee device if it is unknown. if (operatingMode == OperatingMode.UNKNOWN) operatingMode = determineOperatingMode(); // Check if the operating mode is a valid and supported one. if (operatingMode == OperatingMode.UNKNOWN) { close(); throw new InvalidOperatingModeException("Could not determine operating mode."); } else if (operatingMode == OperatingMode.AT) { close(); throw new InvalidOperatingModeException(operatingMode); } // Read the device info (obtain its parameters and protocol). readDeviceInfo(); } /** * Closes the connection interface associated with this XBee device. * * @see #isOpen() * @see #open() */ public void close() { // Stop XBee reader. if (dataReader != null && dataReader.isRunning()) dataReader.stopReader(); // Close interface. connectionInterface.close(); logger.info(toString() + "Connection interface closed."); } /** * Retrieves whether or not the connection interface associated to the * device is open. * * @return {@code true} if the interface is open, {@code false} otherwise. * * @see #open() * @see #close() */ public boolean isOpen() { if (connectionInterface != null) return connectionInterface.isOpen(); return false; } /* * (non-Javadoc) * @see com.digi.xbee.api.AbstractXBeeDevice#isRemote() */ @Override public boolean isRemote() { return false; } /** * Returns the network associated with the device. * * @return The XBee network of the device. * * @throws InterfaceNotOpenException If the device is not open. * * @see XBeeNetwork */ public XBeeNetwork getNetwork() { if (!isOpen()) throw new InterfaceNotOpenException(); if (network == null) network = new XBeeNetwork(this); return network; } /* * (non-Javadoc) * @see com.digi.xbee.api.AbstractXBeeDevice#getOperatingMode() */ @Override public OperatingMode getOperatingMode() { return super.getOperatingMode(); } /* * (non-Javadoc) * @see com.digi.xbee.api.AbstractXBeeDevice#getNextFrameID() */ @Override protected int getNextFrameID() { return super.getNextFrameID(); } /** * Retrieves the configured timeout for receiving packets in synchronous * operations. * * @return The current receive timeout in milliseconds. * * @see #setReceiveTimeout(int) */ public int getReceiveTimeout() { return receiveTimeout; } public void setReceiveTimeout(int receiveTimeout) { if (receiveTimeout < 0) throw new IllegalArgumentException("Receive timeout cannot be less than 0."); this.receiveTimeout = receiveTimeout; } /** * Determines the operating mode of the XBee device. * * @return The operating mode of the XBee device. * * @throws OperationNotSupportedException if the packet is being sent from * a remote device. * @throws InterfaceNotOpenException if the device is not open. * * @see OperatingMode */ protected OperatingMode determineOperatingMode() throws OperationNotSupportedException { try { // Check if device is in API or API Escaped operating modes. operatingMode = OperatingMode.API; dataReader.setXBeeReaderMode(operatingMode); ATCommandResponse response = sendATCommand(new ATCommand("AP")); if (response.getResponse() != null && response.getResponse().length > 0) { if (response.getResponse()[0] != OperatingMode.API.getID()) operatingMode = OperatingMode.API_ESCAPE; logger.debug(toString() + "Using {}.", operatingMode.getName()); return operatingMode; } } catch (TimeoutException e) { // Check if device is in AT operating mode. operatingMode = OperatingMode.AT; dataReader.setXBeeReaderMode(operatingMode); try { // It is necessary to wait at least 1 second to enter in command mode after // sending any data to the device. Thread.sleep(TIMEOUT_BEFORE_COMMAND_MODE); // Try to enter in AT command mode, if so the module is in AT mode. boolean success = enterATCommandMode(); if (success) return OperatingMode.AT; } catch (TimeoutException e1) { logger.error(e1.getMessage(), e1); } catch (InvalidOperatingModeException e1) { logger.error(e1.getMessage(), e1); } catch (InterruptedException e1) { logger.error(e1.getMessage(), e1); } } catch (InvalidOperatingModeException e) { logger.error("Invalid operating mode", e); } catch (IOException e) { logger.error(e.getMessage(), e); } return OperatingMode.UNKNOWN; } /** * Attempts to put the device in AT Command mode. Only valid if device is * working in AT mode. * * @return {@code true} if the device entered in AT command mode, * {@code false} otherwise. * * @throws InvalidOperatingModeException if the operating mode cannot be * determined or is not supported. * @throws TimeoutException if the configured time expires. * @throws InterfaceNotOpenException if the device is not open. */ private boolean enterATCommandMode() throws InvalidOperatingModeException, TimeoutException { if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); if (operatingMode != OperatingMode.AT) throw new InvalidOperatingModeException("Invalid mode. Command mode can be only accessed while in AT mode."); // Enter in AT command mode (send '+++'). The process waits 1,5 seconds for the 'OK\n'. byte[] readData = new byte[256]; try { // Send the command mode sequence. connectionInterface.writeData(COMMAND_MODE_CHAR.getBytes()); connectionInterface.writeData(COMMAND_MODE_CHAR.getBytes()); connectionInterface.writeData(COMMAND_MODE_CHAR.getBytes()); // Wait some time to let the module generate a response. Thread.sleep(TIMEOUT_ENTER_COMMAND_MODE); // Read data from the device (it should answer with 'OK\r'). int readBytes = connectionInterface.readData(readData); if (readBytes < COMMAND_MODE_OK.length()) throw new TimeoutException(); // Check if the read data is 'OK\r'. String readString = new String(readData, 0, readBytes); if (!readString.contains(COMMAND_MODE_OK)) return false; // Read data was 'OK\r'. return true; } catch (IOException e) { logger.error(e.getMessage(), e); } catch (InterruptedException e) { logger.error(e.getMessage(), e); } return false; } /* * (non-Javadoc) * @see com.digi.xbee.api.AbstractXBeeDevice#addPacketListener(com.digi.xbee.api.listeners.IPacketReceiveListener) */ @Override public void addPacketListener(IPacketReceiveListener listener) { super.addPacketListener(listener); } /* * (non-Javadoc) * @see com.digi.xbee.api.AbstractXBeeDevice#removePacketListener(com.digi.xbee.api.listeners.IPacketReceiveListener) */ @Override public void removePacketListener(IPacketReceiveListener listener) { super.removePacketListener(listener); } /* * (non-Javadoc) * @see com.digi.xbee.api.AbstractXBeeDevice#addDataListener(com.digi.xbee.api.listeners.IDataReceiveListener) */ @Override public void addDataListener(IDataReceiveListener listener) { super.addDataListener(listener); } /* * (non-Javadoc) * @see com.digi.xbee.api.AbstractXBeeDevice#removeDataListener(com.digi.xbee.api.listeners.IDataReceiveListener) */ @Override public void removeDataListener(IDataReceiveListener listener) { super.removeDataListener(listener); } /* * (non-Javadoc) * @see com.digi.xbee.api.AbstractXBeeDevice#addIOSampleListener(com.digi.xbee.api.listeners.IIOSampleReceiveListener) */ @Override public void addIOSampleListener(IIOSampleReceiveListener listener) { super.addIOSampleListener(listener); } /* * (non-Javadoc) * @see com.digi.xbee.api.AbstractXBeeDevice#removeIOSampleListener(com.digi.xbee.api.listeners.IIOSampleReceiveListener) */ @Override public void removeIOSampleListener(IIOSampleReceiveListener listener) { super.removeIOSampleListener(listener); } /* * (non-Javadoc) * @see com.digi.xbee.api.AbstractXBeeDevice#addModemStatusListener(com.digi.xbee.api.listeners.IModemStatusReceiveListener) */ @Override public void addModemStatusListener(IModemStatusReceiveListener listener) { super.addModemStatusListener(listener); } /* * (non-Javadoc) * @see com.digi.xbee.api.AbstractXBeeDevice#removeModemStatusListener(com.digi.xbee.api.listeners.IModemStatusReceiveListener) */ @Override public void removeModemStatusListener(IModemStatusReceiveListener listener) { super.removeModemStatusListener(listener); } /** * Sends the provided data to the XBee device of the network corresponding * to the given 64-bit address asynchronously. * * <p>Asynchronous transmissions do not wait for answer from the remote * device or for transmit status packet.</p> * * @param address The 64-bit address of the XBee that will receive the data. * @param data Byte array containing data to be sent. * * @throws XBeeException if there is any XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code address == null} or * if {@code data == null}. * * @see XBee64BitAddress * @see #sendDataAsync(RemoteXBeeDevice, byte[]) * @see #sendDataAsync(XBee64BitAddress, XBee16BitAddress, byte[]) * @see #sendData(RemoteXBeeDevice, byte[]) * @see #sendData(XBee64BitAddress, byte[]) * @see #sendData(XBee64BitAddress, XBee16BitAddress, byte[]) */ protected void sendDataAsync(XBee64BitAddress address, byte[] data) throws XBeeException { // Verify the parameters are not null, if they are null, throw an exception. if (address == null) throw new NullPointerException("Address cannot be null"); if (data == null) throw new NullPointerException("Data cannot be null"); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Check if device is remote. if (isRemote()) throw new OperationNotSupportedException("Cannot send data to a remote device from a remote device."); logger.debug(toString() + "Sending data asynchronously to {} >> {}.", address, HexUtils.prettyHexString(data)); XBeePacket xbeePacket; switch (getXBeeProtocol()) { case RAW_802_15_4: xbeePacket = new TX64Packet(getNextFrameID(), address, XBeeTransmitOptions.NONE, data); break; default: xbeePacket = new TransmitPacket(getNextFrameID(), address, XBee16BitAddress.UNKNOWN_ADDRESS, 0, XBeeTransmitOptions.NONE, data); } sendAndCheckXBeePacket(xbeePacket, true); } /** * Sends the provided data to the XBee device of the network corresponding * to the given 64-Bit/16-Bit address asynchronously. * * <p>Asynchronous transmissions do not wait for answer from the remote * device or for transmit status packet.</p> * * @param address64Bit The 64-bit address of the XBee that will receive the * data. * @param address16bit The 16-bit address of the XBee that will receive the * data. If it is unknown the * {@code XBee16BitAddress.UNKNOWN_ADDRESS} must be used. * @param data Byte array containing data to be sent. * * @throws XBeeException if a remote device is trying to send data or * if there is any other XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code address64Bit == null} or * if {@code address16bit == null} or * if {@code data == null}. * * @see XBee64BitAddress * @see XBee16BitAddress * @see #getReceiveTimeout() * @see #setReceiveTimeout(int) * @see #sendDataAsync(RemoteXBeeDevice, byte[]) * @see #sendDataAsync(XBee64BitAddress, byte[]) * @see #sendData(RemoteXBeeDevice, byte[]) * @see #sendData(XBee64BitAddress, byte[]) * @see #sendData(XBee64BitAddress, XBee16BitAddress, byte[]) */ protected void sendDataAsync(XBee64BitAddress address64Bit, XBee16BitAddress address16bit, byte[] data) throws XBeeException { // Verify the parameters are not null, if they are null, throw an exception. if (address64Bit == null) throw new NullPointerException("64-bit address cannot be null"); if (address16bit == null) throw new NullPointerException("16-bit address cannot be null"); if (data == null) throw new NullPointerException("Data cannot be null"); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Check if device is remote. if (isRemote()) throw new OperationNotSupportedException("Cannot send data to a remote device from a remote device."); logger.debug(toString() + "Sending data asynchronously to {}[{}] >> {}.", address64Bit, address16bit, HexUtils.prettyHexString(data)); XBeePacket xbeePacket = new TransmitPacket(getNextFrameID(), address64Bit, address16bit, 0, XBeeTransmitOptions.NONE, data); sendAndCheckXBeePacket(xbeePacket, true); } /** * Sends the provided data to the provided XBee device asynchronously. * * <p>Asynchronous transmissions do not wait for answer from the remote * device or for transmit status packet.</p> * * @param xbeeDevice The XBee device of the network that will receive the data. * @param data Byte array containing data to be sent. * * @throws XBeeException if there is any XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code xbeeDevice == null} or * if {@code data == null}. * * @see #sendData(RemoteXBeeDevice, byte[]) */ public void sendDataAsync(RemoteXBeeDevice xbeeDevice, byte[] data) throws XBeeException { if (xbeeDevice == null) throw new NullPointerException("Remote XBee device cannot be null"); sendDataAsync(xbeeDevice.get64BitAddress(), data); } /** * Sends the provided data to the XBee device of the network corresponding * to the given 64-bit address. * * <p>This method blocks till a success or error response arrives or the * configured receive timeout expires.</p> * * <p>The received timeout is configured using the {@code setReceiveTimeout} * method and can be consulted with {@code getReceiveTimeout} method.</p> * * <p>For non-blocking operations use the method * {@link #sendData(XBee64BitAddress, byte[])}.</p> * * @param address The 64-bit address of the XBee that will receive the data. * @param data Byte array containing data to be sent. * * @throws TimeoutException if there is a timeout sending the data. * @throws XBeeException if there is any other XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code address == null} or * if {@code data == null}. * * @see XBee64BitAddress * @see #getReceiveTimeout() * @see #setReceiveTimeout(int) * @see #sendData(RemoteXBeeDevice, byte[]) * @see #sendData(XBee64BitAddress, XBee16BitAddress, byte[]) * @see #sendDataAsync(RemoteXBeeDevice, byte[]) * @see #sendDataAsync(XBee64BitAddress, byte[]) * @see #sendDataAsync(XBee64BitAddress, XBee16BitAddress, byte[]) */ protected void sendData(XBee64BitAddress address, byte[] data) throws TimeoutException, XBeeException { // Verify the parameters are not null, if they are null, throw an exception. if (address == null) throw new NullPointerException("Address cannot be null"); if (data == null) throw new NullPointerException("Data cannot be null"); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Check if device is remote. if (isRemote()) throw new OperationNotSupportedException("Cannot send data to a remote device from a remote device."); logger.debug(toString() + "Sending data to {} >> {}.", address, HexUtils.prettyHexString(data)); XBeePacket xbeePacket; switch (getXBeeProtocol()) { case RAW_802_15_4: xbeePacket = new TX64Packet(getNextFrameID(), address, XBeeTransmitOptions.NONE, data); break; default: xbeePacket = new TransmitPacket(getNextFrameID(), address, XBee16BitAddress.UNKNOWN_ADDRESS, 0, XBeeTransmitOptions.NONE, data); } sendAndCheckXBeePacket(xbeePacket, false); } /** * Sends the provided data to the XBee device of the network corresponding * to the given 64-Bit/16-Bit address. * * <p>This method blocks till a success or error response arrives or the * configured receive timeout expires.</p> * * <p>The received timeout is configured using the {@code setReceiveTimeout} * method and can be consulted with {@code getReceiveTimeout} method.</p> * * <p>For non-blocking operations use the method * {@link #sendDataAsync(XBee64BitAddress, XBee16BitAddress, byte[])}.</p> * * @param address64Bit The 64-bit address of the XBee that will receive the * data. * @param address16bit The 16-bit address of the XBee that will receive the * data. If it is unknown the * {@code XBee16BitAddress.UNKNOWN_ADDRESS} must be used. * @param data Byte array containing data to be sent. * * @throws TimeoutException if there is a timeout sending the data. * @throws XBeeException if a remote device is trying to send data or * if there is any other XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code address64Bit == null} or * if {@code address16bit == null} or * if {@code data == null}. * * @see XBee64BitAddress * @see XBee16BitAddress * @see #getReceiveTimeout() * @see #setReceiveTimeout(int) * @see #sendData(RemoteXBeeDevice, byte[]) * @see #sendData(XBee64BitAddress, byte[]) * @see #sendDataAsync(RemoteXBeeDevice, byte[]) * @see #sendDataAsync(XBee64BitAddress, byte[]) * @see #sendDataAsync(XBee64BitAddress, XBee16BitAddress, byte[]) */ protected void sendData(XBee64BitAddress address64Bit, XBee16BitAddress address16bit, byte[] data) throws TimeoutException, XBeeException { // Verify the parameters are not null, if they are null, throw an exception. if (address64Bit == null) throw new NullPointerException("64-bit address cannot be null"); if (address16bit == null) throw new NullPointerException("16-bit address cannot be null"); if (data == null) throw new NullPointerException("Data cannot be null"); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Check if device is remote. if (isRemote()) throw new OperationNotSupportedException("Cannot send data to a remote device from a remote device."); logger.debug(toString() + "Sending data to {}[{}] >> {}.", address64Bit, address16bit, HexUtils.prettyHexString(data)); XBeePacket xbeePacket = new TransmitPacket(getNextFrameID(), address64Bit, address16bit, 0, XBeeTransmitOptions.NONE, data); sendAndCheckXBeePacket(xbeePacket, false); } /** * Sends the provided data to the given XBee device choosing the optimal send method * depending on the protocol of the local XBee device. * * <p>This method blocks till a success or error response arrives or the * configured receive timeout expires.</p> * * <p>The received timeout is configured using the {@code setReceiveTimeout} * method and can be consulted with {@code getReceiveTimeout} method.</p> * * <p>For non-blocking operations use the method * {@link #sendDataAsync(RemoteXBeeDevice, byte[])}.</p> * * @param xbeeDevice The XBee device of the network that will receive the data. * @param data Byte array containing data to be sent. * * @throws TimeoutException if there is a timeout sending the data. * @throws XBeeException if there is any other XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code xbeeDevice == null} or * if {@code data == null}. * * @see #getReceiveTimeout() * @see #setReceiveTimeout(int) * @see #sendDataAsync(RemoteXBeeDevice, byte[]) */ public void sendData(RemoteXBeeDevice xbeeDevice, byte[] data) throws TimeoutException, XBeeException { if (xbeeDevice == null) throw new NullPointerException("Remote XBee device cannot be null"); switch (getXBeeProtocol()) { case ZIGBEE: case DIGI_POINT: if (xbeeDevice.get64BitAddress() != null && xbeeDevice.get16BitAddress() != null) sendData(xbeeDevice.get64BitAddress(), xbeeDevice.get16BitAddress(), data); else sendData(xbeeDevice.get64BitAddress(), data); break; case RAW_802_15_4: if (this instanceof Raw802Device) { if (xbeeDevice.get64BitAddress() != null) ((Raw802Device)this).sendData(xbeeDevice.get64BitAddress(), data); else ((Raw802Device)this).sendData(xbeeDevice.get16BitAddress(), data); } else sendData(xbeeDevice.get64BitAddress(), data); break; case DIGI_MESH: default: sendData(xbeeDevice.get64BitAddress(), data); } } /** * Sends the provided data to all the XBee nodes of the network (broadcast). * * <p>This method blocks till a success or error transmit status arrives or * the configured receive timeout expires.</p> * * <p>The received timeout is configured using the {@code setReceiveTimeout} * method and can be consulted with {@code getReceiveTimeout} method.</p> * * @param data Byte array containing data to be sent. * * @throws NullPointerException if {@code data == null}. * @throws InterfaceNotOpenException if the device is not open. * @throws TimeoutException if there is a timeout sending the data. * @throws XBeeException if there is any other XBee related exception. * * @see #getReceiveTimeout() * @see #setReceiveTimeout(int) */ public void sendBroadcastData(byte[] data) throws TimeoutException, XBeeException { sendData(XBee64BitAddress.BROADCAST_ADDRESS, data); } /** * Sends the given XBee packet and registers the given packet listener * (if not {@code null}) to wait for an answer. * * @param packet XBee packet to be sent. * @param packetReceiveListener Listener for the operation, {@code null} * not to be notified when the answer arrives. * * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code packet == null}. * @throws XBeeException if there is any other XBee related exception. * * @see XBeePacket * @see IPacketReceiveListener * @see #sendXBeePacket(XBeePacket) * @see #sendXBeePacketAsync(XBeePacket) */ public void sendPacket(XBeePacket packet, IPacketReceiveListener packetReceiveListener) throws XBeeException { try { sendXBeePacket(packet, packetReceiveListener); } catch (IOException e) { throw new XBeeException("Error writing in the communication interface.", e); } } /** * Sends the given XBee packet asynchronously. * * <p>To be notified when the answer is received, use * {@link #sendXBeePacket(XBeePacket, IPacketReceiveListener)}.</p> * * @param packet XBee packet to be sent asynchronously. * * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code packet == null}. * @throws XBeeException if there is any other XBee related exception. * * @see XBeePacket * @see #sendXBeePacket(XBeePacket) * @see #sendXBeePacket(XBeePacket, IPacketReceiveListener) */ public void sendPacketAsync(XBeePacket packet) throws XBeeException { try { super.sendXBeePacket(packet, null); } catch (IOException e) { throw new XBeeException("Error writing in the communication interface.", e); } } /** * Sends the given XBee packet synchronously and blocks until the response * is received or the configured receive timeout expires. * * <p>The received timeout is configured using the {@code setReceiveTimeout} * method and can be consulted with {@code getReceiveTimeout} method.</p> * * <p>Use {@link #sendXBeePacketAsync(XBeePacket)} for non-blocking * operations.</p> * * @param packet XBee packet to be sent. * * @return An {@code XBeePacket} object containing the response of the sent * packet or {@code null} if there is no response. * * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code packet == null}. * @throws TimeoutException if there is a timeout sending the XBee packet. * @throws XBeeException if there is any other XBee related exception. * * @see XBeePacket * @see #sendXBeePacket(XBeePacket, IPacketReceiveListener) * @see #sendXBeePacketAsync(XBeePacket) * @see #setReceiveTimeout(int) * @see #getReceiveTimeout() */ public XBeePacket sendPacket(XBeePacket packet) throws TimeoutException, XBeeException { try { return super.sendXBeePacket(packet); } catch (IOException e) { throw new XBeeException("Error writing in the communication interface.", e); } } /** * Waits until a Modem Status packet with status 0x00 (hardware reset) or * 0x01 (Watchdog timer reset) is received or the timeout is reached. * * @return True if the Modem Status packet is received, false otherwise. */ private boolean waitForModemStatusPacket() { modemStatusReceived = false; addPacketListener(modemStatusListener); synchronized (resetLock) { try { resetLock.wait(TIMEOUT_RESET); } catch (InterruptedException e) { } } removePacketListener(modemStatusListener); return modemStatusReceived; } /** * Custom listener for Modem Status packets. * * <p>When a Modem Status packet is received with status 0x00 or 0x01, it * notifies the object that was waiting for the reception.</p> */ private IPacketReceiveListener modemStatusListener = new IPacketReceiveListener() { /* * (non-Javadoc) * @see com.digi.xbee.api.listeners.IPacketReceiveListener#packetReceived(com.digi.xbee.api.packet.XBeePacket) */ public void packetReceived(XBeePacket receivedPacket) { // Discard non API packets. if (!(receivedPacket instanceof XBeeAPIPacket)) return; byte[] hardwareReset = new byte[] {(byte) 0x8A, 0x00}; byte[] watchdogTimerReset = new byte[] {(byte) 0x8A, 0x01}; if (Arrays.equals(receivedPacket.getPacketData(), hardwareReset) || Arrays.equals(receivedPacket.getPacketData(), watchdogTimerReset)) { modemStatusReceived = true; // Continue execution by notifying the lock object. synchronized (resetLock) { resetLock.notify(); } } } }; /* * (non-Javadoc) * @see com.digi.xbee.api.AbstractXBeeDevice#reset() */ @Override public void reset() throws TimeoutException, XBeeException { // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); logger.info(toString() + "Resetting the local module..."); ATCommandResponse response = null; try { response = sendATCommand(new ATCommand("FR")); } catch (IOException e) { throw new XBeeException("Error writing in the communication interface.", e); } // Check if AT Command response is valid. checkATCommandResponseIsValid(response); // Wait for a Modem Status packet. if (!waitForModemStatusPacket()) throw new TimeoutException("Timeout waiting for the Modem Status packet."); logger.info(toString() + "Module reset successfully."); } /** * Retrieves an XBee Message object received by the local XBee device and * containing the data and the source address of the node that sent the * data. * * <p>The method will try to read (receive) a data packet during the configured * receive timeout.</p> * * @return An XBee Message object containing the data and the source address * of the node that sent the data. Null if the local device didn't * receive a data packet during the configured receive timeout. * * @throws InterfaceNotOpenException if the device is not open. * * @see XBeeMessage * @see #getReceiveTimeout() * @see #setReceiveTimeout(int) */ public XBeeMessage readData() { return readDataPacket(null, TIMEOUT_READ_PACKET); } public XBeeMessage readData(int timeout) { if (timeout < 0) throw new IllegalArgumentException("Read timeout must be 0 or greater."); return readDataPacket(null, timeout); } /** * Retrieves an XBee Message object received by the local XBee device that was * sent by the provided remote XBee device. The XBee Message contains the data * and the source address of the node that sent the data. * * <p>The method will try to read (receive) a data packet from the provided * remote device during the configured receive timeout.</p> * * @param remoteXBeeDevice The remote device to get a data packet from. * @return An XBee Message object containing the data and the source address * of the node that sent the data. Null if the local device didn't * receive a data packet from the remote XBee device during the * configured receive timeout. * * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code remoteXBeeDevice == null}. * * @see XBeeMessage * @see RemoteXBeeDevice * @see #getReceiveTimeout() * @see #setReceiveTimeout(int) */ public XBeeMessage readDataFrom(RemoteXBeeDevice remoteXBeeDevice) { if (remoteXBeeDevice == null) throw new NullPointerException("Remote XBee device cannot be null."); return readDataPacket(remoteXBeeDevice, TIMEOUT_READ_PACKET); } public XBeeMessage readDataFrom(RemoteXBeeDevice remoteXBeeDevice, int timeout) { if (remoteXBeeDevice == null) throw new NullPointerException("Remote XBee device cannot be null."); if (timeout < 0) throw new IllegalArgumentException("Read timeout must be 0 or greater."); return readDataPacket(remoteXBeeDevice, timeout); } /** * Retrieves an XBee Message object received by the local XBee device. The * XBee Message contains the data and the source address of the node that * sent the data. Depending on if the provided remote XBee device is null * or not, the method will get the first data packet read from any remote * XBee device or from the provided one. * * <p>The method will try to read (receive) a data packet from the provided * remote device or any other device during the provided timeout.</p> * * @param remoteXBeeDevice The remote device to get a data packet from. Null to * read a data packet sent by any remote XBee device. * @param timeout The time to wait for a data packet in milliseconds. * @return An XBee Message object containing the data and the source address * of the node that sent the data. * * @throws InterfaceNotOpenException if the device is not open. * * @see XBeeMessage * @see RemoteXBeeDevice */ private XBeeMessage readDataPacket(RemoteXBeeDevice remoteXBeeDevice, int timeout) { // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); XBeePacketsQueue xbeePacketsQueue = dataReader.getXBeePacketsQueue(); XBeePacket xbeePacket = null; if (remoteXBeeDevice != null) xbeePacket = xbeePacketsQueue.getFirstDataPacketFrom(remoteXBeeDevice, timeout); else xbeePacket = xbeePacketsQueue.getFirstDataPacket(timeout); if (xbeePacket == null) return null; // Obtain the source address and data from the packet. RemoteXBeeDevice remoteDevice; byte[] data; APIFrameType packetType = ((XBeeAPIPacket)xbeePacket).getFrameType(); switch (packetType) { case RECEIVE_PACKET: remoteDevice = new RemoteXBeeDevice(this, ((ReceivePacket)xbeePacket).get64bitSourceAddress()); data = ((ReceivePacket)xbeePacket).getRFData(); break; case RX_16: remoteDevice = new RemoteRaw802Device(this, ((RX16Packet)xbeePacket).get16bitSourceAddress()); data = ((RX16Packet)xbeePacket).getRFData(); break; case RX_64: remoteDevice = new RemoteXBeeDevice(this, ((RX64Packet)xbeePacket).get64bitSourceAddress()); data = ((RX64Packet)xbeePacket).getRFData(); break; default: return null; } // TODO: The remote XBee device should be retrieved from the XBee Network (contained // in the xbeeDevice variable). If the network does not contain such remote device, // then it should be instantiated and added there. // Create and return the XBee message. return new XBeeMessage(remoteDevice, data, ((XBeeAPIPacket)xbeePacket).isBroadcast()); } /* * (non-Javadoc) * @see com.digi.xbee.api.AbstractXBeeDevice#toString() */ @Override public String toString() { String id = getNodeID() == null ? "" : getNodeID(); String addr64 = get64BitAddress() == null || get64BitAddress() == XBee64BitAddress.UNKNOWN_ADDRESS ? "" : get64BitAddress().toString(); if (id.length() == 0 && addr64.length() == 0) return super.toString(); StringBuilder message = new StringBuilder(super.toString()); message.append(addr64); if (id.length() > 0) { message.append(" ("); message.append(id); message.append(")"); } message.append(" - "); return message.toString(); } }
package ly.count.android.sdk.messaging; import android.app.Activity; import android.app.ActivityManager; import android.app.AlertDialog; import android.app.Application; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.Typeface; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Parcelable; import android.util.Log; import android.view.Gravity; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; import java.util.Map; import java.util.Set; import ly.count.android.sdk.Countly; import ly.count.android.sdk.CountlyStore; import ly.count.android.sdk.Utils; /** * Just a public holder class for Messaging-related display logic, listeners, managers, etc. */ public class CountlyPush { public static final String EXTRA_ACTION_INDEX = "ly.count.android.sdk.CountlyPush.Action"; public static final String EXTRA_MESSAGE = "ly.count.android.sdk.CountlyPush.message"; public static final String EXTRA_INTENT = "ly.count.android.sdk.CountlyPush.intent"; public static final String CHANNEL_ID = "ly.count.android.sdk.CountlyPush.CHANNEL_ID"; public static final String NOTIFICATION_BROADCAST = "ly.count.android.sdk.CountlyPush.NOTIFICATION_BROADCAST"; private static Application.ActivityLifecycleCallbacks callbacks = null; private static Activity activity = null; private static Countly.CountlyMessagingMode mode = null; private static Countly.CountlyMessagingProvider provider = null; static Integer notificationAccentColor = null; /** * Read & connection timeout for rich push media download */ static int MEDIA_DOWNLOAD_TIMEOUT = 15000; /** * Maximum attempts to download a media for a rich push */ static int MEDIA_DOWNLOAD_ATTEMPTS = 3; @SuppressWarnings("FieldCanBeLocal") private static BroadcastReceiver notificationActionReceiver = null, consentReceiver = null; /** * Message object encapsulating data in {@code RemoteMessage} sent from Countly server. */ public interface Message extends Parcelable { /** * Countly internal message ID * * @return id string or {@code null} if no id in the message */ String id(); /** * Title of message * * @return title string or {@code null} if no title in the message */ String title(); /** * Message text itself * * @return message string or {@code null} if no message specified */ String message(); /** * Message sound. Default message is sent as "default" string, other sounds are * supposed to be sent as URI of sound from app resources. * * @return sound string or {@code null} if no sound specified */ String sound(); /** * Message badge if any * * @return message badge number or {@code null} if no badge specified */ Integer badge(); /** * Default message link to open * * @return message link Uri or {@code null} if no link specified */ Uri link(); /** * Message media URL to jpeg or png image * * @return message media URL or {@code null} if no media specified */ URL media(); /** * List of buttons to display along this message if any * * @return message buttons list or empty list if no buttons specified */ List<Button> buttons(); /** * Set of data keys sent in this message, includes all standard keys like "title" or "message" * * @return message data keys set */ Set<String> dataKeys(); /** * Check whether data contains the key specified * * @param key key String to look for * @return {@code true} if key exists in the data, {@code false} otherwise */ boolean has(String key); /** * Get data associated with the key specified * * @param key key String to look for * @return value String for the key or {@code null} if no such key exists in the data */ String data(String key); /** * Record action event occurrence for this message and put it to current session. * If no session is open at the moment, opens new session. * Event is recorded for a whole message, not for specific button. * * @param context Context to record action in */ void recordAction(Context context); /** * Record action event occurrence for a particular button index and put it to current session. * If no session is open at the moment, opens new session. * Event is recorded for a particular button, not for a whole message. * Behaviour is identical to {@link Button#recordAction(Context)} * * @param context Context to record action in * @param buttonIndex index of button to record Action on: first button has index 1, second one is 2 (0 is reserved for notification-wide action) * @see Button#index() * @see Button#recordAction(Context); */ void recordAction(Context context, int buttonIndex); } /** * Button encapsulates information about single button in {@link Message} payload */ public interface Button { /** * Button index, starts from 1 * * @return index of this button */ int index(); /** * Button title * * @return title of this button */ String title(); /** * Button link * * @return link of this button */ Uri link(); /** * Record action event for this button, usually after a click * * @param context Context to run in * @see Message#recordAction(Context, int) */ void recordAction(Context context); /** * Optional method to return icon code * * @return int resource code for {@link Notification.Action#getSmallIcon()} */ int icon(); } /** * Notification action (or contentIntent) receiver. Responsible for recording action event. * Starts: * - activity specified in last parameter of {@link #displayNotification(Context, Message, int, Intent)} if it's not {@code null}; * - currently active activity if there is one, see {@link #callbacks}; * - main activity otherwise. */ public static class NotificationBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent broadcast) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "[CountlyPush, NotificationBroadcastReceiver] Push broadcast receiver receiving message"); } broadcast.setExtrasClassLoader(CountlyPush.class.getClassLoader()); Intent intent = broadcast.getParcelableExtra(EXTRA_INTENT); intent.setExtrasClassLoader(CountlyPush.class.getClassLoader()); int index = intent.getIntExtra(EXTRA_ACTION_INDEX, 0); Bundle bundle = intent.getParcelableExtra(EXTRA_MESSAGE); if (bundle == null) { return; } Message message = bundle.getParcelable(EXTRA_MESSAGE); if (message == null) { return; } message.recordAction(context, index); final NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); if (manager != null) { manager.cancel(message.hashCode()); } Intent closeNotificationsPanel = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); context.sendBroadcast(closeNotificationsPanel); if (index == 0) { if (message.link() != null) { Intent i = new Intent(Intent.ACTION_VIEW, message.link()); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.putExtra(EXTRA_MESSAGE, bundle); i.putExtra(EXTRA_ACTION_INDEX, index); context.startActivity(i); } else { intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } } else { Intent i = new Intent(Intent.ACTION_VIEW, message.buttons().get(index - 1).link()); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.putExtra(EXTRA_MESSAGE, bundle); i.putExtra(EXTRA_ACTION_INDEX, index); context.startActivity(i); } // final NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); // if (manager != null) { // Log.d("cly", message.id() + ", code: " + message.hashCode()); // manager.cancel(message.hashCode()); } } /** * Listens for push consent given and sends existing token to the server if any. */ public static class ConsentBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent broadcast) { if (mode != null && provider != null && Countly.sharedInstance().getConsent(Countly.CountlyFeatureNames.push)) { String token = getToken(context, provider); if (token != null && !"".equals(token)) { onTokenRefresh(token, provider); } } } } /** * Retrieves current FCM token from FIREBASE_INSTANCEID_CLASS. * * @return token string or null if no token is currently available. */ private static String getToken(Context context, Countly.CountlyMessagingProvider prov) { try { if (prov == Countly.CountlyMessagingProvider.FCM) { Object instance = UtilsMessaging.reflectiveCall(FIREBASE_INSTANCEID_CLASS, null, "getInstance"); return (String) UtilsMessaging.reflectiveCall(FIREBASE_INSTANCEID_CLASS, instance, "getToken"); } else if (prov == Countly.CountlyMessagingProvider.HMS) { Object config = UtilsMessaging.reflectiveCallStrict(HUAWEI_CONFIG_CLASS, null, "fromContext", context, Context.class); if (config == null) { Log.e(Countly.TAG, "No Huawei Config"); return null; } Object appId = UtilsMessaging.reflectiveCall(HUAWEI_CONFIG_CLASS, config, "getString", "client/app_id"); if (appId == null || "".equals(appId)) { Log.e(Countly.TAG, "No Huawei app id in config"); return null; } Object instanceId = UtilsMessaging.reflectiveCallStrict(HUAWEI_INSTANCEID_CLASS, null, "getInstance", context, Context.class); if (instanceId == null) { Log.e(Countly.TAG, "No Huawei instance id class"); return null; } Object token = UtilsMessaging.reflectiveCall(HUAWEI_INSTANCEID_CLASS, instanceId, "getToken", appId, "HCM"); return (String) token; } else { return null; } } catch (Throwable logged) { Log.e(Countly.TAG, "[CountlyPush, getToken] Couldn't get token for Countly FCM", logged); return null; } } /** * Standard Countly logic for displaying a {@link Message} * * @param context context to run in (supposed to be called from {@code FirebaseMessagingService}) * @param data {@code RemoteMessage#getData()} result * @return {@code Boolean.TRUE} if displayed successfully, {@code Boolean.FALSE} if cannot display now, {@code null} if no Countly message is found in {@code data} */ public static Boolean displayMessage(Context context, final Map<String, String> data, final int notificationSmallIcon, final Intent notificationIntent) { return displayMessage(context, decodeMessage(data), notificationSmallIcon, notificationIntent); } /** * Standard Countly logic for displaying a {@link Message} * * @param context context to run in (supposed to be called from {@code FirebaseMessagingService}) * @param msg {@link Message} instance * @return {@code Boolean.TRUE} if displayed successfully, {@code Boolean.FALSE} if cannot display now, {@code null} if no Countly message is found in {@code data} */ public static Boolean displayMessage(final Context context, final Message msg, final int notificationSmallIcon, final Intent notificationIntent) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "[CountlyPush, displayMessage] Displaying push message"); } if (msg == null) { return null; } else if (msg.message() == null) { // nothing to display return null; } else if (isAppRunningInForeground(context)) { if (activity != null) { return displayDialog(activity, msg); } else { return displayNotification(context, msg, notificationSmallIcon, notificationIntent); } } else { return displayNotification(context, msg, notificationSmallIcon, notificationIntent); } } /** * Standard Countly logic for displaying a {@link Notification} based on the {@link Message} * * @param context context to run in * @param msg message to get information from * @param notificationSmallIcon smallIcon for notification {@link Notification#getSmallIcon()} * @param notificationIntent activity-starting intent to send when user taps on {@link Notification} or one of its {@link android.app.Notification.Action}s. Pass {@code null} to go with main activity. * @return {@code Boolean.TRUE} if displayed successfully, {@code Boolean.FALSE} if cannot display now, {@code null} if message is not displayable as {@link Notification} */ public static Boolean displayNotification(final Context context, final Message msg, final int notificationSmallIcon, final Intent notificationIntent) { if (!Countly.sharedInstance().getConsent(Countly.CountlyFeatureNames.push)) { return null; } if (msg == null) { return null; } else if (msg.title() == null && msg.message() == null) { return null; } if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "[CountlyPush, displayNotification] Displaying push notification"); } final NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); if (manager == null) { return Boolean.FALSE; } Intent broadcast = new Intent(NOTIFICATION_BROADCAST); broadcast.putExtra(EXTRA_INTENT, actionIntent(context, notificationIntent, msg, 0)); final Notification.Builder builder = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? new Notification.Builder(context.getApplicationContext(), CHANNEL_ID) : new Notification.Builder(context.getApplicationContext())) .setAutoCancel(true) .setSmallIcon(notificationSmallIcon) .setTicker(msg.message()) .setContentTitle(msg.title()) .setContentText(msg.message()); if (android.os.Build.VERSION.SDK_INT > 21) { if (notificationAccentColor != null) { builder.setColor(notificationAccentColor); } } builder.setAutoCancel(true) .setContentIntent(PendingIntent.getBroadcast(context, msg.hashCode(), broadcast, 0)); if (android.os.Build.VERSION.SDK_INT > 16) { builder.setStyle(new Notification.BigTextStyle().bigText(msg.message()).setBigContentTitle(msg.title())); } for (int i = 0; i < msg.buttons().size(); i++) { Button button = msg.buttons().get(i); broadcast = new Intent(NOTIFICATION_BROADCAST); broadcast.putExtra(EXTRA_INTENT, actionIntent(context, notificationIntent, msg, i + 1)); if (android.os.Build.VERSION.SDK_INT > 16) { builder.addAction(button.icon(), button.title(), PendingIntent.getBroadcast(context, msg.hashCode() + i + 1, broadcast, 0)); } } if (msg.sound() != null) { if (msg.sound().equals("default")) { builder.setDefaults(Notification.DEFAULT_SOUND); } else { builder.setSound(Uri.parse(msg.sound())); } } if (msg.media() != null) { loadImage(context, msg, new BitmapCallback() { @Override public void call(Bitmap bitmap) { if (android.os.Build.VERSION.SDK_INT > 16) { if (bitmap != null) { builder.setStyle(new Notification.BigPictureStyle() .bigPicture(bitmap) .setBigContentTitle(msg.title()) .setSummaryText(msg.message())); } manager.notify(msg.hashCode(), builder.build()); } } }, 1); } else { if (android.os.Build.VERSION.SDK_INT > 16) { manager.notify(msg.hashCode(), builder.build()); } } return Boolean.TRUE; } private static Intent actionIntent(Context context, Intent notificationIntent, Message message, int index) { Intent intent; if (notificationIntent == null) { intent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName()); } else { intent = (Intent) notificationIntent.clone(); } Bundle bundle = new Bundle(); bundle.putParcelable(EXTRA_MESSAGE, message); intent.putExtra(EXTRA_MESSAGE, bundle); intent.putExtra(EXTRA_ACTION_INDEX, index); return intent; } /** * Standard Countly logic for displaying a {@link AlertDialog} based on the {@link Message} * * @param activity context to run in * @param msg message to get information from * @return {@code Boolean.TRUE} if displayed successfully, {@code Boolean.FALSE} if cannot display now, {@code null} if message is not displayable as {@link Notification} */ public static Boolean displayDialog(final Activity activity, final Message msg) { if (!Countly.sharedInstance().getConsent(Countly.CountlyFeatureNames.push)) { return null; } if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "[CountlyPush, displayDialog] Displaying push dialog"); } loadImage(activity, msg, new BitmapCallback() { @Override public void call(Bitmap bitmap) { AlertDialog.Builder builder = new AlertDialog.Builder(activity); if (msg.media() != null) { addButtons(activity, builder, msg); final LinearLayout layout = new LinearLayout(activity); layout.setBackgroundColor(Color.TRANSPARENT); layout.setOrientation(LinearLayout.VERTICAL); int padding = (int) (10 * activity.getResources().getDisplayMetrics().density + 0.5f); if (msg.title() != null) { TextView textview = new TextView(activity); textview.setText(msg.title()); textview.setPadding(padding, padding, padding, padding); textview.setTypeface(null, Typeface.BOLD); textview.setGravity(Gravity.CENTER); layout.addView(textview); } if (bitmap != null) { ImageView imageView = new ImageView(activity); imageView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.TOP)); if (msg.media() != null) { imageView.setImageBitmap(bitmap); } imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setAdjustViewBounds(true); imageView.setPadding(padding, padding, padding, padding); layout.addView(imageView); } if (msg.message() != null) { TextView textview = new TextView(activity); textview.setText(msg.message()); textview.setPadding(padding, padding, padding, padding); layout.addView(textview); } builder.setView(layout); } else if (msg.link() != null) { if (msg.title() != null) { builder.setTitle(msg.title()); } if (msg.message() != null) { builder.setMessage(msg.message()); } if (msg.buttons().size() > 0) { addButtons(activity, builder, msg); } else { builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { msg.recordAction(activity, 0); dialog.dismiss(); Intent i = new Intent(Intent.ACTION_VIEW, msg.link()); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.putExtra(EXTRA_ACTION_INDEX, 0);// put zero because non 'button' action activity.startActivity(i); } }); } } else if (msg.message() != null) { if (msg.buttons().size() > 0) { addButtons(activity, builder, msg); } else { msg.recordAction(activity); } builder.setTitle(msg.title()); builder.setMessage(msg.message()); builder.setCancelable(true); builder.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { dialog.dismiss(); } }); } else { throw new IllegalStateException("Countly Message with UNKNOWN type in ProxyActivity"); } builder.create().show(); } }, 1); return Boolean.TRUE; } private static void addButtons(final Context context, final AlertDialog.Builder builder, final Message msg) { if (msg.buttons().size() > 0) { DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { msg.recordAction(context, which == DialogInterface.BUTTON_POSITIVE ? 2 : 1); Intent intent = new Intent(Intent.ACTION_VIEW, msg.buttons().get(which == DialogInterface.BUTTON_POSITIVE ? 1 : 0).link()); Bundle bundle = new Bundle(); bundle.putParcelable(EXTRA_MESSAGE, msg); intent.putExtra(EXTRA_MESSAGE, bundle); intent.putExtra(EXTRA_ACTION_INDEX, which == DialogInterface.BUTTON_POSITIVE ? 2 : 1); context.startActivity(intent); dialog.dismiss(); } }; builder.setNeutralButton(msg.buttons().get(0).title(), listener); if (msg.buttons().size() > 1) { builder.setPositiveButton(msg.buttons().get(1).title(), listener); } } } /** * Decode message from {@code RemoteMessage#getData()} map into {@link Message}. * * @param data map to decode * @return message instance or {@code null} if cannot decode */ public static Message decodeMessage(Map<String, String> data) { ModulePush.MessageImpl message = new ModulePush.MessageImpl(data); return message.id == null ? null : message; } /** * Token refresh callback to be called from {@code FirebaseInstanceIdService}. * * @param token String token to be sent to Countly server */ public static void onTokenRefresh(String token) { onTokenRefresh(token, Countly.CountlyMessagingProvider.FCM); } /** * Token refresh callback to be called from {@code FirebaseInstanceIdService}. * * @param token String token to be sent to Countly server * @param provider which provider the token belongs to */ public static void onTokenRefresh(String token, Countly.CountlyMessagingProvider provider) { if(!Countly.sharedInstance().isInitialized()){ //is some edge cases this might be called before the SDK is initialized if (Countly.sharedInstance().isLoggingEnabled()) { Log.i(Countly.TAG, "[CountlyPush, onTokenRefresh] SDK is not initialized, ignoring call"); } return; } if (!Countly.sharedInstance().getConsent(Countly.CountlyFeatureNames.push)) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.i(Countly.TAG, "[CountlyPush, onTokenRefresh] Consent not given, ignoring call"); } return; } if (Countly.sharedInstance().isLoggingEnabled()) { Log.i(Countly.TAG, "[CountlyPush, onTokenRefresh] Refreshing FCM push token, with mode: [" + mode + "] for [" + provider + "]"); } Countly.sharedInstance().onRegistrationId(token, mode, provider); } static final String FIREBASE_MESSAGING_CLASS = "com.google.firebase.messaging.FirebaseMessaging"; static final String FIREBASE_INSTANCEID_CLASS = "com.google.firebase.iid.FirebaseInstanceId"; static final String HUAWEI_MESSAGING_CLASS = "com.huawei.hms.push.HmsMessageService"; static final String HUAWEI_CONFIG_CLASS = "com.huawei.agconnect.config.AGConnectServicesConfig"; static final String HUAWEI_INSTANCEID_CLASS = "com.huawei.hms.aaid.HmsInstanceId"; @SuppressWarnings("unchecked") public static void init(final Application application, Countly.CountlyMessagingMode mode) throws IllegalStateException { init(application, mode, null); } @SuppressWarnings("unchecked") public static void init(final Application application, Countly.CountlyMessagingMode mode, Countly.CountlyMessagingProvider preferredProvider) throws IllegalStateException { if (application == null) { throw new IllegalStateException("Non null application must be provided!"); } // set preferred push provider CountlyPush.provider = preferredProvider; if (provider == null) { if (UtilsMessaging.reflectiveClassExists(FIREBASE_MESSAGING_CLASS)) { provider = Countly.CountlyMessagingProvider.FCM; } else if (UtilsMessaging.reflectiveClassExists(HUAWEI_MESSAGING_CLASS)) { provider = Countly.CountlyMessagingProvider.HMS; } } else if (provider == Countly.CountlyMessagingProvider.FCM && !UtilsMessaging.reflectiveClassExists(FIREBASE_MESSAGING_CLASS)) { provider = Countly.CountlyMessagingProvider.HMS; } else if (provider == Countly.CountlyMessagingProvider.HMS && !UtilsMessaging.reflectiveClassExists(HUAWEI_MESSAGING_CLASS)) { provider = Countly.CountlyMessagingProvider.FCM; } // print error in case preferred push provider is not available if (provider == Countly.CountlyMessagingProvider.FCM && !UtilsMessaging.reflectiveClassExists(FIREBASE_MESSAGING_CLASS)) { Log.e("Countly", "No FirebaseMessaging class in the class path. Please either add it to your gradle config or don't use CountlyPush."); return; } else if (provider == Countly.CountlyMessagingProvider.HMS && !UtilsMessaging.reflectiveClassExists(HUAWEI_MESSAGING_CLASS)) { Log.e("Countly", "No HmsMessageService class in the class path. Please either add it to your gradle config or don't use CountlyPush."); return; } else if (provider == null) { Log.e("Countly", "Neither FirebaseMessaging, nor HmsMessageService class in the class path. Please either add Firebase / Huawei dependencies or don't use CountlyPush."); return; } if (Countly.sharedInstance().isLoggingEnabled()) { Log.i(Countly.TAG, "[CountlyPush] Initializing Countly FCM push with mode: [" + mode + "] and [" + provider + "]"); } CountlyPush.mode = mode; CountlyStore.cacheLastMessagingMode(mode == Countly.CountlyMessagingMode.TEST ? 0 : 1, application); CountlyStore.storeMessagingProvider(provider == Countly.CountlyMessagingProvider.FCM ? 1 : 2, application); if (callbacks == null) { callbacks = new Application.ActivityLifecycleCallbacks() { @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { } @Override public void onActivityStarted(Activity activity) { CountlyPush.activity = activity; } @Override public void onActivityResumed(Activity activity) { } @Override public void onActivityPaused(Activity activity) { } @Override public void onActivityStopped(Activity activity) { if (activity.equals(CountlyPush.activity)) { CountlyPush.activity = null; } } @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) { } @Override public void onActivityDestroyed(Activity activity) { } }; application.registerActivityLifecycleCallbacks(callbacks); IntentFilter filter = new IntentFilter(); filter.addAction(NOTIFICATION_BROADCAST); notificationActionReceiver = new NotificationBroadcastReceiver(); application.registerReceiver(notificationActionReceiver, filter); filter = new IntentFilter(); filter.addAction(Countly.CONSENT_BROADCAST); consentReceiver = new ConsentBroadcastReceiver(); application.registerReceiver(consentReceiver, filter); } if (provider == Countly.CountlyMessagingProvider.HMS && Countly.sharedInstance().consent().getConsent(Countly.CountlyFeatureNames.push)) { String version = getEMUIVersion(); if (version.startsWith("10")) { new Thread(new Runnable() { @Override public void run() { String token = getToken(application, Countly.CountlyMessagingProvider.HMS); if (token != null && !"".equals(token)) { onTokenRefresh(token, Countly.CountlyMessagingProvider.HMS); } } }).start(); } } } private static String getEMUIVersion () { try { String line = Build.DISPLAY; int spaceIndex = line.indexOf(" "); int lastIndex = line.indexOf("("); if (lastIndex != -1) { return line.substring(spaceIndex, lastIndex).trim(); } else { return line.substring(spaceIndex).trim(); } } catch (Throwable t) { return ""; } } /** * Returns which messaging mode was used in the previous init * -1 - no data / no init has hapened * 0 - test mode * 1 - production mode */ public static int getLastMessagingMethod(Context context) { return CountlyStore.getLastMessagingMode(context); } public static void setNotificationAccentColor(int alpha, int red, int green, int blue) { alpha = Math.min(255, Math.max(0, alpha)); red = Math.min(255, Math.max(0, red)); green = Math.min(255, Math.max(0, green)); blue = Math.min(255, Math.max(0, blue)); if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "[CountlyPush] Calling [setNotificationAccentColor], [" + alpha + "][" + red + "][" + green + "][" + blue + "]"); } notificationAccentColor = Color.argb(alpha, red, green, blue); } /** * Check whether app is running in foreground. * * @param context context to check in * @return {@code true} if running in foreground, {@code false} otherwise */ private static boolean isAppRunningInForeground(Context context) { ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses(); if (appProcesses == null) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "[CountlyPush] Checking if app in foreground, NO"); } return false; } final String packageName = context.getPackageName(); for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) { if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "[CountlyPush] Checking if app in foreground, YES"); } return true; } } if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "[CountlyPush] Checking if app in foreground, NO"); } return false; } private interface BitmapCallback { void call(Bitmap bitmap); } private static void loadImage(final Context context, final Message msg, final BitmapCallback callback, final int attempt) { Utils.runInBackground(new Runnable() { @Override public void run() { final Bitmap[] bitmap = new Bitmap[] { null }; if (msg.media() != null) { HttpURLConnection connection = null; InputStream input = null; try { connection = (HttpURLConnection) msg.media().openConnection(); connection.setDoInput(true); connection.setConnectTimeout(MEDIA_DOWNLOAD_TIMEOUT); connection.setReadTimeout(MEDIA_DOWNLOAD_TIMEOUT); connection.connect(); input = connection.getInputStream(); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); byte[] buf = new byte[16384]; int read; while ((read = input.read(buf, 0, buf.length)) != -1) { bytes.write(buf, 0, read); } bytes.flush(); byte[] data = bytes.toByteArray(); bitmap[0] = BitmapFactory.decodeByteArray(data, 0, data.length); } catch (Exception e) { System.out.println("Cannot download message media " + e); if (attempt < MEDIA_DOWNLOAD_ATTEMPTS) { loadImage(context, msg, callback, attempt + 1); return; } } finally { if (input != null) { try { input.close(); } catch (IOException ignored) { } } if (connection != null) { try { connection.disconnect(); } catch (Throwable ignored) { } } } } new Handler(context.getMainLooper()).post(new Runnable() { @Override public void run() { callback.call(bitmap[0]); } }); } }); } }
package me.originqiu.library; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.TextView; import java.util.ArrayList; import java.util.List; public class EditTag extends FrameLayout implements View.OnClickListener { private FlowLayout mFlowLayout; private EditText mEditText; private int tagViewLayoutRes; private int inputTagLayoutRes; private int deleteModeBgRes; private Drawable defaultTagBg; private boolean isEditableStatus = true; private TextView lastSelectTagView; private List<String> mTagList = new ArrayList<>(); private boolean isDelAction = false; public EditTag(Context context) { this(context, null); } public EditTag(Context context, AttributeSet attrs) { this(context, attrs, 0); } public EditTag(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); TypedArray mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.EditTag); tagViewLayoutRes = mTypedArray.getResourceId(R.styleable.EditTag_tag_layout, R.layout.view_default_tag); inputTagLayoutRes = mTypedArray.getResourceId(R.styleable.EditTag_input_layout, R.layout.view_default_input_tag); deleteModeBgRes = mTypedArray.getResourceId(R.styleable.EditTag_delete_mode_bg, R.color.colorAccent); mTypedArray.recycle(); setupView(); } private void setupView() { mFlowLayout = new FlowLayout(getContext()); LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); mFlowLayout.setLayoutParams(layoutParams); addView(mFlowLayout); addInputTagView(); } private void addInputTagView() { mEditText = createInputTag(mFlowLayout); mEditText.setTag(new Object()); mEditText.setOnClickListener(this); setupListener(); mFlowLayout.addView(mEditText); isEditableStatus = true; } private void setupListener() { mEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { boolean isHandle = false; if (actionId == EditorInfo.IME_ACTION_DONE) { String tagContent = mEditText.getText().toString(); if (TextUtils.isEmpty(tagContent)) { // do nothing, or you can tip "can'nt add empty tag" } else { TextView tagTextView = createTag(mFlowLayout, tagContent); if (defaultTagBg == null) { defaultTagBg = tagTextView.getBackground(); } tagTextView.setOnClickListener(EditTag.this); mFlowLayout.addView(tagTextView, mFlowLayout.getChildCount() - 1); mTagList.add(tagContent); // reset action status mEditText.getText().clear(); mEditText.performClick(); isDelAction = false; isHandle = true; } } return isHandle; } }); mEditText.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { boolean isHandle = false; if (keyCode == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_DOWN) { String tagContent = mEditText.getText().toString(); if (TextUtils.isEmpty(tagContent)) { int tagCount = mFlowLayout.getChildCount(); if (lastSelectTagView == null && tagCount > 1) { if (isDelAction) { mFlowLayout.removeViewAt(tagCount - 2); mTagList.remove(tagCount - 2); isHandle = true; } else { TextView delActionTagView = (TextView) mFlowLayout.getChildAt(tagCount - 2); delActionTagView.setBackgroundDrawable(getDrawableByResId(deleteModeBgRes)); lastSelectTagView = delActionTagView; isDelAction = true; } } else { removeSelectedTag(); } } else { mEditText.getText().delete(tagContent.length() - 1, tagContent.length()); } } return isHandle; } }); } private void removeSelectedTag() { mFlowLayout.removeView(lastSelectTagView); int size = mTagList.size(); String delTagContent = lastSelectTagView.getText().toString(); for (int i = 0; i < size; i++) { if (delTagContent.equals(mTagList.get(i))) { mTagList.remove(i); break; } } lastSelectTagView = null; isDelAction = false; } private TextView createTag(ViewGroup parent, String s) { TextView tagTv = (TextView) LayoutInflater.from(getContext()) .inflate(tagViewLayoutRes, parent, false); tagTv.setText(s); return tagTv; } private EditText createInputTag(ViewGroup parent) { mEditText = (EditText) LayoutInflater.from(getContext()) .inflate(inputTagLayoutRes, parent, false); return mEditText; } private void addTagView() { int size = mTagList.size(); for (int i = 0; i < size; i++) { TextView tagTextView = createTag(mFlowLayout, mTagList.get(i)); if (defaultTagBg == null) { defaultTagBg = tagTextView.getBackground(); } tagTextView.setOnClickListener(this); if (isEditableStatus) { mFlowLayout.addView(tagTextView, mFlowLayout.getChildCount() - 1); } else { mFlowLayout.addView(tagTextView); } } } @Override public void onClick(View view) { if (view.getTag() == null && isEditableStatus) { // TextView tag click if (lastSelectTagView == null) { lastSelectTagView = (TextView) view; view.setBackgroundDrawable(getDrawableByResId(deleteModeBgRes)); } else { if (lastSelectTagView.equals(view)) { lastSelectTagView.setBackgroundDrawable(defaultTagBg); lastSelectTagView = null; } else { lastSelectTagView.setBackgroundDrawable(defaultTagBg); lastSelectTagView = (TextView) view; view.setBackgroundDrawable(getDrawableByResId(deleteModeBgRes)); } } } else { // EditText tag click if (lastSelectTagView != null) { lastSelectTagView.setBackgroundDrawable(defaultTagBg); lastSelectTagView = null; } } } private Drawable getDrawableByResId(int resId) { return getContext().getResources().getDrawable(resId); } public void setEditable(boolean editable) { if (editable) { if (!isEditableStatus) { mFlowLayout.addView((mEditText)); } } else { int childCount = mFlowLayout.getChildCount(); if (isEditableStatus && childCount > 0) { mFlowLayout.removeViewAt(childCount - 1); if (lastSelectTagView != null) { lastSelectTagView.setBackgroundDrawable(defaultTagBg); isDelAction = false; mEditText.getText().clear(); } } } this.isEditableStatus = editable; } public List<String> getTagList() { return mTagList; } public boolean addTag(String tagContent) { if (TextUtils.isEmpty(tagContent)) { // do nothing, or you can tip "can'nt add empty tag" return false; } else { TextView tagTextView = createTag(mFlowLayout, tagContent); if (defaultTagBg == null) { defaultTagBg = tagTextView.getBackground(); } tagTextView.setOnClickListener(EditTag.this); mFlowLayout.addView(tagTextView, mFlowLayout.getChildCount() - 1); mTagList.add(tagContent); // reset action status mEditText.getText().clear(); mEditText.performClick(); isDelAction = false; return true; } } public void setTagList(List<String> mTagList) { this.mTagList = mTagList; addTagView(); } }
package org.sejda.model.parameter; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; public class PageSize { private float width; private float height; private String name; /** user space units per inch */ private static final float POINTS_PER_INCH = 72; /** user space units per millimeter */ private static final float POINTS_PER_MM = 1 / (10 * 2.54f) * POINTS_PER_INCH; /** A rectangle the size of U.S. Letter, 8.5" x 11". */ public static final PageSize LETTER = new PageSize(8.5f * POINTS_PER_INCH, 11f * POINTS_PER_INCH, "Letter"); public static final PageSize LEGAL = new PageSize(8.5f * POINTS_PER_INCH, 14f * POINTS_PER_INCH, "Legal"); /** A rectangle the size of A0 Paper. */ public static final PageSize A0 = new PageSize(841 * POINTS_PER_MM, 1189 * POINTS_PER_MM, "A0"); /** A rectangle the size of A1 Paper. */ public static final PageSize A1 = new PageSize(594 * POINTS_PER_MM, 841 * POINTS_PER_MM, "A1"); /** A rectangle the size of A2 Paper. */ public static final PageSize A2 = new PageSize(420 * POINTS_PER_MM, 594 * POINTS_PER_MM, "A2"); /** A rectangle the size of A3 Paper. */ public static final PageSize A3 = new PageSize(297 * POINTS_PER_MM, 420 * POINTS_PER_MM, "A3"); /** A rectangle the size of A4 Paper. */ public static final PageSize A4 = new PageSize(210 * POINTS_PER_MM, 297 * POINTS_PER_MM, "A4"); /** A rectangle the size of A5 Paper. */ public static final PageSize A5 = new PageSize(148 * POINTS_PER_MM, 210 * POINTS_PER_MM, "A5"); /** A rectangle the size of A6 Paper. */ public static final PageSize A6 = new PageSize(105 * POINTS_PER_MM, 148 * POINTS_PER_MM, "A6"); public PageSize(float width, float height, String name) { this.width = width; this.height = height; this.name = name; } public PageSize(float width, float height) { this(width, height, null); } public float getWidth() { return width; } public float getHeight() { return height; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PageSize pageSize = (PageSize) o; return new EqualsBuilder() .append(width, pageSize.width) .append(height, pageSize.height) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(17, 37) .append(width) .append(height) .toHashCode(); } @Override public String toString() { return "PageSize{" + "widthInches=" + width + ", heightInches=" + height + '}'; } public PageSize rotate() { return new PageSize(height, width); } public static PageSize fromInches(float widthInch, float heightInch) { return new PageSize(widthInch * POINTS_PER_INCH, heightInch * POINTS_PER_INCH); } public String getName() { return name; } }
package com.voisintech.easeljs.utils; /** * The Ticker provides a centralized tick or heartbeat broadcast at a set * interval. Listeners can subscribe to the tick event to be notified when a set * time interval has elapsed. * * Note that the interval that the tick event is called is a target interval, * and may be broadcast at a slower interval during times of high CPU load. The * Ticker class uses a static interface (ex. <code>Ticker.getPaused()</code>) * and should not be instantiated. * * <h4>Example</h4> createjs.Ticker.addEventListener("tick", handleTick); * function handleTick(event) { // Actions carried out each frame if * (!event.paused) { // Actions carried out when the Ticker is not paused. } } * * To update a stage every tick, the {{#crossLink "Stage"}}{{/crossLink}} * instance can also be used as a listener, as it will automatically update when * it receives a tick event: * * createjs.Ticker.addEventListener("tick", stage); * * @class Ticker * @uses EventDispatcher * @static **/ public class Ticker { private static String RAF_SYNCHED = "synched"; private static String RAF = "raf"; private static String TIMEOUT = "timeout"; private static boolean useRAF = false; private static String timingMode = null; private static int maxDelta = 0; private Ticker() { } /** * Starts the tick. This is called automatically when the first listener is * added. * * @method init * @static **/ public static native void init()/*-{ Ticker.init(); }-*/; /** * Stops the Ticker and removes all listeners. Use init() to restart the * Ticker. * * @method reset * @static **/ public static native void reset()/*-{ Ticker.reset(); }-*/; /** * Sets the target time (in milliseconds) between ticks. Default is 50 (20 * FPS). * * Note actual time between ticks may be more than requested depending on * CPU load. * * @method setInterval * @static * @param {Number} interval Time in milliseconds between ticks. Default * value is 50. **/ public static native void setInterval(int interval)/*-{ Ticker.setInterval(interval); }-*/; /** * Returns the current target time between ticks, as set with {{#crossLink * "Ticker/setInterval"}}{{/crossLink}}. * * @method getInterval * @static * @return {Number} The current target interval in milliseconds between tick * events. **/ public static native void getInterval()/*-{ Ticker.getInterval(); }-*/; /** * Sets the target frame rate in frames per second (FPS). For example, with * an interval of 40, <code>getFPS()</code> will return 25 (1000ms per * second divided by 40 ms per tick = 25fps). * * @method setFPS * @static * @param {Number} value Target number of ticks broadcast per second. **/ public static native int setFPS(int value)/*-{ return Ticker.setFPS(value); }-*/; /** * Returns the target frame rate in frames per second (FPS). For example, * with an interval of 40, <code>getFPS()</code> will return 25 (1000ms per * second divided by 40 ms per tick = 25fps). * * @method getFPS * @static * @return {Number} The current target number of frames / ticks broadcast * per second. **/ public static native void getFPS()/*-{ Ticker.getFPS(); }-*/; /** * Returns the average time spent within a tick. This can vary significantly * from the value provided by getMeasuredFPS because it only measures the * time spent within the tick execution stack. * * Example 1: With a target FPS of 20, getMeasuredFPS() returns 20fps, which * indicates an average of 50ms between the end of one tick and the end of * the next. However, getMeasuredTickTime() returns 15ms. This indicates * that there may be up to 35ms of "idle" time between the end of one tick * and the start of the next. * * Example 2: With a target FPS of 30, getFPS() returns 10fps, which * indicates an average of 100ms between the end of one tick and the end of * the next. However, getMeasuredTickTime() returns 20ms. This would * indicate that something other than the tick is using ~80ms (another * script, DOM rendering, etc). * * @method getMeasuredTickTime * @static * @param {Number} [ticks] The number of previous ticks over which to * measure the average time spent in a tick. Defaults to the number * of ticks per second. To get only the last tick's time, pass in 1. * @return {Number} The average time spent in a tick in milliseconds. **/ public static native int getMeasuredTickTime(int ticks)/*-{ return Ticker.getMeasuredTickTime(ticks); }-*/; /** * Returns the actual frames / ticks per second. * * @method getMeasuredFPS * @static * @param {Number} [ticks] The number of previous ticks over which to * measure the actual frames / ticks per second. Defaults to the * number of ticks per second. * @return {Number} The actual frames / ticks per second. Depending on * performance, this may differ from the target frames per second. **/ public static native int getMeasuredFPS(int ticks)/*-{ return Ticker.getMeasuredFPS(ticks); }-*/; /** * Changes the "paused" state of the Ticker, which can be retrieved by the {{#crossLink "Ticker/getPaused"}}{{/crossLink}} * method, and is passed as the "paused" property of the <code>tick</code> event. When the ticker is paused, all * listeners will still receive a tick event, but the <code>paused</code> property will be false. * * Note that in EaselJS v0.5.0 and earlier, "pauseable" listeners would <strong>not</strong> receive the tick * callback when Ticker was paused. This is no longer the case. * * <h4>Example</h4> * createjs.Ticker.addEventListener("tick", handleTick); * createjs.Ticker.setPaused(true); * function handleTick(event) { * console.log("Paused:", event.paused, createjs.Ticker.getPaused()); * } * * @method setPaused * @static * @param {Boolean} value Indicates whether to pause (true) or unpause (false) Ticker. **/ public static native void setPaused(int value)/*-{ Ticker.setPaused(value); }-*/; /** * Returns a boolean indicating whether Ticker is currently paused, as set with {{#crossLink "Ticker/setPaused"}}{{/crossLink}}. * When the ticker is paused, all listeners will still receive a tick event, but this value will be false. * * Note that in EaselJS v0.5.0 and earlier, "pauseable" listeners would <strong>not</strong> receive the tick * callback when Ticker was paused. This is no longer the case. * * <h4>Example</h4> * createjs.Ticker.addEventListener("tick", handleTick); * createjs.Ticker.setPaused(true); * function handleTick(event) { * console.log("Paused:", createjs.Ticker.getPaused()); * } * * @method getPaused * @static * @return {Boolean} Whether the Ticker is currently paused. **/ public static native void getPaused()/*-{ return Ticker.getPaused(); }-*/; }
package com.alvazan.orm.api.base; import java.util.Map; import com.alvazan.orm.api.z8spi.SpiConstants; import com.alvazan.orm.api.z8spi.conv.Converter; @SuppressWarnings("rawtypes") public abstract class Bootstrap { public static final String AUTO_CREATE_KEY = "nosql.autoCreateKey"; public static final String LIST_OF_EXTRA_CLASSES_TO_SCAN_KEY = "nosql.listOfClassesToScan"; public static final String CASSANDRA_BUILDER = SpiConstants.CASSANDRA_BUILDER; private static final String OUR_IMPL = "com.alvazan.orm.impl.bindings.BootstrapImpl"; public synchronized static NoSqlEntityManagerFactory create(DbTypeEnum type, Map<String, Object> properties, Map<Class, Converter> converters, ClassLoader cl) { return create(type, OUR_IMPL, properties, converters, cl); } public synchronized static NoSqlEntityManagerFactory create(DbTypeEnum type, String impl, Map<String, Object> properties, Map<Class, Converter> converters, ClassLoader cl) { Bootstrap newInstance = createInstance(impl); NoSqlEntityManagerFactory inst = newInstance.createInstance(type, properties, converters, cl); return inst; } private static Bootstrap createInstance(String impl) { try { Class<?> clazz = Class.forName(impl); Bootstrap newInstance = (Bootstrap) clazz.newInstance(); return newInstance; } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } protected abstract NoSqlEntityManagerFactory createInstance(DbTypeEnum type, Map<String, Object> properties, Map<Class, Converter> converters, ClassLoader cl); public static void createAndAddBestCassandraConfiguration( Map<String, Object> properties, String clusterName, String keyspace, String seeds) { Bootstrap bootstrap = createInstance(OUR_IMPL); bootstrap.createBestCassandraConfig(properties, clusterName, keyspace, seeds); } protected abstract void createBestCassandraConfig(Map<String, Object> properties, String clusterName, String keyspace2, String seeds2); }
package com.commercetools.util; import org.apache.http.Consts; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.ContentType; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultHttpRequestRetryHandler; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.net.ssl.SSLException; import java.io.IOException; import java.net.ConnectException; import java.net.UnknownHostException; import java.util.Arrays; import java.util.Objects; /** * Util to make simple retryable HTTP GET/POST requests. * <p> * The http client options: <ul> * <li>reusable, e.g. one instance per application</li> * <li>multi-threading</li> * <li>socket/request/connect timeouts are 10 sec</li> * <li>retries on connections exceptions up to 3 times, if request has not been sent yet * (see {@link DefaultHttpRequestRetryHandler#isRequestSentRetryEnabled()} * and {@link #HTTP_REQUEST_RETRY_ON_SOCKET_TIMEOUT})</li> * <li>connections pool is 200 connections, up to 20 per route (see {@link #CONNECTION_MAX_TOTAL} * and {@link #CONNECTION_MAX_PER_ROUTE}</li> * </ul> * <p> * This util is intended to replace <i>Unirest</i> and <i>fluent-hc</i> dependencies, which don't propose any flexible * way to implement retry strategy. * <p> * Implementation notes (for developers):<ul> * <li>remember, the responses must be closed, otherwise the connections won't be return to the pool, * no new connections will be available and {@link org.apache.http.conn.ConnectionPoolTimeoutException} will be * thrown. See {@link #executeReadAndCloseRequest(HttpUriRequest)}</li> * <li>{@link UrlEncodedFormEntity} the charset should be explicitly set to UTF-8, otherwise * {@link HTTP#DEF_CONTENT_CHARSET ISO_8859_1} is used, which is not acceptable for German alphabet</li> * </ul> */ public final class HttpRequestUtil { public static final int REQUEST_TIMEOUT = 10000; public static final int RETRY_TIMES = 3; private static final int CONNECTION_MAX_TOTAL = 200; private static final int CONNECTION_MAX_PER_ROUTE = 20; /** * This retry handler implementation overrides default list of <i>nonRetriableClasses</i> excluding * {@link java.io.InterruptedIOException} and {@link ConnectException} so the client will retry on interruption and * socket timeouts. * <p> * The implementation will retry 3 times. */ private static final DefaultHttpRequestRetryHandler HTTP_REQUEST_RETRY_ON_SOCKET_TIMEOUT = new DefaultHttpRequestRetryHandler(RETRY_TIMES, false, Arrays.asList( UnknownHostException.class, SSLException.class)) { // empty implementation, we just need to use protected constructor }; private static final CloseableHttpClient CLIENT = HttpClientBuilder.create() .setDefaultRequestConfig(RequestConfig.custom() .setConnectionRequestTimeout(REQUEST_TIMEOUT) .setSocketTimeout(REQUEST_TIMEOUT) .setConnectTimeout(REQUEST_TIMEOUT) .build()) .setRetryHandler(HTTP_REQUEST_RETRY_ON_SOCKET_TIMEOUT) .setConnectionManager(buildDefaultConnectionManager()) .build(); private static final BasicResponseHandler BASIC_RESPONSE_HANDLER = new BasicResponseHandler(); private static PoolingHttpClientConnectionManager buildDefaultConnectionManager() { final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); connectionManager.setMaxTotal(CONNECTION_MAX_TOTAL); connectionManager.setDefaultMaxPerRoute(CONNECTION_MAX_PER_ROUTE); return connectionManager; } /** * Execute retryable HTTP GET request with default {@link #REQUEST_TIMEOUT} * * @param url url to get * @return response from the {@code url} * @throws IOException in case of a problem or the connection was aborted */ public static HttpResponse executeGetRequest(@Nonnull String url) throws IOException { return executeReadAndCloseRequest(new HttpGet(url)); } /** * Make URL request and return a response string. * * @param url URL to get/query * @return response string from the request * @throws IOException in case of a problem or the connection was aborted */ public static String executeGetRequestToString(@Nonnull String url) throws IOException { return responseToString(executeGetRequest(url)); } /** * Execute retryable HTTP POST request with specified {@code timeoutMsec} * * @param url url to post * @param parameters list of values to send as URL encoded form data. If <b>null</b> - not data is sent, but * empty POST request is executed. * @return response from the {@code url} * @throws IOException in case of a problem or the connection was aborted */ public static HttpResponse executePostRequest(@Nonnull String url, @Nullable Iterable<? extends NameValuePair> parameters) throws IOException { final HttpPost request = new HttpPost(url); if (parameters != null) { request.setEntity(new UrlEncodedFormEntity(parameters, Consts.UTF_8)); } return executeReadAndCloseRequest(request); } /** * Make URL request and return a response string. * * @param url URL to post/query * @param parameters list of values to send as URL encoded form data. If <b>null</b> - not data is sent, but * empty POST request is executed. * @return response string from the request * @throws IOException in case of a problem or the connection was aborted */ public static String executePostRequestToString(@Nonnull String url, @Nullable Iterable<? extends NameValuePair> parameters) throws IOException { return responseToString(executePostRequest(url, parameters)); } /** * Read string content from {@link HttpResponse}. * * @param response response to read * @return string content of the response * @throws IOException in case of a problem or the connection was aborted */ public static String responseToString(@Nonnull final HttpResponse response) throws IOException { return BASIC_RESPONSE_HANDLER.handleResponse(response); } /** * Short {@link BasicNameValuePair} factory alias. * * @param name request argument name * @param value request argument value. If value is <b>null</b> - {@link BasicNameValuePair#value} set to <b>null</b>, * otherwise {@link Object#toString()} is applied. * @return new instance of {@link BasicNameValuePair} with {@code name} and {@code value} */ public static BasicNameValuePair nameValue(@Nonnull final String name, @Nullable final Object value) { return new BasicNameValuePair(name, Objects.toString(value, null)); } /** * By default apache httpclient responses are not closed, thus we should explicitly read the stream and close the * connection. * <p> * The connection will be closed even if read exception occurs. * * @param request GET/POST/other request to execute, read and close * @return read and closed {@link CloseableHttpResponse} instance from {@link CloseableHttpClient#execute(HttpUriRequest)} * where {@link HttpResponse#getEntity()} is set to read string value. * @throws IOException if reading failed. Note, even in case of exception the {@code response} will be closed. */ private static CloseableHttpResponse executeReadAndCloseRequest(@Nonnull final HttpUriRequest request) throws IOException { final CloseableHttpResponse response = CLIENT.execute(request); try { final HttpEntity entity = response.getEntity(); if (entity != null) { final ByteArrayEntity byteArrayEntity = new ByteArrayEntity(EntityUtils.toByteArray(entity)); final ContentType contentType = ContentType.getOrDefault(entity); byteArrayEntity.setContentType(contentType.toString()); response.setEntity(byteArrayEntity); } } finally { response.close(); } return response; } private HttpRequestUtil() { } }
import java.io.Writer; import java.io.PrintWriter; import java.util.List; import java.util.ArrayList; public class SimpleIA32Generator extends AssemblyGenerator { public int getSystemIntSize() { return 4; } public int getPointerSize() { return 4; } public int getFunctionSize() { return 4; } private PrintWriter out; private String currentFunctionName; private DataType currentFunctionReturnType; private int nextLabelId; private List<String> stringLiteralList; private String getNextLabel() { return "stoa.label." + (nextLabelId++); } public void generateAssembly(Writer out, StaticVariable[] staticVariableDefinitionList, Function[] functionDefinitionList) { this.out = new PrintWriter(out); nextLabelId = 0; stringLiteralList = new ArrayList<String>(); this.out.println(".section .text"); for (int i = 0; i < functionDefinitionList.length; i++) { generateFunction(functionDefinitionList[i]); } this.out.println(".section .bss"); for (int i = 0; i < staticVariableDefinitionList.length; i++) { StaticVariable sv = staticVariableDefinitionList[i]; this.out.println(".comm " + sv.getName() + ", " + sv.getDataType().getWidth()); } this.out.println(".section .rodata"); for (int i = 0; i < stringLiteralList.size(); i++) { this.out.println("stoa.string" + i + ":"); this.out.print("\t.byte "); byte[] b = stringLiteralList.get(i).getBytes(); for (int j = 0; j < b.length; j++) { int num = b[j]; if (num < 0) num += 256; this.out.print(num + ", "); } this.out.println("0"); } this.out.flush(); } private void generateFunction(Function func) { currentFunctionName = func.getName(); currentFunctionReturnType = func.getReturnType(); out.println(".globl " + currentFunctionName); out.println(currentFunctionName + ":"); int instNum = func.getInstructionNumber(); for (int i = 0; i < instNum; i++) { generateInstruction(func.getInstruction(i)); } out.println("stoa.funcend." + currentFunctionName + ":"); out.println("\tret"); } private void generateInstruction(Instruction inst) { if (inst instanceof NormalExpression) { Expression expr = ((NormalExpression)inst).getExpression(); generateExpressionEvaluation(expr, 0, false); out.println("\tpop %eax"); } else if (inst instanceof ReturnInstruction) { ReturnInstruction ret = (ReturnInstruction)inst; if (ret.hasExpression()) { generateExpressionEvaluation(ret.getExpression(), currentFunctionReturnType.getWidth(), false); out.println("\tpop %eax"); } out.println("\tjmp stoa.funcend." + currentFunctionName); } else if (inst instanceof ConditionalBranch) { ConditionalBranch cb = (ConditionalBranch)inst; int insNum; generateExpressionEvaluation(cb.getCondition(), 4, false); out.println("\tpop %eax"); out.println("\ttest %eax, %eax"); String label1 = getNextLabel(); String label2 = getNextLabel(); String label3 = null; out.println("\tjnz " + label1); out.println("\tjmp " + label2); out.println(label1 + ":"); insNum = cb.getThenInstructionNumber(); for (int i = 0; i < insNum; i++) { generateInstruction(cb.getThenInstruction(i)); } if (cb.hasElse()) { label3 = getNextLabel(); out.println("\tjmp " + label3); } out.println(label2 + ":"); if (cb.hasElse()) { insNum = cb.getElseInstructionNumber(); for (int i = 0; i < insNum; i++) { generateInstruction(cb.getElseInstruction(i)); } out.println(label3 + ":"); } } else if (inst instanceof InfiniteLoop) { InfiniteLoop infLoop = (InfiniteLoop)inst; int insNum = infLoop.getInstructionNumber(); String label = getNextLabel(); out.println(label + ":"); for (int i = 0; i < insNum; i++) { generateInstruction(infLoop.getInstruction(i)); } out.println("\tjmp " + label); } else if (inst instanceof WhileLoop) { WhileLoop wLoop = (WhileLoop)inst; int insNum = wLoop.getInstructionNumber(); String label1 = getNextLabel(); String label2 = getNextLabel(); String label3 = getNextLabel(); out.println(label1 + ":"); generateExpressionEvaluation(wLoop.getCondition(), 4, false); out.println("\tpop %eax"); out.println("\ttest %eax, %eax"); out.println("\tjnz " + label3); out.println("\tjmp " + label2); out.println(label3 + ":"); for (int i = 0; i < insNum; i++) { generateInstruction(wLoop.getInstruction(i)); } out.println("\tjmp " + label1); out.println(label2 + ":"); } else if (inst instanceof BreakInstruction) { throw new SystemLimitException("BreakInstruction not implemented yet"); } else if (inst instanceof ContinueInstruction) { throw new SystemLimitException("ContinueInstruction not implemented yet"); } } private void generateExpressionEvaluation(Expression expr, int requestedSize, boolean wantAddress) { if (expr instanceof BinaryOperator) { generateBinaryOperatorEvaluation((BinaryOperator)expr, requestedSize, wantAddress); } else if (expr instanceof UnaryOperator) { generateUnaryOperatorEvaluation((UnaryOperator)expr, requestedSize, wantAddress); } else if (expr instanceof FunctionCallOperator) { FunctionCallOperator funcCall = (FunctionCallOperator)expr; int argumentNum = funcCall.getArgumentsNum(); for (int i = argumentNum - 1; i >= 0; i generateExpressionEvaluation(funcCall.getArgument(i), 4, false); } generateExpressionEvaluation(funcCall.getFunction(), 4, false); out.println("\tpop %eax"); out.println("\tcall *%eax"); out.println("\tadd $" + (4 * argumentNum) + ", %esp"); out.println("\tpush %eax"); } else if (expr instanceof CastOperator) { throw new SystemLimitException("CastOperator not implemented yet"); } else if (expr instanceof VariableAccess) { if (expr.getDataType().getWidth() != 4) { throw new SystemLimitException("currently only 4-byte variable is supported"); } Identifier ident = ((VariableAccess)expr).getIdentifier(); if (ident instanceof StaticVariable) { if (wantAddress || expr.getDataType() instanceof FunctionType) { out.println("\tpushl $" + ident.getName()); } else { out.println("\tpushl (" + ident.getName() + ")"); } } else if (ident instanceof AutomaticVariable) { throw new SystemLimitException("AutomaticVariable not implemented yet"); } else if (ident instanceof DefinedValue) { out.println("\tpushl $" + ((DefinedValue)ident).getValue()); } else if (ident instanceof AddressVariable) { if (wantAddress) { out.println("\tpushl $" + ((AddressVariable)ident).getAddress()); } else { out.println("\tpushl (" + ((AddressVariable)ident).getAddress() + ")"); } } } else if (expr instanceof IntegerLiteral) { out.println("\tpushl $" + ((IntegerLiteral)expr).getValue()); } else if (expr instanceof StringLiteral) { StringLiteral sl = (StringLiteral)expr; String str = sl.getString(); int idx = stringLiteralList.indexOf(str); if (idx < 0) { idx = stringLiteralList.size(); stringLiteralList.add(str); } out.println("\tpushl $stoa.string" + idx); } } private void generateBinaryOperatorEvaluation(BinaryOperator op, int requestedSize, boolean wantAddress) { generateExpressionEvaluation(op.getLeft(), op.getDataType().getWidth(), op.getKind() == BinaryOperator.Kind.OP_ASSIGN); if (op.getKind() != BinaryOperator.Kind.OP_LOGICAL_AND && op.getKind() != BinaryOperator.Kind.OP_LOGICAL_OR) { generateExpressionEvaluation(op.getRight(), op.getDataType().getWidth(), false); out.println("\tpop %ecx"); } out.println("\tpop %eax"); boolean isComparisionSigned = false; if (op.getLeft().getDataType() instanceof IntegerType && op.getRight().getDataType() instanceof IntegerType) { IntegerType leftType = (IntegerType)op.getLeft().getDataType(); IntegerType rightType = (IntegerType)op.getRight().getDataType(); if (leftType.getWidth() >= rightType.getWidth()) { isComparisionSigned = leftType.isSigned(); } else { isComparisionSigned = rightType.isSigned(); } } String comparisionOperatorInstruction = null; switch(op.getKind()) { case OP_ARRAY: throw new SystemLimitException("OP_ARRAY not implemented yet"); case OP_MUL: if (((IntegerType)op.getDataType()).isSigned()) { out.println("\timul %ecx"); } else { out.println("\tmul %ecx"); } break; case OP_DIV: if (((IntegerType)op.getDataType()).isSigned()) { out.println("\tcdq"); out.println("\tidiv %ecx"); } else { out.println("xor %edx, %edx"); out.println("\tdiv %ecx"); } break; case OP_MOD: if (((IntegerType)op.getDataType()).isSigned()) { out.println("\tcdq"); out.println("\tidiv %ecx"); } else { out.println("xor %edx, %edx"); out.println("\tdiv %ecx"); } out.println("\tmov %edx, %eax"); break; case OP_ADD: out.println("\tadd %ecx, %eax"); break; case OP_SUB: out.println("\tsub %ecx, %eax"); break; case OP_LEFT_SHIFT: throw new SystemLimitException("OP_LEFT_SHIFT not implemented yet"); case OP_RIGHT_SHIFT_ARITIMETIC: throw new SystemLimitException("OP_RIGHT_SHIFT_ARITIMETIC not implemented yet"); case OP_RIGHT_SHIFT_LOGICAL: throw new SystemLimitException("OP_RIGHT_SHIFT_LOGICAL not implemented yet"); case OP_LEFT_ROTATE: throw new SystemLimitException("OP_LEFT_ROTATE not implemented yet"); case OP_RIGHT_ROTATE: throw new SystemLimitException("OP_RIGHT_ROTATE not implemented yet"); case OP_BIT_AND: throw new SystemLimitException("OP_BIT_AND not implemented yet"); case OP_BIT_OR: throw new SystemLimitException("OP_BIT_OR not implemented yet"); case OP_BIT_XOR: throw new SystemLimitException("OP_BIT_XOR not implemented yet"); case OP_ASSIGN: out.println("\txchg %ecx, %eax"); out.println("\tmov %eax, (%ecx)"); break; case OP_GT: comparisionOperatorInstruction = isComparisionSigned ? "jng" : "jna"; break; case OP_GTE: comparisionOperatorInstruction = isComparisionSigned ? "jnge" : "jnae"; break; case OP_LT: comparisionOperatorInstruction = isComparisionSigned ? "jnl" : "jnb"; break; case OP_LTE: comparisionOperatorInstruction = isComparisionSigned ? "jnle" : "jnbe"; break; case OP_EQUAL: comparisionOperatorInstruction = "jne"; break; case OP_NOT_EQUAL: comparisionOperatorInstruction = "je"; break; case OP_LOGICAL_AND: throw new SystemLimitException("OP_LOGICAL_AND not implemented yet"); case OP_LOGICAL_OR: throw new SystemLimitException("OP_LOGICAL_OR not implemented yet"); default: throw new SystemLimitException("unexpected kind of BinaryOperator: " + op.getKind()); } if (comparisionOperatorInstruction != null) { String label = getNextLabel(); out.println("\tcmp %ecx, %eax"); out.println("\tmov $0, %eax"); out.println("\t" + comparisionOperatorInstruction + " " + label); out.println("\tinc %eax"); out.println(label + ":"); } out.println("\tpush %eax"); } private void generateUnaryOperatorEvaluation(UnaryOperator op, int requestedSize, boolean wantAddress) { if (op.getKind() != UnaryOperator.Kind.UNARY_SIZE) { generateExpressionEvaluation(op.getOperand(), op.getDataType().getWidth(), op.getKind() == UnaryOperator.Kind.UNARY_DEREFERENCE || op.getKind() == UnaryOperator.Kind.UNARY_ADDRESS); out.println("\tpop %eax"); } switch(op.getKind()) { case UNARY_MINUS: out.println("\tneg %eax"); break; case UNARY_PLUS: break; case UNARY_LOGICAL_NOT: break; case UNARY_BIT_NOT: out.println("\tnot %eax"); break; case UNARY_DEREFERENCE: if (!wantAddress) { out.println("\tmov (%eax), %eax"); } break; case UNARY_ADDRESS: break; case UNARY_SIZE: out.println("\tmov $" + op.getDataType().getWidth() + ", %eax"); break; case UNARY_AUTO_TO_POINTER: break; default: throw new SystemLimitException("unexpected kind of UnaryOperator: " + op.getKind()); } out.println("\tpush %eax"); } }
package com.winterwell.depot; public interface IHasDesc { /** * @return a description for this artifact. This must not use * {@link Desc#getDescription(Object)} as that would generate an * infinite loop. * <p> * Should this bind the object to it's description? No - keep * binding as something done by depot, or explicitly. */ Desc getDesc(); /** * @return the sub-modules (those parts which implement @ModularXML), or * null (the default). * This should not recursively collect the sub-sub-modules; * the Depot will do that. It is VITAL that this includes all fields * which implement @ModularXML, otherwise these parts will not get * saved. * @see @ModularXML */ default IHasDesc[] getModules() { return null; } }
package org.slc.sli.client; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import com.google.gson.Gson; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slc.sli.entity.GenericEntity; import org.slc.sli.util.Constants; import org.slc.sli.util.SecurityUtil; import org.slc.sli.util.URLBuilder; /** * * API Client class used by the Dashboard to make calls to the API service. * * @author svankina * */ public class LiveAPIClient implements APIClient { private Logger logger = LoggerFactory.getLogger(LiveAPIClient.class); private static final String SECTIONS_URL = "/sections/"; private static final String STUDENT_SECTION_ASSOC_URL = "/studentSectionAssociations/"; private static final String SCHOOLS_URL = "/schools/"; private static final String STUDENTS_URL = "/students/"; private static final String COURSES_URL = "/courses/"; private static final String ED_ORG_URL = "/educationOrganizations/"; private static final String HOME_URL = "/home/"; private static final String TEACHER_SECTION_ASSOC_URL = "/teacherSectionAssociations/"; private static final String STUDENT_ASSMT_ASSOC_URL = "/student-assessment-associations/"; private static final String ASSMT_URL = "/assessments/"; private String apiUrl; private RESTClient restClient; private Gson gson; // For now, the live client will use the mock client for api calls not yet implemented private MockAPIClient mockClient; public LiveAPIClient() { mockClient = new MockAPIClient(); gson = new Gson(); } /** * Get a list of schools for the user */ @Override public List<GenericEntity> getSchools(String token, List<String> schoolIds) { String teacherId = getId(token); List<GenericEntity> sections = getSectionsForTeacher(teacherId, token); List<GenericEntity> schools = getSchoolsForSection(sections, token); List<GenericEntity> schoolList = new ArrayList<GenericEntity>(); for (GenericEntity school : schools) { schoolList.add(school); } return schoolList; } /** * Get a list of student objects, given the student ids */ @Override public List<GenericEntity> getStudents(final String token, List<String> ids) { if (ids == null) { return null; } List<GenericEntity> students = new ArrayList<GenericEntity>(); for (String id : ids) { students.add(getStudent(id, token)); } return students; } /** * Get a list of student assessment results, given a student id */ @Override public List<GenericEntity> getStudentAssessments(final String token, String studentId) { // make a call to student-assessments, with the student id List<GenericEntity> responses = createEntitiesFromAPI(getApiUrl() + STUDENT_ASSMT_ASSOC_URL + studentId, token); // for each link in the returned list, make the student-assessment call for the result data List<GenericEntity> studentAssmts = new ArrayList<GenericEntity>(); for (GenericEntity response : responses) { studentAssmts.add(getStudentAssessment(parseId(response.getMap(Constants.ATTR_LINK)), token)); } return studentAssmts; } /** * Get custom data */ @Override public List<GenericEntity> getCustomData(final String token, String key) { return mockClient.getCustomData(getUsername(), key); } /** * Get assessment info, given a list of assessment ids */ @Override public List<GenericEntity> getAssessments(final String token, List<String> assessmentIds) { List<GenericEntity> assmts = new ArrayList<GenericEntity>(); for (String assmtId : assessmentIds) { assmts.add(getAssessment(assmtId, token)); } return assmts; } /** * Get program participation, given a list of student ids */ @Override public List<GenericEntity> getPrograms(final String token, List<String> studentIds) { return mockClient.getPrograms(getUsername(), studentIds); } @Override public GenericEntity getParentEducationalOrganization(final String token, GenericEntity edOrg) { String parentEdOrgId = edOrg.getString(Constants.ATTR_PARENT_EDORG); if (parentEdOrgId == null) { return null; } return getEducationalOrganization(parentEdOrgId, token); } // TODO: This version works with v1 of the API, which is not ready. /** * Get a list of student ids belonging to a section private List<String> getStudentIdsForSection(String id, String token) { List<GenericEntity> responses = createEntitiesFromAPI(STUDENT_SECTION_ASSOC_URL + '?' + Constants.ATTR_SECTION_ID + '=' + id, token); List<String> studentIds = new ArrayList<String>(); for (GenericEntity response : responses) { studentIds.add(response.getString(Constants.ATTR_STUDENT_ID)); } return studentIds; } */ /* This version works with v0 of the API, which will be removed by the end of sprint 3.3 */ private List<String> getStudentIdsForSection(String id, String token) { List<GenericEntity> responses = createEntitiesFromAPI(restClient.getSecurityUrl()+ "api/rest/student-section-associations/" + id + "/targets", token); List<String> studentIds = new ArrayList<String>(); for (GenericEntity response : responses) { studentIds.add(response.getString(Constants.ATTR_STUDENT_ID)); } return studentIds; } /** * Get one student */ private GenericEntity getStudent(String id, String token) { return createEntityFromAPI(getApiUrl() + STUDENTS_URL + id, token); } /** * Get one school */ private GenericEntity getSchool(String id, String token) { return createEntityFromAPI(getApiUrl() + SCHOOLS_URL + id, token); } /** * Get one section */ private GenericEntity getSection(String id, String token) { GenericEntity section = createEntityFromAPI(getApiUrl() + SECTIONS_URL + id, token); section.put(Constants.ATTR_STUDENT_UIDS, getStudentIdsForSection(id, token)); // if no section name, fill in with section code if (section.get(Constants.ATTR_SECTION_NAME) == null) { section.put(Constants.ATTR_SECTION_NAME, section.get(Constants.ATTR_UNIQUE_SECTION_CODE)); } return section; } /** * Get one course */ private GenericEntity getCourse(String id, String token) { return createEntityFromAPI(getApiUrl() + COURSES_URL + id, token); } /** * Get one ed-org */ private GenericEntity getEducationalOrganization(String id, String token) { return createEntityFromAPI(getApiUrl() + ED_ORG_URL + id, token); } /** * Get one student-assessment association */ private GenericEntity getStudentAssessment(String id, String token) { return createEntityFromAPI(getApiUrl() + STUDENT_ASSMT_ASSOC_URL + id, token); } /** * Get one assessment */ private GenericEntity getAssessment(String id, String token) { return createEntityFromAPI(getApiUrl() + ASSMT_URL + id, token); } /** * Get the user's unique identifier * * @param token * @return */ private String getId(String token) { // Make a call to the /home uri and retrieve id from there String returnValue = ""; GenericEntity response = createEntityFromAPI(getApiUrl() + HOME_URL, token); for (Map link : (List<Map>) (response.get(Constants.ATTR_LINKS))) { if (link.get(Constants.ATTR_REL).equals(Constants.ATTR_SELF)) { returnValue = parseId(link); } } return returnValue; } /** * Given a link in the API response, extract the entity's unique id * * @param link * @return */ private String parseId(Map link) { String returnValue; int index = ((String) (link.get(Constants.ATTR_HREF))).lastIndexOf("/"); returnValue = ((String) (link.get(Constants.ATTR_HREF))).substring(index + 1); return returnValue; } /** * Get a list of sections, given a teacher id */ private List<GenericEntity> getSectionsForTeacher(String id, String token) { // TODO: Change this (and similar places where you ask for associations) to a properly-built // query. Probably with a "createEntitiesWithQuery" method. List<GenericEntity> responses = createEntitiesFromAPI(getApiUrl() + TEACHER_SECTION_ASSOC_URL + "?" + Constants.ATTR_TEACHER_ID + '=' + id, token); List<GenericEntity> sections = new ArrayList<GenericEntity>(); // TODO: for a more efficient implementation, build a comma-delimited list of section ids, // make one single api call, and then loop through the response JSONArray and parse // out the section entities one by one. for (GenericEntity response : responses) { sections.add(getSection(response.getString(Constants.ATTR_SECTION_ID), token)); } return sections; } /** * Get a list of schools, given a list of sections * * @param sections * @param token * @return */ private List<GenericEntity> getSchoolsForSection(List<GenericEntity> sections, String token) { // collect associated course first. HashMap<String, GenericEntity> courseMap = new HashMap<String, GenericEntity>(); HashMap<String, String> sectionIDToCourseIDMap = new HashMap<String, String>(); getCourseSectionsMappings(sections, token, courseMap, sectionIDToCourseIDMap); // now collect associated schools. HashMap<String, GenericEntity> schoolMap = new HashMap<String, GenericEntity>(); HashMap<String, String> sectionIDToSchoolIDMap = new HashMap<String, String>(); getSchoolSectionsMappings(sections, token, schoolMap, sectionIDToSchoolIDMap); // Now associate course and school. // There is no direct course-school association in ed-fi, so in dashboard // the "course-school" association is defined as follows: // course C is associated with school S if there exists a section X s.t. C is associated // with X and S is associated with X. HashMap<String, HashSet<String>> schoolIDToCourseIDMap = new HashMap<String, HashSet<String>>(); for (int i = 0; i < sections.size(); i++) { GenericEntity section = sections.get(i); if (sectionIDToSchoolIDMap.containsKey(section.get(Constants.ATTR_ID)) && sectionIDToCourseIDMap.containsKey(section.get(Constants.ATTR_ID))) { String schoolId = sectionIDToSchoolIDMap.get(section.get(Constants.ATTR_ID)); String courseId = sectionIDToCourseIDMap.get(section.get(Constants.ATTR_ID)); if (!schoolIDToCourseIDMap.containsKey(schoolId)) { schoolIDToCourseIDMap.put(schoolId, new HashSet<String>()); } schoolIDToCourseIDMap.get(schoolId).add(courseId); } } // now create the generic entity for (String schoolId : schoolIDToCourseIDMap.keySet()) { for (String courseId : schoolIDToCourseIDMap.get(schoolId)) { GenericEntity s = schoolMap.get(schoolId); GenericEntity c = courseMap.get(courseId); s.appendToList(Constants.ATTR_COURSES, c); } } return new ArrayList<GenericEntity>(schoolMap.values()); } /** * Get the associations between courses and sections */ private void getCourseSectionsMappings(List<GenericEntity> sections, String token, Map<String, GenericEntity> courseMap, Map<String, String> sectionIDToCourseIDMap) { for (int i = 0; i < sections.size(); i++) { GenericEntity section = sections.get(i); // Get course using courseId reference in section GenericEntity course = getCourse(section.getString(Constants.ATTR_COURSE_ID), token); // Add course to courseMap, if it doesn't exist already if (!courseMap.containsKey(course.get(Constants.ATTR_ID))) { courseMap.put(course.getString(Constants.ATTR_ID), course); } // Grab the most up to date course from the map // Add the section to it's section list, and update sectionIdToCourseIdMap course = courseMap.get(course.get(Constants.ATTR_ID)); course.appendToList(Constants.ATTR_SECTIONS, section); sectionIDToCourseIDMap.put(section.getString(Constants.ATTR_ID), course.getString(Constants.ATTR_ID)); } } /** * Get the associations between schools and sections */ private void getSchoolSectionsMappings(List<GenericEntity> sections, String token, Map<String, GenericEntity> schoolMap, Map<String, String> sectionIDToSchoolIDMap) { for (int i = 0; i < sections.size(); i++) { GenericEntity section = sections.get(i); sectionIDToSchoolIDMap.put(section.getString(Constants.ATTR_ID), section.getString(Constants.ATTR_SCHOOL_ID)); // Add school to map. if (!schoolMap.containsKey(section.get(Constants.ATTR_SCHOOL_ID))) { Map<String, String> query = new HashMap<String, String>(); query.put(Constants.ATTR_SCHOOL_ID, (String) section.get(Constants.ATTR_SCHOOL_ID)); schoolMap.put((String) section.get(Constants.ATTR_SCHOOL_ID), createEntityFromAPI(getApiUrl() + SCHOOLS_URL + section.get(Constants.ATTR_SCHOOL_ID), token)); } } } /** * Simple method to return a list of attendance data. * * @return A list of attendance events for a student. */ @Override public List<GenericEntity> getStudentAttendance(final String token, String studentId) { String url = "/students/" + studentId + "/attendances"; try { return createEntitiesFromAPI(getApiUrl() + url, token); } catch (Exception e) { logger.error("Couldn't retrieve attendance for id:" + studentId, e.getStackTrace()); return new ArrayList<GenericEntity>(); } } private String getUsername() { return SecurityUtil.getPrincipal().getUsername().replace(" ", ""); } /** * Creates a generic entity from an API call * * @param url * @param token * @return the entity */ private GenericEntity createEntityFromAPI(String url, String token) { GenericEntity e = gson.fromJson(restClient.makeJsonRequestWHeaders(url, token), GenericEntity.class); return e; } /** * Retrieves an entity list from the specified API url * and instantiates from its JSON representation * * @param token * - the principle authentication token * @param url * - the API url to retrieve the entity list JSON string representation * @return entityList * - the generic entity list */ private List<GenericEntity> createEntitiesFromAPI(String url, String token) { List<GenericEntity> entityList = new ArrayList<GenericEntity>(); // Parse JSON List<Map> maps = gson.fromJson(restClient.makeJsonRequestWHeaders(url, token), new ArrayList<Map>().getClass()); for (Map<String, Object> map : maps) { entityList.add(new GenericEntity(map)); } return entityList; } private GenericEntity createEntityWithQuery(String baseUrl, Map<String, String> queries, String token) { URLBuilder builder = new URLBuilder(baseUrl); for (Map.Entry<String, String> entry : queries.entrySet()) { builder.addQueryParam(entry.getKey(), entry.getValue()); } return gson.fromJson(restClient.makeJsonRequestWHeaders(builder.toString(), token), GenericEntity.class); } /** * Getter and Setter used by Spring to instantiate the live/test api class * * @return */ public RESTClient getRestClient() { return restClient; } public void setRestClient(RESTClient restClient) { this.restClient = restClient; } public String getApiUrl() { return apiUrl + Constants.API_PREFIX; } public void setApiUrl(String apiUrl) { this.apiUrl = apiUrl; } }
package com.health.operations; import static org.junit.Assert.*; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.Period; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Function; import org.junit.Before; import org.junit.Test; import com.health.Column; import com.health.Event; import com.health.EventList; import com.health.EventSequence; import com.health.Record; import com.health.Table; import com.health.ValueType; import com.health.output.Output; public class CodeTest { Table table; @Before public void setup() { List<Column> columns = new ArrayList<Column>(); columns.add(new Column("date", 0, ValueType.Date)); columns.add(new Column("waarde", 1, ValueType.Number)); columns.add(new Column("name", 2, ValueType.String)); table = new Table(columns); Record tmp = new Record(table); tmp.setValue("date", LocalDateTime.of(2013, 12, 20, 0, 0)); tmp.setValue("waarde", 8.0); tmp.setValue("name", "Jan"); tmp = new Record(table); tmp.setValue("date", LocalDateTime.of(2013, 12, 22, 0, 0)); tmp.setValue("waarde", 10.0); tmp.setValue("name", "Peter"); tmp = new Record(table); tmp.setValue("date", LocalDateTime.of(2013, 12, 26, 0, 0)); tmp.setValue("waarde", 10.0); tmp.setValue("name", "dolfje"); tmp = new Record(table); tmp.setValue("date", LocalDateTime.of(2013, 12, 27, 0, 0)); tmp.setValue("waarde", 10.0); tmp.setValue("name", "Jan"); tmp = new Record(table); tmp.setValue("date", LocalDateTime.of(2013, 12, 29, 0, 0)); tmp.setValue("waarde", 10.0); tmp.setValue("name", "Jan"); tmp = new Record(table); tmp.setValue("date", LocalDateTime.of(2013, 12, 16, 0, 0)); tmp.setValue("waarde", 10.0); tmp.setValue("name", "dolfje"); tmp.setValue("date", LocalDateTime.of(2013, 12, 20, 0, 0)); tmp.setValue("waarde", 8.0); tmp.setValue("name", "Piet"); tmp = new Record(table); tmp.setValue("date", LocalDateTime.of(2013, 12, 12, 0, 0)); tmp.setValue("waarde", 10.0); tmp.setValue("name", "Hein"); tmp = new Record(table); tmp.setValue("date", LocalDateTime.of(2013, 12, 13, 0, 0)); tmp.setValue("waarde", 10.0); tmp.setValue("name", "Dolf"); tmp = new Record(table); tmp.setValue("date", LocalDateTime.of(2013, 12, 10, 0, 0)); tmp.setValue("waarde", 10.0); tmp.setValue("name", "Piet"); tmp = new Record(table); tmp.setValue("date", LocalDateTime.of(2013, 11, 15, 0, 0)); tmp.setValue("waarde", 10.0); tmp.setValue("name", "Piet"); tmp = new Record(table); tmp.setValue("date", LocalDateTime.of(2013, 12, 16, 0, 0)); tmp.setValue("waarde", 10.0); tmp.setValue("name", "Dolf"); } @Test public void testNoCodes() { Map<String, Function<Record, Boolean>> codes = null; EventList eList = Code.makeEventList(table, codes); assertEquals(0, eList.getList().size()); assertFalse(eList.getList().size() > 0); assertFalse(eList.getList().size() != 0); } @Test public void testCodesSize() { Map<String, Function<Record, Boolean>> map = new HashMap<>(); map.put("A", table -> table.getStringValue("name").contains("Dolf")); map.put("B", table -> table.getStringValue("name").contains("Piet")); EventList eList = Code.makeEventList(table, map); assertNotEquals(0, eList.getList().size()); assertTrue(eList.getList().size() == 5); assertFalse(eList.getList().size() != 5); } @Test public void testCodesEventList() { Map<String, Function<Record, Boolean>> map = new HashMap<>(); map.put("A", table -> table.getStringValue("name").contains("Dolf")); map.put("B", table -> table.getStringValue("name").contains("Piet")); EventList eList = Code.makeEventList(table, map); assertNotEquals(0, eList.getList().size()); assertTrue(eList.getList().size() == 5); assertFalse(eList.getList().size() != 5); assertTrue(eList.getEvent(0).getCode().equals("B")); assertTrue(eList.getEvent(2).getCode().equals("A")); } @Test public void testCodesEventListsEmpty() { Map<String, Function<Record, Boolean>> map = new HashMap<>(); Map<String, Function<Record, Boolean>> maps = new HashMap<>(); map.put("A", table -> table.getStringValue("name").contains("Dolf")); map.put("B", table -> table.getStringValue("name").contains("Piet")); EventList eList = Code.makeEventList(table, maps); assertEquals(0, eList.getList().size()); } @Test public void testFillEventSequence() { EventList eList = new EventList(); Event e1 = new Event("A", table.getRecords().get(0)); Event e2 = new Event("B", table.getRecords().get(1)); Event e3 = new Event("A", table.getRecords().get(2)); Event e4 = new Event("B", table.getRecords().get(3)); Event e5 = new Event("C", table.getRecords().get(4)); eList.addEvent(e1); eList.addEvent(e2); eList.addEvent(e3); eList.addEvent(e4); eList.addEvent(e5); String[] codePattern = { "A", "B" }; EventSequence eSeq = new EventSequence(codePattern, true); assertTrue(Code.fillEventSequence(eSeq, eList).size() == 2); } @Test public void testFillEventSequenceWithinPeriod() { EventList eList = new EventList(); Event e1 = new Event("A", table.getRecords().get(0)); Event e2 = new Event("B", table.getRecords().get(1)); Event e3 = new Event("A", table.getRecords().get(2)); Event e4 = new Event("B", table.getRecords().get(3)); Event e5 = new Event("C", table.getRecords().get(4)); eList.addEvent(e1); eList.addEvent(e2); eList.addEvent(e3); eList.addEvent(e4); eList.addEvent(e5); String[] codePattern = { "A", "B" }; EventSequence eSeq = new EventSequence(codePattern, true); Period per = Period.parse("P3M"); Code.fillEventSequenceWithinPeriod(eSeq, eList, per); assertTrue(eSeq.getSequences().size() == 2); EventSequence eSeqe = new EventSequence(codePattern, true); per = Period.parse("P1D"); Code.fillEventSequenceWithinPeriod(eSeqe, eList, per); assertTrue(eSeqe.getSequences().size() == 1); } @Test public void simpleFillTest() { EventList eList = new EventList(); Event e1 = new Event("A", table.getRecords().get(0)); Event e2 = new Event("B", table.getRecords().get(1)); Event e3 = new Event("A", table.getRecords().get(2)); Event e4 = new Event("B", table.getRecords().get(3)); Event e5 = new Event("C", table.getRecords().get(4)); eList.addEvent(e1); eList.addEvent(e2); eList.addEvent(e3); eList.addEvent(e4); eList.addEvent(e5); String[] codePattern = { "A", "B" }; EventSequence eSeq = new EventSequence(codePattern, true); Code.fillEventSequence(eSeq, eList); } }
package com.intellij.openapi.application.impl; import com.intellij.CommonBundle; import com.intellij.ide.GeneralSettings; import com.intellij.ide.IdeEventQueue; import com.intellij.ide.plugins.IdeaPluginDescriptor; import com.intellij.ide.plugins.PluginManager; import com.intellij.openapi.application.*; import com.intellij.openapi.application.ex.ApplicationEx; import com.intellij.openapi.application.ex.ApplicationManagerEx; import com.intellij.openapi.application.ex.DecodeDefaultsUtil; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.components.BaseComponent; import com.intellij.openapi.components.impl.ComponentManagerImpl; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.AreaPicoContainer; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.extensions.PluginId; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.util.ProgressWindow; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.project.ex.ProjectEx; import com.intellij.openapi.project.ex.ProjectManagerEx; import com.intellij.openapi.project.impl.convertors.Convertor34; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; import com.intellij.psi.impl.source.PostprocessReformattingAspect; import com.intellij.util.ArrayUtil; import com.intellij.util.concurrency.ReentrantWriterPreferenceReadWriteLock; import com.intellij.util.containers.HashMap; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.Nullable; import org.picocontainer.MutablePicoContainer; import javax.swing.*; import java.awt.*; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; @SuppressWarnings({"AssignmentToStaticFieldFromInstanceMethod"}) public class ApplicationImpl extends ComponentManagerImpl implements ApplicationEx { private static final Logger LOG = Logger.getInstance("#com.intellij.application.impl.ApplicationImpl"); private ModalityState MODALITY_STATE_NONE; private final List<ApplicationListener> myListeners = new CopyOnWriteArrayList<ApplicationListener>(); private boolean myTestModeFlag = false; private boolean myHeadlessMode = false; private String myComponentsDescriptor; private boolean myIsInternal = false; private static boolean ourSaveSettingsInProgress = false; @NonNls private static final String APPLICATION_LAYER = "application-components"; private String myName; private ReentrantWriterPreferenceReadWriteLock myActionsLock = new ReentrantWriterPreferenceReadWriteLock(); private final Stack<Runnable> myWriteActionsStack = new Stack<Runnable>(); private Thread myExceptionalThreadWithReadAccess = null; private int myInEditorPaintCounter = 0; private long myStartTime = 0; private boolean myDoNotSave = false; private boolean myIsWaitingForWriteAction = false; @NonNls private static final String APPLICATION_ELEMENT = "application"; @NonNls private static final String ELEMENT_COMPONENT = "component"; @NonNls private static final String ATTRIBUTE_NAME = "name"; @NonNls private static final String ATTRIBUTE_CLASS = "class"; @NonNls private static final String NULL_STR = "null"; @NonNls private static final String XML_EXTENSION = ".xml"; private List<Runnable> myPostprocessActions = new ArrayList<Runnable>(); public ApplicationImpl(String componentsDescriptor, boolean isInternal, boolean isUnitTestMode, boolean isHeadless, String appName) { myStartTime = System.currentTimeMillis(); myName = appName; ApplicationManagerEx.setApplication(this); PluginsFacade.INSTANCE = new PluginsFacade() { public IdeaPluginDescriptor getPlugin(PluginId id) { return PluginManager.getPlugin(id); } public IdeaPluginDescriptor[] getPlugins() { return PluginManager.getPlugins(); } }; if (!isUnitTestMode) { Toolkit.getDefaultToolkit().getSystemEventQueue().push(IdeEventQueue.getInstance()); IconLoader.activate(); } getPicoContainer().registerComponentInstance(ApplicationEx.class, this); myComponentsDescriptor = componentsDescriptor; myIsInternal = isInternal; myTestModeFlag = isUnitTestMode; myHeadlessMode = isHeadless; loadApplicationComponents(); if (SystemInfo.isMac || myTestModeFlag) { registerShutdownHook(); } } private void registerShutdownHook() { ShutDownTracker.getInstance(); // Necessary to avoid creating an instance while already shutting down. ShutDownTracker.getInstance().registerShutdownThread(new Thread(new Runnable() { public void run() { try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { saveAll(); dispose(); } }); } catch (InterruptedException e) { LOG.error(e); } catch (InvocationTargetException e) { LOG.error(e); } } })); } public String getComponentsDescriptor() { return myComponentsDescriptor; } public String getName() { return myName; } protected void initComponents() { initComponentsFromExtensions(Extensions.getRootArea()); super.initComponents(); } @Override protected void handleInitComponentError(final BaseComponent component, final Class componentClass, final Throwable ex) { if (PluginManager.isPluginClass(componentClass.getName())) { PluginId pluginId = PluginManager.getPluginByClassName(componentClass.getName()); final String errorMessage = "Plugin " + pluginId.getIdString() + " failed to initialize:\n" + ex.getMessage() + "\nPlease remove the plugin and restart " + ApplicationNamesInfo.getInstance().getFullProductName() + "."; if (!GraphicsEnvironment.isHeadless()) { JOptionPane.showMessageDialog(null, errorMessage); } else { System.out.println(errorMessage); } System.exit(1); } super.handleInitComponentError(component, componentClass, ex); } private void loadApplicationComponents() { loadComponentsConfiguration(APPLICATION_LAYER, true); if (PluginManager.shouldLoadPlugins()) { final IdeaPluginDescriptor[] plugins = PluginManager.getPlugins(); for (IdeaPluginDescriptor plugin : plugins) { if (!PluginManager.shouldLoadPlugin(plugin)) continue; final Element appComponents = plugin.getAppComponents(); if (appComponents != null) { loadComponentsConfiguration(appComponents, plugin, true); } } } } protected MutablePicoContainer createPicoContainer() { final AreaPicoContainer picoContainer = Extensions.getRootArea().getPicoContainer(); picoContainer.setComponentAdapterFactory(new MyComponentAdapterFactory()); return picoContainer; } public boolean isInternal() { return myIsInternal; } public boolean isUnitTestMode() { return myTestModeFlag; } public boolean isHeadlessEnvironment() { return myHeadlessMode; } public IdeaPluginDescriptor getPlugin(PluginId id) { return PluginsFacade.INSTANCE.getPlugin(id); } public IdeaPluginDescriptor[] getPlugins() { return PluginsFacade.INSTANCE.getPlugins(); } private static Thread ourDispatchThread = null; public boolean isDispatchThread() { return EventQueue.isDispatchThread(); } private void save(String path) throws IOException { deleteBackupFiles(path); backupFiles(path); Class[] componentClasses = getComponentInterfaces(); HashMap<String, Element> fileNameToRootElementMap = new HashMap<String, Element>(); for (Class<?> componentClass : componentClasses) { Object component = getComponent(componentClass); if (!(component instanceof BaseComponent)) continue; String fileName; if (component instanceof NamedJDOMExternalizable) { fileName = ((NamedJDOMExternalizable)component).getExternalFileName() + XML_EXTENSION; } else { fileName = PathManager.DEFAULT_OPTIONS_FILE_NAME + XML_EXTENSION; } Element root = getRootElement(fileNameToRootElementMap, fileName); try { Element node = serializeComponent((BaseComponent)component); if (node != null) { root.addContent(node); } } catch (Exception e) { LOG.error(e); } } for (String fileName : fileNameToRootElementMap.keySet()) { Element root = fileNameToRootElementMap.get(fileName); try { JDOMUtil.writeDocument(new Document(root), path + File.separatorChar + fileName, CodeStyleSettingsManager.getSettings(null).getLineSeparator()); } catch (IOException e) { LOG.error(e); } } deleteBackupFiles(path); } private static void backupFiles(String path) throws IOException { String[] list = new File(path).list(); for (String name : list) { if (name.toLowerCase().endsWith(XML_EXTENSION)) { File file = new File(path + File.separatorChar + name); File newFile = new File(path + File.separatorChar + name + "~"); FileUtil.rename(file, newFile); } } } private static Element getRootElement(Map<String, Element> fileNameToRootElementMap, String fileName) { Element root = fileNameToRootElementMap.get(fileName); if (root == null) { root = new Element(APPLICATION_ELEMENT); fileNameToRootElementMap.put(fileName, root); } return root; } private static void deleteBackupFiles(String path) throws IOException { String[] list = new File(path).list(); for (String name : list) { if (StringUtil.endsWithChar(name.toLowerCase(), '~')) { File file = new File(path + File.separatorChar + name); if (!file.delete()) { throw new IOException(ApplicationBundle.message("backup.cannot.delete.file", file.getPath())); } } } } public void load(String path) throws IOException, InvalidDataException { try { if (path == null) return; loadConfiguration(path); } finally { initComponents(); clearDomMap(); } } private void loadConfiguration(String path) { clearDomMap(); File configurationDir = new File(path); if (!configurationDir.exists()) return; Set<String> names = new HashSet<String>(Arrays.asList(configurationDir.list())); for (Iterator<String> i = names.iterator(); i.hasNext();) { String name = i.next(); if (name.endsWith(XML_EXTENSION)) { String backupName = name + "~"; if (names.contains(backupName)) i.remove(); } } for (String name : names) { if (!name.endsWith(XML_EXTENSION) && !name.endsWith(XML_EXTENSION + "~")) continue; // see SCR #12791 final String filePath = path + File.separatorChar + name; File file = new File(filePath); if (!file.exists() || !file.isFile()) continue; try { loadFile(filePath); } catch (Exception e) { //OK here. Just drop corrupted settings. } } } private void loadFile(String filePath) throws JDOMException, InvalidDataException, IOException { Document document = JDOMUtil.loadDocument(new File(filePath)); if (document == null) { throw new InvalidDataException(); } Element root = document.getRootElement(); if (root == null || !APPLICATION_ELEMENT.equals(root.getName())) { throw new InvalidDataException(); } final List<String> additionalFiles = new ArrayList<String>(); synchronized (this) { List children = root.getChildren(ELEMENT_COMPONENT); for (final Object aChildren : children) { Element element = (Element)aChildren; String name = element.getAttributeValue(ATTRIBUTE_NAME); if (name == null || name.length() == 0) { String className = element.getAttributeValue(ATTRIBUTE_CLASS); if (className == null) { throw new InvalidDataException(); } name = className.substring(className.lastIndexOf('.') + 1); } convertComponents(root, filePath, additionalFiles); addConfiguration(name, element); } } for (String additionalPath : additionalFiles) { loadFile(additionalPath); } } private static void convertComponents(Element root, String filePath, final List<String> additionalFiles) {// Converting components final String additionalFilePath; additionalFilePath = Convertor34.convertLibraryTable34(root, filePath); if (additionalFilePath != null) { additionalFiles.add(additionalFilePath); } // Additional converors here probably, adding new files to load // to aditionalFiles } public void dispose() { Project[] openProjects = ProjectManagerEx.getInstanceEx().getOpenProjects(); final boolean[] canClose = new boolean[]{true}; for (final Project project : openProjects) { CommandProcessor commandProcessor = CommandProcessor.getInstance(); commandProcessor.executeCommand(project, new Runnable() { public void run() { FileDocumentManager.getInstance().saveAllDocuments(); if (!ProjectManagerEx.getInstanceEx().closeProject(project)) { canClose[0] = false; } } }, ApplicationBundle.message("command.exit"), null); if (!canClose[0]) break; Disposer.dispose(project); } if (canClose[0]) { fireApplicationExiting(); disposeComponents(); } Disposer.assertIsEmpty(); } public boolean runProcessWithProgressSynchronously(final Runnable process, String progressTitle, boolean canBeCanceled, Project project) { assertIsDispatchThread(); if (myExceptionalThreadWithReadAccess != null || ApplicationManager.getApplication().isUnitTestMode()) { process.run(); return true; } final ProgressWindow progress = new ProgressWindow(canBeCanceled, project); progress.setTitle(progressTitle); class MyThread extends Thread { private final Runnable myProcess; public MyThread() { //noinspection HardCodedStringLiteral super("Process with Progress"); myProcess = process; } public void run() { if (myExceptionalThreadWithReadAccess != this) { if (myExceptionalThreadWithReadAccess == null) { LOG.error("myExceptionalThreadWithReadAccess = null!"); } else { LOG.error("myExceptionalThreadWithReadAccess != thread, process = " + ((MyThread)myExceptionalThreadWithReadAccess).myProcess); } } try { ProgressManager.getInstance().runProcess(myProcess, progress); } catch (ProcessCanceledException e) { // ok to ignore. } } } final MyThread thread = new MyThread(); try { myExceptionalThreadWithReadAccess = thread; final boolean[] threadStarted = new boolean[]{false}; SwingUtilities.invokeLater(new Runnable() { public void run() { if (myExceptionalThreadWithReadAccess != thread) { if (myExceptionalThreadWithReadAccess == null) { LOG.error("myExceptionalThreadWithReadAccess = null!"); } else { LOG.error("myExceptionalThreadWithReadAccess != thread, process = " + ((MyThread)myExceptionalThreadWithReadAccess) .myProcess); } } thread.start(); threadStarted[0] = true; } }); progress.startBlocking(); LOG.assertTrue(threadStarted[0]); LOG.assertTrue(!progress.isRunning()); } finally { myExceptionalThreadWithReadAccess = null; } return !progress.isCanceled(); } public void invokeLater(Runnable runnable) { LaterInvocator.invokeLater(runnable); } public void invokeLater(Runnable runnable, ModalityState state) { LaterInvocator.invokeLater(runnable, state); } public void invokeAndWait(Runnable runnable, ModalityState modalityState) { if (isDispatchThread()) { LOG.error("invokeAndWait should not be called from event queue thread"); runnable.run(); return; } Thread currentThread = Thread.currentThread(); if (myExceptionalThreadWithReadAccess == currentThread) { //OK if we're in exceptional thread. LaterInvocator.invokeAndWait(runnable, modalityState); return; } if (myActionsLock.isReadLockAcquired(currentThread)) { final Throwable stack = new Throwable(); SwingUtilities.invokeLater(new Runnable() { public void run() { LOG.error("Calling invokeAndWait from read-action leads to possible deadlock.", stack); } }); if (myIsWaitingForWriteAction) return; // The deadlock indeed. Do not perform request or we'll stall here immediately. } LaterInvocator.invokeAndWait(runnable, modalityState); } public ModalityState getCurrentModalityState() { Object[] entities = LaterInvocator.getCurrentModalEntities(); return entities.length > 0 ? new ModalityStateEx(entities) : getNoneModalityState(); } public ModalityState getModalityStateForComponent(Component c) { Window window = c instanceof Window ? (Window)c : SwingUtilities.windowForComponent(c); if (window == null) return getNoneModalityState(); return LaterInvocator.modalityStateForWindow(window); } public ModalityState getDefaultModalityState() { if (EventQueue.isDispatchThread()) { return getCurrentModalityState(); } else { ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); if (progress != null) { return progress.getModalityState(); } else { return getNoneModalityState(); } } } public ModalityState getNoneModalityState() { if (MODALITY_STATE_NONE == null) { MODALITY_STATE_NONE = new ModalityStateEx(ArrayUtil.EMPTY_OBJECT_ARRAY); } return MODALITY_STATE_NONE; } public long getStartTime() { return myStartTime; } public long getIdleTime() { return IdeEventQueue.getInstance().getIdleTime(); } public void exit() { exit(false); } public void exit(final boolean force) { if (SystemInfo.isMac) { if (!force) { if (!showConfirmation()) return; } if (!canExit()) return; new Thread(new Runnable() { public void run() { System.exit(0); } }).start(); } else { Runnable runnable = new Runnable() { public void run() { if (!force) { if (!showConfirmation()) { saveAll(); return; } } saveAll(); if (!canExit()) return; dispose(); System.exit(0); } }; if (!isDispatchThread()) { invokeLater(runnable, ModalityState.NON_MMODAL); } else { runnable.run(); } } } private static boolean showConfirmation() { if (GeneralSettings.getInstance().isConfirmExit()) { final ConfirmExitDialog confirmExitDialog = new ConfirmExitDialog(); confirmExitDialog.show(); if (!confirmExitDialog.isOK()) { return false; } } return true; } private boolean canExit() { for (ApplicationListener applicationListener : myListeners) { if (!applicationListener.canExitApplication()) { return false; } } ProjectManagerEx projectManager = (ProjectManagerEx)ProjectManager.getInstance(); Project[] projects = projectManager.getOpenProjects(); for (Project project : projects) { if (!projectManager.canClose(project)) { return false; } } return true; } public void runReadAction(final Runnable action) { boolean isExceptionalThread = isExceptionalThreadWithReadAccess(Thread.currentThread()); if (!isExceptionalThread) { while (true) { try { myActionsLock.readLock().acquire(); } catch (InterruptedException e) { throw new RuntimeInterruptedException(e); } break; } } try { action.run(); } finally { if (!isExceptionalThread) { myActionsLock.readLock().release(); } } } public boolean isExceptionalThreadWithReadAccess(final Thread thread) { return myExceptionalThreadWithReadAccess != null && thread == myExceptionalThreadWithReadAccess; } public <T> T runReadAction(final Computable<T> computation) { final Ref<T> ref = Ref.create(null); runReadAction(new Runnable() { public void run() { ref.set(computation.compute()); } }); return ref.get(); } public void runWriteAction(final Runnable action) { assertCanRunWriteAction(); fireBeforeWriteActionStart(action); myIsWaitingForWriteAction = true; try { while (true) { try { myActionsLock.writeLock().acquire(); } catch (InterruptedException e) { throw new RuntimeInterruptedException(e); } break; } } finally { myIsWaitingForWriteAction = false; } fireWriteActionStarted(action); try { synchronized (myWriteActionsStack) { myWriteActionsStack.push(action); } final Project project = CommandProcessor.getInstance().getCurrentCommandProject(); if(project != null) { // run postprocess formatting inside commands only PostprocessReformattingAspect.getInstance(project).postponeFormattingInside(new Computable<Object>() { public Object compute() { action.run(); return null; } }); } else action.run(); } finally { synchronized (myWriteActionsStack) { writeActionPostprocessing(); myWriteActionsStack.pop(); } fireWriteActionFinished(action); myActionsLock.writeLock().release(); } } public void addPostWriteAction(Runnable action) { myPostprocessActions.add(action); } public void removePostWriteAction(Runnable action) { myPostprocessActions.remove(action); } private void writeActionPostprocessing() { for (Runnable postprocessAction : myPostprocessActions) { postprocessAction.run(); } } public <T> T runWriteAction(final Computable<T> computation) { final Ref<T> ref = Ref.create(null); runWriteAction(new Runnable() { public void run() { ref.set(computation.compute()); } }); return ref.get(); } public Object getCurrentWriteAction(Class actionClass) { synchronized (myWriteActionsStack) { for (int i = myWriteActionsStack.size() - 1; i >= 0; i Runnable action = myWriteActionsStack.get(i); if (actionClass == null || actionClass.isAssignableFrom(action.getClass())) return action; } } return null; } public void assertReadAccessAllowed() { if (myTestModeFlag || myHeadlessMode) return; if (!isReadAccessAllowed()) { LOG.error( "Read access is allowed from event dispatch thread or inside read-action only (see com.intellij.openapi.application.Application.runReadAction())", "Current thread: " + describe(Thread.currentThread()), "Our dispatch thread:" + describe(ourDispatchThread), "SystemEventQueueThread: " + describe(getEventQueueThread())); } } private static String describe(Thread o) { if (o == null) return NULL_STR; return o.toString() + " " + System.identityHashCode(o); } @Nullable private static Thread getEventQueueThread() { EventQueue eventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue(); try { //noinspection HardCodedStringLiteral Method method = EventQueue.class.getDeclaredMethod("getDispatchThread"); method.setAccessible(true); return (Thread)method.invoke(eventQueue); } catch (Exception e1) { } return null; } public boolean isReadAccessAllowed() { Thread currentThread = Thread.currentThread(); if (ourDispatchThread == currentThread) { //TODO! /* IdeEventQueue eventQueue = IdeEventQueue.getInstance(); //TODO: cache? if (!eventQueue.isInInputEvent() && !LaterInvocator.isInMyRunnable() && !myInEditorPaint) { LOG.error("Read access from event dispatch thread is allowed only inside input event processing or LaterInvocator.invokeLater"); } */ return true; } else { if (myExceptionalThreadWithReadAccess == currentThread) return true; if (myActionsLock.isReadLockAcquired(currentThread)) return true; if (myActionsLock.isWriteLockAcquired(currentThread)) return true; return isDispatchThread(); } } public void assertReadAccessToDocumentsAllowed() { /* TODO Thread currentThread = Thread.currentThread(); if (ourDispatchThread != currentThread) { if (myExceptionalThreadWithReadAccess == currentThread) return; if (myActionsLock.isReadLockAcquired(currentThread)) return; if (myActionsLock.isWriteLockAcquired(currentThread)) return; if (isDispatchThread(currentThread)) return; LOG.error( "Read access is allowed from event dispatch thread or inside read-action only (see com.intellij.openapi.application.Application.runReadAction())"); } */ } protected void assertCanRunWriteAction() { assertIsDispatchThread("Write access is allowed from event dispatch thread only"); } public void assertIsDispatchThread() { assertIsDispatchThread("Access is allowed from event dispatch thread only."); } private void assertIsDispatchThread(String message) { if (myTestModeFlag || myHeadlessMode) return; final Thread currentThread = Thread.currentThread(); if (ourDispatchThread == currentThread) return; if (EventQueue.isDispatchThread()) { ourDispatchThread = currentThread; } if (ourDispatchThread == currentThread) return; LOG.error(message, "Current thread: " + describe(Thread.currentThread()), "Our dispatch thread:" + describe(ourDispatchThread), "SystemEventQueueThread: " + describe(getEventQueueThread())); } public void assertWriteAccessAllowed() { LOG.assertTrue(isWriteAccessAllowed(), "Write access is allowed inside write-action only (see com.intellij.openapi.application.Application.runWriteAction())"); } public boolean isWriteAccessAllowed() { return myActionsLock.isWriteLockAcquired(Thread.currentThread()); } public void editorPaintStart() { myInEditorPaintCounter++; } public void editorPaintFinish() { myInEditorPaintCounter LOG.assertTrue(myInEditorPaintCounter >= 0); } public void addApplicationListener(ApplicationListener l) { myListeners.add(l); } public void removeApplicationListener(ApplicationListener l) { myListeners.remove(l); } private void fireApplicationExiting() { for (ApplicationListener applicationListener : myListeners) { applicationListener.applicationExiting(); } } private void fireBeforeWriteActionStart(Runnable action) { for (ApplicationListener listener : myListeners) { listener.beforeWriteActionStart(action); } } private void fireWriteActionStarted(Runnable action) { for (ApplicationListener listener : myListeners) { listener.writeActionStarted(action); } } private void fireWriteActionFinished(Runnable action) { for (ApplicationListener listener : myListeners) { listener.writeActionFinished(action); } } protected Element getDefaults(BaseComponent component) throws IOException, JDOMException, InvalidDataException { InputStream stream = getDefaultsInputStream(component); if (stream != null) { Document document = null; try { document = JDOMUtil.loadDocument(stream); } finally { stream.close(); } if (document == null) { throw new InvalidDataException(); } Element root = document.getRootElement(); if (root == null || !ELEMENT_COMPONENT.equals(root.getName())) { throw new InvalidDataException(); } return root; } return null; } @Nullable protected ComponentManagerImpl getParentComponentManager() { return null; } private static InputStream getDefaultsInputStream(BaseComponent component) { return DecodeDefaultsUtil.getDefaultsInputStream(component); } public void saveSettings() { if (myDoNotSave) return; ShutDownTracker.getInstance().registerStopperThread(Thread.currentThread()); try { if (!ourSaveSettingsInProgress) { ourSaveSettingsInProgress = true; final String optionsPath = PathManager.getOptionsPath(); File file = new File(optionsPath); if (!file.exists()) { file.mkdirs(); } try { save(optionsPath); } catch (final Throwable ex) { ex.printStackTrace(); invokeLater(new Runnable() { public void run() { Messages.showMessageDialog(ApplicationBundle.message("application.save.settings.error", ex.getLocalizedMessage()), CommonBundle.getErrorTitle(), Messages.getErrorIcon()); } }); } finally { ourSaveSettingsInProgress = false; } } saveSettingsSavingComponents(); } finally { ShutDownTracker.getInstance().unregisterStopperThread(Thread.currentThread()); } } public void saveAll() { if (myDoNotSave || isUnitTestMode() || isHeadlessEnvironment()) return; FileDocumentManager.getInstance().saveAllDocuments(); Project[] openProjects = ProjectManager.getInstance().getOpenProjects(); for (Project openProject : openProjects) { ProjectEx project = (ProjectEx)openProject; project.save(); } saveSettings(); } public void doNotSave() { myDoNotSave = true; } }
package jadx.api; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.ResourceFile.ZipRef; import jadx.api.impl.SimpleCodeInfo; import jadx.api.plugins.utils.ZipSecurity; import jadx.core.codegen.CodeWriter; import jadx.core.utils.Utils; import jadx.core.utils.android.Res9patchStreamDecoder; import jadx.core.utils.exceptions.JadxException; import jadx.core.utils.files.FileUtils; import jadx.core.xmlgen.ResContainer; import jadx.core.xmlgen.ResTableParser; import static jadx.core.utils.files.FileUtils.READ_BUFFER_SIZE; import static jadx.core.utils.files.FileUtils.copyStream; // TODO: move to core package public final class ResourcesLoader { private static final Logger LOG = LoggerFactory.getLogger(ResourcesLoader.class); private final JadxDecompiler jadxRef; ResourcesLoader(JadxDecompiler jadxRef) { this.jadxRef = jadxRef; } List<ResourceFile> load() { List<File> inputFiles = jadxRef.getArgs().getInputFiles(); List<ResourceFile> list = new ArrayList<>(inputFiles.size()); for (File file : inputFiles) { loadFile(list, file); } return list; } public interface ResourceDecoder<T> { T decode(long size, InputStream is) throws IOException; } public static <T> T decodeStream(ResourceFile rf, ResourceDecoder<T> decoder) throws JadxException { try { ZipRef zipRef = rf.getZipRef(); if (zipRef == null) { File file = new File(rf.getOriginalName()); try (InputStream inputStream = new BufferedInputStream(new FileInputStream(file))) { return decoder.decode(file.length(), inputStream); } } else { try (ZipFile zipFile = new ZipFile(zipRef.getZipFile())) { ZipEntry entry = zipFile.getEntry(zipRef.getEntryName()); if (entry == null) { throw new IOException("Zip entry not found: " + zipRef); } if (!ZipSecurity.isValidZipEntry(entry)) { return null; } try (InputStream inputStream = ZipSecurity.getInputStreamForEntry(zipFile, entry)) { return decoder.decode(entry.getSize(), inputStream); } } } } catch (Exception e) { throw new JadxException("Error decode: " + rf.getDeobfName(), e); } } static ResContainer loadContent(JadxDecompiler jadxRef, ResourceFile rf) { try { return decodeStream(rf, (size, is) -> loadContent(jadxRef, rf, is)); } catch (JadxException e) { LOG.error("Decode error", e); CodeWriter cw = new CodeWriter(); cw.add("Error decode ").add(rf.getType().toString().toLowerCase()); Utils.appendStackTrace(cw, e.getCause()); return ResContainer.textResource(rf.getDeobfName(), cw.finish()); } } private static ResContainer loadContent(JadxDecompiler jadxRef, ResourceFile rf, InputStream inputStream) throws IOException { switch (rf.getType()) { case MANIFEST: case XML: ICodeInfo content = jadxRef.getXmlParser().parse(inputStream); return ResContainer.textResource(rf.getDeobfName(), content); case ARSC: return new ResTableParser(jadxRef.getRoot()).decodeFiles(inputStream); case IMG: return decodeImage(rf, inputStream); default: return ResContainer.resourceFileLink(rf); } } private static ResContainer decodeImage(ResourceFile rf, InputStream inputStream) { String name = rf.getOriginalName(); if (name.endsWith(".9.png")) { try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { Res9patchStreamDecoder decoder = new Res9patchStreamDecoder(); decoder.decode(inputStream, os); return ResContainer.decodedData(rf.getDeobfName(), os.toByteArray()); } catch (Exception e) { LOG.error("Failed to decode 9-patch png image, path: {}", name, e); } } return ResContainer.resourceFileLink(rf); } private void loadFile(List<ResourceFile> list, File file) { if (file == null) { return; } if (FileUtils.isZipFile(file)) { ZipSecurity.visitZipEntries(file, (zipFile, entry) -> addEntry(list, file, entry)); } else { addResourceFile(list, file); } } private void addResourceFile(List<ResourceFile> list, File file) { String name = file.getAbsolutePath(); ResourceType type = ResourceType.getFileType(name); ResourceFile rf = ResourceFile.createResourceFile(jadxRef, name, type); if (rf != null) { list.add(rf); } } private void addEntry(List<ResourceFile> list, File zipFile, ZipEntry entry) { if (entry.isDirectory()) { return; } String name = entry.getName(); ResourceType type = ResourceType.getFileType(name); ResourceFile rf = ResourceFile.createResourceFile(jadxRef, name, type); if (rf != null) { rf.setZipRef(new ZipRef(zipFile, name)); list.add(rf); } } public static ICodeInfo loadToCodeWriter(InputStream is) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(READ_BUFFER_SIZE); copyStream(is, baos); return new SimpleCodeInfo(baos.toString("UTF-8")); } }
import models.AutoTs; import org.junit.Before; import org.junit.Test; import play.Logger; import play.test.UnitTest; public class AutoTsTest extends UnitTest { @Before public void setup() { AutoTs.deleteAll(); } @Test public void testAutoTimestamp() throws Exception { AutoTs model = new AutoTs(); model.content = "hello"; assertSame(model._getCreated(), 0L); assertSame(model._getModified(), 0L); long ts = System.currentTimeMillis(); Thread.sleep(1000L); model.save(); Logger.info("created: %1$s", model._getCreated()); assertTrue(model._getCreated() >= ts); assertTrue(model._getModified() >= ts); Thread.sleep(1000L); ts = System.currentTimeMillis(); model.content = "world"; model.save(); assertTrue(model._getCreated() < ts); assertTrue(model._getModified() >= ts); } }
package net.sourceforge.texlipse.texparser; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.regex.Pattern; import net.sourceforge.texlipse.TexlipsePlugin; import net.sourceforge.texlipse.model.DocumentReference; import net.sourceforge.texlipse.model.OutlineNode; import net.sourceforge.texlipse.model.ParseErrorMessage; import net.sourceforge.texlipse.model.ReferenceEntry; import net.sourceforge.texlipse.model.TexCommandEntry; import net.sourceforge.texlipse.texparser.lexer.LexerException; import net.sourceforge.texlipse.texparser.node.*; import org.eclipse.core.resources.IMarker; /** * Simple parser for LaTeX: does very basic structure checking and * extracts useful data. * * @author Oskar Ojala * @author Boris von Loesch */ public class LatexParser { // These should be allocated between 1000-2000 public static final int TYPE_LABEL = 1000; private static final Pattern PART_RE = Pattern.compile("\\\\part(?:[^a-zA-Z]|$)"); private static final Pattern CHAPTER_RE = Pattern.compile("\\\\chapter(?:[^a-zA-Z]|$)"); private static final Pattern SECTION_RE = Pattern.compile("\\\\section(?:[^a-zA-Z]|$)"); private static final Pattern SSECTION_RE = Pattern.compile("\\\\subsection(?:[^a-zA-Z]|$)"); private static final Pattern SSSECTION_RE = Pattern.compile("\\\\subsubsection(?:[^a-zA-Z]|$)"); private static final Pattern PARAGRAPH_RE = Pattern.compile("\\\\paragraph(?:[^a-zA-Z]|$)"); private static final Pattern LABEL_RE = Pattern.compile("\\\\label(?:[^a-zA-Z]|$)"); /** * Defines a new stack implementation, which is unsynchronized and * tuned for the needs of the parser, making it much faster than * java.util.Stack * * @author Oskar Ojala */ private final static class StackUnsynch<E> { private static final int INITIAL_SIZE = 10; private static final int GROWTH_FACTOR = 2; private int capacity; private int size; private Object[] stack; /** * Creates a new stack. */ public StackUnsynch() { stack = new Object[INITIAL_SIZE]; size = 0; capacity = INITIAL_SIZE; } /** * @return True if the stack is empty, false if it contains items */ public boolean empty() { return (size == 0); } /** * @return The item at the top of the stack */ @SuppressWarnings("unchecked") public E peek() { return (E)(stack[size-1]); } /** * Removes the item at the stop of the stack. * * @return The item at the top of the stack */ @SuppressWarnings("unchecked") public E pop() { size E top = (E) stack[size]; stack[size] = null; return top; } /** * Pushes an item to the top of the stack. * * @param item The item to push on the stack */ public void push(final E item) { // what if size would be where to put the next item? if (size >= capacity) { capacity *= GROWTH_FACTOR; Object[] newStack = new Object[capacity]; System.arraycopy(stack, 0, newStack, 0, stack.length); stack = newStack; } stack[size] = item; size++; } /** * Clears the stack; removes all entries. */ public void clear() { for (size--; size >= 0; size--) { stack[size] = null; } size = 0; } } private List<ReferenceEntry> labels; private List<DocumentReference> cites; private List<DocumentReference> refs; private ArrayList<TexCommandEntry> commands; private List<ParseErrorMessage> tasks; private String[] bibs; private String bibstyle; private List<OutlineNode> inputs; private ArrayList<OutlineNode> outlineTree; private List<ParseErrorMessage> errors; private OutlineNode documentEnv; private boolean index; private boolean fatalErrors; /** * Initializes the internal datastructures that are exported after parsing. */ private void initializeDatastructs() { this.labels = new ArrayList<ReferenceEntry>(); this.cites = new ArrayList<DocumentReference>(); this.refs = new ArrayList<DocumentReference>(); this.commands = new ArrayList<TexCommandEntry>(); this.tasks = new ArrayList<ParseErrorMessage>(); this.inputs = new ArrayList<OutlineNode>(2); this.outlineTree = new ArrayList<OutlineNode>(); this.errors = new ArrayList<ParseErrorMessage>(); this.bibs = null; this.index = false; this.fatalErrors = false; } /** * Parses a LaTeX document. Uses the given lexer's <code>next()</code> * method to receive tokens that are processed. * * @param lex The lexer to use for extracting the document tokens * @param definedLabels Labels that are defined, used to check for references to * nonexistant labels * @param definedBibs Defined bibliography entries, used to check for references to * nonexistant bibliography entries * @throws LexerException If the given lexer cannot tokenize the document * @throws IOException If the document is unreadable */ public void parse(LatexLexer lex, boolean checkForMissingSections) throws LexerException, IOException { parse(lex, null, checkForMissingSections); } /** * Parses a LaTeX document. Uses the given lexer's <code>next()</code> * method to receive tokens that are processed. * * @param lexer The lexer to use for extracting the document tokens * @param definedLabels Labels that are defined, used to check for references to * nonexistant labels * @param definedBibs Defined bibliography entries, used to check for references to * nonexistant bibliography entries * @param preamble An <code>OutlineNode</code> containing the preamble, null if there is no preamble * @param checkForMissingSections * @throws LexerException If the given lexer cannot tokenize the document * @throws IOException If the document is unreadable */ public void parse(final LatexLexer lexer, final OutlineNode preamble, final boolean checkForMissingSections) throws LexerException, IOException { initializeDatastructs(); StackUnsynch<OutlineNode> blocks = new StackUnsynch<OutlineNode>(); StackUnsynch<Token> braces = new StackUnsynch<Token>(); boolean expectArg = false; boolean expectArg2 = false; Token prevToken = null; TexCommandEntry currentCommand = null; int argCount = 0; int nodeType; HashMap<String, Integer> sectioning = new HashMap<String, Integer>(); if (preamble != null) { outlineTree.add(preamble); blocks.push(preamble); } // newcommand would need to check for the valid format // duplicate labels? // change order of ifs to optimize performance? int accumulatedLength = 0; Token t = lexer.next(); for (; !(t instanceof EOF); t = lexer.next()) { if (expectArg) { if (t instanceof TArgument) { if (prevToken instanceof TClabel) { //this.labels.add(new ReferenceEntry(t.getText())); ReferenceEntry l = new ReferenceEntry(t.getText()); l.setPosition(t.getPos(), t.getText().length()); l.startLine = t.getLine(); this.labels.add(l); OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_LABEL, t.getLine(), t.getPos(), t.getText().length()); on.setEndLine(t.getLine()); if (!blocks.empty()) { OutlineNode prev = blocks.peek(); prev.addChild(on); on.setParent(prev); } else { outlineTree.add(on); } } else if (prevToken instanceof TCref) { this.refs.add(new DocumentReference(t.getText(), t.getLine(), t.getPos(), t.getText().length())); } else if (prevToken instanceof TCcite) { if (!"*".equals(t.getText())) { String[] cs = t.getText().split(","); for (String c : cs) { //just add all citation and check for errors later, after updating the citation index this.cites.add(new DocumentReference(c.trim(), t.getLine(), t.getPos(), t.getText().length())); } } } else if (prevToken instanceof TCbegin) { // \begin{...} OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_ENVIRONMENT, t.getLine(), prevToken.getPos(), prevToken.getText().length() + accumulatedLength + t.getText().length()); if ("document".equals(t.getText())) { if (preamble != null) preamble.setEndLine(t.getLine()); blocks.clear(); documentEnv = on; } else { if (!blocks.empty()) { OutlineNode prev = blocks.peek(); prev.addChild(on); on.setParent(prev); } else { outlineTree.add(on); } blocks.push(on); } } else if (prevToken instanceof TCend) { // \end{...} int endLine = t.getLine(); OutlineNode prev = null; // check if the document ends if ("document".equals(t.getText())) { documentEnv.setEndLine(endLine + 1); // terminate open blocks here; check for errors while (!blocks.empty()) { prev = blocks.pop(); prev.setEndLine(endLine); if (prev.getType() == OutlineNode.TYPE_ENVIRONMENT) { errors.add(new ParseErrorMessage(prevToken.getLine(), prevToken.getPos(), prevToken.getText().length() + accumulatedLength + t.getText().length(), "\\end{" + prev.getName() + "} expected, but \\end{document} found; at least one unbalanced begin-end", IMarker.SEVERITY_ERROR)); fatalErrors = true; } } } else { // the "normal" case boolean traversing = true; if (!blocks.empty()) { while (traversing && !blocks.empty()) { prev = blocks.pop(); if (prev.getType() == OutlineNode.TYPE_ENVIRONMENT) { prev.setEndLine(endLine + 1); traversing = false; } else { prev.setEndLine(endLine); } } } if (blocks.empty() && traversing) { fatalErrors = true; errors.add(new ParseErrorMessage(prevToken.getLine(), prevToken.getPos(), prevToken.getText().length() + accumulatedLength + t.getText().length(), "\\end{" + t.getText() + "} found with no preceding \\begin", IMarker.SEVERITY_ERROR)); } else if (!prev.getName().equals(t.getText())) { fatalErrors = true; errors.add(new ParseErrorMessage(prev.getBeginLine(), prev.getOffsetOnLine(), prev.getDeclarationLength(), "\\end{" + prev.getName() + "} expected, but \\end{" + t.getText() + "} found; unbalanced begin-end", IMarker.SEVERITY_ERROR)); errors.add(new ParseErrorMessage(prevToken.getLine(), prevToken.getPos(), prevToken.getText().length() + accumulatedLength + t.getText().length(), "\\end{" + prev.getName() + "} expected, but \\end{" + t.getText() + "} found; unbalanced begin-end", IMarker.SEVERITY_ERROR)); } } } else if (prevToken instanceof TCpart) { int startLine = prevToken.getLine(); OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_PART, startLine, null); if (!blocks.empty()) { boolean traversing = true; while (traversing && !blocks.empty()) { OutlineNode prev = blocks.peek(); if (prev.getType() == OutlineNode.TYPE_ENVIRONMENT) { prev.addChild(on); on.setParent(prev); traversing = false; } else { prev.setEndLine(startLine); blocks.pop(); } } } if (blocks.empty()) outlineTree.add(on); blocks.push(on); } else if (prevToken instanceof TCchapter) { int startLine = prevToken.getLine(); OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_CHAPTER, startLine, null); if (!blocks.empty()) { boolean traversing = true; while (traversing && !blocks.empty()) { OutlineNode prev = blocks.peek(); switch (prev.getType()) { case OutlineNode.TYPE_PART: case OutlineNode.TYPE_ENVIRONMENT: prev.addChild(on); on.setParent(prev); traversing = false; break; default: prev.setEndLine(startLine); blocks.pop(); break; } } } // add directly to tree if no parent was found if (blocks.empty()) outlineTree.add(on); blocks.push(on); } else if (prevToken instanceof TCsection) { int startLine = prevToken.getLine(); OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_SECTION, startLine, null); if (!blocks.empty()) { boolean traversing = true; while (traversing && !blocks.empty()) { OutlineNode prev = blocks.peek(); switch (prev.getType()) { case OutlineNode.TYPE_PART: case OutlineNode.TYPE_CHAPTER: case OutlineNode.TYPE_ENVIRONMENT: prev.addChild(on); on.setParent(prev); traversing = false; break; default: prev.setEndLine(startLine); blocks.pop(); break; } } } // add directly to tree if no parent was found if (blocks.empty()) { outlineTree.add(on); } blocks.push(on); } else if (prevToken instanceof TCssection) { int startLine = prevToken.getLine(); OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_SUBSECTION, startLine, null); boolean foundSection = false; if (!blocks.empty()) { boolean traversing = true; while (traversing && !blocks.empty()) { OutlineNode prev = blocks.peek(); switch (prev.getType()) { case OutlineNode.TYPE_ENVIRONMENT: case OutlineNode.TYPE_SECTION: foundSection = true; case OutlineNode.TYPE_PART: case OutlineNode.TYPE_CHAPTER: prev.addChild(on); on.setParent(prev); traversing = false; break; default: prev.setEndLine(startLine); blocks.pop(); break; } } } // add directly to tree if no parent was found if (blocks.empty()) outlineTree.add(on); if (!foundSection && checkForMissingSections) { errors.add(new ParseErrorMessage(prevToken.getLine(), prevToken.getPos(), prevToken.getText().length() + accumulatedLength + t.getText().length(), "Subsection " + prevToken.getText() + " has no preceding section", IMarker.SEVERITY_WARNING)); } blocks.push(on); } else if (prevToken instanceof TCsssection) { int startLine = prevToken.getLine(); OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_SUBSUBSECTION, prevToken.getLine(), null); boolean foundSsection = false; if (!blocks.empty()) { boolean traversing = true; while (traversing && !blocks.empty()) { OutlineNode prev = blocks.peek(); switch (prev.getType()) { case OutlineNode.TYPE_ENVIRONMENT: case OutlineNode.TYPE_SUBSECTION: foundSsection = true; case OutlineNode.TYPE_PART: case OutlineNode.TYPE_CHAPTER: case OutlineNode.TYPE_SECTION: prev.addChild(on); on.setParent(prev); traversing = false; break; default: prev.setEndLine(startLine); blocks.pop(); break; } } } // add directly to tree if no parent was found if (blocks.empty()) outlineTree.add(on); if (!foundSsection && checkForMissingSections) { errors.add(new ParseErrorMessage(prevToken.getLine(), prevToken.getPos(), prevToken.getText().length() + accumulatedLength + t.getText().length(), "Subsubsection " + prevToken.getText() + " has no preceding subsection", IMarker.SEVERITY_WARNING)); } blocks.push(on); } else if (prevToken instanceof TCparagraph) { int startLine = prevToken.getLine(); OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_PARAGRAPH, prevToken.getLine(), null); boolean foundSssection = false; if (!blocks.empty()) { boolean traversing = true; while (traversing && !blocks.empty()) { OutlineNode prev = blocks.peek(); switch (prev.getType()) { case OutlineNode.TYPE_ENVIRONMENT: case OutlineNode.TYPE_SUBSUBSECTION: foundSssection = true; case OutlineNode.TYPE_PART: case OutlineNode.TYPE_CHAPTER: case OutlineNode.TYPE_SECTION: case OutlineNode.TYPE_SUBSECTION: prev.addChild(on); on.setParent(prev); traversing = false; break; default: prev.setEndLine(startLine); blocks.pop(); break; } } } // add directly to tree if no parent was found if (blocks.empty()) outlineTree.add(on); if (!foundSssection && checkForMissingSections) { errors.add(new ParseErrorMessage(prevToken.getLine(), prevToken.getPos(), prevToken.getText().length() + accumulatedLength + t.getText().length(), "Paragraph " + prevToken.getText() + " has no preceding subsubsection", IMarker.SEVERITY_WARNING)); } blocks.push(on); } else if (prevToken instanceof TCbib) { bibs = t.getText().split(","); for (int i = 0; i < bibs.length; i++) { bibs[i] = bibs[i].trim(); } int startLine = prevToken.getLine(); while (!blocks.empty()) { OutlineNode prev = blocks.pop(); if (prev.getType() == OutlineNode.TYPE_ENVIRONMENT) { // this is an error... blocks.push(prev); break; } prev.setEndLine(startLine); } } else if (prevToken instanceof TCbibstyle) { this.bibstyle = t.getText(); int startLine = prevToken.getLine(); while (!blocks.empty()) { OutlineNode prev = blocks.pop(); if (prev.getType() == OutlineNode.TYPE_ENVIRONMENT) { // this is an error... blocks.push(prev); break; } prev.setEndLine(startLine); } } else if (prevToken instanceof TCinput || prevToken instanceof TCinclude) { //inputs.add(t.getText()); if (!blocks.empty()) { OutlineNode prev = blocks.peek(); OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_INPUT, t.getLine(), prev); on.setEndLine(t.getLine()); prev.addChild(on); inputs.add(on); } else { OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_INPUT, t.getLine(), null); on.setEndLine(t.getLine()); outlineTree.add(on); inputs.add(on); } } else if (prevToken instanceof TCnew) { //currentCommand = new CommandEntry(t.getText().substring(1)); currentCommand = new TexCommandEntry(t.getText().substring(1), "", 0); currentCommand.startLine = t.getLine(); lexer.registerCommand(currentCommand.key); expectArg2 = true; } // reset state to normal scanning accumulatedLength = 0; prevToken = null; expectArg = false; } else if ((t instanceof TCword) && (prevToken instanceof TCnew)) { // this handles the \newcommand\comx{...} -format //currentCommand = new CommandEntry(t.getText().substring(1)); currentCommand = new TexCommandEntry(t.getText().substring(1), "", 0); currentCommand.startLine = t.getLine(); lexer.registerCommand(currentCommand.key); expectArg2 = true; accumulatedLength = 0; prevToken = null; expectArg = false; } else if (!(t instanceof TOptargument) && !(t instanceof TWhitespace) && !(t instanceof TStar) && !(t instanceof TCommentline) && !(t instanceof TTaskcomment)) { // if we didn't get the mandatory argument we were expecting... //fatalErrors = true; errors.add(new ParseErrorMessage(prevToken.getLine(), prevToken.getPos(), prevToken.getText().length() + accumulatedLength + t.getText().length(), "No argument following " + prevToken.getText(), IMarker.SEVERITY_WARNING)); accumulatedLength = 0; prevToken = null; expectArg = false; } else { accumulatedLength += t.getText().length(); } } else if (expectArg2) { // we are capturing the second argument of a command with two arguments // the only one of those that interests us is newcommand if (t instanceof TArgument) { currentCommand.info = t.getText(); commands.add(currentCommand); if (PART_RE.matcher(currentCommand.info).find()) sectioning.put("\\" + currentCommand.key, OutlineNode.TYPE_PART); //else if (currentCommand.info.indexOf("\\chapter") != -1) else if (CHAPTER_RE.matcher(currentCommand.info).find()) sectioning.put("\\" + currentCommand.key, OutlineNode.TYPE_CHAPTER); //else if (currentCommand.info.indexOf("\\section") != -1) else if (SECTION_RE.matcher(currentCommand.info).find()) sectioning.put("\\" + currentCommand.key, OutlineNode.TYPE_SECTION); //else if (currentCommand.info.indexOf("\\subsection") != -1) else if (SSECTION_RE.matcher(currentCommand.info).find()) sectioning.put("\\" + currentCommand.key, OutlineNode.TYPE_SUBSECTION); //else if (currentCommand.info.indexOf("\\subsubsection") != -1) else if (SSSECTION_RE.matcher(currentCommand.info).find()) sectioning.put("\\" + currentCommand.key, OutlineNode.TYPE_SUBSUBSECTION); //else if (currentCommand.info.indexOf("\\paragraph") != -1) else if (PARAGRAPH_RE.matcher(currentCommand.info).find()) sectioning.put("\\" + currentCommand.key, OutlineNode.TYPE_PARAGRAPH); //else if (currentCommand.info.indexOf("\\label") != -1) else if (LABEL_RE.matcher(currentCommand.info).find()) sectioning.put("\\" + currentCommand.key, LatexParser.TYPE_LABEL); argCount = 0; expectArg2 = false; } else if (t instanceof TOptargument) { if (argCount == 0) { try { currentCommand.arguments = Integer.parseInt(t.getText()); } catch (NumberFormatException nfe) { errors.add(new ParseErrorMessage(prevToken.getLine(), t.getPos(), t.getText().length(), "The first optional argument of newcommand must only contain the number of arguments", IMarker.SEVERITY_ERROR)); expectArg2 = false; } } argCount++; } else if (!(t instanceof TWhitespace) && !(t instanceof TCommentline) && !(t instanceof TTaskcomment)) { // if we didn't get the mandatory argument we were expecting... errors.add(new ParseErrorMessage(t.getLine(), t.getPos(), t.getText().length(), "No 2nd argument following newcommand", IMarker.SEVERITY_WARNING)); argCount = 0; expectArg2 = false; } } else { if (t instanceof TClabel || t instanceof TCref || t instanceof TCcite || t instanceof TCbib || t instanceof TCbibstyle || t instanceof TCbegin || t instanceof TCend || t instanceof TCinput || t instanceof TCinclude || t instanceof TCpart || t instanceof TCchapter || t instanceof TCsection || t instanceof TCssection || t instanceof TCsssection || t instanceof TCparagraph || t instanceof TCnew) { prevToken = t; expectArg = true; } else if (t instanceof TCword) { // macros (\newcommand) show up as TCword when used, so we need // to check (for each word!) whether it happens to be a command if (sectioning.containsKey(t.getText())) { nodeType = sectioning.get(t.getText()); switch (nodeType) { case OutlineNode.TYPE_PART: prevToken = new TCpart(t.getLine(), t.getPos()); break; case OutlineNode.TYPE_CHAPTER: prevToken = new TCchapter(t.getLine(), t.getPos()); break; case OutlineNode.TYPE_SECTION: prevToken = new TCsection(t.getLine(), t.getPos()); break; case OutlineNode.TYPE_SUBSECTION: prevToken = new TCssection(t.getLine(), t.getPos()); break; case OutlineNode.TYPE_SUBSUBSECTION: prevToken = new TCsssection(t.getLine(), t.getPos()); break; case OutlineNode.TYPE_PARAGRAPH: prevToken = new TCparagraph(t.getLine(), t.getPos()); break; case LatexParser.TYPE_LABEL: prevToken = new TClabel(t.getLine(), t.getPos()); break; default: break; } expectArg = true; } } else if (t instanceof TCpindex) { this.index = true; } else if (t instanceof TTaskcomment) { int severity = IMarker.PRIORITY_HIGH; int start = t.getText().indexOf("FIXME"); if (start == -1) { severity = IMarker.PRIORITY_NORMAL; start = t.getText().indexOf("TODO"); if (start == -1) { start = t.getText().indexOf("XXX"); } } String taskText = t.getText().substring(start).trim(); tasks.add(new ParseErrorMessage(t.getLine(), t.getPos(), taskText.length(), taskText, severity)); } else if (t instanceof TVtext) { // Fold OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_ENVIRONMENT, t.getLine(), t.getPos(), t.getText().length()); // TODO uses memory, but doesn't require much code... String[] lines = t.getText().split("\\r\\n|\\n|\\r"); on.setEndLine(t.getLine() + lines.length); if (!blocks.empty()) { OutlineNode prev = blocks.peek(); prev.addChild(on); on.setParent(prev); } else { outlineTree.add(on); } } } if (t instanceof TLBrace) { braces.push(t); } else if (t instanceof TRBrace) { if (braces.empty()) { //There is an opening brace missing errors.add(new ParseErrorMessage(t.getLine(), t.getPos()-1, 1, TexlipsePlugin.getResourceString("parseErrorMissingLBrace"), IMarker.SEVERITY_ERROR)); } else { braces.pop(); } } } //Check for missing closing braces while (!braces.empty()) { Token mt = (Token) braces.pop(); errors.add(new ParseErrorMessage(mt.getLine(), mt.getPos() - 1, 1, TexlipsePlugin.getResourceString("parseErrorMissingRBrace"), IMarker.SEVERITY_ERROR)); } int endLine = t.getLine() + 1; //endline is exclusive while (!blocks.empty()) { OutlineNode prev = blocks.pop(); prev.setEndLine(endLine); if (prev.getType() == OutlineNode.TYPE_ENVIRONMENT) { fatalErrors = true; errors.add(new ParseErrorMessage(prev.getBeginLine(), 0, prev.getName().length(), "\\begin{" + prev.getName() + "} does not have matching end; at least one unbalanced begin-end", IMarker.SEVERITY_ERROR)); } } } /** * @return The labels defined in this document */ public List<ReferenceEntry> getLabels() { return this.labels; } /** * @return The BibTeX citations */ public List<DocumentReference> getCites() { return this.cites; } /** * @return The refencing commands */ public List<DocumentReference> getRefs() { return this.refs; } /** * @return The bibliography files to use. */ public String[] getBibs() { return this.bibs; } /** * @return The bibliography style. */ public String getBibstyle() { return bibstyle; } /** * @return The input commands in this document */ public List<OutlineNode> getInputs() { return this.inputs; } /** * @return The outline tree of the document (OutlineNode objects). */ public ArrayList<OutlineNode> getOutlineTree() { return this.outlineTree; } /** * @return The list of errors (ParseErrorMessage objects) in the document */ public List<ParseErrorMessage> getErrors() { return this.errors; } /** * @return Returns whether makeindex is to be used or not */ public boolean isIndex() { return index; } /** * @return Returns the documentEnv. */ public OutlineNode getDocumentEnv() { return documentEnv; } /** * @return Returns whether there are fatal errors in the document */ public boolean isFatalErrors() { return fatalErrors; } /** * @return Returns the commands. */ public ArrayList<TexCommandEntry> getCommands() { return commands; } /** * @return Returns the tasks. */ public List<ParseErrorMessage> getTasks() { return tasks; } }
package org.jfree.data.category; import java.io.Serializable; import java.util.List; import org.jfree.data.DefaultKeyedValues2D; import org.jfree.data.UnknownKeyException; import org.jfree.data.general.AbstractDataset; import org.jfree.data.general.DatasetChangeEvent; /** * A default implementation of the {@link CategoryDataset} interface. */ public class DefaultCategoryDataset extends AbstractDataset implements CategoryDataset, Serializable { /** For serialization. */ private static final long serialVersionUID = -8168173757291644622L; /** A storage structure for the data. */ private DefaultKeyedValues2D data; /** * Creates a new (empty) dataset. */ public DefaultCategoryDataset() { this.data = new DefaultKeyedValues2D(); } /** * Returns the number of rows in the table. * * @return The row count. * * @see #getColumnCount() */ public int getRowCount() { return this.data.getRowCount(); } /** * Returns the number of columns in the table. * * @return The column count. * * @see #getRowCount() */ public int getColumnCount() { return this.data.getColumnCount(); } /** * Returns a value from the table. * * @param row the row index (zero-based). * @param column the column index (zero-based). * * @return The value (possibly <code>null</code>). * * @see #addValue(Number, Comparable, Comparable) * @see #removeValue(Comparable, Comparable) */ public Number getValue(int row, int column) { return this.data.getValue(row, column); } /** * Returns the key for the specified row. * * @param row the row index (zero-based). * * @return The row key. * * @see #getRowIndex(Comparable) * @see #getRowKeys() * @see #getColumnKey(int) */ public Comparable getRowKey(int row) { return this.data.getRowKey(row); } /** * Returns the row index for a given key. * * @param key the row key (<code>null</code> not permitted). * * @return The row index. * * @see #getRowKey(int) */ public int getRowIndex(Comparable key) { // defer null argument check return this.data.getRowIndex(key); } /** * Returns the row keys. * * @return The keys. * * @see #getRowKey(int) */ public List getRowKeys() { return this.data.getRowKeys(); } /** * Returns a column key. * * @param column the column index (zero-based). * * @return The column key. * * @see #getColumnIndex(Comparable) */ public Comparable getColumnKey(int column) { return this.data.getColumnKey(column); } /** * Returns the column index for a given key. * * @param key the column key (<code>null</code> not permitted). * * @return The column index. * * @see #getColumnKey(int) */ public int getColumnIndex(Comparable key) { // defer null argument check return this.data.getColumnIndex(key); } /** * Returns the column keys. * * @return The keys. * * @see #getColumnKey(int) */ public List getColumnKeys() { return this.data.getColumnKeys(); } /** * Returns the value for a pair of keys. * * @param rowKey the row key (<code>null</code> not permitted). * @param columnKey the column key (<code>null</code> not permitted). * * @return The value (possibly <code>null</code>). * * @throws UnknownKeyException if either key is not defined in the dataset. * * @see #addValue(Number, Comparable, Comparable) */ public Number getValue(Comparable rowKey, Comparable columnKey) { return this.data.getValue(rowKey, columnKey); } /** * Adds a value to the table. Performs the same function as setValue(). * * @param value the value. * @param rowKey the row key. * @param columnKey the column key. * * @see #getValue(Comparable, Comparable) * @see #removeValue(Comparable, Comparable) */ public void addValue(Number value, Comparable rowKey, Comparable columnKey) { this.data.addValue(value, rowKey, columnKey); fireDatasetChanged(); } /** * Adds a value to the table. * * @param value the value. * @param rowKey the row key. * @param columnKey the column key. * * @see #getValue(Comparable, Comparable) */ public void addValue(double value, Comparable rowKey, Comparable columnKey) { addValue(new Double(value), rowKey, columnKey); } /** * Adds or updates a value in the table and sends a * {@link DatasetChangeEvent} to all registered listeners. * * @param value the value (<code>null</code> permitted). * @param rowKey the row key (<code>null</code> not permitted). * @param columnKey the column key (<code>null</code> not permitted). * * @see #getValue(Comparable, Comparable) */ public void setValue(Number value, Comparable rowKey, Comparable columnKey) { this.data.setValue(value, rowKey, columnKey); fireDatasetChanged(); } /** * Adds or updates a value in the table and sends a * {@link DatasetChangeEvent} to all registered listeners. * * @param value the value. * @param rowKey the row key (<code>null</code> not permitted). * @param columnKey the column key (<code>null</code> not permitted). * * @see #getValue(Comparable, Comparable) */ public void setValue(double value, Comparable rowKey, Comparable columnKey) { setValue(new Double(value), rowKey, columnKey); } /** * Adds the specified value to an existing value in the dataset (if the * existing value is <code>null</code>, it is treated as if it were 0.0). * * @param value the value. * @param rowKey the row key (<code>null</code> not permitted). * @param columnKey the column key (<code>null</code> not permitted). * * @throws UnknownKeyException if either key is not defined in the dataset. */ public void incrementValue(double value, Comparable rowKey, Comparable columnKey) { double existing = 0.0; Number n = getValue(rowKey, columnKey); if (n != null) { existing = n.doubleValue(); } setValue(existing + value, rowKey, columnKey); } /** * Removes a value from the dataset and sends a {@link DatasetChangeEvent} * to all registered listeners. * * @param rowKey the row key. * @param columnKey the column key. * * @see #addValue(Number, Comparable, Comparable) */ public void removeValue(Comparable rowKey, Comparable columnKey) { this.data.removeValue(rowKey, columnKey); fireDatasetChanged(); } /** * Removes a row from the dataset and sends a {@link DatasetChangeEvent} * to all registered listeners. * * @param rowIndex the row index. * * @see #removeColumn(int) */ public void removeRow(int rowIndex) { this.data.removeRow(rowIndex); fireDatasetChanged(); } /** * Removes a row from the dataset and sends a {@link DatasetChangeEvent} * to all registered listeners. * * @param rowKey the row key. * * @see #removeColumn(Comparable) */ public void removeRow(Comparable rowKey) { this.data.removeRow(rowKey); fireDatasetChanged(); } /** * Removes a column from the dataset and sends a {@link DatasetChangeEvent} * to all registered listeners. * * @param columnIndex the column index. * * @see #removeRow(int) */ public void removeColumn(int columnIndex) { this.data.removeColumn(columnIndex); fireDatasetChanged(); } /** * Removes a column from the dataset and sends a {@link DatasetChangeEvent} * to all registered listeners. * * @param columnKey the column key (<code>null</code> not permitted). * * @see #removeRow(Comparable) * * @throws UnknownKeyException if <code>columnKey</code> is not defined * in the dataset. */ public void removeColumn(Comparable columnKey) { this.data.removeColumn(columnKey); fireDatasetChanged(); } /** * Clears all data from the dataset and sends a {@link DatasetChangeEvent} * to all registered listeners. */ public void clear() { this.data.clear(); fireDatasetChanged(); } /** * Tests this dataset for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof CategoryDataset)) { return false; } CategoryDataset that = (CategoryDataset) obj; if (!getRowKeys().equals(that.getRowKeys())) { return false; } if (!getColumnKeys().equals(that.getColumnKeys())) { return false; } int rowCount = getRowCount(); int colCount = getColumnCount(); for (int r = 0; r < rowCount; r++) { for (int c = 0; c < colCount; c++) { Number v1 = getValue(r, c); Number v2 = that.getValue(r, c); if (v1 == null) { if (v2 != null) { return false; } } else if (!v1.equals(v2)) { return false; } } } return true; } /** * Returns a hash code for the dataset. * * @return A hash code. */ public int hashCode() { return this.data.hashCode(); } /** * Returns a clone of the dataset. * * @return A clone. * * @throws CloneNotSupportedException if there is a problem cloning the * dataset. */ public Object clone() throws CloneNotSupportedException { DefaultCategoryDataset clone = (DefaultCategoryDataset) super.clone(); clone.data = (DefaultKeyedValues2D) this.data.clone(); return clone; } }
package acr.browser.lightning.utils; import android.Manifest; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Shader; import android.os.Environment; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.StringRes; import android.support.design.widget.Snackbar; import android.support.v7.app.AlertDialog; import android.util.DisplayMetrics; import android.util.Log; import android.view.View; import android.webkit.URLUtil; import com.anthonycr.grant.PermissionsManager; import com.anthonycr.grant.PermissionsResultAction; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.text.SimpleDateFormat; import java.util.Date; import acr.browser.lightning.R; import acr.browser.lightning.constant.Constants; import acr.browser.lightning.download.DownloadHandler; public final class Utils { public static void downloadFile(final Activity activity, final String url, final String userAgent, final String contentDisposition) { PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult(activity, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, new PermissionsResultAction() { @Override public void onGranted() { String fileName = URLUtil.guessFileName(url, null, null); DownloadHandler.onDownloadStart(activity, url, userAgent, contentDisposition, null ); Log.i(Constants.TAG, "Downloading" + fileName); } @Override public void onDenied(String permission) { // TODO Show Message } }); } /** * Creates a new intent that can launch the email * app with a subject, address, body, and cc. It * is used to handle mail:to links. * * @param address the address to send the email to. * @param subject the subject of the email. * @param body the body of the email. * @param cc extra addresses to CC. * @return a valid intent. */ @NonNull public static Intent newEmailIntent(String address, String subject, String body, String cc) { Intent intent = new Intent(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_EMAIL, new String[]{address}); intent.putExtra(Intent.EXTRA_TEXT, body); intent.putExtra(Intent.EXTRA_SUBJECT, subject); intent.putExtra(Intent.EXTRA_CC, cc); intent.setType("message/rfc822"); return intent; } /** * Creates a dialog with only a title, message, and okay button. * * @param activity the activity needed to create a dialog. * @param title the title of the dialog. * @param message the message of the dialog. */ public static void createInformativeDialog(Activity activity, @StringRes int title, @StringRes int message) { AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle(title); builder.setMessage(message) .setCancelable(true) .setPositiveButton(activity.getResources().getString(R.string.action_ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { } }); AlertDialog alert = builder.create(); alert.show(); } /** * Displays a snackbar to the user with a String resource. * * @param activity the activity needed to create a snackbar. * @param resource the string resource to show to the user. */ public static void showSnackbar(@NonNull Activity activity, @StringRes int resource) { View view = activity.findViewById(android.R.id.content); if (view == null) return; Snackbar.make(view, resource, Snackbar.LENGTH_SHORT).show(); } /** * Displays a snackbar to the user with a string message. * * @param activity the activity needed to create a snackbar. * @param message the string message to show to the user. */ public static void showSnackbar(@NonNull Activity activity, @NonNull String message) { View view = activity.findViewById(android.R.id.content); if (view == null) return; Snackbar.make(view, message, Snackbar.LENGTH_SHORT).show(); } /** * Converts Density Pixels (DP) to Pixels (PX). * * @param dp the number of density pixels to convert. * @return the number of pixels that the conversion generates. */ public static int dpToPx(int dp) { DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics(); return (int) (dp * metrics.density + 0.5f); } /** * Extracts the domain name from a URL. * * @param url the URL to extract the domain from. * @return the domain name, or the URL if the domain * could not be extracted. The domain name may include * HTTPS if the URL is an SSL supported URL. */ public static String getDomainName(@Nullable String url) { if (url == null || url.isEmpty()) return ""; boolean ssl = url.startsWith(Constants.HTTPS); int index = url.indexOf('/', 8); if (index != -1) { url = url.substring(0, index); } URI uri; String domain; try { uri = new URI(url); domain = uri.getHost(); } catch (URISyntaxException e) { e.printStackTrace(); domain = null; } if (domain == null || domain.isEmpty()) { return url; } if (ssl) return Constants.HTTPS + domain; else return domain.startsWith("www.") ? domain.substring(4) : domain; } public static String getProtocol(String url) { int index = url.indexOf('/'); return url.substring(0, index + 2); } public static String[] getArray(String input) { return input.split(Constants.SEPARATOR); } public static void trimCache(Context context) { try { File dir = context.getCacheDir(); if (dir != null && dir.isDirectory()) { deleteDir(dir); } } catch (Exception ignored) { } } private static boolean deleteDir(File dir) { if (dir != null && dir.isDirectory()) { String[] children = dir.list(); for (String aChildren : children) { boolean success = deleteDir(new File(dir, aChildren)); if (!success) { return false; } } } // The directory is now empty so delete it return dir != null && dir.delete(); } /** * Creates and returns a new favicon which is the same as the provided * favicon but with horizontal or vertical padding of 4dp * * @param bitmap is the bitmap to pad. * @return the padded bitmap. */ public static Bitmap padFavicon(Bitmap bitmap) { int padding = Utils.dpToPx(4); Bitmap paddedBitmap = Bitmap.createBitmap(bitmap.getWidth() + padding, bitmap.getHeight() + padding, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(paddedBitmap); canvas.drawARGB(0x00, 0x00, 0x00, 0x00); // this represents white color canvas.drawBitmap(bitmap, padding / 2, padding / 2, new Paint(Paint.FILTER_BITMAP_FLAG)); return paddedBitmap; } public static boolean isColorTooDark(int color) { final byte RED_CHANNEL = 16; final byte GREEN_CHANNEL = 8; //final byte BLUE_CHANNEL = 0; int r = ((int) ((float) (color >> RED_CHANNEL & 0xff) * 0.3f)) & 0xff; int g = ((int) ((float) (color >> GREEN_CHANNEL & 0xff) * 0.59)) & 0xff; int b = ((int) ((float) (color /* >> BLUE_CHANNEL */ & 0xff) * 0.11)) & 0xff; int gr = (r + g + b) & 0xff; int gray = gr /* << BLUE_CHANNEL */ + (gr << GREEN_CHANNEL) + (gr << RED_CHANNEL); return gray < 0x727272; } public static int mixTwoColors(int color1, int color2, float amount) { final byte ALPHA_CHANNEL = 24; final byte RED_CHANNEL = 16; final byte GREEN_CHANNEL = 8; //final byte BLUE_CHANNEL = 0; final float inverseAmount = 1.0f - amount; int r = ((int) (((float) (color1 >> RED_CHANNEL & 0xff) * amount) + ((float) (color2 >> RED_CHANNEL & 0xff) * inverseAmount))) & 0xff; int g = ((int) (((float) (color1 >> GREEN_CHANNEL & 0xff) * amount) + ((float) (color2 >> GREEN_CHANNEL & 0xff) * inverseAmount))) & 0xff; int b = ((int) (((float) (color1 & 0xff) * amount) + ((float) (color2 & 0xff) * inverseAmount))) & 0xff; return 0xff << ALPHA_CHANNEL | r << RED_CHANNEL | g << GREEN_CHANNEL | b; } @SuppressLint("SimpleDateFormat") public static File createImageFile() throws IOException { // Create an image file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "JPEG_" + timeStamp + '_'; File storageDir = Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); return File.createTempFile(imageFileName, /* prefix */ ".jpg", /* suffix */ storageDir /* directory */ ); } /** * Checks if flash player is installed * * @param context the context needed to obtain the PackageManager * @return true if flash is installed, false otherwise */ public static boolean isFlashInstalled(Context context) { try { PackageManager pm = context.getPackageManager(); ApplicationInfo ai = pm.getApplicationInfo("com.adobe.flashplayer", 0); if (ai != null) { return true; } } catch (PackageManager.NameNotFoundException e) { return false; } return false; } /** * Quietly closes a closeable object like an InputStream or OutputStream without * throwing any errors or requiring you do do any checks. * * @param closeable the object to close */ public static void close(Closeable closeable) { if (closeable == null) return; try { closeable.close(); } catch (IOException e) { e.printStackTrace(); } } /** * Utility method to close cursors. Cursor did not * implement Closeable until API 16, so using this * method for when we want to close a cursor. * * @param cursor the cursor to close */ public static void close(Cursor cursor) { if (cursor == null) { return; } try { cursor.close(); } catch (Exception e) { e.printStackTrace(); } } /** * Draws the trapezoid background for the horizontal tabs on a canvas object using * the specified color. * * @param canvas the canvas to draw upon * @param color the color to use to draw the tab */ public static void drawTrapezoid(Canvas canvas, int color, boolean withShader) { Paint paint = new Paint(); paint.setColor(color); paint.setStyle(Paint.Style.FILL); // paint.setFilterBitmap(true); paint.setAntiAlias(true); paint.setDither(true); if (withShader) { paint.setShader(new LinearGradient(0, 0.9f * canvas.getHeight(), 0, canvas.getHeight(), color, mixTwoColors(Color.BLACK, color, 0.5f), Shader.TileMode.CLAMP)); } else { paint.setShader(null); } int width = canvas.getWidth(); int height = canvas.getHeight(); double radians = Math.PI / 3; int base = (int) (height / Math.tan(radians)); Path wallpath = new Path(); wallpath.reset(); wallpath.moveTo(0, height); wallpath.lineTo(width, height); wallpath.lineTo(width - base, 0); wallpath.lineTo(base, 0); wallpath.close(); canvas.drawPath(wallpath, paint); } }
package org.yamcs; import java.text.SimpleDateFormat; import java.util.Date; import java.util.logging.Formatter; import java.util.logging.LogRecord; public class CompactFormatter extends Formatter { SimpleDateFormat sdf=new SimpleDateFormat("MMM dd HH:mm:ss.SSS"); Date d=new Date(); @Override public String format(LogRecord r) { d.setTime(r.getMillis()); StringBuffer sb=new StringBuffer(); String name; name=r.getLoggerName(); sb.append(sdf.format(d)).append(" [").append(r.getThreadID()).append("] ").append(name).append(" ").append(r.getSourceMethodName()).append(" ").append(r.getLevel()).append(":").append(r.getMessage()); Object[] params=r.getParameters(); if(params!=null) { for(Object p:params) { sb.append(p.toString()); } } Throwable t=r.getThrown(); if(t!=null) { sb.append(t.toString()).append("\n"); for(StackTraceElement ste:t.getStackTrace()) { sb.append("\t").append(ste.toString()).append("\n"); } Throwable cause=t.getCause(); while(cause!=null && cause!=t) { sb.append("Caused by: ").append(cause.toString()).append("\n"); for(StackTraceElement ste:cause.getStackTrace()) { sb.append("\t").append(ste.toString()).append("\n"); } cause=cause.getCause(); } } sb.append("\n"); return sb.toString(); } }
package cbgm.de.listapi.data; import android.graphics.Color; /** * Singleton for vars that need global availability concerning the mode switching. * @author Christian Bergmann */ @SuppressWarnings({"SameParameterValue", "unused"}) public class CBModeHelper { //tells if an item is in active swiping private boolean isSwipeActive = false; //needed to tell the sort type which position should be highlighted private int selectedPosition = - 1; //the list mode private CBListMode listMode = CBListMode.NULL; //tells if list mode was changed (for reload) private boolean modeChanged = false; //tells the swiping if the swipe is still on the same item private int currentPosition = -1; //tells if a button of the list item (delete, edit) was clicked private boolean buttonClicked = false; //the color for highlighting a touch private int highlightColor = Color.WHITE; //the color for highlighting a selection private int selectColor = Color.LTGRAY; private static CBModeHelper modeHelper; public static CBModeHelper getInstance() { if (modeHelper == null) { modeHelper = new CBModeHelper(); } return modeHelper; } public void resetModeChanged() { this.modeChanged = false; } public int getSelectedPosition() { return selectedPosition; } public void setSelectedPosition(int selectedPosition) { this.selectedPosition = selectedPosition; } public boolean isSwipeActive() { return isSwipeActive; } public void setSwipeActive(boolean swipeActive) { isSwipeActive = swipeActive; } public CBListMode getListMode() { return listMode; } public void setListMode(CBListMode listMode) { this.modeChanged = this.listMode != listMode; this.listMode = listMode; } public void reset() { this.isSwipeActive = false; this.selectedPosition = - 1; this.listMode = CBListMode.NULL; this.modeChanged = false; this.currentPosition = -1; } public boolean isModeChanged() { return modeChanged; } public int getCurrentPosition() { return currentPosition; } public void setCurrentPosition(int currentPosition) { this.currentPosition = currentPosition; } public boolean isButtonClicked() { return buttonClicked; } public void setButtonClicked(final boolean buttonClicked) { this.buttonClicked = buttonClicked; } /** * MEthod to check if touch is still on the item which raised the event. * @param position the item position * @return boolean */ public boolean isItemTouchCurrentItem(final int position) { return modeHelper.isSwipeActive() && modeHelper.getCurrentPosition() == position; } public int getHighlightColor() { return highlightColor; } public void setHightightColor(int highlightColor) { this.highlightColor = highlightColor; } public int getSelectColor() { return selectColor; } public void setSelectColor(int selectColor) { this.selectColor = selectColor; } }
package com.afifzafri.studentsdb; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DBHelper extends SQLiteOpenHelper { public static final String DATABASE_NAME = "StudentsDB.db"; public static final String TABLE_NAME = "students"; public static final String COLUMN_ID = "id"; public static final String COLUMN_NAME = "name"; public static final String COLUMN_IC = "ic"; public static final String COLUMN_DOB = "dob"; public static final String COLUMN_ADDRESS = "address"; public static final String COLUMN_PROGRAM = "program"; public static final String COLUMN_PHONE = "phone"; public static final String COLUMN_EMAIL = "email"; public DBHelper(Context context) { super(context, DATABASE_NAME , null, 1); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL( "create table " + TABLE_NAME + " ("+COLUMN_ID+" text primary key, " +COLUMN_NAME+ " text," +COLUMN_IC+" text," +COLUMN_DOB+" text," +COLUMN_ADDRESS+" text," +COLUMN_PROGRAM+" text," +COLUMN_PHONE+" text," +COLUMN_EMAIL+" text)" ); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME); onCreate(db); } // function for insert data into db public boolean insertData (String id, String name, String ic, String dob, String address, String program, String phone, String email) { SQLiteDatabase db = this.getWritableDatabase(); // open db for writing ContentValues contentValues = new ContentValues(); contentValues.put("id", id); contentValues.put("name", name); contentValues.put("ic", ic); contentValues.put("dob", dob); contentValues.put("address", address); contentValues.put("program", program); contentValues.put("phone", phone); contentValues.put("email", email); db.insert(TABLE_NAME, null, contentValues); return true; } // function to select all data public Cursor getAllData () { SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery("select * from "+TABLE_NAME, null); return cursor; } // function for search data public Cursor searchData (String searchInput) { SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery( "select * from "+TABLE_NAME+" where id = '"+searchInput+ "' or name LIKE '%"+searchInput+"%'", null ); return cursor; } // function for update data public boolean updateData (String id, String name, String ic, String dob, String address, String program, String phone, String email) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("id", id); contentValues.put("name", name); contentValues.put("ic", ic); contentValues.put("dob", dob); contentValues.put("address", address); contentValues.put("program", program); contentValues.put("phone", phone); contentValues.put("email", email); db.update(TABLE_NAME, contentValues, "id = ? ", new String[] {id} ); return true; } // function for delete data public boolean deleteData (String id) { SQLiteDatabase db = this.getWritableDatabase(); db.delete(TABLE_NAME, "id = ? ", new String[] {id} ); return true; } }
package homework; import java.util.Scanner; public class StartHomework { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Calculating rectangle area. Please input 2 numbers:"); int a = scanner.nextInt(); int b = scanner.nextInt(); long area = RectangleArea.rectangleArea(a, b); System.out.println(area); System.out.println("Calculating triangle area. Please input 6 numbers:"); int aA1 = scanner.nextInt(); int aA2 = scanner.nextInt(); int bB1 = scanner.nextInt(); int bB2 = scanner.nextInt(); int cC1 = scanner.nextInt(); int cC2 = scanner.nextInt(); area = TriangleArea.triangleArea(aA1, aA2, bB1, bB2, cC1, cC2); System.out.println(area); System.out.println("Calculating Smalest of 3 numbers. Please input 3 numbers:"); double first = scanner.nextDouble(); double second = scanner.nextDouble(); double third = scanner.nextDouble(); double smallest = SmallestOfThreeNumbers.smallestOfThreeNumbers(first, second, third); System.out.println(smallest); scanner.close(); } }
package com.exedio.cope.instrument; import java.io.IOException; import java.io.InputStream; import java.io.Writer; import java.lang.reflect.Modifier; import java.text.MessageFormat; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import com.exedio.cope.lib.AttributeValue; import com.exedio.cope.lib.LengthViolationException; import com.exedio.cope.lib.NestingRuntimeException; import com.exedio.cope.lib.NotNullViolationException; import com.exedio.cope.lib.ReadOnlyViolationException; import com.exedio.cope.lib.Type; import com.exedio.cope.lib.UniqueViolationException; import com.exedio.cope.lib.util.ReactivationConstructorDummy; // TODO use jspm final class Generator { private static final String THROWS_NULL = "if {0} is null."; private static final String THROWS_UNIQUE = "if {0} is not unique."; private static final String THROWS_LENGTH = "if {0} violates its length constraint."; private static final String CONSTRUCTOR_INITIAL = "Creates a new {0} with all the attributes initially needed."; private static final String CONSTRUCTOR_INITIAL_PARAMETER = "the initial value for attribute {0}."; private static final String CONSTRUCTOR_GENERIC = "Creates a new {0} and sets the given attributes initially."; private static final String CONSTRUCTOR_GENERIC_CALLED = "This constructor is called by {0}."; private static final String CONSTRUCTOR_REACTIVATION = "Reactivation constructor. Used for internal purposes only."; private static final String GETTER = "Returns the value of the persistent attribute {0}."; private static final String CHECKER = "Returns whether the given value corresponds to the hash in {0}."; private static final String SETTER = "Sets a new value for the persistent attribute {0}."; private static final String SETTER_DATA = "Sets the new data for the data attribute {0}."; private static final String SETTER_DATA_IOEXCEPTION = "if accessing {0} throws an IOException."; private static final String GETTER_DATA_URL = "Returns a URL the data of the data attribute {0} is available under."; private static final String GETTER_DATA_VARIANT = "Returns a URL the data of the {1} variant of the data attribute {0} is available under."; private static final String GETTER_DATA_MAJOR = "Returns the major mime type of the data attribute {0}."; private static final String GETTER_DATA_MINOR = "Returns the minor mime type of the data attribute {0}."; private static final String GETTER_DATA_DATA = "Returns the data of the data attribute {0}."; private static final String TOUCHER = "Sets the current date for the date attribute {0}."; private static final String FINDER_UNIQUE = "Finds a {0} by it''s unique attributes."; private static final String FINDER_UNIQUE_PARAMETER = "shall be equal to attribute {0}."; private static final String QUALIFIER = "Returns the qualifier."; private static final String QUALIFIER_GETTER = "Returns the qualifier."; private static final String QUALIFIER_SETTER = "Sets the qualifier."; private static final String TYPE = "The persistent type information for {0}."; private final Writer o; private final String lineSeparator; Generator(final Writer output) { this.o=output; final String systemLineSeparator = System.getProperty("line.separator"); if(systemLineSeparator==null) { System.out.println("warning: property \"line.separator\" is null, using LF (unix style)."); lineSeparator = "\n"; } else lineSeparator = systemLineSeparator; } public static final String toCamelCase(final String name) { final char first = name.charAt(0); if (Character.isUpperCase(first)) return name; else return Character.toUpperCase(first) + name.substring(1); } private static final String lowerCamelCase(final String s) { final char first = s.charAt(0); if(Character.isLowerCase(first)) return s; else return Character.toLowerCase(first) + s.substring(1); } private static final String getShortName(final Class aClass) { final String name = aClass.getName(); final int pos = name.lastIndexOf('.'); return name.substring(pos+1); } private void writeThrowsClause(final Collection exceptions) throws IOException { if(!exceptions.isEmpty()) { o.write("\t\t\tthrows"); boolean first = true; for(final Iterator i = exceptions.iterator(); i.hasNext(); ) { if(first) first = false; else o.write(','); o.write(lineSeparator); o.write("\t\t\t\t"); o.write(((Class)i.next()).getName()); } o.write(lineSeparator); } } private final void writeCommentHeader() throws IOException { o.write("/**"); o.write(lineSeparator); o.write(lineSeparator); o.write("\t **"); o.write(lineSeparator); } private final void writeCommentGenerated() throws IOException { o.write("\t * <p><small>"+Instrumentor.GENERATED+"</small>"); o.write(lineSeparator); } private final void writeCommentFooter() throws IOException { o.write("\t *"); o.write(lineSeparator); o.write(" */"); } private static final String link(final String target) { return "{@link #" + target + '}'; } private static final String link(final String target, final String name) { return "{@link #" + target + ' ' + name + '}'; } private static final String format(final String pattern, final String parameter1) { return MessageFormat.format(pattern, new Object[]{ parameter1 }); } private static final String format(final String pattern, final String parameter1, final String parameter2) { return MessageFormat.format(pattern, new Object[]{ parameter1, parameter2 }); } private void writeInitialConstructor(final CopeClass copeClass) throws IOException { if(!copeClass.hasInitialConstructor()) return; final List initialAttributes = copeClass.getInitialAttributes(); final SortedSet constructorExceptions = copeClass.getConstructorExceptions(); writeCommentHeader(); o.write("\t * "); o.write(format(CONSTRUCTOR_INITIAL, copeClass.getName())); o.write(lineSeparator); writeCommentGenerated(); for(Iterator i = initialAttributes.iterator(); i.hasNext(); ) { final CopeAttribute initialAttribute = (CopeAttribute)i.next(); o.write("\t * @param initial"); o.write(toCamelCase(initialAttribute.getName())); o.write(' '); o.write(format(CONSTRUCTOR_INITIAL_PARAMETER, link(initialAttribute.getName()))); o.write(lineSeparator); } for(Iterator i = constructorExceptions.iterator(); i.hasNext(); ) { final Class constructorException = (Class)i.next(); o.write("\t * @throws "); o.write(constructorException.getName()); o.write(' '); boolean first = true; final StringBuffer initialAttributesBuf = new StringBuffer(); for(Iterator j = initialAttributes.iterator(); j.hasNext(); ) { final CopeAttribute initialAttribute = (CopeAttribute)j.next(); if(!initialAttribute.getSetterExceptions().contains(constructorException)) continue; if(first) first = false; else initialAttributesBuf.append(", "); initialAttributesBuf.append("initial"); initialAttributesBuf.append(toCamelCase(initialAttribute.getName())); } final String pattern; if(NotNullViolationException.class.equals(constructorException)) pattern = THROWS_NULL; else if(UniqueViolationException.class.equals(constructorException)) pattern = THROWS_UNIQUE; else if(LengthViolationException.class.equals(constructorException)) pattern = THROWS_LENGTH; else throw new RuntimeException(constructorException.getName()); o.write(format(pattern, initialAttributesBuf.toString())); o.write(lineSeparator); } writeCommentFooter(); final String modifier = Modifier.toString(copeClass.getInitialConstructorModifier()); if(modifier.length()>0) { o.write(modifier); o.write(' '); } o.write(copeClass.getName()); o.write('('); boolean first = true; for(Iterator i = initialAttributes.iterator(); i.hasNext(); ) { if(first) first = false; else o.write(','); final CopeAttribute initialAttribute = (CopeAttribute)i.next(); o.write(lineSeparator); o.write("\t\t\t\tfinal "); o.write(initialAttribute.getBoxedType()); o.write(" initial"); o.write(toCamelCase(initialAttribute.getName())); } o.write(')'); o.write(lineSeparator); writeThrowsClause(constructorExceptions); o.write("\t{"); o.write(lineSeparator); o.write("\t\tthis(new "+AttributeValue.class.getName()+"[]{"); o.write(lineSeparator); for(Iterator i = initialAttributes.iterator(); i.hasNext(); ) { final CopeAttribute initialAttribute = (CopeAttribute)i.next(); o.write("\t\t\tnew "+AttributeValue.class.getName()+"("); o.write(initialAttribute.getName()); o.write(','); writePrefixedAttribute("initial", initialAttribute); o.write("),"); o.write(lineSeparator); } o.write("\t\t});"); o.write(lineSeparator); for(Iterator i = copeClass.getConstructorExceptions().iterator(); i.hasNext(); ) { final Class exception = (Class)i.next(); o.write("\t\tthrowInitial"); o.write(getShortName(exception)); o.write("();"); o.write(lineSeparator); } o.write("\t}"); } private void writeGenericConstructor(final CopeClass copeClass) throws IOException { final Option option = copeClass.genericConstructorOption; if(!option.exists) return; writeCommentHeader(); o.write("\t * "); o.write(format(CONSTRUCTOR_GENERIC, copeClass.getName())); o.write(lineSeparator); o.write("\t * "); o.write(format(CONSTRUCTOR_GENERIC_CALLED, "{@link " + Type.class.getName() + "#newItem Type.newItem}")); o.write(lineSeparator); writeCommentGenerated(); writeCommentFooter(); o.write( Modifier.toString( option.getModifier(copeClass.isAbstract() ? Modifier.PROTECTED : Modifier.PRIVATE) ) ); o.write(' '); o.write(copeClass.getName()); o.write("(final "+AttributeValue.class.getName()+"[] initialAttributes)"); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\tsuper(initialAttributes);"); o.write(lineSeparator); o.write("\t}"); } private void writeReactivationConstructor(final CopeClass copeClass) throws IOException { writeCommentHeader(); o.write("\t * "); o.write(CONSTRUCTOR_REACTIVATION); o.write(lineSeparator); writeCommentGenerated(); o.write("\t * @see Item#Item(" + ReactivationConstructorDummy.class.getName() + ",int)"); o.write(lineSeparator); writeCommentFooter(); o.write( copeClass.isAbstract() ? "protected " : "private " ); o.write(copeClass.getName()); o.write("("+ReactivationConstructorDummy.class.getName()+" d,final int pk)"); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\tsuper(d,pk);"); o.write(lineSeparator); o.write("\t}"); } private void writeAccessMethods(final CopeAttribute copeAttribute) throws IOException { final String type = copeAttribute.getBoxedType(); // getter if(copeAttribute.getterOption.exists) { writeCommentHeader(); o.write("\t * "); o.write(format(GETTER, link(copeAttribute.getName()))); o.write(lineSeparator); writeCommentGenerated(); writeCommentFooter(); o.write(Modifier.toString(copeAttribute.getGeneratedGetterModifier())); o.write(' '); o.write(type); if(copeAttribute.hasIsGetter()) o.write(" is"); else o.write(" get"); o.write(toCamelCase(copeAttribute.getName())); o.write("()"); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); writeGetterBody(copeAttribute); o.write("\t}"); } // setter if(copeAttribute.hasGeneratedSetter()) { writeCommentHeader(); o.write("\t * "); o.write(format(SETTER, link(copeAttribute.getName()))); o.write(lineSeparator); writeCommentGenerated(); writeCommentFooter(); o.write(Modifier.toString(copeAttribute.getGeneratedSetterModifier())); o.write(" void set"); o.write(toCamelCase(copeAttribute.getName())); o.write("(final "); o.write(type); o.write(' '); o.write(copeAttribute.getName()); o.write(')'); o.write(lineSeparator); writeThrowsClause(copeAttribute.getSetterExceptions()); o.write("\t{"); o.write(lineSeparator); writeSetterBody(copeAttribute); o.write("\t}"); // touch for date attributes if(copeAttribute instanceof CopeNativeAttribute && ((CopeNativeAttribute)copeAttribute).touchable) { writeCommentHeader(); o.write("\t * "); o.write(format(TOUCHER, link(copeAttribute.getName()))); o.write(lineSeparator); writeCommentGenerated(); writeCommentFooter(); o.write(Modifier.toString(copeAttribute.getGeneratedSetterModifier())); o.write(" void touch"); o.write(toCamelCase(copeAttribute.getName())); o.write("()"); o.write(lineSeparator); writeThrowsClause(copeAttribute.getToucherExceptions()); o.write("\t{"); o.write(lineSeparator); writeToucherBody(copeAttribute); o.write("\t}"); } } for(Iterator i = copeAttribute.getHashes().iterator(); i.hasNext(); ) { final CopeHash hash = (CopeHash)i.next(); writeHash(hash); } } private void writeHash(final CopeHash hash) throws IOException { // checker writeCommentHeader(); o.write("\t * "); o.write(format(CHECKER, link(hash.name))); o.write(lineSeparator); writeCommentGenerated(); writeCommentFooter(); o.write(Modifier.toString(hash.storageAttribute.getGeneratedGetterModifier())); o.write(" boolean check"); o.write(toCamelCase(hash.name)); o.write("(final "); o.write(hash.storageAttribute.getBoxedType()); o.write(' '); o.write(hash.name); o.write(')'); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); writeCheckerBody(hash); o.write("\t}"); // setter final CopeAttribute storageAttribute = hash.storageAttribute; writeCommentHeader(); o.write("\t * "); o.write(format(SETTER, link(hash.name))); o.write(lineSeparator); writeCommentGenerated(); writeCommentFooter(); o.write(Modifier.toString(storageAttribute.getGeneratedSetterModifier())); o.write(" void set"); o.write(toCamelCase(hash.name)); o.write("(final "); o.write(storageAttribute.getBoxedType()); o.write(' '); o.write(hash.name); o.write(')'); o.write(lineSeparator); writeThrowsClause(storageAttribute.getSetterExceptions()); o.write("\t{"); o.write(lineSeparator); writeSetterBody(hash); o.write("\t}"); } private void writeDataGetterMethod(final CopeAttribute mediaAttribute, final Class returnType, final String part, final CopeMediaVariant variant, final String commentPattern) throws IOException { writeCommentHeader(); o.write("\t * "); o.write(variant==null ? format(commentPattern, link(mediaAttribute.getName())) : format(commentPattern, link(mediaAttribute.getName()), link(variant.name, variant.shortName))); o.write(lineSeparator); writeCommentGenerated(); writeCommentFooter(); o.write(Modifier.toString(mediaAttribute.getGeneratedGetterModifier())); o.write(' '); o.write(returnType.getName()); o.write(" get"); o.write(toCamelCase(mediaAttribute.getName())); o.write(part); if(variant!=null) o.write(variant.shortName); o.write("()"); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\treturn get"); o.write(part); o.write('('); o.write(mediaAttribute.copeClass.getName()); o.write('.'); if(variant!=null) o.write(variant.name); else o.write(mediaAttribute.getName()); o.write(");"); o.write(lineSeparator); o.write("\t}"); } private void writeMediaAccessMethods(final CopeMediaAttribute mediaAttribute) throws IOException { final String mimeMajor = mediaAttribute.mimeMajor; final String mimeMinor = mediaAttribute.mimeMinor; // getters writeDataGetterMethod(mediaAttribute, String.class, "URL", null, GETTER_DATA_URL); final List mediaVariants = mediaAttribute.getVariants(); if(mediaVariants!=null) { for(Iterator i = mediaVariants.iterator(); i.hasNext(); ) writeDataGetterMethod(mediaAttribute, String.class, "URL", (CopeMediaVariant)i.next(), GETTER_DATA_VARIANT); } writeDataGetterMethod(mediaAttribute, String.class, "MimeMajor", null, GETTER_DATA_MAJOR); writeDataGetterMethod(mediaAttribute, String.class, "MimeMinor", null, GETTER_DATA_MINOR); writeDataGetterMethod(mediaAttribute, InputStream.class, "Data", null, GETTER_DATA_DATA); // setters if(mediaAttribute.hasGeneratedSetter()) { writeCommentHeader(); o.write("\t * "); o.write(format(SETTER_DATA, link(mediaAttribute.getName()))); o.write(lineSeparator); writeCommentGenerated(); o.write("\t * @throws "); o.write(IOException.class.getName()); o.write(' '); o.write(format(SETTER_DATA_IOEXCEPTION, "<code>data</code>")); o.write(lineSeparator); writeCommentFooter(); o.write(Modifier.toString(mediaAttribute.getGeneratedSetterModifier())); o.write(" void set"); o.write(toCamelCase(mediaAttribute.getName())); o.write("Data(final " + InputStream.class.getName() + " data"); if(mimeMajor==null) o.write(",final "+String.class.getName()+" mimeMajor"); if(mimeMinor==null) o.write(",final "+String.class.getName()+" mimeMinor"); o.write(')'); final SortedSet setterExceptions = mediaAttribute.getSetterExceptions(); writeThrowsClause(setterExceptions); if(setterExceptions.isEmpty()) o.write("throws "); o.write(IOException.class.getName()); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); final SortedSet exceptionsToCatch = new TreeSet(mediaAttribute.getExceptionsToCatchInSetter()); exceptionsToCatch.remove(ReadOnlyViolationException.class); exceptionsToCatch.remove(LengthViolationException.class); exceptionsToCatch.remove(UniqueViolationException.class); writeTryCatchClausePrefix(exceptionsToCatch); o.write("\t\tsetData("); o.write(mediaAttribute.copeClass.getName()); o.write('.'); o.write(mediaAttribute.getName()); o.write(",data"); o.write(mimeMajor==null ? ",mimeMajor" : ",null"); o.write(mimeMinor==null ? ",mimeMinor" : ",null"); o.write(");"); o.write(lineSeparator); writeTryCatchClausePostfix(exceptionsToCatch); o.write("\t}"); } } private void writeUniqueFinder(final CopeUniqueConstraint constraint) throws IOException { final CopeAttribute[] copeAttributes = constraint.copeAttributes; final String className = copeAttributes[0].getParent().name; writeCommentHeader(); o.write("\t * "); o.write(format(FINDER_UNIQUE, lowerCamelCase(className))); o.write(lineSeparator); writeCommentGenerated(); for(int i=0; i<copeAttributes.length; i++) { o.write("\t * @param searched"); o.write(toCamelCase(copeAttributes[i].getName())); o.write(' '); o.write(format(FINDER_UNIQUE_PARAMETER, link(copeAttributes[i].getName()))); o.write(lineSeparator); } writeCommentFooter(); o.write(Modifier.toString((constraint.modifier & (Modifier.PRIVATE|Modifier.PROTECTED|Modifier.PUBLIC)) | (Modifier.STATIC|Modifier.FINAL) )); o.write(' '); o.write(className); o.write(" findBy"); o.write(toCamelCase(constraint.name)); o.write('('); final Set qualifiers = new HashSet(); for(int i=0; i<copeAttributes.length; i++) { if(i>0) o.write(','); final CopeAttribute copeAttribute = copeAttributes[i]; o.write("final "); o.write(copeAttribute.getBoxedType()); o.write(" searched"); o.write(toCamelCase(copeAttribute.getName())); } o.write(')'); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\treturn ("); o.write(className); o.write(')'); if(copeAttributes.length==1) { o.write(copeAttributes[0].getName()); o.write(".searchUnique("); writePrefixedAttribute("searched", copeAttributes[0]); } else { o.write(constraint.name); o.write(".searchUnique(new Object[]{"); writePrefixedAttribute("searched", copeAttributes[0]); for(int i = 1; i<copeAttributes.length; i++) { o.write(','); writePrefixedAttribute("searched", copeAttributes[i]); } o.write('}'); } o.write(");"); o.write(lineSeparator); o.write("\t}"); } private void writePrefixedAttribute(final String prefix, final CopeAttribute attribute) throws IOException { if(attribute.isBoxed()) o.write(attribute.getBoxingPrefix()); o.write(prefix); o.write(toCamelCase(attribute.getName())); if(attribute.isBoxed()) o.write(attribute.getBoxingPostfix()); } private void writeQualifierParameters(final CopeQualifier qualifier) throws IOException { final CopeAttribute[] keys = qualifier.keyAttributes; for(int i = 0; i<keys.length; i++) { if(i>0) o.write(','); o.write("final "); o.write(keys[i].persistentType); o.write(' '); o.write(keys[i].javaAttribute.name); } } private void writeQualifierCall(final CopeQualifier qualifier) throws IOException { final CopeAttribute[] keys = qualifier.keyAttributes; for(int i = 0; i<keys.length; i++) { o.write(','); o.write(keys[i].javaAttribute.name); } } private void writeQualifier(final CopeQualifier qualifier) throws IOException { writeCommentHeader(); o.write("\t * "); o.write(QUALIFIER); o.write(lineSeparator); writeCommentGenerated(); writeCommentFooter(); o.write("public final "); // TODO: obey attribute visibility o.write(qualifier.qualifierClassString); o.write(" get"); o.write(toCamelCase(qualifier.name)); o.write('('); writeQualifierParameters(qualifier); o.write(')'); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\treturn ("); o.write(qualifier.qualifierClassString); o.write(")"); o.write(qualifier.name); o.write(".getQualifier(new Object[]{this"); writeQualifierCall(qualifier); o.write("});"); o.write(lineSeparator); o.write("\t}"); final List qualifierAttributes = Arrays.asList(qualifier.uniqueConstraint.copeAttributes); for(Iterator i = qualifier.qualifierClass.getCopeAttributes().iterator(); i.hasNext(); ) { final CopeAttribute attribute = (CopeAttribute)i.next(); if(qualifierAttributes.contains(attribute)) continue; writeQualifierGetter(qualifier, attribute); writeQualifierSetter(qualifier, attribute); } } private void writeQualifierGetter(final CopeQualifier qualifier, final CopeAttribute attribute) throws IOException { writeCommentHeader(); o.write("\t * "); o.write(QUALIFIER_GETTER); o.write(lineSeparator); writeCommentGenerated(); writeCommentFooter(); final String resultType = attribute.persistentType; o.write("public final "); // TODO: obey attribute visibility o.write(resultType); o.write(" get"); o.write(toCamelCase(attribute.getName())); o.write('('); writeQualifierParameters(qualifier); o.write(')'); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\treturn ("); o.write(resultType); o.write(')'); o.write(qualifier.name); o.write(".getQualified(new Object[]{this"); writeQualifierCall(qualifier); o.write("},"); o.write(qualifier.qualifierClassString); o.write('.'); o.write(attribute.getName()); o.write(");"); o.write(lineSeparator); o.write("\t}"); } private void writeQualifierSetter(final CopeQualifier qualifier, final CopeAttribute attribute) throws IOException { writeCommentHeader(); o.write("\t * "); o.write(QUALIFIER_SETTER); o.write(lineSeparator); writeCommentGenerated(); writeCommentFooter(); final String resultType = attribute.persistentType; o.write("public final void set"); // TODO: obey attribute visibility o.write(toCamelCase(attribute.getName())); o.write('('); writeQualifierParameters(qualifier); o.write(",final "); o.write(resultType); o.write(' '); o.write(attribute.getName()); o.write(')'); o.write(lineSeparator); writeThrowsClause(Arrays.asList(new Class[]{ NotNullViolationException.class, LengthViolationException.class, ReadOnlyViolationException.class, ClassCastException.class})); o.write("\t{"); o.write(lineSeparator); o.write("\t\t"); o.write(qualifier.name); o.write(".setQualified(new Object[]{this"); writeQualifierCall(qualifier); o.write("},"); o.write(qualifier.qualifierClassString); o.write('.'); o.write(attribute.getName()); o.write(','); o.write(attribute.getName()); o.write(");"); o.write(lineSeparator); o.write("\t}"); } private final void writeType(final CopeClass copeClass) throws IOException { final Option option = copeClass.typeOption; if(option.exists) { writeCommentHeader(); o.write("\t * "); o.write(format(TYPE, lowerCamelCase(copeClass.getName()))); o.write(lineSeparator); writeCommentGenerated(); writeCommentFooter(); o.write(Modifier.toString(option.getModifier(Modifier.PUBLIC) | Modifier.STATIC | Modifier.FINAL)); // TODO obey class visibility o.write(" "+Type.class.getName()+" TYPE = "); o.write(lineSeparator); o.write("\t\tnew "+Type.class.getName()+"("); o.write(copeClass.getName()); o.write(".class)"); o.write(lineSeparator); o.write(";"); } } void writeClassFeatures(final CopeClass copeClass) throws IOException, InjectorParseException { if(!copeClass.isInterface()) { //System.out.println("onClassEnd("+jc.getName()+") writing"); writeInitialConstructor(copeClass); writeGenericConstructor(copeClass); writeReactivationConstructor(copeClass); for(final Iterator i = copeClass.getCopeAttributes().iterator(); i.hasNext(); ) { // write setter/getter methods final CopeAttribute copeAttribute = (CopeAttribute)i.next(); //System.out.println("onClassEnd("+jc.getName()+") writing attribute "+copeAttribute.getName()); if(copeAttribute instanceof CopeMediaAttribute) writeMediaAccessMethods((CopeMediaAttribute)copeAttribute); else writeAccessMethods(copeAttribute); } for(final Iterator i = copeClass.getUniqueConstraints().iterator(); i.hasNext(); ) { // write unique finder methods final CopeUniqueConstraint constraint = (CopeUniqueConstraint)i.next(); writeUniqueFinder(constraint); } for(final Iterator i = copeClass.getQualifiers().iterator(); i.hasNext(); ) { final CopeQualifier qualifier = (CopeQualifier)i.next(); writeQualifier(qualifier); } writeType(copeClass); } } /** * Identation contract: * This methods is called, when o stream is immediately after a line break, * and it should return the o stream after immediately after a line break. * This means, doing nothing fullfils the contract. */ private void writeGetterBody(final CopeAttribute attribute) throws IOException { o.write("\t\treturn "); if(attribute.isBoxed()) o.write(attribute.getUnBoxingPrefix()); o.write('('); o.write(attribute.persistentType); o.write(")getAttribute("); o.write(attribute.copeClass.getName()); o.write('.'); o.write(attribute.getName()); o.write(')'); if(attribute.isBoxed()) o.write(attribute.getUnBoxingPostfix()); o.write(';'); o.write(lineSeparator); } /** * Identation contract: * This methods is called, when o stream is immediately after a line break, * and it should return the o stream after immediately after a line break. * This means, doing nothing fullfils the contract. */ private void writeSetterBody(final CopeAttribute attribute) throws IOException { final SortedSet exceptionsToCatch = attribute.getExceptionsToCatchInSetter(); writeTryCatchClausePrefix(exceptionsToCatch); o.write("\t\tsetAttribute("); o.write(attribute.copeClass.getName()); o.write('.'); o.write(attribute.getName()); o.write(','); if(attribute.isBoxed()) o.write(attribute.getBoxingPrefix()); o.write(attribute.getName()); if(attribute.isBoxed()) o.write(attribute.getBoxingPostfix()); o.write(");"); o.write(lineSeparator); writeTryCatchClausePostfix(exceptionsToCatch); } /** * Identation contract: * This methods is called, when o stream is immediately after a line break, * and it should return the o stream after immediately after a line break. * This means, doing nothing fullfils the contract. */ private void writeToucherBody(final CopeAttribute attribute) throws IOException { final SortedSet exceptionsToCatch = attribute.getExceptionsToCatchInToucher(); writeTryCatchClausePrefix(exceptionsToCatch); o.write("\t\ttouchAttribute("); o.write(attribute.copeClass.getName()); o.write('.'); o.write(attribute.getName()); o.write(");"); o.write(lineSeparator); writeTryCatchClausePostfix(exceptionsToCatch); } /** * Identation contract: * This methods is called, when o stream is immediately after a line break, * and it should return the o stream after immediately after a line break. * This means, doing nothing fullfils the contract. */ private void writeCheckerBody(final CopeHash hash) throws IOException { o.write("\t\treturn "); o.write(hash.storageAttribute.copeClass.getName()); o.write('.'); o.write(hash.name); o.write(".checkHash(this,"); o.write(hash.name); o.write(");"); o.write(lineSeparator); } /** * Identation contract: * This methods is called, when o stream is immediately after a line break, * and it should return the o stream after immediately after a line break. * This means, doing nothing fullfils the contract. */ private void writeSetterBody(final CopeHash hash) throws IOException { final CopeAttribute attribute = hash.storageAttribute; final SortedSet exceptionsToCatch = attribute.getExceptionsToCatchInSetter(); writeTryCatchClausePrefix(exceptionsToCatch); o.write("\t\t"); o.write(attribute.copeClass.getName()); o.write('.'); o.write(hash.name); o.write(".setHash(this,"); o.write(hash.name); o.write(");"); o.write(lineSeparator); writeTryCatchClausePostfix(exceptionsToCatch); } private void writeTryCatchClausePrefix(final SortedSet exceptionsToCatch) throws IOException { if(!exceptionsToCatch.isEmpty()) { o.write("\t\ttry"); o.write(lineSeparator); o.write("\t\t{"); o.write(lineSeparator); o.write('\t'); } } private void writeTryCatchClausePostfix(final SortedSet exceptionsToCatch) throws IOException { if(!exceptionsToCatch.isEmpty()) { o.write("\t\t}"); o.write(lineSeparator); for(Iterator i = exceptionsToCatch.iterator(); i.hasNext(); ) { final Class exceptionClass = (Class)i.next(); o.write("\t\tcatch("+exceptionClass.getName()+" e)"); o.write(lineSeparator); o.write("\t\t{"); o.write(lineSeparator); o.write("\t\t\tthrow new "+NestingRuntimeException.class.getName()+"(e);"); o.write(lineSeparator); o.write("\t\t}"); o.write(lineSeparator); } } } }
package com.dyhpoon.fodex.util; import android.content.Context; import android.content.res.AssetFileDescriptor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Process; import android.widget.ImageView; import com.bumptech.glide.Glide; import java.io.FileNotFoundException; import java.lang.ref.WeakReference; public class MediaImage { public static void loadBitmapAsynchronously(ImageView imageView, Uri uri, int width, int height) { boolean isLocal = uri.toString().contains("content: if (isLocal) { if (cancelPotentialWork(imageView, uri)) { final BitmapWorkerTask task = new BitmapWorkerTask(imageView, width, height); final AsyncDrawable asyncDrawable = new AsyncDrawable(imageView.getContext(), null, task); imageView.setImageDrawable(asyncDrawable); task.execute(uri); } } else { Glide.with(imageView.getContext()).load(uri).override(width, height).into(imageView); } } public static Bitmap loadBitmapSynchronously(Context context, Uri uri, int reqWidth, int reqHeight) { return loadBitmapSynchronously(context, uri, reqWidth, reqHeight, true); } public static Bitmap loadBitmapSynchronously(Context context, Uri uri, int reqWidth, int reqHeight, Boolean highResolution) { boolean isLocal = uri.toString().contains("content: if (isLocal) { try { // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; AssetFileDescriptor fd = context.getContentResolver().openAssetFileDescriptor(uri, "r"); BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor(), null, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight, highResolution); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; return BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor(), null, options); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (OutOfMemoryError e) { // When receive OOM, and try to get a smaller size of image. return loadBitmapSynchronously(context, uri, reqWidth / 2, reqHeight / 2); } } return null; } private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight, boolean highResolution) { // Raw height and width of image final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { if (highResolution) { final int halfHeight = height/2; final int halfWidth = width/2; // Calculate the largest inSampleSize value that is a power of 2 and keeps both // height and width larger than the requested height and width. while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) { inSampleSize *= 2; } } else { final int tripeHeight = height*3; final int tripeWidth = width*3; while ((tripeHeight / inSampleSize) > reqHeight || (tripeWidth / inSampleSize) > reqWidth) { inSampleSize *= 2; } } } return inSampleSize; } private static class BitmapWorkerTask extends AsyncTask<Uri, Void, Bitmap> { private final WeakReference<ImageView> imageViewWeakReference; private int mWidth, mHeight; private Uri uri; public BitmapWorkerTask(ImageView imageView, int width, int height) { imageViewWeakReference = new WeakReference<>(imageView); mWidth = width; mHeight = height; } @Override protected Bitmap doInBackground(Uri... params) { android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DISPLAY); if (imageViewWeakReference != null) { final ImageView imageView = imageViewWeakReference.get(); if (imageView != null) { uri = params[0]; return loadBitmapSynchronously(imageView.getContext(), uri, mWidth, mHeight); } } return null; } @Override protected void onPostExecute(Bitmap bitmap) { if (isCancelled()) { bitmap = null; } if (imageViewWeakReference != null && bitmap != null) { final ImageView imageView = imageViewWeakReference.get(); if (imageView != null) { imageView.setImageBitmap(bitmap); } } } } private static class AsyncDrawable extends BitmapDrawable { private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskWeakReference; public AsyncDrawable(Context context, Bitmap bitmap, BitmapWorkerTask task) { super(context.getResources(), bitmap); bitmapWorkerTaskWeakReference = new WeakReference<>(task); } public BitmapWorkerTask getBitmapWorkerTask() { return bitmapWorkerTaskWeakReference.get(); } } private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) { if (imageView != null) { final Drawable drawable = imageView.getDrawable(); if (drawable instanceof AsyncDrawable) { final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable; return asyncDrawable.getBitmapWorkerTask(); } } return null; } private static boolean cancelPotentialWork(ImageView imageView, Uri uri) { final BitmapWorkerTask task = getBitmapWorkerTask(imageView); if (task != null) { if (task.uri == null || task.uri != uri) { task.cancel(true); } else { return false; } } return true; } }
package lucee.loader.engine; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLDecoder; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import lucee.VersionInfo; import lucee.loader.TP; import lucee.loader.osgi.BundleCollection; import lucee.loader.osgi.BundleLoader; import lucee.loader.osgi.BundleUtil; import lucee.loader.osgi.LoggerImpl; import lucee.loader.util.ExtensionFilter; import lucee.loader.util.Util; import lucee.loader.util.ZipUtil; import lucee.runtime.config.Identification; import lucee.runtime.config.Password; import org.apache.felix.framework.Felix; import org.apache.felix.framework.Logger; import org.osgi.framework.BundleException; import org.osgi.framework.Constants; import org.osgi.framework.Version; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.intergral.fusiondebug.server.FDControllerFactory; /** * Factory to load CFML Engine */ public class CFMLEngineFactory extends CFMLEngineFactorySupport { // set to false to disable patch loading, for example in major alpha releases private static final boolean PATCH_ENABLED = true; public static final Version VERSION_ZERO = new Version(0,0,0,"0"); private static final String UPDATE_LOCATION ="http://stable.lucee.org"; // MUST from server.xml private static CFMLEngineFactory factory; //private static CFMLEngineWrapper engineListener; private static CFMLEngineWrapper singelton; private static File luceeServerRoot; private Felix felix; private BundleCollection bundleCollection; //private CFMLEngineWrapper engine; private ClassLoader mainClassLoader = new TP().getClass().getClassLoader(); private Version version; private List<EngineChangeListener> listeners = new ArrayList<EngineChangeListener>(); private File resourceRoot; //private PrintWriter out; private final LoggerImpl logger; protected ServletConfig config; /** * Constructor of the class */ protected CFMLEngineFactory(ServletConfig config) { File logFile=null; this.config=config; try { logFile = new File(getResourceRoot(),"context/logs/felix.log"); } catch (IOException e) { e.printStackTrace(); } logFile.getParentFile().mkdirs(); logger=new LoggerImpl(logFile); } /** * returns instance of this factory (singelton-> always the same instance) * do auto update when changes occur * * @param config * @return Singelton Instance of the Factory * @throws ServletException */ public static CFMLEngine getInstance(ServletConfig config) throws ServletException { if (singelton != null) { if (factory == null) factory = singelton.getCFMLEngineFactory(); // not sure if this ever is done, but it does not hurt return singelton; } if (factory == null) factory = new CFMLEngineFactory(config); // read init param from config factory.readInitParam(config); factory.initEngineIfNecessary(); singelton.addServletConfig(config); // add listener for update //factory.addListener(singelton); return singelton; } /** * returns instance of this factory (singelton-> always the same instance) * do auto update when changes occur * * @return Singelton Instance of the Factory * @throws RuntimeException */ public static CFMLEngine getInstance() throws RuntimeException { if (singelton != null) return singelton; throw new RuntimeException( "engine is not initalized, you must first call getInstance(ServletConfig)"); } public static void registerInstance(CFMLEngine engine) { if(engine instanceof CFMLEngineWrapper) throw new RuntimeException("that should not happen!"); setEngine(engine); } /** * used only for internal usage * * @param engine * @throws RuntimeException */ /*public static void registerInstance(CFMLEngineWrapper engine) throws RuntimeException { if (factory == null) factory = engine.getCFMLEngineFactory(); // first update existing listener if (singelton != null) { if (engineListener.equalTo(engine, true)) return; engineListener.onUpdate(engine);// perhaps this is still refrenced in the code, because of that we update it factory.removeListener(engineListener); } // now register this if (engine instanceof CFMLEngineWrapper) engineListener = (CFMLEngineWrapper) engine; else engineListener = new CFMLEngineWrapper(engine); factory.addListener(engineListener); }*/ /** * returns instance of this factory (singelton-> always the same instance) * * @param config * @param listener * @return Singelton Instance of the Factory * @throws ServletException */ public static CFMLEngine getInstance(ServletConfig config, EngineChangeListener listener) throws ServletException { getInstance(config); // add listener for update factory.addListener(listener); // read init param from config factory.readInitParam(config); factory.initEngineIfNecessary(); singelton.addServletConfig(config); // make the FDController visible for the FDClient FDControllerFactory.makeVisible(); return singelton; } void readInitParam(ServletConfig config) { if (luceeServerRoot != null) return; String initParam = config.getInitParameter("lucee-server-directory"); if (Util.isEmpty(initParam)) initParam = config.getInitParameter("lucee-server-root"); if (Util.isEmpty(initParam)) initParam = config.getInitParameter("lucee-server-dir"); if (Util.isEmpty(initParam)) initParam = config.getInitParameter("lucee-server"); initParam = parsePlaceHolder(removeQuotes(initParam, true)); try { if (!Util.isEmpty(initParam)) { File root = new File(initParam); if (!root.exists()) { if (root.mkdirs()) { luceeServerRoot = root.getCanonicalFile(); return; } } else if (root.canWrite()) { luceeServerRoot = root.getCanonicalFile(); return; } } } catch (IOException ioe) { ioe.printStackTrace(); } } /** * adds a listener to the factory that will be informed when a new engine * will be loaded. * * @param listener */ private void addListener(EngineChangeListener listener) { if (!listeners.contains(listener)) { listeners.add(listener); } } /** * @return CFML Engine * @throws ServletException */ private void initEngineIfNecessary() throws ServletException { if (singelton == null) initEngine(); } private void initEngine() throws ServletException { Version coreVersion = VersionInfo.getIntVersion(); long coreCreated = VersionInfo.getCreateTime(); // get newest lucee version as file File patcheDir = null; try { patcheDir = getPatchDirectory(); log(Logger.LOG_DEBUG,"lucee-server-root:" + patcheDir.getParent()); } catch (IOException e) { throw new ServletException(e); } File[] patches = PATCH_ENABLED ? patcheDir .listFiles(new ExtensionFilter(new String[] { ".lco" })) : null; File lucee = null; if (patches != null) { for (int i = 0; i < patches.length; i++) { if (patches[i].getName().startsWith("tmp.lco")) { patches[i].delete(); } else if (patches[i].lastModified() < coreCreated) { patches[i].delete(); } else if (lucee == null || isNewerThan(toVersion(patches[i].getName(), VERSION_ZERO), toVersion(lucee.getName(), VERSION_ZERO))) { lucee = patches[i]; } } } if (lucee != null && isNewerThan(coreVersion, toVersion(lucee.getName(), VERSION_ZERO))) lucee = null; // Load Lucee //URL url=null; try { // Load core version when no patch available if (lucee == null) { log(Logger.LOG_DEBUG,"Load Build in Core"); String coreExt = "lco"; setEngine( getCore()); lucee = new File(patcheDir, singelton.getInfo().getVersion().toString() + "." + coreExt); if (PATCH_ENABLED) { InputStream bis = new TP().getClass().getResourceAsStream( "/core/core." + coreExt); OutputStream bos = new BufferedOutputStream( new FileOutputStream(lucee)); copy(bis, bos); closeEL(bis); closeEL(bos); } } else { bundleCollection = BundleLoader.loadBundles(this, getFelixCacheDirectory(), getBundleDirectory(), lucee, bundleCollection); //bundle=loadBundle(lucee); log(Logger.LOG_DEBUG,"loaded bundle:" + bundleCollection.core.getSymbolicName()); setEngine(getEngine(bundleCollection)); log(Logger.LOG_DEBUG,"loaded engine:" + singelton); } version = singelton.getInfo().getVersion(); log(Logger.LOG_DEBUG,"Loaded Lucee Version " + singelton.getInfo().getVersion()); } catch (InvocationTargetException e) { e.getTargetException().printStackTrace(); throw new ServletException(e.getTargetException()); } catch (Exception e) { e.printStackTrace(); throw new ServletException(e); } //check updates String updateType = singelton.getUpdateType(); if (updateType == null || updateType.length() == 0) updateType = "manuell"; if (updateType.equalsIgnoreCase("auto")) { new UpdateChecker(this,null).start(); } } private static CFMLEngineWrapper setEngine(CFMLEngine engine) { //new RuntimeException("setEngine").printStackTrace(); if(singelton==null) singelton=new CFMLEngineWrapper(engine); else if(!singelton.isIdentical(engine)) { engine.reset(); singelton.setEngine(engine); } else { //new RuntimeException("useless call").printStackTrace(); } return singelton; } public Felix getFelix(File cacheRootDir, Map<String, Object> config) throws BundleException { if(config==null)config=new HashMap<String, Object>(); // Log Level int logLevel=1; // 1 = error, 2 = warning, 3 = information, and 4 = debug String strLogLevel = (String)config.get("felix.log.level"); if(!Util.isEmpty(strLogLevel)) { if("warn".equalsIgnoreCase(strLogLevel) || "warning".equalsIgnoreCase(strLogLevel) || "2".equalsIgnoreCase(strLogLevel)) logLevel=2; else if("info".equalsIgnoreCase(strLogLevel) || "information".equalsIgnoreCase(strLogLevel) || "3".equalsIgnoreCase(strLogLevel)) logLevel=3; else if("debug".equalsIgnoreCase(strLogLevel) || "4".equalsIgnoreCase(strLogLevel)) logLevel=4; } config.put("felix.log.level", "" + logLevel); // storage clean String storageClean = (String)config.get(Constants.FRAMEWORK_STORAGE_CLEAN); if (Util.isEmpty(storageClean)) config.put(Constants.FRAMEWORK_STORAGE_CLEAN,Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT); // parent classLoader String parentClassLoader = (String)config.get(Constants.FRAMEWORK_BUNDLE_PARENT); if (Util.isEmpty(parentClassLoader)) config.put(Constants.FRAMEWORK_BUNDLE_PARENT,Constants.FRAMEWORK_BUNDLE_PARENT_FRAMEWORK); else config.put(Constants.FRAMEWORK_BUNDLE_PARENT,BundleUtil.toFrameworkBundleParent(parentClassLoader)); // felix.cache.rootdir if (!cacheRootDir.exists()) { cacheRootDir.mkdirs(); } if (cacheRootDir.isDirectory()) { config.put("felix.cache.rootdir", cacheRootDir.getAbsolutePath()); } if(logger!=null)config.put("felix.log.logger", logger); // TODO felix.log.logger // remove any empty record, this can produce trouble { Iterator<Entry<String, Object>> it = config.entrySet().iterator(); Entry<String, Object> e; Object v; while(it.hasNext()){ e = it.next(); v=e.getValue(); if(v==null || v.toString().isEmpty()) it.remove(); } } StringBuilder sb=new StringBuilder("loading felix with config:"); Iterator<Entry<String, Object>> it = config.entrySet().iterator(); Entry<String, Object> e; while(it.hasNext()){ e=it.next(); sb.append("\n- ").append(e.getKey()).append(':').append(e.getValue()); } log(Logger.LOG_INFO,sb.toString()); felix = new Felix(config); felix.start(); return felix; } public void log(Throwable t) { if(logger!=null) logger.log(Logger.LOG_ERROR, "",t); } public void log(int level, String msg) { if(logger!=null) logger.log(level, msg); } private CFMLEngine getCore() throws IOException, BundleException, ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { File rc = new File(getTempDirectory(), "tmp_" + System.currentTimeMillis() + ".lco"); try { InputStream is = null; OutputStream os = null; try { is = new TP().getClass().getResourceAsStream("/core/core.lco"); os = new FileOutputStream(rc); copy(is, os); } finally { closeEL(is); closeEL(os); } bundleCollection = BundleLoader.loadBundles(this, getFelixCacheDirectory(), getBundleDirectory(), rc, bundleCollection); return getEngine(bundleCollection); } finally { rc.delete(); } } /** * method to initalize a update of the CFML Engine. * checks if there is a new Version and update it whwn a new version is * available * * @param password * @return has updated * @throws IOException * @throws ServletException */ public boolean update(Password password, Identification id) throws IOException, ServletException { if (!singelton.can(CFMLEngine.CAN_UPDATE, password)) throw new IOException("access denied to update CFMLEngine"); //new RunUpdate(this).start(); return _update(id); } /** * restart the cfml engine * * @param password * @return has updated * @throws IOException * @throws ServletException */ public boolean restart(Password password) throws IOException, ServletException { if (!singelton.can(CFMLEngine.CAN_RESTART_ALL, password)) throw new IOException("access denied to restart CFMLEngine"); return _restart(); } /** * restart the cfml engine * * @param password * @return has updated * @throws IOException * @throws ServletException */ public boolean restart(String configId, Password password) throws IOException, ServletException { if (!singelton.can(CFMLEngine.CAN_RESTART_CONTEXT, password))// TODO restart single context throw new IOException( "access denied to restart CFML Context (configId:" + configId + ")"); return _restart(); } /** * restart the cfml engine * * @param password * @return has updated * @throws IOException * @throws ServletException */ private synchronized boolean _restart() throws ServletException { //engine.reset(); initEngine(); //registerInstance(engine); they all have only the reference to the wrapper and the wrapper does not change //callListeners(engine); System.gc(); return true; } /** * updates the engine when a update is available * * @return has updated * @throws IOException * @throws ServletException */ private boolean _update(Identification id) throws IOException, ServletException { File newLucee = downloadCore(id); if (newLucee == null) return false; /* happens in setEngine try { singelton.reset(); } catch (Throwable t) { t.printStackTrace(); }*/ Version v =null; try { bundleCollection = BundleLoader.loadBundles(this, getFelixCacheDirectory(), getBundleDirectory(), newLucee, bundleCollection); CFMLEngine e = getEngine(bundleCollection); if (e == null) throw new IOException("can't load engine"); version = e.getInfo().getVersion(); //engine = e; setEngine(e); //e.reset(); callListeners(e); } catch (Exception e) { System.gc(); try { newLucee.delete(); } catch (Exception ee) { } log(e); e.printStackTrace(); return false; } log(Logger.LOG_DEBUG,"Version (" + v + ")installed"); return true; } public File downloadBundle(String symbolicName, String symbolicVersion,Identification id) throws IOException { File jarDir = getBundleDirectory(); File jar = new File(jarDir, symbolicName.replace('.', '-') + "-" + symbolicVersion.replace('.', '-') + (".jar")); URL updateProvider = getUpdateLocation(); if(id==null && singelton!=null)id=singelton.getIdentification(); System.out.println("download:"+symbolicName+":"+symbolicVersion); // MUST remove URL updateUrl = new URL(updateProvider, "/rest/update/provider/download/" + symbolicName + "/" + symbolicVersion + "/"+(id!=null?id.toQueryString():"")); log(Logger.LOG_DEBUG, "download bundle [" + symbolicName + ":" + symbolicVersion + "] from " + updateUrl); int code; HttpURLConnection conn; try { conn = (HttpURLConnection) updateUrl.openConnection(); conn.setRequestMethod("GET"); conn.connect(); code = conn.getResponseCode(); } catch (UnknownHostException e) { log(e); throw e; } if (code != 200) { String msg = "Lucee is not able do download the bundle for [" + symbolicName + "] in version ["+symbolicVersion+"] from " + updateUrl + ", please donwload manually and copy to [" + jarDir + "]"; log(Logger.LOG_ERROR, msg); throw new IOException(msg); } //if(jar.createNewFile()) { copy((InputStream) conn.getContent(), new FileOutputStream(jar)); return jar; /*} else { throw new IOException("File ["+jar.getName()+"] already exists, won't copy new one"); }*/ } private File downloadCore(Identification id) throws IOException { URL updateProvider = getUpdateLocation(); if(id==null && singelton!=null) id=singelton.getIdentification(); URL infoUrl = new URL(updateProvider,"/rest/update/provider/update-for/"+version.toString()+(id!=null?id.toQueryString():"")); log(Logger.LOG_DEBUG,"Check for update at " + updateProvider); String strAvailableVersion = toString( (InputStream) infoUrl.getContent()).trim(); log(Logger.LOG_DEBUG,"receive available update version from update provider (" + strAvailableVersion + ") "); strAvailableVersion = CFMLEngineFactory.removeQuotes( strAvailableVersion, true); CFMLEngineFactory.removeQuotes(strAvailableVersion, true); // not necessary but does not hurt if (strAvailableVersion.length() == 0 || !isNewerThan(toVersion(strAvailableVersion, VERSION_ZERO), version)) { log(Logger.LOG_DEBUG,"There is no newer Version available"); return null; } log(Logger.LOG_DEBUG,"Found a newer Version \n - current Version " + version.toString() + "\n - available Version " + strAvailableVersion +("/rest/update/provider/download/" + version.toString() +(id!=null?id.toQueryString():""))); URL updateUrl = new URL(updateProvider, "/rest/update/provider/download/" + version.toString() +(id!=null?id.toQueryString():"")); log(Logger.LOG_DEBUG,"download update from "+updateUrl); System.out.println(updateUrl); File patchDir = getPatchDirectory(); File newLucee = new File(patchDir, strAvailableVersion + (".lco")); if (newLucee.createNewFile()) { copy((InputStream) updateUrl.getContent(), new FileOutputStream( newLucee)); } else { log(Logger.LOG_DEBUG,"File for new Version already exists, won't copy new one"); return null; } return newLucee; } public URL getUpdateLocation() throws MalformedURLException { URL location = singelton == null ? null : singelton.getUpdateLocation(); // read location directly from xml if (location == null) { InputStream is = null; try { File xml = new File(getResourceRoot(),"context/lucee-server.xml"); if(xml.exists() || xml.length()>0) { DocumentBuilderFactory dbFactory = DocumentBuilderFactory .newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(xml); Element root = doc.getDocumentElement(); NodeList children = root.getChildNodes(); for (int i = children.getLength() - 1; i >= 0; i Node node = children.item(i); if (node.getNodeType() == Node.ELEMENT_NODE && node.getNodeName().equals("update")) { String loc = ((Element) node).getAttribute("location"); if (!Util.isEmpty(loc)) { location = new URL(loc); } } } } } catch (Throwable t) { t.printStackTrace(); } finally { CFMLEngineFactory.closeEL(is); } } // if there is no lucee-server.xml if (location == null) location = new URL(UPDATE_LOCATION); return location; } /** * method to initalize a update of the CFML Engine. * checks if there is a new Version and update it whwn a new version is * available * * @param password * @return has updated * @throws IOException * @throws ServletException */ public boolean removeUpdate(Password password) throws IOException, ServletException { if (!singelton.can(CFMLEngine.CAN_UPDATE, password)) throw new IOException("access denied to update CFMLEngine"); return removeUpdate(); } /** * method to initalize a update of the CFML Engine. * checks if there is a new Version and update it whwn a new version is * available * * @param password * @return has updated * @throws IOException * @throws ServletException */ public boolean removeLatestUpdate(Password password) throws IOException, ServletException { if (!singelton.can(CFMLEngine.CAN_UPDATE, password)) throw new IOException("access denied to update CFMLEngine"); return removeLatestUpdate(); } /** * updates the engine when a update is available * * @return has updated * @throws IOException * @throws ServletException */ private boolean removeUpdate() throws IOException, ServletException { File patchDir = getPatchDirectory(); File[] patches = patchDir.listFiles(new ExtensionFilter(new String[] { "rc", "rcs" })); for (int i = 0; i < patches.length; i++) { if (!patches[i].delete()) patches[i].deleteOnExit(); } _restart(); return true; } private boolean removeLatestUpdate() throws IOException, ServletException { File patchDir = getPatchDirectory(); File[] patches = patchDir.listFiles(new ExtensionFilter( new String[] { ".lco" })); File patch = null; for (int i = 0; i < patches.length; i++) { if (patch == null || isNewerThan(toVersion(patches[i].getName(), VERSION_ZERO), toVersion(patch.getName(), VERSION_ZERO))) { patch = patches[i]; } } if (patch != null && !patch.delete()) patch.deleteOnExit(); _restart(); return true; } public String[] getInstalledPatches() throws ServletException, IOException { File patchDir = getPatchDirectory(); File[] patches = patchDir.listFiles(new ExtensionFilter( new String[] { ".lco" })); List<String> list = new ArrayList<String>(); String name; int extLen = "rc".length() + 1; for (int i = 0; i < patches.length; i++) { name = patches[i].getName(); name = name.substring(0, name.length() - extLen); list.add(name); } String[] arr = list.toArray(new String[list.size()]); Arrays.sort(arr); return arr; } /** * call all registred listener for update of the engine * * @param engine */ private void callListeners(CFMLEngine engine) { Iterator<EngineChangeListener> it = listeners.iterator(); while (it.hasNext()) { it.next().onUpdate(); } } public File getPatchDirectory() throws IOException { File pd = new File(getResourceRoot(), "patches"); if (!pd.exists()) pd.mkdirs(); return pd; } public File getBundleDirectory() throws IOException { File bd = new File(getResourceRoot(), "bundles"); if (!bd.exists()) bd.mkdirs(); return bd; } public File getFelixCacheDirectory() throws IOException { return getResourceRoot(); //File bd = new File(getResourceRoot(),"felix-cache"); //if(!bd.exists())bd.mkdirs(); //return bd; } /** * return directory to lucee resource root * * @return lucee root directory * @throws IOException */ public File getResourceRoot() throws IOException { if (resourceRoot == null) { resourceRoot = new File(_getResourceRoot(), "lucee-server"); if (!resourceRoot.exists()) resourceRoot.mkdirs(); } return resourceRoot; } /** * @return return running context root * @throws IOException * @throws IOException */ private File _getResourceRoot() throws IOException { // custom configuration if(luceeServerRoot==null) readInitParam(config); if (luceeServerRoot != null) return luceeServerRoot; // get the root directory File root=getDirectoryByProp("jboss.server.home.dir"); // Jboss/Jetty|Tomcat if(root==null)root=getDirectoryByProp("jonas.base"); // Jonas if(root==null)root=getDirectoryByProp("catalina.base"); // Tomcat if(root==null)root=getDirectoryByProp("jetty.home"); // Jetty if(root==null)root=getDirectoryByProp("org.apache.geronimo.base.dir"); // Geronimo if(root==null)root=getDirectoryByProp("com.sun.aas.instanceRoot"); // Glassfish if(root==null)root=getDirectoryByProp("env.DOMAIN_HOME"); // weblogic if(root==null)throw new IOException( "can't locate the root of the servlet container, please define a location (physical path) for the server configuration" + " with help of the servlet init param [lucee-server-directory] in the web.xml where the Lucee Servlet is defined"); File modernDir = new File(root,"lucee-server"); if(true) { // there is a server context in the old lucee location, move that one File classicRoot = getClassLoaderRoot(mainClassLoader),classicDir; System.out.println("classicRoot:"+classicRoot); boolean had=false; if(classicRoot.isDirectory() && (classicDir=new File(classicRoot,"lucee-server")).isDirectory()) { System.out.println("had lucee-server classic"+classicDir); moveContent(classicDir,modernDir); had=true; } // there is a railo context if(!had && classicRoot.isDirectory() && (classicDir=new File(classicRoot,"railo-server")).isDirectory()) { System.out.println("had railo-server classic"+classicDir); // check if there is a Railo context copyRecursiveAndRename(classicDir,modernDir); // zip the railo-server di and delete it (optional) try { ZipUtil.zip(classicDir, new File(root,"railo-server-context-old.zip")); Util.delete(classicDir); } catch(Throwable t){t.printStackTrace();} //moveContent(classicDir,new File(root,"lucee-server")); } } return root; } private static void copyRecursiveAndRename(File src,File trg) throws IOException { System.out.println("src:"+src); System.out.println("trg:"+trg); if(!src.exists()) return ; System.out.println("exists:"); if(src.isDirectory()) { if(!trg.exists())trg.mkdirs(); File[] files = src.listFiles(); for(int i=0;i<files.length;i++) { copyRecursiveAndRename(files[i],new File(trg,files[i].getName())); } } else if(src.isFile()) { if(trg.getName().endsWith(".rc") || trg.getName().startsWith(".")) { return; } System.out.println("trg2:"+trg); if(trg.getName().equals("railo-server.xml")) { trg=new File(trg.getParentFile(),"lucee-server.xml"); // cfLuceeConfiguration FileInputStream is = new FileInputStream(src); FileOutputStream os = new FileOutputStream(trg); try{ String str=Util.toString(is); str=str.replace("<cfRailoConfiguration", "<!-- copy from Railo context --><cfLuceeConfiguration"); str=str.replace("</cfRailoConfiguration", "</cfLuceeConfiguration"); str=str.replace("<railo-configuration", "<!-- copy from Railo context --><cfLuceeConfiguration"); str=str.replace("</railo-configuration", "</cfLuceeConfiguration"); str=str.replace("{railo-config}", "{lucee-config}"); str=str.replace("{railo-server}", "{lucee-server}"); str=str.replace("{railo-web}", "{lucee-web}"); str=str.replace("\"railo.commons.", "\"lucee.commons."); str=str.replace("\"railo.runtime.", "\"lucee.runtime."); str=str.replace("\"railo.cfx.", "\"lucee.cfx."); str=str.replace("/railo-context.ra", "/lucee-context.lar"); str=str.replace("/railo-context", "/lucee"); str=str.replace("railo-server-context", "lucee-server"); str=str.replace("http: str=str.replace("http: ByteArrayInputStream bais = new ByteArrayInputStream(str.getBytes()); try { Util.copy(bais, os); bais.close(); } finally { Util.closeEL(is, os); } } finally { Util.closeEL(is,os); } return; } FileInputStream is = new FileInputStream(src); FileOutputStream os = new FileOutputStream(trg); try{ Util.copy(is, os); } finally { Util.closeEL(is, os); } } } private void moveContent(File src, File trg) throws IOException { if(src.isDirectory()) { File[] children = src.listFiles(); if(children!=null)for(int i=0;i<children.length;i++){ moveContent(children[i], new File(trg,children[i].getName())); } src.delete(); } else if(src.isFile()){ trg.getParentFile().mkdirs(); src.renameTo(trg); } } private File getDirectoryByProp(String name) { String value=System.getProperty(name); if(Util.isEmpty(value,true)) return null; File dir=new File(value); dir.mkdirs(); if (dir.isDirectory()) return dir; return null; } /** * returns the path where the classloader is located * * @param cl ClassLoader * @return file of the classloader root */ public static File getClassLoaderRoot(ClassLoader cl) { String path = "lucee/loader/engine/CFMLEngine.class"; URL res = cl.getResource(path); if(res==null) return null; // get file and remove all after ! String strFile = null; try { strFile = URLDecoder.decode(res.getFile().trim(), "iso-8859-1"); } catch (UnsupportedEncodingException e) { } int index = strFile.indexOf('!'); if (index != -1) strFile = strFile.substring(0, index); // remove path at the end index = strFile.lastIndexOf(path); if (index != -1) strFile = strFile.substring(0, index); // remove "file:" at start and lucee.jar at the end if (strFile.startsWith("file:")) strFile = strFile.substring(5); if (strFile.endsWith("lucee.jar")) strFile = strFile.substring(0, strFile.length() - 9); File file = new File(strFile); if (file.isFile()) file = file.getParentFile(); return file; } /** * check left value against right value * * @param left * @param right * @return returns if right is newer than left */ private boolean isNewerThan(Version left, Version right) { return left.compareTo(right) > 0; } private CFMLEngine getEngine(BundleCollection bc) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { log(Logger.LOG_DEBUG,"state:" + BundleUtil.bundleState(bc.core.getState(), "")); //bundle.getBundleContext().getServiceReference(CFMLEngine.class.getName()); log(Logger.LOG_DEBUG,Constants.FRAMEWORK_BOOTDELEGATION + ":" + bc.getBundleContext().getProperty( Constants.FRAMEWORK_BOOTDELEGATION)); log(Logger.LOG_DEBUG,"felix.cache.rootdir:" + bc.getBundleContext().getProperty("felix.cache.rootdir")); //log(Logger.LOG_DEBUG,bc.master.loadClass(TP.class.getName()).getClassLoader().toString()); Class<?> clazz = bc.core .loadClass("lucee.runtime.engine.CFMLEngineImpl"); log(Logger.LOG_DEBUG,"class:" + clazz.getName()); Method m = clazz.getMethod("getInstance", new Class[] { CFMLEngineFactory.class, BundleCollection.class }); return (CFMLEngine) m.invoke(null, new Object[] { this, bc }); } private class UpdateChecker extends Thread { private CFMLEngineFactory factory; private Identification id; private UpdateChecker(CFMLEngineFactory factory, Identification id) { this.factory = factory; this.id=id; } public void run() { long time = 10000; while (true) { try { sleep(time); time = 1000 * 60 * 60 * 24; factory._update(id); } catch (Exception e) { } } } } }
package com.expidev.gcmapp.db; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import android.util.Pair; import com.expidev.gcmapp.model.Training; import com.expidev.gcmapp.sql.TableNames; import com.expidev.gcmapp.utils.DatabaseOpenHelper; import org.ccci.gto.android.common.db.AbstractDao; import org.ccci.gto.android.common.db.Mapper; import org.json.JSONArray; import org.json.JSONObject; import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; public class TrainingDao extends AbstractDao { private final String TAG = getClass().getSimpleName(); private static final Mapper<Training> TRAINING_MAPPER = new TrainingMapper(); private static final Object instanceLock = new Object(); private static TrainingDao instance; private TrainingDao(final Context context) { super(DatabaseOpenHelper.getInstance(context)); } public static TrainingDao getInstance(Context context) { synchronized (instanceLock) { if (instance == null) { instance = new TrainingDao(context.getApplicationContext()); } } return instance; } @NonNull @Override protected String getTable(@NonNull final Class<?> clazz) { if (Training.class.equals(clazz)) { return Contract.Training.TABLE_NAME; } return super.getTable(clazz); } @NonNull @Override protected String[] getFullProjection(@NonNull final Class<?> clazz) { if (Training.class.equals(clazz)) { return Contract.Training.PROJECTION_ALL; } return super.getFullProjection(clazz); } @NonNull @Override @SuppressWarnings("unchecked") protected <T> Mapper<T> getMapper(@NonNull final Class<T> clazz) { if (Training.class.equals(clazz)) { return (Mapper<T>) TRAINING_MAPPER; } return super.getMapper(clazz); } @NonNull @Override protected Pair<String, String[]> getPrimaryKeyWhere(@NonNull final Class<?> clazz, @NonNull final Object... key) { final String where; if (Training.class.equals(clazz)) { if (key.length != 1) { throw new IllegalArgumentException("invalid key for " + clazz); } where = Contract.Training.SQL_WHERE_PRIMARY_KEY; } else { return super.getPrimaryKeyWhere(clazz, key); } // return where clause pair return Pair.create(where, this.getBindValues(key)); } @NonNull @Override protected Pair<String, String[]> getPrimaryKeyWhere(@NonNull final Object obj) { if (obj instanceof Training) { return this.getPrimaryKeyWhere(Training.class, ((Training) obj).getId()); } return super.getPrimaryKeyWhere(obj); } public Cursor retrieveTrainingCursor(String tableName) { final SQLiteDatabase database = dbHelper.getReadableDatabase(); try { return database.query(tableName, null, null, null, null, null, null); } catch (Exception e) { Log.e(TAG, "Failed to retrieve training: " + e.getMessage(), e); } return null; } public Cursor retrieveCompletedTrainingCursor(String tableName) { final SQLiteDatabase database = dbHelper.getReadableDatabase(); try { return database.query(tableName, null, null, null, null, null, null); } catch (Exception e) { Log.e(TAG, e.getMessage(), e); } return null; } public Cursor retrieveCompletedTrainingCursor(int trainingId) { final SQLiteDatabase database = dbHelper.getReadableDatabase(); String whereCondition = "training_id = ?"; String[] whereArgs = {String.valueOf(trainingId)}; try { return database.query(TableNames.TRAINING_COMPLETIONS.getTableName(), null, whereCondition, whereArgs, null, null, null); } catch (Exception e) { Log.e(TAG, e.getMessage(), e); } return null; } public Training retrieveTrainingById(int id) { try { final Training training = this.find(Training.class, id); if (training != null) { training.setCompletions(getCompletedTrainingByTrainingId(training.getId())); } return training; } catch (Exception e) { Log.e(TAG, e.getMessage(), e); } return null; } @Nullable public List<Training> getAllMinistryTraining(String ministry_id) { Log.i(TAG, "Getting all training for ministry: " + ministry_id); try { final List<Training> trainings = this.get(Training.class, Contract.Training.SQL_WHERE_MINISTRY_ID, this.getBindValues(ministry_id)); for (final Training training : trainings) { training.setCompletions(getCompletedTrainingByTrainingId(training.getId())); } Log.i(TAG, "Trainings returned: " + trainings.size()); return trainings; } catch (Exception e) { Log.e(TAG, e.getMessage(), e); } return null; } public List<Training.GCMTrainingCompletions> getCompletedTrainingByTrainingId(int id) { Cursor cursor = null; List<Training.GCMTrainingCompletions> completed = new ArrayList<>(); try { cursor = retrieveCompletedTrainingCursor(id); if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); for (int i = 0; i < cursor.getCount(); i++) { Training.GCMTrainingCompletions completedTraining = setCompletedTrainingFromCursor(cursor); // if size is 0, go ahead and add if (completed.size() > 0) { boolean exists = false; for (Training.GCMTrainingCompletions trainingAlreadyAdded : completed) { if (Training.GCMTrainingCompletions.equals(trainingAlreadyAdded, completedTraining)) exists = true; } if (!exists) completed.add(completedTraining); } else { completed.add(completedTraining); } cursor.moveToNext(); } } return completed; } catch (Exception e) { Log.e(TAG, e.getMessage(), e); } finally { if (cursor != null) cursor.close(); } return null; } public void saveTrainingFromAPI(JSONArray jsonArray) { final SQLiteDatabase database = dbHelper.getWritableDatabase(); try { database.beginTransaction(); String trainingCompleteTable = TableNames.TRAINING_COMPLETIONS.getTableName(); Cursor existingCompletedTraining = retrieveTrainingCursor(trainingCompleteTable); Log.i(TAG, "API returned: " + jsonArray.length()); for (int i = 0; i < jsonArray.length(); i++) { final JSONObject json = jsonArray.getJSONObject(i); // build training object final Training training = new Training(); training.setId(json.getInt("id")); training.setMinistryId(json.getString("ministry_id")); training.setName(json.getString("name")); training.setDate(stringToDate(json.getString("date"))); training.setType(json.getString("type")); training.setMcc(json.getString("mcc")); training.setLatitude(json.getDouble("latitude")); training.setLongitude(json.getDouble("longitude")); training.setLastSynced(new Date()); // update or insert training object this.updateOrInsert(training, Contract.Training.PROJECTION_ALL); JSONArray trainingCompletedArray = json.getJSONArray("gcm_training_completions"); for (int j = 0; j < trainingCompletedArray.length(); j++) { JSONObject completedTraining = trainingCompletedArray.getJSONObject(j); int completedId = completedTraining.getInt("id"); ContentValues completedTrainingToInsert = new ContentValues(); completedTrainingToInsert.put("id", completedId); completedTrainingToInsert.put("phase", completedTraining.getInt("phase")); completedTrainingToInsert.put("number_completed", completedTraining.getInt("number_completed")); completedTrainingToInsert.put("date", completedTraining.getString("date")); completedTrainingToInsert.put("training_id", completedTraining.getInt("training_id")); completedTrainingToInsert.put("synced", new Timestamp(new Date().getTime()).toString()); if (!trainingExistsInDatabase(completedId, existingCompletedTraining)) { database.insert(trainingCompleteTable, null, completedTrainingToInsert); } else { database.update(trainingCompleteTable, completedTrainingToInsert, null, null); } Log.i(TAG, "Inserted/Updated completed training: " + completedId); } } database.setTransactionSuccessful(); } catch (Exception e) { Log.e(TAG, e.getMessage(), e); } finally { database.endTransaction(); if (database.isDbLockedByCurrentThread()) Log.w(TAG, "Database Locked by thread (saveTrainingFromAPI)"); } } public void saveTraining(Training training) { final SQLiteDatabase database = dbHelper.getWritableDatabase(); try { database.beginTransaction(); this.updateOrInsert(training, Contract.Training.PROJECTION_ALL); String completedTrainingTable = TableNames.TRAINING_COMPLETIONS.getTableName(); Cursor existingCompletedTraining = retrieveCompletedTrainingCursor(completedTrainingTable); if (training.getCompletions() != null && training.getCompletions().size() > 0) { for (Training.GCMTrainingCompletions completion : training.getCompletions()) { ContentValues completedTrainingToInsert = new ContentValues(); completedTrainingToInsert.put("id", completion.getId()); completedTrainingToInsert.put("phase", completion.getPhase()); completedTrainingToInsert.put("number_completed", completion.getNumberCompleted()); completedTrainingToInsert.put("training_id", completion.getTrainingId()); completedTrainingToInsert.put("synced", completion.getSynced().toString()); if (!trainingExistsInDatabase(completion.getId(), existingCompletedTraining)) { database.insert(completedTrainingTable, null, completedTrainingToInsert); } else { database.update(completedTrainingTable, completedTrainingToInsert, null, null); } Log.i(TAG, "Inserted/Updated completed training: " + completion.getId()); } } database.setTransactionSuccessful(); } catch (Exception e) { Log.e(TAG, e.getMessage(), e); } finally { database.endTransaction(); if (database.isDbLockedByCurrentThread()) Log.w(TAG, "Database Locked by thread (saveTraining)"); } } void deleteAllData() { final SQLiteDatabase database = this.dbHelper.getWritableDatabase(); database.beginTransaction(); try { database.delete(TableNames.TRAINING.getTableName(), null, null); database.setTransactionSuccessful(); } catch (Exception e) { Log.e(TAG, e.getMessage()); } finally { database.endTransaction(); if (database.isDbLockedByCurrentThread()) Log.w(TAG, "Database Locked by thread (deleteAllData)"); } } private boolean trainingExistsInDatabase(int id, Cursor existingTraining) { existingTraining.moveToFirst(); for (int i = 0; i < existingTraining.getCount(); i++) { int existingId = existingTraining.getInt(existingTraining.getColumnIndex("id")); if (existingId == id) return true; existingTraining.moveToNext(); } return false; } private Date stringToDate(String string) throws ParseException { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.US); return format.parse(string); } private Training.GCMTrainingCompletions setCompletedTrainingFromCursor(Cursor cursor) throws ParseException { Training.GCMTrainingCompletions trainingCompletions = new Training.GCMTrainingCompletions(); trainingCompletions.setId(cursor.getInt(cursor.getColumnIndex("id"))); trainingCompletions.setPhase(cursor.getInt(cursor.getColumnIndex("phase"))); trainingCompletions.setNumberCompleted(cursor.getInt(cursor.getColumnIndex("number_completed"))); trainingCompletions.setTrainingId(cursor.getInt(cursor.getColumnIndex("training_id"))); trainingCompletions.setDate(stringToDate(cursor.getString(cursor.getColumnIndex("date")))); if (!cursor.getString(cursor.getColumnIndex("synced")).isEmpty()) { try { trainingCompletions.setSynced(Timestamp.valueOf(cursor.getString(cursor.getColumnIndex("synced")))); } catch (Exception e) { Log.i(TAG, "Could not parse Timestamp"); } } return trainingCompletions; } }
package edu.umd.cs.findbugs.bcel; import org.apache.bcel.Constants; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method; import org.apache.bcel.generic.ConstantPoolGen; import org.apache.bcel.generic.InvokeInstruction; import edu.umd.cs.findbugs.classfile.ClassDescriptor; import edu.umd.cs.findbugs.classfile.MethodDescriptor; /** * Utility methods for detectors and analyses using BCEL. * * @author David Hovemeyer */ public abstract class BCELUtil { /** * Construct a MethodDescriptor from JavaClass and method. * * @param jclass a JavaClass * @param method a Method belonging to the JavaClass * @return a MethodDescriptor identifying the method */ public static MethodDescriptor getMethodDescriptor(JavaClass jclass, Method method) { return new MethodDescriptor( jclass.getClassName().replace('.', '/'), method.getName(), method.getSignature(), method.isStatic()); } /** * Get a MethodDescriptor describing the method called by * given InvokeInstruction. * * @param inv the InvokeInstruction * @param cpg ConstantPoolGen of class containing instruction * @return MethodDescriptor describing the called method */ public static MethodDescriptor getCalledMethodDescriptor(InvokeInstruction inv, ConstantPoolGen cpg) { String calledClassName = inv.getClassName(cpg).replace('.', '/'); String calledMethodName = inv.getMethodName(cpg); String calledMethodSig = inv.getSignature(cpg); boolean isStatic = inv.getOpcode() == Constants.INVOKESTATIC; return new MethodDescriptor(calledClassName, calledMethodName, calledMethodSig, isStatic); } /** * Construct a ClassDescriptor from a JavaClass. * * @param jclass a JavaClass * @return a ClassDescriptor identifying that JavaClass */ public static ClassDescriptor getClassDescriptor(JavaClass jclass) { return new ClassDescriptor(jclass.getClassName().replace('.', '/')); } }
package org.intermine.web; import javax.servlet.ServletContext; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import java.util.Map; import java.util.Iterator; import org.intermine.objectstore.query.ConstraintOp; /** * Action to handle submit from the template page * @author Mark Woodbridge */ public class TemplateAction extends Action { /** * @see Action#execute */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); ServletContext servletContext = session.getServletContext(); Map templateQueries = (Map) servletContext.getAttribute(Constants.TEMPLATE_QUERIES); String queryName = (String) session.getAttribute("queryName"); TemplateQuery template = (TemplateQuery) templateQueries.get(queryName); for (Iterator i = template.getNodes().iterator(); i.hasNext();) { PathNode node = (PathNode) i.next(); int j = template.getNodes().indexOf(node); String op = (String) ((TemplateForm) form).getAttributeOps("" + (j + 1)); ConstraintOp constraintOp = ConstraintOp.getOpForIndex(Integer.valueOf(op)); Object constraintValue = ((TemplateForm) form).getParsedAttributeValues("" + (j + 1)); node.getConstraints().set(0, new Constraint(constraintOp, constraintValue)); } LoadQueryAction.loadQuery(template.getQuery(), request.getSession()); if (request.getParameter("skipBuilder") != null) { // If the form wants to skip the query builder we need to execute the query if (!SessionMethods.runQuery (session, request)) { return mapping.findForward("failure"); } return mapping.findForward("results"); } return mapping.findForward("query"); } }
package de.xikolo.controller; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.v4.content.ContextCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.widget.FrameLayout; import com.google.android.libraries.cast.companionlibrary.cast.BaseCastManager; import com.google.android.libraries.cast.companionlibrary.cast.VideoCastManager; import com.google.android.libraries.cast.companionlibrary.cast.callbacks.VideoCastConsumerImpl; import com.google.android.libraries.cast.companionlibrary.widgets.IntroductoryOverlay; import com.path.android.jobqueue.JobManager; import de.greenrobot.event.EventBus; import de.xikolo.GlobalApplication; import de.xikolo.R; import de.xikolo.data.database.DatabaseHelper; import de.xikolo.model.events.NetworkStateEvent; import de.xikolo.model.events.PermissionDeniedEvent; import de.xikolo.model.events.PermissionGrantedEvent; public abstract class BaseActivity extends AppCompatActivity { protected GlobalApplication globalApplication; protected JobManager jobManager; protected DatabaseHelper databaseHelper; protected ActionBar actionBar; protected Toolbar toolbar; protected VideoCastManager videoCastManager; private DrawerLayout drawerLayout; private FrameLayout contentLayout; private MenuItem mediaRouteMenuItem; private VideoCastConsumerImpl castConsumer; private boolean offlineModeToolbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); globalApplication = GlobalApplication.getInstance(); jobManager = globalApplication.getJobManager(); offlineModeToolbar = true; BaseCastManager.checkGooglePlayServices(this); videoCastManager = VideoCastManager.getInstance(); castConsumer = new VideoCastConsumerImpl() { @Override public void onCastAvailabilityChanged(boolean castPresent) { if (castPresent) { new Handler().postDelayed(new Runnable() { @Override public void run() { if (mediaRouteMenuItem.isVisible()) { showOverlay(); } } }, 1000); } } }; videoCastManager.addVideoCastConsumer(castConsumer); } private void showOverlay() { IntroductoryOverlay overlay = new IntroductoryOverlay.Builder(this) .setMenuItem(mediaRouteMenuItem) .setTitleText(R.string.intro_overlay_text) .setSingleTime() .build(); overlay.show(); } protected void setupActionBar() { Toolbar tb = (Toolbar) findViewById(R.id.toolbar); if (tb != null) { setSupportActionBar(tb); } toolbar = tb; actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeButtonEnabled(true); } drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); contentLayout = (FrameLayout) findViewById(R.id.contentLayout); setColorScheme(R.color.apptheme_main, R.color.apptheme_main_dark_status); } protected void setActionBarElevation(float elevation) { if (actionBar != null && Build.VERSION.SDK_INT >= 21) { actionBar.setElevation(elevation); } } protected void enableOfflineModeToolbar(boolean enable) { this.offlineModeToolbar = enable; } public void onEventMainThread(NetworkStateEvent event) { if (toolbar != null && offlineModeToolbar) { if (event.isOnline()) { toolbar.setSubtitle(""); setColorScheme(R.color.apptheme_main, R.color.apptheme_main_dark_status); } else { toolbar.setSubtitle(getString(R.string.offline_mode)); setColorScheme(R.color.offline_mode, R.color.offline_mode_dark); } } } protected void setColorScheme(int color, int darkColor) { if (toolbar != null) { toolbar.setBackgroundColor(ContextCompat.getColor(this, color)); if (Build.VERSION.SDK_INT >= 21) { if (drawerLayout != null) { drawerLayout.setStatusBarBackgroundColor(ContextCompat.getColor(this, color)); } else { getWindow().setStatusBarColor(ContextCompat.getColor(this, darkColor)); } if (contentLayout != null) { contentLayout.setBackgroundColor(ContextCompat.getColor(this, color)); } } } } @Override protected void onStart() { super.onStart(); EventBus.getDefault().registerSticky(this); } @Override protected void onResume() { super.onResume(); globalApplication.startCookieSyncManager(); videoCastManager.incrementUiCounter(); } @Override protected void onPause() { super.onPause(); globalApplication.syncCookieSyncManager(); globalApplication.stopCookieSyncManager(); videoCastManager.decrementUiCounter(); } @Override protected void onStop() { super.onStop(); globalApplication.flushHttpResponseCache(); EventBus.getDefault().unregister(this); } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { EventBus.getDefault().post(new PermissionGrantedEvent(requestCode)); } else { EventBus.getDefault().post(new PermissionDeniedEvent(requestCode)); } } protected void enableCastMediaRouterButton(boolean enable) { if (mediaRouteMenuItem != null) { mediaRouteMenuItem.setVisible(enable); invalidateOptionsMenu(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.cast, menu); mediaRouteMenuItem = videoCastManager.addMediaRouterButton(menu, R.id.media_route_menu_item); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { return super.onOptionsItemSelected(item); } }
package local.tomo.login.model; import android.util.Log; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; public class Medicament { DateExpirationYearMonth dateExpirationYearMonth = new DateExpirationYearMonth(); private int id; private int idServer; private String name; private String producent; private double price; private String kind; private String dateExpiration; private Date dateFormatExpiration; private int productLineID; private int packageID; public Medicament() { } public Medicament(MedicamentDb medicamentDb) { this.name = medicamentDb.getProductName(); this.producent = medicamentDb.getProducer(); this.price = medicamentDb.getPrice(); this.kind = medicamentDb.getPack(); this.productLineID = medicamentDb.getProductLineID(); this.packageID = medicamentDb.getPackageID(); } public static class List extends ArrayList<Medicament> { } public void createDate() { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(Long.parseLong(getDateExpiration())); calendar.add(Calendar.DAY_OF_MONTH,1); dateFormatExpiration = calendar.getTime(); } @Override public boolean equals(Object obj) { if (obj == null) return false; if (obj == this) return true; if (!(obj instanceof Medicament))return false; Medicament medicament = (Medicament)obj; if(this.hashCode() == medicament.hashCode()) return true; else return false; } @Override public int hashCode() { int result = 17; int multipler = 31; //int result = multipler * result + idServer; result = multipler * result + productLineID; result = multipler * result + packageID; //String result = multipler * result + (name == null ? 0 : name.hashCode()); result = multipler * result + (producent == null ? 0 : producent.hashCode()); result = multipler * result + (dateExpiration == null ? 0 : dateExpiration.hashCode()); result = multipler * result + (kind == null ? 0 : kind.hashCode()); //double long priceBits = Double.doubleToLongBits(price); result = multipler * result + (int)(priceBits ^ (priceBits >>> 32)); return result; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getProducent() { return producent; } public void setProducent(String producent) { this.producent = producent; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public String getKind() { return kind; } public void setKind(String kind) { this.kind = kind; } public int getIdServer() { return idServer; } public void setIdServer(int idServer) { this.idServer = idServer; } public String getDateExpiration() { return dateExpiration; } public void setDateExpiration(String dateExpiration) { this.dateExpiration = dateExpiration; } public int getProductLineID() { return productLineID; } public void setProductLineID(int productLineID) { this.productLineID = productLineID; } public int getPackageID() { return packageID; } public void setPackageID(int packageID) { this.packageID = packageID; } public Date getDateFormatExpiration() { return dateFormatExpiration; } public void setDateFormatExpiration(Date dateFormatExpiration) { this.dateFormatExpiration = dateFormatExpiration; } public DateExpirationYearMonth getDateExpirationYearMonth() { return dateExpirationYearMonth; } public void setDateExpirationYearMonth(DateExpirationYearMonth dateExpirationYearMonth) { this.dateExpirationYearMonth = dateExpirationYearMonth; } @Override public String toString() { return "Medicament{" + "idServer=" + idServer + ", name='" + name + '\'' + ", producent='" + producent + '\'' + ", price=" + price + ", kind='" + kind + '\'' + ", dateExpiration='" + dateExpiration + '\'' + ", productLineID=" + productLineID + ", packageID=" + packageID + '}'; } }
package org.ieatta.analytics; import org.ieatta.IEATTAApp; import org.wikipedia.analytics.Funnel; import org.ieatta.database.models.DBEvent; import org.ieatta.database.models.DBNewRecord; import org.ieatta.database.models.DBPeopleInEvent; import org.ieatta.database.models.DBPhoto; import org.ieatta.database.models.DBRecipe; import org.ieatta.database.models.DBRestaurant; import org.ieatta.database.models.DBReview; import org.ieatta.database.models.DBTeam; public class ModelsFunnel extends Funnel { private static final String SCHEMA_NAME = "MobileIEATTAModels"; private static final int REV_ID = 101010; ModelsFunnel(IEATTAApp app, String schemaName, int revision) { super(app, SCHEMA_NAME, REV_ID, SAMPLE_LOG_1K); } public void logEvent(DBEvent event){ } public void logNewRecord(DBNewRecord newRecord){ } public void logPeopleInEvent(DBPeopleInEvent peopleInEvent){ } public void logPhoto(DBPhoto photo){ } public void logRecipe(DBRecipe recipe){ } public void logRestaurant(DBRestaurant restaurant){ } public void logReview(DBReview review){ } public void logTeam(DBTeam team){ } }
package org.wikipedia.main; import android.content.Context; import android.net.Uri; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.ScrollView; import android.widget.TextView; import androidx.annotation.Nullable; import org.wikipedia.BuildConfig; import org.wikipedia.R; import org.wikipedia.WikipediaApp; import org.wikipedia.auth.AccountUtil; import org.wikipedia.util.ResourceUtil; import org.wikipedia.util.UriUtil; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class MainDrawerView extends ScrollView { public interface Callback { void loginLogoutClick(); void notificationsClick(); void settingsClick(); void configureFeedClick(); void aboutClick(); } @BindView(R.id.main_drawer_account_name) TextView accountNameView; @BindView(R.id.main_drawer_login_button) Button loginLogoutButton; @BindView(R.id.main_drawer_account_avatar) ImageView accountAvatar; @BindView(R.id.main_drawer_account_wiki_globe) ImageView accountWikiGlobe; @BindView(R.id.main_drawer_notifications_container) ViewGroup notificationsContainer; @Nullable Callback callback; public MainDrawerView(Context context) { super(context); init(); } public MainDrawerView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public MainDrawerView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } public void setCallback(@Nullable Callback callback) { this.callback = callback; } public void updateState() { if (AccountUtil.isLoggedIn()) { accountNameView.setText(AccountUtil.getUserName()); accountNameView.setVisibility(VISIBLE); loginLogoutButton.setText(getContext().getString(R.string.preference_title_logout)); loginLogoutButton.setTextColor(ResourceUtil.getThemedColor(getContext(), R.attr.colorError)); accountAvatar.setVisibility(View.VISIBLE); accountWikiGlobe.setVisibility(View.GONE); notificationsContainer.setVisibility(View.VISIBLE); } else { accountNameView.setVisibility(GONE); loginLogoutButton.setText(getContext().getString(R.string.main_drawer_login)); loginLogoutButton.setTextColor(ResourceUtil.getThemedColor(getContext(), R.attr.colorAccent)); accountAvatar.setVisibility(View.GONE); accountWikiGlobe.setVisibility(View.VISIBLE); notificationsContainer.setVisibility(View.GONE); } } @OnClick(R.id.main_drawer_settings_container) void onSettingsClick() { if (callback != null) { callback.settingsClick(); } } @OnClick(R.id.main_drawer_configure_container) void onConfigureClick() { if (callback != null) { callback.configureFeedClick(); } } @OnClick(R.id.main_drawer_notifications_container) void onNotificationsClick() { if (callback != null) { callback.notificationsClick(); } } @OnClick(R.id.main_drawer_donate_container) void onDonateClick() { UriUtil.visitInExternalBrowser(getContext(), Uri.parse(String.format(getContext().getString(R.string.donate_url), BuildConfig.VERSION_NAME, WikipediaApp.getInstance().language().getSystemLanguageCode()))); } @OnClick(R.id.main_drawer_about_container) void onAboutClick() { if (callback != null) { callback.aboutClick(); } } @OnClick(R.id.main_drawer_help_container) void onHelpClick() { UriUtil.visitInExternalBrowser(getContext(), Uri.parse(getContext().getString(R.string.android_app_faq_url))); } @OnClick(R.id.main_drawer_login_button) void onLoginClick() { if (callback != null) { callback.loginLogoutClick(); } } private void init() { inflate(getContext(), R.layout.view_main_drawer, this); ButterKnife.bind(this); } }
package water.api; import water.DKV; import water.Key; import water.exceptions.H2OIllegalArgumentException; import water.fvec.Frame; import water.parser.ValueString; import water.rapids.Env; import water.util.Log; import water.util.PrettyPrint; class RapidsHandler extends Handler { public RapidsV3 isEvaluated(int version, RapidsV3 rapids) { if (rapids == null) return null; if (rapids.ast_key == null) throw new IllegalArgumentException("No key supplied to getKey."); boolean isEval = false; if ((DKV.get(rapids.ast_key.key()))!=null) { isEval = true; } rapids.evaluated = isEval; return rapids; } public RapidsV3 exec(int version, RapidsV3 rapids) { if (rapids == null) return null; Throwable e = null; Env env = null; try { //learn all fcns if( rapids.fun!=null ) water.rapids.Exec.new_func(rapids.fun); if (rapids.ast == null || rapids.ast.equals("")) return rapids; env = water.rapids.Exec.exec(rapids.ast); StringBuilder sb = env._sb; if( sb.length()!=0 ) sb.append("\n"); if( !env.isEmpty() ) { if (env.isAry()) { Frame fr = env.popAry(); Key[] keys = fr.keys(); if (keys != null && keys.length > 0) { rapids.vec_ids = new KeyV3.VecKeyV3[keys.length]; for (int i = 0; i < keys.length; i++) rapids.vec_ids[i] = new KeyV3.VecKeyV3(keys[i]); } if (fr.numRows() == 1 && fr.numCols() == 1) { rapids.key = new KeyV3.FrameKeyV3(fr._key); rapids.num_rows = 0; rapids.num_cols = 0; if (fr.anyVec().isEnum()) { rapids.string = fr.anyVec().domain()[(int) fr.anyVec().at(0)]; sb.append(rapids.string); rapids.result_type = RapidsV3.ARYSTR; } else if (fr.anyVec().isString()) { rapids.string = fr.anyVec().atStr(new ValueString(), 0).toString(); sb.append(rapids.string); rapids.result_type = RapidsV3.ARYSTR; } else if (fr.anyVec().isUUID()) { rapids.string = PrettyPrint.UUID(fr.anyVec().at16l(0), fr.anyVec().at16h(0)); sb.append(rapids.string); rapids.result_type = RapidsV3.ARYSTR; } else { rapids.scalar = fr.anyVec().at(0); sb.append(Double.toString(rapids.scalar)); rapids.string = null; rapids.result_type = RapidsV3.ARYNUM; } } else { rapids.result_type = RapidsV3.ARY; rapids.key = new KeyV3.FrameKeyV3(fr._key); rapids.num_rows = fr.numRows(); rapids.num_cols = fr.numCols(); rapids.col_names = fr.names(); rapids.string = null; String[][] head = rapids.head = new String[Math.min(200, fr.numCols())][(int) Math.min(100, fr.numRows())]; for (int r = 0; r < head[0].length; ++r) { for (int c = 0; c < head.length; ++c) { if (fr.vec(c).isNA(r)) head[c][r] = ""; else if (fr.vec(c).isUUID()) head[c][r] = PrettyPrint.UUID(fr.vec(c).at16l(r), fr.vec(c).at16h(r)); else if (fr.vec(c).isString()) head[c][r] = String.valueOf(fr.vec(c).atStr(new ValueString(), r)); else if( fr.vec(c).isEnum() ) head[c][r] = fr.domains()[c][(int)fr.vec(c).at(r)]; else head[c][r] = String.valueOf(fr.vec(c).at(r)); } } } //TODO: colSummary cols = new Inspect2.ColSummary[num_cols]; } else if (env.isNum()) { rapids.scalar = env.popDbl(); sb.append(Double.toString(rapids.scalar)); rapids.string = null; rapids.result_type = RapidsV3.NUM; } else if (env.isStr()) { rapids.string = env.popStr(); sb.append(rapids.string); rapids.result_type = RapidsV3.STR; } } rapids.result = sb.toString(); return rapids; } catch( IllegalArgumentException pe ) { e=pe;} catch( Throwable e2 ) { Log.err(e=e2); } finally { if (env != null) { try {env.remove_and_unlock(); } catch (Exception xe) { Log.err("env.remove_and_unlock() failed", xe); } } } if( e!=null ) e.printStackTrace(); if( e!=null ) rapids.error = e.getMessage() == null ? e.toString() : e.getMessage(); if( e!=null && e instanceof ArrayIndexOutOfBoundsException) rapids.error = e.toString(); if( e!=null ) throw new H2OIllegalArgumentException(rapids.error); return rapids; } }
package water.api; import water.*; import water.api.schemas3.H2OErrorV3; import water.api.schemas3.H2OModelBuilderErrorV3; import water.api.schemas99.AssemblyV99; import water.exceptions.*; import water.init.NodePersistentStorage; import water.nbhm.NonBlockingHashMap; import water.rapids.Assembly; import water.util.*; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.MalformedURLException; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.atomic.AtomicLong; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * This is a simple web server which accepts HTTP requests and routes them * to methods in Handler classes for processing. Schema classes are used to * provide a more stable external JSON interface while allowing the implementation * to evolve rapidly. As part of request handling the framework translates * back and forth between the stable external representation of objects (Schema) * and the less stable internal classes. * <p> * Request <i>routing</i> is done by searching a list of registered * handlers, in order of registration, for a handler whose path regex matches * the request URI and whose HTTP method (GET, POST, DELETE...) matches the * request's method. If none is found an HTTP 404 is returned. * <p> * A Handler class is parametrized by the kind of Schema that it accepts * for request handling, as well as the internal implementation class (Iced * class) that the Schema translates from and to. Handler methods are allowed to * return other Schema types than in the type parameter if that makes * sense for a given request. For example, a prediction (scoring) call on * a Model might return a Frame schema. * <p> * When an HTTP request is accepted the framework does the following steps: * <ol> * <li>searches the registered handler methods for a matching URL and HTTP method</li> * <li>collects any parameters which are captured from the URI and adds them to the map of HTTP query parameters</li> * <li>creates an instance of the correct Handler class and calls handle() on it, passing the version, route and params</li> * <li>Handler.handle() creates the correct Schema object given the version and calls fillFromParms(params) on it</li> * <li>calls schema.createImpl() to create a schema-independent "back end" object</li> * <li>dispatches to the handler method, passing in the schema-independent impl object and returning the result Schema object</li> * </ol> * * @see water.api.Handler * @see water.api.RegisterV3Api */ public class RequestServer extends HttpServlet { // TODO: merge doGeneric() and serve() // Originally we had RequestServer based on NanoHTTPD. At some point we switched to JettyHTTPD, but there are // still some leftovers from the Nano times. // TODO: invoke DatasetServlet, PostFileServlet and NpsBinServlet using standard Routes // Right now those 3 servlets are handling 5 "special" api endpoints from JettyHTTPD, and we also have several // "special" endpoints in maybeServeSpecial(). We don't want them to be special. The Route class should be // made flexible enough to generate responses of various kinds, and then all of those "special" cases would // become regular API calls. // TODO: Move JettyHTTPD.sendErrorResponse here, and combine with other error-handling functions // That method is only called from 3 servlets mentioned above, and we want to standardize the way how errors // are handled in different responses. // Returned in REST API responses as X-h2o-rest-api-version-max // Do not bump to 4 until when the API v4 is fully ready for release. public static final int H2O_REST_API_VERSION = 3; private static RouteTree routesTree = new RouteTree(""); private static ArrayList<Route> routesList = new ArrayList<>(150); public static int numRoutes() { return routesList.size(); } public static ArrayList<Route> routes() { return routesList; } public static Route lookupRoute(RequestUri uri) { return routesTree.lookup(uri, null); } /** * Some HTTP response status codes */ public static final String HTTP_OK = "200 OK", HTTP_CREATED = "201 Created", HTTP_ACCEPTED = "202 Accepted", HTTP_NO_CONTENT = "204 No Content", HTTP_PARTIAL_CONTENT = "206 Partial Content", HTTP_REDIRECT = "301 Moved Permanently", HTTP_NOT_MODIFIED = "304 Not Modified", HTTP_BAD_REQUEST = "400 Bad Request", HTTP_UNAUTHORIZED = "401 Unauthorized", HTTP_FORBIDDEN = "403 Forbidden", HTTP_NOT_FOUND = "404 Not Found", HTTP_BAD_METHOD = "405 Method Not Allowed", HTTP_PRECONDITION_FAILED = "412 Precondition Failed", HTTP_TOO_LONG_REQUEST = "414 Request-URI Too Long", HTTP_RANGE_NOT_SATISFIABLE = "416 Requested Range Not Satisfiable", HTTP_TEAPOT = "418 I'm a Teapot", HTTP_THROTTLE = "429 Too Many Requests", HTTP_INTERNAL_ERROR = "500 Internal Server Error", HTTP_NOT_IMPLEMENTED = "501 Not Implemented", HTTP_SERVICE_NOT_AVAILABLE = "503 Service Unavailable"; /** * Common mime types for dynamic content */ public static final String MIME_PLAINTEXT = "text/plain", MIME_HTML = "text/html", MIME_CSS = "text/css", MIME_JSON = "application/json", MIME_JS = "application/javascript", MIME_JPEG = "image/jpeg", MIME_PNG = "image/png", MIME_SVG = "image/svg+xml", MIME_GIF = "image/gif", MIME_WOFF = "application/x-font-woff", MIME_DEFAULT_BINARY = "application/octet-stream", MIME_XML = "text/xml"; /** * Calculates number of routes having the specified version. */ public static int numRoutes(int version) { int count = 0; for (Route route : routesList) if (route.getVersion() == version) count++; return count; } /** * Register an HTTP request handler method for a given URL pattern, with parameters extracted from the URI. * <p> * URIs which match this pattern will have their parameters collected from the path and from the query params * * @param api_name suggested method name for this endpoint in the external API library. These names should be * unique. If null, the api_name will be created from the class name and the handler method name. * @param method_uri combined method / url pattern of the request, e.g.: "GET /3/Jobs/{job_id}" * @param handler_class class which contains the handler method * @param handler_method name of the handler method * @param summary help string which explains the functionality of this endpoint * @see Route * @see water.api.RequestServer * @return the Route for this request */ public static Route registerEndpoint( String api_name, String method_uri, Class<? extends Handler> handler_class, String handler_method, String summary ) { String[] spl = method_uri.split(" "); assert spl.length == 2 : "Unexpected method_uri parameter: " + method_uri; return registerEndpoint(api_name, spl[0], spl[1], handler_class, handler_method, summary, HandlerFactory.DEFAULT); } /** * @param api_name suggested method name for this endpoint in the external API library. These names should be * unique. If null, the api_name will be created from the class name and the handler method name. * @param http_method HTTP verb (GET, POST, DELETE) this handler will accept * @param url url path, possibly containing placeholders in curly braces, e.g: "/3/DKV/{key}" * @param handler_class class which contains the handler method * @param handler_method name of the handler method * @param summary help string which explains the functionality of this endpoint * @param handler_factory factory to create instance of handler (used by Sparkling Water) * @return the Route for this request */ public static Route registerEndpoint( String api_name, String http_method, String url, Class<? extends Handler> handler_class, String handler_method, String summary, HandlerFactory handler_factory ) { assert api_name != null : "api_name should not be null"; try { RequestUri uri = new RequestUri(http_method, url); Route route = new Route(uri, api_name, summary, handler_class, handler_method, handler_factory); routesTree.add(uri, route); routesList.add(route); return route; } catch (MalformedURLException e) { throw H2O.fail(e.getMessage()); } } @Override protected void doGet(HttpServletRequest rq, HttpServletResponse rs) { doGeneric("GET", rq, rs); } @Override protected void doPut(HttpServletRequest rq, HttpServletResponse rs) { doGeneric("PUT", rq, rs); } @Override protected void doPost(HttpServletRequest rq, HttpServletResponse rs) { doGeneric("POST", rq, rs); } @Override protected void doHead(HttpServletRequest rq, HttpServletResponse rs) { doGeneric("HEAD", rq, rs); } @Override protected void doDelete(HttpServletRequest rq, HttpServletResponse rs) { doGeneric("DELETE", rq, rs); } /** * Top-level dispatch handling */ public void doGeneric(String method, HttpServletRequest request, HttpServletResponse response) { try { JettyHTTPD.startTransaction(request.getHeader("User-Agent")); // Note that getServletPath does an un-escape so that the %24 of job id's are turned into $ characters. String uri = request.getServletPath(); Properties headers = new Properties(); Enumeration<String> en = request.getHeaderNames(); while (en.hasMoreElements()) { String key = en.nextElement(); String value = request.getHeader(key); headers.put(key, value); } final String contentType = request.getContentType(); Properties parms = new Properties(); String postBody = null; if ("application/json".equals(contentType)) { StringBuffer jb = new StringBuffer(); String line = null; try { BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) jb.append(line); } catch (Exception e) { throw new H2OIllegalArgumentException("Exception reading POST body JSON for URL: " + uri); } postBody = jb.toString(); } else { // application/x-www-form-urlencoded Map<String, String[]> parameterMap; parameterMap = request.getParameterMap(); for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) { String key = entry.getKey(); String[] values = entry.getValue(); if (values.length == 1) { parms.put(key, values[0]); } else if (values.length > 1) { StringBuilder sb = new StringBuilder(); sb.append("["); boolean first = true; for (String value : values) { if (!first) sb.append(","); sb.append("\"").append(value).append("\""); first = false; } sb.append("]"); parms.put(key, sb.toString()); } } } // Make serve() call. NanoResponse resp = serve(uri, method, headers, parms, postBody); // Un-marshal Nano response back to Jetty. String choppedNanoStatus = resp.status.substring(0, 3); assert (choppedNanoStatus.length() == 3); int sc = Integer.parseInt(choppedNanoStatus); JettyHTTPD.setResponseStatus(response, sc); response.setContentType(resp.mimeType); Properties header = resp.header; Enumeration<Object> en2 = header.keys(); while (en2.hasMoreElements()) { String key = (String) en2.nextElement(); String value = header.getProperty(key); response.setHeader(key, value); } resp.writeTo(response.getOutputStream()); } catch (IOException e) { JettyHTTPD.setResponseStatus(response, 500); // Trying to send an error message or stack trace will produce another IOException... } finally { JettyHTTPD.logRequest(method, request, response); // Handle shutdown if it was requested. if (H2O.getShutdownRequested()) { (new Thread() { public void run() { boolean [] confirmations = new boolean[H2O.CLOUD.size()]; if (H2O.SELF.index() >= 0) { confirmations[H2O.SELF.index()] = true; } for(H2ONode n:H2O.CLOUD._memary) { if(n != H2O.SELF) new RPC<>(n, new UDPRebooted.ShutdownTsk(H2O.SELF,n.index(), 1000, confirmations)).call(); } try { Thread.sleep(2000); } catch (Exception ignore) {} int failedToShutdown = 0; // shutdown failed for(boolean b:confirmations) if(!b) failedToShutdown++; Log.info("Orderly shutdown: " + (failedToShutdown > 0? failedToShutdown + " nodes failed to shut down! ":"") + " Shutting down now."); H2O.closeAll(); H2O.exit(failedToShutdown); } }).start(); } JettyHTTPD.endTransaction(); } } /** * Subsequent handling of the dispatch */ public static NanoResponse serve(String url, String method, Properties header, Properties parms, String post_body) { try { // Jack priority for user-visible requests Thread.currentThread().setPriority(Thread.MAX_PRIORITY - 1); RequestType type = RequestType.requestType(url); RequestUri uri = new RequestUri(method, url); // Log the request maybeLogRequest(uri, header, parms); // For certain "special" requests that produce non-JSON payloads we require special handling. NanoResponse special = maybeServeSpecial(uri); if (special != null) return special; // Determine the Route corresponding to this request, and also fill in {parms} with the path parameters Route route = routesTree.lookup(uri, parms); // These APIs are broken, because they lead users to create invalid URLs. For example the endpoint // /3/Frames/{frameid}/export/{path}/overwrite/{force} // is invalid, because it leads to URLs like this: // /3/Frames/predictions_9bd5_GLM_model_R_1471148_36_on_RTMP_sid_afec_27/export//tmp/pred.csv/overwrite/TRUE // Here both the {frame_id} and {path} usually contain "/" (making them non-tokens), they may contain other // special characters not valid within URLs (for example if filename is not in ASCII); finally the use of strings // to represent booleans creates ambiguities: should I write "true", "True", "TRUE", or perhaps "1"? // TODO These should be removed as soon as possible... if (url.startsWith("/3/Frames/")) { // /3/Frames/{frame_id}/export/{path}/overwrite/{force} if ((url.toLowerCase().endsWith("/overwrite/true") || url.toLowerCase().endsWith("/overwrite/false")) && url.contains("/export/")) { int i = url.indexOf("/export/"); boolean force = url.toLowerCase().endsWith("true"); parms.put("frame_id", url.substring(10, i)); parms.put("path", url.substring(i+8, url.length()-15-(force?0:1))); parms.put("force", force? "true" : "false"); route = findRouteByApiName("exportFrame_deprecated"); } // /3/Frames/{frame_id}/export else if (url.endsWith("/export")) { parms.put("frame_id", url.substring(10, url.length()-7)); route = findRouteByApiName("exportFrame"); } // /3/Frames/{frame_id}/columns/{column}/summary else if (url.endsWith("/summary") && url.contains("/columns/")) { int i = url.indexOf("/columns/"); parms.put("frame_id", url.substring(10, i)); parms.put("column", url.substring(i+9, url.length()-8)); route = findRouteByApiName("frameColumnSummary"); } // /3/Frames/{frame_id}/columns/{column}/domain else if (url.endsWith("/domain") && url.contains("/columns/")) { int i = url.indexOf("/columns/"); parms.put("frame_id", url.substring(10, i)); parms.put("column", url.substring(i+9, url.length()-7)); route = findRouteByApiName("frameColumnDomain"); } // /3/Frames/{frame_id}/columns/{column} else if (url.contains("/columns/")) { int i = url.indexOf("/columns/"); parms.put("frame_id", url.substring(10, i)); parms.put("column", url.substring(i+9)); route = findRouteByApiName("frameColumn"); } // /3/Frames/{frame_id}/summary else if (url.endsWith("/summary")) { parms.put("frame_id", url.substring(10, url.length()-8)); route = findRouteByApiName("frameSummary"); } // /3/Frames/{frame_id}/columns else if (url.endsWith("/columns")) { parms.put("frame_id", url.substring(10, url.length()-8)); route = findRouteByApiName("frameColumns"); } // /3/Frames/{frame_id} else { parms.put("frame_id", url.substring(10)); route = findRouteByApiName(method.equals("DELETE")? "deleteFrame" : "frame"); } } else if (url.startsWith("/3/ModelMetrics/predictions_frame/")){ route = findRouteByApiName("makeMetrics"); } if (route == null) { // if the request is not known, treat as resource request, or 404 if not found if (uri.isGetMethod()) return getResource(type, url); else return response404(method + " " + url, type); } else { Schema response = route._handler.handle(uri.getVersion(), route, parms, post_body); PojoUtils.filterFields(response, (String)parms.get("_include_fields"), (String)parms.get("_exclude_fields")); return serveSchema(response, type); } } catch (H2OFailException e) { H2OError error = e.toH2OError(url); Log.fatal("Caught exception (fatal to the cluster): " + error.toString()); throw H2O.fail(serveError(error).toString()); } catch (H2OModelBuilderIllegalArgumentException e) { H2OModelBuilderError error = e.toH2OError(url); Log.warn("Caught exception: " + error.toString()); return serveSchema(new H2OModelBuilderErrorV3().fillFromImpl(error), RequestType.json); } catch (H2OAbstractRuntimeException e) { H2OError error = e.toH2OError(url); Log.warn("Caught exception: " + error.toString()); return serveError(error); } catch (AssertionError e) { H2OError error = new H2OError( System.currentTimeMillis(), url, e.toString(), e.toString(), HttpResponseStatus.INTERNAL_SERVER_ERROR.getCode(), new IcedHashMapGeneric.IcedHashMapStringObject(), e); Log.err("Caught assertion error: " + error.toString()); return serveError(error); } catch (Exception e) { // make sure that no Exception is ever thrown out from the request H2OError error = new H2OError(e, url); // some special cases for which we return 400 because it's likely a problem with the client request: if (e instanceof IllegalArgumentException || e instanceof FileNotFoundException || e instanceof MalformedURLException) error._http_status = HttpResponseStatus.BAD_REQUEST.getCode(); Log.err("Caught exception: " + error.toString()); return serveError(error); } } /** * Log the request (unless it's an overly common one). */ private static void maybeLogRequest(RequestUri uri, Properties header, Properties parms) { String url = uri.getUrl(); if (url.endsWith(".css") || url.endsWith(".js") || url.endsWith(".png") || url.endsWith(".ico")) return; String[] path = uri.getPath(); if (path[2].equals("Cloud") || path[2].equals("Jobs") && uri.isGetMethod() || path[2].equals("Log") || path[2].equals("Progress") || path[2].equals("Typeahead") || path[2].equals("WaterMeterCpuTicks")) return; Log.info(uri + ", parms: " + parms); GAUtils.logRequest(url, header); } private static class RouteTree { private String root; private boolean isWildcard; private HashMap<String, RouteTree> branches; private Route leaf; public RouteTree(String token) { isWildcard = isWildcardToken(token); root = isWildcard ? "*" : token; branches = new HashMap<>(); leaf = null; } public void add(RequestUri uri, Route route) { String[] path = uri.getPath(); addByPath(path, 0, route); } public Route lookup(RequestUri uri, Properties parms) { if (!uri.isApiUrl()) return null; String[] path = uri.getPath(); ArrayList<String> path_params = new ArrayList<>(3); Route route = this.lookupByPath(path, 0, path_params); // Fill in the path parameters if (parms != null && route != null) { String[] param_names = route._path_params; assert path_params.size() == param_names.length; for (int i = 0; i < param_names.length; i++) parms.put(param_names[i], path_params.get(i)); } return route; } private void addByPath(String[] path, int index, Route route) { if (index + 1 < path.length) { String nextToken = isWildcardToken(path[index+1])? "*" : path[index+1]; if (!branches.containsKey(nextToken)) branches.put(nextToken, new RouteTree(nextToken)); branches.get(nextToken).addByPath(path, index + 1, route); } else { assert leaf == null : "Duplicate path encountered: " + Arrays.toString(path); leaf = route; } } private Route lookupByPath(String[] path, int index, ArrayList<String> path_params) { assert isWildcard || root.equals(path[index]); if (index + 1 < path.length) { String nextToken = path[index+1]; // First attempt an exact match if (branches.containsKey(nextToken)) { Route route = branches.get(nextToken).lookupByPath(path, index+1, path_params); if (route != null) return route; } // Then match against a wildcard if (branches.containsKey("*")) { path_params.add(path[index+1]); Route route = branches.get("*").lookupByPath(path, index + 1, path_params); if (route != null) return route; path_params.remove(path_params.size() - 1); } // If we are at the deepest level of the tree and no match was found, attempt to look for alternative versions. // For example, if the user requests /4/About, and we only have /3/About, then we should deliver that version // instead. if (index == path.length - 2) { int v = Integer.parseInt(nextToken); for (String key : branches.keySet()) { if (branches.get(key).leaf == null) continue; if (Integer.parseInt(key) <= v) { // We also create a new branch in the tree to memorize this new route path. RouteTree newBranch = new RouteTree(nextToken); newBranch.leaf = branches.get(key).leaf; branches.put(nextToken, newBranch); return newBranch.leaf; } } } } else { return leaf; } return null; } private static boolean isWildcardToken(String token) { return token.equals("*") || token.startsWith("{") && token.endsWith("}"); } } private static Route findRouteByApiName(String apiName) { for (Route route : routesList) { if (route._api_name.equals(apiName)) return route; } return null; } /** * Handle any URLs that bypass the standard route approach. This is stuff that has abnormal non-JSON response * payloads. * @param uri RequestUri object of the incoming request. * @return Response object, or null if the request does not require any special handling. */ private static NanoResponse maybeServeSpecial(RequestUri uri) { assert uri != null; if (uri.isHeadMethod()) { // Blank response used by R's uri.exists("/") if (uri.getUrl().equals("/")) return new NanoResponse(HTTP_OK, MIME_PLAINTEXT, ""); } if (uri.isGetMethod()) { // url "/3/Foo/bar" => path ["", "GET", "Foo", "bar", "3"] String[] path = uri.getPath(); if (path[2].equals("")) return redirectToFlow(); if (path[2].equals("Logs") && path[3].equals("download")) return downloadLogs(); if (path[2].equals("NodePersistentStorage.bin") && path.length == 6) return downloadNps(path[3], path[4]); } return null; } private static NanoResponse response404(String what, RequestType type) { H2ONotFoundArgumentException e = new H2ONotFoundArgumentException(what + " not found", what + " not found"); H2OError error = e.toH2OError(what); Log.warn(error._dev_msg); return serveError(error); } private static NanoResponse serveSchema(Schema s, RequestType type) { // Convert Schema to desired output flavor String http_response_header = H2OError.httpStatusHeader(HttpResponseStatus.OK.getCode()); // If we're given an http response code use it. if (s instanceof SpecifiesHttpResponseCode) { http_response_header = H2OError.httpStatusHeader(((SpecifiesHttpResponseCode) s).httpStatus()); } // If we've gotten an error always return the error as JSON if (s instanceof SpecifiesHttpResponseCode && HttpResponseStatus.OK.getCode() != ((SpecifiesHttpResponseCode) s).httpStatus()) { type = RequestType.json; } if (s instanceof H2OErrorV3) { return new NanoResponse(http_response_header, MIME_JSON, s.toJsonString()); } if (s instanceof StreamingSchema) { StreamingSchema ss = (StreamingSchema) s; NanoResponse r = new NanoStreamResponse(http_response_header, MIME_DEFAULT_BINARY, ss.getStreamWriter()); // Needed to make file name match class name r.addHeader("Content-Disposition", "attachment; filename=\"" + ss.getFilename() + "\""); return r; } // TODO: remove this entire switch switch (type) { case html: // return JSON for html requests case json: return new NanoResponse(http_response_header, MIME_JSON, s.toJsonString()); case xml: throw H2O.unimpl("Unknown type: " + type.toString()); case java: if (s instanceof AssemblyV99) { // TODO: fix the AssemblyV99 response handler so that it produces the appropriate StreamingSchema Assembly ass = DKV.getGet(((AssemblyV99) s).assembly_id); NanoResponse r = new NanoResponse(http_response_header, MIME_DEFAULT_BINARY, ass.toJava(((AssemblyV99) s).pojo_name)); r.addHeader("Content-Disposition", "attachment; filename=\""+JCodeGen.toJavaId(((AssemblyV99) s).pojo_name)+".java\""); return r; } else { throw new H2OIllegalArgumentException("Cannot generate java for type: " + s.getClass().getSimpleName()); } default: throw H2O.unimpl("Unknown type to serveSchema(): " + type); } } @SuppressWarnings(value = "unchecked") private static NanoResponse serveError(H2OError error) { // Note: don't use Schema.schema(version, error) because we have to work at bootstrap: return serveSchema(new H2OErrorV3().fillFromImpl(error), RequestType.json); } private static NanoResponse redirectToFlow() { NanoResponse res = new NanoResponse(HTTP_REDIRECT, MIME_PLAINTEXT, ""); res.addHeader("Location", "/flow/index.html"); return res; } private static NanoResponse downloadNps(String categoryName, String keyName) { NodePersistentStorage nps = H2O.getNPS(); AtomicLong length = new AtomicLong(); InputStream is = nps.get(categoryName, keyName, length); NanoResponse res = new NanoResponse(HTTP_OK, MIME_DEFAULT_BINARY, is); res.addHeader("Content-Length", Long.toString(length.get())); res.addHeader("Content-Disposition", "attachment; filename=" + keyName + ".flow"); return res; } private static NanoResponse downloadLogs() { Log.info("\nCollecting logs."); H2ONode[] members = H2O.CLOUD.members(); byte[][] perNodeZipByteArray = new byte[members.length][]; byte[] clientNodeByteArray = null; for (int i = 0; i < members.length; i++) { byte[] bytes; try { // Skip nodes that aren't healthy, since they are likely to cause the entire process to hang. boolean healthy = (System.currentTimeMillis() - members[i]._last_heard_from) < HeartBeatThread.TIMEOUT; if (healthy) { GetLogsFromNode g = new GetLogsFromNode(); g.nodeidx = i; g.doIt(); bytes = g.bytes; } else { bytes = "Node not healthy".getBytes(); } } catch (Exception e) { bytes = e.toString().getBytes(); } perNodeZipByteArray[i] = bytes; } if (H2O.ARGS.client) { byte[] bytes; try { GetLogsFromNode g = new GetLogsFromNode(); g.nodeidx = -1; g.doIt(); bytes = g.bytes; } catch (Exception e) { bytes = e.toString().getBytes(); } clientNodeByteArray = bytes; } String outputFileStem = getOutputLogStem(); byte[] finalZipByteArray; try { finalZipByteArray = zipLogs(perNodeZipByteArray, clientNodeByteArray, outputFileStem); } catch (Exception e) { finalZipByteArray = e.toString().getBytes(); } NanoResponse res = new NanoResponse(HTTP_OK, MIME_DEFAULT_BINARY, new ByteArrayInputStream(finalZipByteArray)); res.addHeader("Content-Length", Long.toString(finalZipByteArray.length)); res.addHeader("Content-Disposition", "attachment; filename=" + outputFileStem + ".zip"); return res; } private static String getOutputLogStem() { String pattern = "yyyyMMdd_hhmmss"; SimpleDateFormat formatter = new SimpleDateFormat(pattern); String now = formatter.format(new Date()); return "h2ologs_" + now; } private static byte[] zipLogs(byte[][] results, byte[] clientResult, String topDir) throws IOException { int l = 0; assert H2O.CLOUD._memary.length == results.length : "Unexpected change in the cloud!"; for (byte[] result : results) l += result.length; ByteArrayOutputStream baos = new ByteArrayOutputStream(l); // Add top-level directory. ZipOutputStream zos = new ZipOutputStream(baos); { ZipEntry zde = new ZipEntry (topDir + File.separator); zos.putNextEntry(zde); } try { // Add zip directory from each cloud member. for (int i =0; i<results.length; i++) { String filename = topDir + File.separator + "node" + i + "_" + H2O.CLOUD._memary[i].getIpPortString().replace(':', '_').replace('/', '_') + ".zip"; ZipEntry ze = new ZipEntry(filename); zos.putNextEntry(ze); zos.write(results[i]); zos.closeEntry(); } // Add zip directory from the client node. Name it 'driver' since that's what Sparking Water users see. if (clientResult != null) { String filename = topDir + File.separator + "driver.zip"; ZipEntry ze = new ZipEntry(filename); zos.putNextEntry(ze); zos.write(clientResult); zos.closeEntry(); } // Close the top-level directory. zos.closeEntry(); } finally { // Close the full zip file. zos.close(); } return baos.toByteArray(); } // cache of all loaded resources @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") // remove this once TO-DO below is addressed private static final NonBlockingHashMap<String,byte[]> _cache = new NonBlockingHashMap<>(); // Returns the response containing the given uri with the appropriate mime type. private static NanoResponse getResource(RequestType request_type, String url) { byte[] bytes = _cache.get(url); if (bytes == null) { // Try-with-resource try (InputStream resource = water.init.JarHash.getResource2(url)) { if( resource != null ) { try { bytes = toByteArray(resource); } catch (IOException e) { Log.err(e); } // PP 06-06-2014 Disable caching for now so that the browser // always gets the latest sources and assets when h2o-client is rebuilt. // TODO need to rethink caching behavior when h2o-dev is merged into h2o. // if (bytes != null) { // byte[] res = _cache.putIfAbsent(url, bytes); // if (res != null) bytes = res; // Racey update; take what is in the _cache } } catch( IOException ignore ) { } } if (bytes == null || bytes.length == 0) // No resource found? return response404("Resource " + url, request_type); int i = url.lastIndexOf('.'); String mime; switch (url.substring(i + 1)) { case "js": mime = MIME_JS; break; case "css": mime = MIME_CSS; break; case "htm":case "html": mime = MIME_HTML; break; case "jpg":case "jpeg": mime = MIME_JPEG; break; case "png": mime = MIME_PNG; break; case "svg": mime = MIME_SVG; break; case "gif": mime = MIME_GIF; break; case "woff": mime = MIME_WOFF; break; default: mime = MIME_DEFAULT_BINARY; } NanoResponse res = new NanoResponse(HTTP_OK, mime, new ByteArrayInputStream(bytes)); res.addHeader("Content-Length", Long.toString(bytes.length)); return res; } // Convenience utility private static byte[] toByteArray(InputStream is) throws IOException { try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { byte[] buffer = new byte[0x2000]; for (int len; (len = is.read(buffer)) != -1; ) os.write(buffer, 0, len); return os.toByteArray(); } } }
import com.example.lambda.*; import software.amazon.awssdk.services.lambda.LambdaClient; import org.junit.jupiter.api.*; import software.amazon.awssdk.regions.Region; import java.io.*; import java.net.URISyntaxException; import java.util.*; import static org.junit.jupiter.api.Assertions.*; @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class LambdaTest { private static LambdaClient awsLambda; private static String functionName=""; private static String completeFunctionName=""; private static String filePath=""; private static String role=""; private static String handler=""; @BeforeAll public static void setUp() throws IOException, URISyntaxException { Region region = Region.US_EAST_1; awsLambda = LambdaClient.builder() .region(region) .build(); try (InputStream input = LambdaTest.class.getClassLoader().getResourceAsStream("config.properties")) { Properties prop = new Properties(); if (input == null) { System.out.println("Sorry, unable to find config.properties"); return; } //load a properties file from class path, inside static method prop.load(input); // Populate the data members required for all tests functionName = prop.getProperty("functionName"); completeFunctionName = prop.getProperty("completeFunctionName"); filePath = prop.getProperty("filePath"); role = prop.getProperty("role"); handler = prop.getProperty("handler"); completeFunctionName = prop.getProperty("completeFunctionName"); } catch (IOException ex) { ex.printStackTrace(); } } @Test @Order(1) public void whenInitializingAWSService_thenNotNull() { assertNotNull(awsLambda); System.out.println("Test 1 passed"); } @Test @Order(2) public void CreateFunction() { CreateFunction.createLambdaFunction(awsLambda, functionName, filePath, role, handler); System.out.println("Test 2 passed"); } @Test @Order(3) public void GetAccountSettings() { GetAccountSettings.getSettings(awsLambda); System.out.println("Test 3 passed"); } @Test @Order(4) public void ListLambdaFunctions() { ListLambdaFunctions.listFunctions(awsLambda); System.out.println("Test 4 passed"); } @Test @Order(5) public void LambdaInvoke() { LambdaInvoke.invokeFunction(awsLambda, completeFunctionName); System.out.println("Test 5 passed"); } @Test @Order(6) public void DeleteFunction() { DeleteFunction.deleteLambdaFunction(awsLambda, functionName); System.out.println("Test 5 passed"); } }
package de.skuzzle.jeve; import java.util.function.BiConsumer; import java.util.function.Supplier; import de.skuzzle.jeve.builder.ConfiguratorImpl; import de.skuzzle.jeve.builder.EventProviderConfigurator; import de.skuzzle.jeve.stores.DefaultListenerStore; import de.skuzzle.jeve.stores.PriorityListenerStore; public interface EventProvider<S extends ListenerStore> extends AutoCloseable { /** * Provides a fluent builder API to construct several kinds of * EventProviders. This replaces the static factory methods used in previous * versions of jeve. * * <p> * Configuring an EventProvider always starts with choosing an appropriate * {@link ListenerStore}. In most cases, the default store is sufficient, * but you could also use a store which provides listener prioritization * like in: * </p> * * <pre> * <code> * EventProvider&lt;PriorityListenerStore&gt; eventProvider = EventProvider.configure() * .store(PriorityListenerStore::new) * .useSynchronousEventProvider() * .create(); * </code> * </pre> * * <p> * After configuring the ListenerStore, several other attributes can be set. * E.g. the {@link ExceptionCallback} to use or, on some threaded * EventProviders, the ExecutorService to use. When configuring multiple * attributes, methods can be chained using <code>and()</code> as shown in * the example below. After your configuration is final, you can either * directly obtain an EventProvider instance using <code>create()</code> or * a {@link Supplier} using <code>asSupplier()</code> which can be used to * recreate the configuration at any time. * </p> * * <pre> * <code> * Supplier&lt;EventProvider&lt;?&gt;&gt; eventProvider = EventProvider.configure() * .defaultStore() * .useSynchronousEventProvider().and() * .exceptionCallBack(myCallback) * .asSupplier(); * </code> * </pre> * * @return A configurator instance to build an EventProvider. * @since 2.0.0 */ public static EventProviderConfigurator configure() { return new ConfiguratorImpl(); } /** * Convenience method for creating a synchronous event provider which uses a * default listener store. * * @return A ready to use event provider. * @see #configure() * @since 2.0.0 */ public static EventProvider<DefaultListenerStore> createDefault() { return configure().defaultStore().useSynchronousProvider().create(); } /** * The default {@link ExceptionCallback} which prints some information about * the occurred error to the standard output. The exact format is not * specified. * * @deprecated Since 2.0.1 - The default call back is now an internal * property of the specific provider implementation. */ @Deprecated public static final ExceptionCallback DEFAULT_HANDLER = (e, l, ev) -> { System.err.printf( "Listener threw an exception while being notified%n" + "Details%n" + " Listener: %s%n" + " Event: %s%n" + " Message: %s%n" + " Current Thread: %s%n" + " Stacktrace:%n", l, ev, e.getMessage(), Thread.currentThread().getName()); e.printStackTrace(); }; /** * Retrieves the {@link ListenerStore} which supplies {@link Listener * Listeners} to this EventProvider. * * @return The listener store. */ public S listeners(); public <L extends Listener, E extends Event<?, L>> void dispatch( E event, BiConsumer<L, E> bc); public <L extends Listener, E extends Event<?, L>> void dispatch( E event, BiConsumer<L, E> bc, ExceptionCallback ec); public <L extends Listener, E extends Event<?, L>> void dispatch( E event); public default <L extends Listener, E extends Event<?, L>> void dispatch( E event, ExceptionCallback ec) { if (event == null) { throw new IllegalArgumentException("event is null"); } else if (ec == null) { throw new IllegalArgumentException("ec is null"); } event.defaultDispatch(this, ec); } @Deprecated public default <L extends Listener, E extends DefaultTargetEvent<?, E, L>> void dispatch( E event) { if (event == null) { throw new IllegalArgumentException("event is null"); } dispatch(event, event.getTarget()); } @Deprecated public default <L extends Listener, E extends DefaultTargetEvent<?, E, L>> void dispatch( E event, ExceptionCallback ec) { if (event == null) { throw new IllegalArgumentException("event is null"); } else if (ec == null) { throw new IllegalArgumentException("ec is null"); } dispatch(event, event.getTarget(), ec); } /** * Gets whether this EventProvider is ready for dispatching. * * @return Whether further events can be dispatched using * {@link #dispatch(Event, BiConsumer, ExceptionCallback) dispatch} */ public boolean canDispatch(); /** * Sets the default {@link ExceptionCallback} which will be notified about * exceptions when dispatching events without explicitly specifying an * ExceptionCallback. The ExceptionCallback which is installed by default * simply prints the stack traces to the error console. * * <p> * You can reset the ExceptionCallback to the default handler by providing * <code>null</code> as parameter. * </p> * * @param ec The ExceptionCallback for handling event handler exceptions, or * <code>null</code> to use the default behavior. */ public void setExceptionCallback(ExceptionCallback ec); /** * Returns whether this EventProvider is sequential, which means it strictly * notifies listeners in the order in which they were registered for a * certain event. * * <p> * <b>Note:</b> Implementors must obey the result of the * {@link ListenerStore#isSequential() isSequential} property of the * currently used ListenerStore. If the store is not sequential, this * provider won't be either. * </p> * * @return Whether this instance is sequential. */ public boolean isSequential(); /** * Closes this EventProvider and its {@link ListenerStore} (thus, removes * all registered Listeners from the store). Depending on the actual * implementation, the EventProvider might not be able to dispatch further * events after closing. On some implementations closing might have no * additional effect. */ @Override public void close(); }
package de.jpaw.enums; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** Factory class which returns an XEnum instance for a given token or name. * It is not a factory in the classic sense that a new object is created, rather the unique instance for that token is returned. * There is one instance of this class per XEnum class. */ public class XEnumFactory<E extends AbstractXEnumBase<E>> { private final int maxTokenLength; private final String pqon; // partially qualified class name of the base private final Class<E> baseClass; private final Map<String,E> tokenToXEnum = new ConcurrentHashMap<String,E>(); private final Map<String,E> nameToXEnum = new ConcurrentHashMap<String,E>(); private final Map<Enum<?>,E> baseEnumToXEnum = new ConcurrentHashMap<Enum<?>,E>(); private static final Map<String, XEnumFactory<?>> registry = new ConcurrentHashMap<String, XEnumFactory<?>>(200); private static final Map<Class<? extends AbstractXEnumBase<?>>, XEnumFactory<?>> classRegistry = new ConcurrentHashMap<Class<? extends AbstractXEnumBase<?>>, XEnumFactory<?>>(200); // private final List<Class<? extends E>> listOfSubclasses = new ArrayList<E>(10); // remembers all XEnum classes which use this factory private E nullToken = null; // stores an instance which has the empty token // TODO: should only be invoked from XEnum classes. How to verify this? (C++ "friend" needed here...) public XEnumFactory(int maxTokenLength, Class<E> baseClass, String pqon) { this.maxTokenLength = maxTokenLength; this.pqon = pqon; this.baseClass = baseClass; // "this" is not yet fully constructed... // if (registry.put(pqon, this) != null) { // throw something; // we do it later instead... } public static final XEnumFactory<?> getFactoryByPQON(String pqon) { return registry.get(pqon); } public static final XEnumFactory<?> getFactoryByClass(Class<? extends AbstractXEnumBase<?>> xenumClass) { XEnumFactory<?> result = classRegistry.get(xenumClass); if (result == null) throw new IllegalArgumentException("No XEnumFactory registered for class " + xenumClass.getCanonicalName()); return result; } public void publishInstance(E e) { if (tokenToXEnum.put(e.getToken(), e) != null) throw new IllegalArgumentException(e.getClass().getSimpleName() + ": duplicate token " + e.getToken() + " for base XEnum " + pqon); if (nameToXEnum.put(e.name(), e) != null) throw new IllegalArgumentException(e.getClass().getSimpleName() + ": duplicate name " + e.name() + " for base XEnum " + pqon); baseEnumToXEnum.put(e.getBaseEnum(), e); // possibly store it as the null token if (e.getToken().length() == 0) nullToken = e; } public void register(String thisPqon, Class<? extends AbstractXEnumBase<E>> xenumClass) { registry.put(thisPqon, this); classRegistry.put(xenumClass, this); } public Class<E> getBaseClass() { return baseClass; } public E getByToken(String token) { return tokenToXEnum.get(token); } public E getByName(String name) { return nameToXEnum.get(name); } public E getByEnum(Enum<?> enumVal) { return baseEnumToXEnum.get(enumVal); } // return an instance which has the token "", or null if no such exists public E getNullToken() { return nullToken; } public int getMaxTokenLength() { return maxTokenLength; } public String getPqon() { return pqon; } public E getByTokenWithNull(String token) { return token == null ? nullToken : tokenToXEnum.get(token); } // same as getByEnum, but throw an exception if the instance isn't known public E of(Enum<?> enumVal) { if (enumVal == null) return null; E myEnum = baseEnumToXEnum.get(enumVal); if (myEnum == null) throw new IllegalArgumentException(enumVal.getClass().getSimpleName() + "." + enumVal.name() + " is not a valid instance for " + baseClass.getSimpleName()); return myEnum; } // array conversion public E [] of(Enum<?> [] arrayOfEnums) { if (arrayOfEnums == null) return null; // the following line does not compile. Why not? B the bound, the lower object type should be known! //E [] result = new E [arrayOfEnums.length]; // the following line does compile, but has a warning of course @SuppressWarnings("unchecked") E [] result = (E[]) new AbstractXEnumBase [arrayOfEnums.length]; for (int i = 0; i < arrayOfEnums.length; ++i) result[i] = of(arrayOfEnums[i]); return result; } public List<E> of(List<Enum<?>> listOfEnums) { if (listOfEnums == null) return null; List<E> result = new ArrayList<E>(listOfEnums.size()); for (Enum<?> i : listOfEnums) result.add(of(i)); return result; } public Set<E> of(Set<Enum<?>> setOfEnums) { if (setOfEnums == null) return null; Set<E> result = new HashSet<E>(setOfEnums.size()); for (Enum<?> i : setOfEnums) result.add(of(i)); return result; } /** Returns the number of different instances for this xenum. */ public int size() { return tokenToXEnum.size(); } /** Returns a copy of the list of values. */ public List<E> valuesAsList() { return Collections.unmodifiableList(new ArrayList<E>(tokenToXEnum.values())); // cast should not be required... } }
package gorden.album.adapter; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import java.util.List; import gorden.album.R; import gorden.album.entity.PictureDirectory; import gorden.album.fragment.AlbumPickerFragment; import gorden.album.item.ItemDir; import gorden.album.loader.ImageLoader; import static gorden.album.AlbumPicker.EXTRA_IMAGE_LOADER; public class DirAdapter extends RecyclerView.Adapter<DirAdapter.DirHolder> { private AlbumPickerFragment mContext; private List<PictureDirectory> directoryList; private ImageLoader imageLoader; private int lastSelected = 0; public DirAdapter(AlbumPickerFragment mContext, List<PictureDirectory> directoryList) { this.mContext = mContext; this.directoryList = directoryList; imageLoader = (ImageLoader) mContext.getArguments().getSerializable(EXTRA_IMAGE_LOADER); } @Override public DirHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = new ItemDir(mContext.getContext()); itemView.setLayoutParams(new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); return new DirHolder(itemView); } @Override public void onBindViewHolder(DirHolder holder, int position) { holder.viewSelected.setVisibility(lastSelected == position ? View.VISIBLE : View.GONE); PictureDirectory directory = directoryList.get(position); holder.textDir.setText(directory.dirName); holder.textCount.setText(directory.pictures.size() + ""); if (imageLoader != null) { imageLoader.displayImage(mContext.getActivity(), holder.imgDir, directory.coverPicture.path, directory.coverPicture.width, directory.coverPicture.height); } else { Glide.with(mContext).load(directory.coverPicture.path).asBitmap().centerCrop().into(holder.imgDir); } } @Override public int getItemCount() { return directoryList.size(); } protected class DirHolder extends RecyclerView.ViewHolder { ImageView imgDir, viewSelected; TextView textDir; TextView textCount; public DirHolder(View itemView) { super(itemView); imgDir = ((ItemDir) itemView).imgDir; viewSelected = ((ItemDir) itemView).viewSelected; textDir = ((ItemDir) itemView).textDir; textCount = ((ItemDir) itemView).textCount; itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mContext.toggleDir(); if (lastSelected != getLayoutPosition()) { int tempPosition = lastSelected; lastSelected = getLayoutPosition(); notifyItemChanged(tempPosition); notifyItemChanged(lastSelected); mContext.onPictureDirectorySelected(directoryList.get(lastSelected), lastSelected == 0); } } }); } } }
package info.limpet.data; import org.junit.runner.RunWith; import org.junit.runners.Suite; import info.limpet.data.export.csv.TestExport; import info.limpet.rcp.TestReflectivePropertySource; import junit.framework.TestSuite; @Suite.SuiteClasses( { TestCollections.class, TestOperations.class, TestAnalysis.class, TestDynamic.class, TestGeotoolsGeometry.class, TestPersistence.class, TestCsvParser.class, TestExport.class, TestReflectivePropertySource.class }) @RunWith(Suite.class) public class AllTests extends TestSuite { }
package net.runelite.client.game; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import java.util.Collection; import javax.annotation.Nullable; import lombok.Getter; import static net.runelite.api.ItemID.*; /** * Converts untradeable items to it's tradeable counterparts */ @Getter public enum ItemMapping { // Barrows equipment ITEM_AHRIMS_HOOD(AHRIMS_HOOD, AHRIMS_HOOD_25, AHRIMS_HOOD_50, AHRIMS_HOOD_75, AHRIMS_HOOD_100), ITEM_AHRIMS_ROBETOP(AHRIMS_ROBETOP, AHRIMS_ROBETOP_25, AHRIMS_ROBETOP_50, AHRIMS_ROBETOP_75, AHRIMS_ROBETOP_100), ITEM_AHRIMS_ROBEBOTTOM(AHRIMS_ROBESKIRT, AHRIMS_ROBESKIRT_25, AHRIMS_ROBESKIRT_50, AHRIMS_ROBESKIRT_75, AHRIMS_ROBESKIRT_100), ITEM_AHRIMS_STAFF(AHRIMS_STAFF, AHRIMS_STAFF_25, AHRIMS_STAFF_50, AHRIMS_STAFF_75, AHRIMS_STAFF_100), ITEM_KARILS_COIF(KARILS_COIF, KARILS_COIF_25, KARILS_COIF_50, KARILS_COIF_75, KARILS_COIF_100), ITEM_KARILS_LEATHERTOP(KARILS_LEATHERTOP, KARILS_LEATHERTOP_25, KARILS_LEATHERTOP_50, KARILS_LEATHERTOP_75, KARILS_LEATHERTOP_100), ITEM_KARILS_LEATHERSKIRT(KARILS_LEATHERSKIRT, KARILS_LEATHERSKIRT_25, KARILS_LEATHERSKIRT_50, KARILS_LEATHERSKIRT_75, KARILS_LEATHERSKIRT_100), ITEM_KARILS_CROSSBOW(KARILS_CROSSBOW, KARILS_CROSSBOW_25, KARILS_CROSSBOW_50, KARILS_CROSSBOW_75, KARILS_CROSSBOW_100), ITEM_DHAROKS_HELM(DHAROKS_HELM, DHAROKS_HELM_25, DHAROKS_HELM_50, DHAROKS_HELM_75, DHAROKS_HELM_100), ITEM_DHAROKS_PLATEBODY(DHAROKS_PLATEBODY, DHAROKS_PLATEBODY_25, DHAROKS_PLATEBODY_50, DHAROKS_PLATEBODY_75, DHAROKS_PLATEBODY_100), ITEM_DHAROKS_PLATELEGS(DHAROKS_PLATELEGS, DHAROKS_PLATELEGS_25, DHAROKS_PLATELEGS_50, DHAROKS_PLATELEGS_75, DHAROKS_PLATELEGS_100), ITEM_DHARKS_GREATEAXE(DHAROKS_GREATAXE, DHAROKS_GREATAXE_25, DHAROKS_GREATAXE_50, DHAROKS_GREATAXE_75, DHAROKS_GREATAXE_100), ITEM_GUTHANS_HELM(GUTHANS_HELM, GUTHANS_HELM_25, GUTHANS_HELM_50, GUTHANS_HELM_75, GUTHANS_HELM_100), ITEM_GUTHANS_PLATEBODY(GUTHANS_PLATEBODY, GUTHANS_PLATEBODY_25, GUTHANS_PLATEBODY_50, GUTHANS_PLATEBODY_75, GUTHANS_PLATEBODY_100), ITEM_GUTHANS_CHAINSKIRT(GUTHANS_CHAINSKIRT, GUTHANS_CHAINSKIRT_25, GUTHANS_CHAINSKIRT_50, GUTHANS_CHAINSKIRT_75, GUTHANS_CHAINSKIRT_100), ITEM_GUTHANS_WARSPEAR(GUTHANS_WARSPEAR, GUTHANS_WARSPEAR_25, GUTHANS_WARSPEAR_50, GUTHANS_WARSPEAR_75, GUTHANS_WARSPEAR_100), ITEM_TORAGS_HELM(TORAGS_HELM, TORAGS_HELM_25, TORAGS_HELM_50, TORAGS_HELM_75, TORAGS_HELM_100), ITEM_TORAGS_PLATEBODY(TORAGS_PLATEBODY, TORAGS_PLATEBODY_25, TORAGS_PLATEBODY_50, TORAGS_PLATEBODY_75, TORAGS_PLATEBODY_100), ITEM_TORAGS_PLATELEGS(TORAGS_PLATELEGS, TORAGS_PLATELEGS_25, TORAGS_PLATELEGS_50, TORAGS_PLATELEGS_75, TORAGS_PLATELEGS_100), ITEM_TORAGS_HAMMERS(TORAGS_HAMMERS, TORAGS_HAMMERS_25, TORAGS_HAMMERS_50, TORAGS_HAMMERS_75, TORAGS_HAMMERS_100), ITEM_VERACS_HELM(VERACS_HELM, VERACS_HELM_25, VERACS_HELM_50, VERACS_HELM_75, VERACS_HELM_100), ITEM_VERACS_BRASSARD(VERACS_BRASSARD, VERACS_BRASSARD_25, VERACS_BRASSARD_50, VERACS_BRASSARD_75, VERACS_BRASSARD_100), ITEM_VERACS_PLATESKIRT(VERACS_PLATESKIRT, VERACS_PLATESKIRT_25, VERACS_PLATESKIRT_50, VERACS_PLATESKIRT_75, VERACS_PLATESKIRT_100), ITEM_VERACS_FLAIL(VERACS_FLAIL, VERACS_FLAIL_25, VERACS_FLAIL_50, VERACS_FLAIL_75, VERACS_FLAIL_100), // Dragon equipment ornament kits ITEM_DRAGON_SCIMITAR(DRAGON_SCIMITAR, DRAGON_SCIMITAR_OR), ITEM_DRAGON_SCIMITAR_ORNAMENT_KIT(DRAGON_SCIMITAR_ORNAMENT_KIT, DRAGON_SCIMITAR_OR), ITEM_DRAGON_DEFENDER(DRAGON_DEFENDER_ORNAMENT_KIT, DRAGON_DEFENDER_T), ITEM_DRAGON_PICKAXE(DRAGON_PICKAXE, DRAGON_PICKAXE_12797, DRAGON_PICKAXE_OR, DRAGON_PICKAXE_OR_25376), ITEM_DRAGON_PICKAXE_OR(ZALCANO_SHARD, DRAGON_PICKAXE_OR), ITEM_DRAGON_AXE(DRAGON_AXE, DRAGON_AXE_OR), ITEM_DRAGON_HARPOON(DRAGON_HARPOON, DRAGON_HARPOON_OR), ITEM_INFERNAL_PICKAXE_OR(INFERNAL_PICKAXE, INFERNAL_PICKAXE_OR), ITEM_INFERNAL_PICKAXE_OR_UNCHARGED(INFERNAL_PICKAXE_UNCHARGED, INFERNAL_PICKAXE_UNCHARGED_25369), ITEM_INFERNAL_AXE_OR(INFERNAL_AXE, INFERNAL_AXE_OR), ITEM_INFERNAL_AXE_OR_UNCHARGED(INFERNAL_AXE_UNCHARGED, INFERNAL_AXE_UNCHARGED_25371), ITEM_INFERNAL_HARPOON_OR(INFERNAL_HARPOON, INFERNAL_HARPOON_OR), ITEM_INFERNAL_HARPOON_OR_UNCHARGED(INFERNAL_HARPOON_UNCHARGED, INFERNAL_HARPOON_UNCHARGED_25367), ITEM_TRAILBLAZER_TOOL_ORNAMENT_KIT(TRAILBLAZER_TOOL_ORNAMENT_KIT, DRAGON_PICKAXE_OR_25376, DRAGON_AXE_OR, DRAGON_HARPOON_OR, INFERNAL_PICKAXE_OR, INFERNAL_AXE_OR, INFERNAL_HARPOON_OR, INFERNAL_PICKAXE_UNCHARGED_25369, INFERNAL_AXE_UNCHARGED_25371, INFERNAL_HARPOON_UNCHARGED_25367), ITEM_DRAGON_KITESHIELD(DRAGON_KITESHIELD, DRAGON_KITESHIELD_G), ITEM_DRAGON_KITESHIELD_ORNAMENT_KIT(DRAGON_KITESHIELD_ORNAMENT_KIT, DRAGON_KITESHIELD_G), ITEM_DRAGON_FULL_HELM(DRAGON_FULL_HELM, DRAGON_FULL_HELM_G), ITEM_DRAGON_FULL_HELM_ORNAMENT_KIT(DRAGON_FULL_HELM_ORNAMENT_KIT, DRAGON_FULL_HELM_G), ITEM_DRAGON_CHAINBODY(DRAGON_CHAINBODY_3140, DRAGON_CHAINBODY_G), ITEM_DRAGON_CHAINBODY_ORNAMENT_KIT(DRAGON_CHAINBODY_ORNAMENT_KIT, DRAGON_CHAINBODY_G), ITEM_DRAGON_PLATEBODY(DRAGON_PLATEBODY, DRAGON_PLATEBODY_G), ITEM_DRAGON_PLATEBODY_ORNAMENT_KIT(DRAGON_PLATEBODY_ORNAMENT_KIT, DRAGON_PLATEBODY_G), ITEM_DRAGON_PLATESKIRT(DRAGON_PLATESKIRT, DRAGON_PLATESKIRT_G), ITEM_DRAGON_SKIRT_ORNAMENT_KIT(DRAGON_LEGSSKIRT_ORNAMENT_KIT, DRAGON_PLATESKIRT_G), ITEM_DRAGON_PLATELEGS(DRAGON_PLATELEGS, DRAGON_PLATELEGS_G), ITEM_DRAGON_LEGS_ORNAMENT_KIT(DRAGON_LEGSSKIRT_ORNAMENT_KIT, DRAGON_PLATELEGS_G), ITEM_DRAGON_SQ_SHIELD(DRAGON_SQ_SHIELD, DRAGON_SQ_SHIELD_G), ITEM_DRAGON_SQ_SHIELD_ORNAMENT_KIT(DRAGON_SQ_SHIELD_ORNAMENT_KIT, DRAGON_SQ_SHIELD_G), ITEM_DRAGON_BOOTS(DRAGON_BOOTS, DRAGON_BOOTS_G), ITEM_DRAGON_BOOTS_ORNAMENT_KIT(DRAGON_BOOTS_ORNAMENT_KIT, DRAGON_BOOTS_G), // Rune ornament kits ITEM_RUNE_SCIMITAR_GUTHIX(RUNE_SCIMITAR, RUNE_SCIMITAR_23330), ITEM_RUNE_SCIMITAR_ORNAMENT_KIT_GUTHIX(RUNE_SCIMITAR_ORNAMENT_KIT_GUTHIX, RUNE_SCIMITAR_23330), ITEM_RUNE_SCIMITAR_SARADOMIN(RUNE_SCIMITAR, RUNE_SCIMITAR_23332), ITEM_RUNE_SCIMITAR_ORNAMENT_KIT_SARADOMIN(RUNE_SCIMITAR_ORNAMENT_KIT_SARADOMIN, RUNE_SCIMITAR_23332), ITEM_RUNE_SCIMITAR_ZAMORAK(RUNE_SCIMITAR, RUNE_SCIMITAR_23334), ITEM_RUNE_SCIMITAR_ORNAMENT_KIT_ZAMORAK(RUNE_SCIMITAR_ORNAMENT_KIT_ZAMORAK, RUNE_SCIMITAR_23334), ITEM_RUNE_DEFENDER(RUNE_DEFENDER, RUNE_DEFENDER_T), ITEM_RUNE_DEFENDER_ORNAMENT_KIT(RUNE_DEFENDER_ORNAMENT_KIT, RUNE_DEFENDER_T), ITEM_RUNE_CROSSBOW(RUNE_CROSSBOW, RUNE_CROSSBOW_OR), // Godsword ornament kits ITEM_ARMADYL_GODSWORD(ARMADYL_GODSWORD, ARMADYL_GODSWORD_OR), ITEM_ARMADYL_GODSWORD_ORNAMENT_KIT(ARMADYL_GODSWORD_ORNAMENT_KIT, ARMADYL_GODSWORD_OR), ITEM_BANDOS_GODSWORD(BANDOS_GODSWORD, BANDOS_GODSWORD_OR), ITEM_BANDOS_GODSWORD_ORNAMENT_KIT(BANDOS_GODSWORD_ORNAMENT_KIT, BANDOS_GODSWORD_OR), ITEM_ZAMORAK_GODSWORD(ZAMORAK_GODSWORD, ZAMORAK_GODSWORD_OR), ITEM_ZAMORAK_GODSWORD_ORNAMENT_KIT(ZAMORAK_GODSWORD_ORNAMENT_KIT, ZAMORAK_GODSWORD_OR), ITEM_SARADOMIN_GODSWORD(SARADOMIN_GODSWORD, SARADOMIN_GODSWORD_OR), ITEM_SARADOMIN_GODSWORD_ORNAMENT_KIT(SARADOMIN_GODSWORD_ORNAMENT_KIT, SARADOMIN_GODSWORD_OR), // Jewellery ornament kits ITEM_AMULET_OF_TORTURE(AMULET_OF_TORTURE, AMULET_OF_TORTURE_OR), ITEM_TORTURE_ORNAMENT_KIT(TORTURE_ORNAMENT_KIT, AMULET_OF_TORTURE_OR), ITEM_NECKLACE_OF_ANGUISH(NECKLACE_OF_ANGUISH, NECKLACE_OF_ANGUISH_OR), ITEM_ANGUISH_ORNAMENT_KIT(ANGUISH_ORNAMENT_KIT, NECKLACE_OF_ANGUISH_OR), ITEM_OCCULT_NECKLACE(OCCULT_NECKLACE, OCCULT_NECKLACE_OR), ITEM_OCCULT_ORNAMENT_KIT(OCCULT_ORNAMENT_KIT, OCCULT_NECKLACE_OR), ITEM_AMULET_OF_FURY(AMULET_OF_FURY, AMULET_OF_FURY_OR, AMULET_OF_BLOOD_FURY), ITEM_FURY_ORNAMENT_KIT(FURY_ORNAMENT_KIT, AMULET_OF_FURY_OR), ITEM_TORMENTED_BRACELET(TORMENTED_BRACELET, TORMENTED_BRACELET_OR), ITEM_TORMENTED_ORNAMENT_KIT(TORMENTED_ORNAMENT_KIT, TORMENTED_BRACELET_OR), ITEM_BERSERKER_NECKLACE(BERSERKER_NECKLACE, BERSERKER_NECKLACE_OR), ITEM_BERSERKER_NECKLACE_ORNAMENT_KIT(BERSERKER_NECKLACE_ORNAMENT_KIT, BERSERKER_NECKLACE_OR), // Other ornament kits ITEM_SHATTERED_RELICS_VARIETY_ORNAMENT_KIT(SHATTERED_RELICS_VARIETY_ORNAMENT_KIT, RUNE_CROSSBOW_OR, ABYSSAL_TENTACLE_OR, ABYSSAL_WHIP_OR, BOOK_OF_BALANCE_OR, BOOK_OF_DARKNESS_OR, BOOK_OF_LAW_OR, BOOK_OF_WAR_OR, HOLY_BOOK_OR, UNHOLY_BOOK_OR), ITEM_SHATTERED_RELICS_VOID_ORNAMENT_KIT(SHATTERED_RELICS_VOID_ORNAMENT_KIT, ELITE_VOID_TOP_OR, ELITE_VOID_ROBE_OR, VOID_KNIGHT_TOP_OR, VOID_KNIGHT_ROBE_OR, VOID_KNIGHT_GLOVES_OR, VOID_MAGE_HELM_OR, VOID_MELEE_HELM_OR, VOID_RANGER_HELM_OR), ITEM_MYSTIC_BOOTS(MYSTIC_BOOTS, MYSTIC_BOOTS_OR), ITEM_MYSTIC_GLOVES(MYSTIC_GLOVES, MYSTIC_GLOVES_OR), ITEM_MYSTIC_HAT(MYSTIC_HAT, MYSTIC_HAT_OR), ITEM_MYSTIC_ROBE_BOTTOM(MYSTIC_ROBE_BOTTOM, MYSTIC_ROBE_BOTTOM_OR), ITEM_MYSTIC_ROBE_TOP(MYSTIC_ROBE_TOP, MYSTIC_ROBE_TOP_OR), ITEM_SHATTERED_RELICS_MYSTIC_ORNAMENT_KIT(SHATTERED_RELICS_MYSTIC_ORNAMENT_KIT, MYSTIC_BOOTS_OR, MYSTIC_GLOVES_OR, MYSTIC_HAT_OR, MYSTIC_ROBE_BOTTOM_OR, MYSTIC_ROBE_TOP_OR), ITEM_CANNON_BARRELS(CANNON_BARRELS, CANNON_BARRELS_OR), ITEM_CANNON_BASE(CANNON_BASE, CANNON_BASE_OR), ITEM_CANNON_FURNACE(CANNON_FURNACE, CANNON_FURNACE_OR), ITEM_CANNON_STAND(CANNON_STAND, CANNON_STAND_OR), ITEM_SHATTERED_CANNON_ORNAMENT_KIT(SHATTERED_CANNON_ORNAMENT_KIT, CANNON_BARRELS_OR, CANNON_BASE_OR, CANNON_FURNACE_OR, CANNON_STAND_OR), // Ensouled heads ITEM_ENSOULED_GOBLIN_HEAD(ENSOULED_GOBLIN_HEAD_13448, ENSOULED_GOBLIN_HEAD), ITEM_ENSOULED_MONKEY_HEAD(ENSOULED_MONKEY_HEAD_13451, ENSOULED_MONKEY_HEAD), ITEM_ENSOULED_IMP_HEAD(ENSOULED_IMP_HEAD_13454, ENSOULED_IMP_HEAD), ITEM_ENSOULED_MINOTAUR_HEAD(ENSOULED_MINOTAUR_HEAD_13457, ENSOULED_MINOTAUR_HEAD), ITEM_ENSOULED_SCORPION_HEAD(ENSOULED_SCORPION_HEAD_13460, ENSOULED_SCORPION_HEAD), ITEM_ENSOULED_BEAR_HEAD(ENSOULED_BEAR_HEAD_13463, ENSOULED_BEAR_HEAD), ITEM_ENSOULED_UNICORN_HEAD(ENSOULED_UNICORN_HEAD_13466, ENSOULED_UNICORN_HEAD), ITEM_ENSOULED_DOG_HEAD(ENSOULED_DOG_HEAD_13469, ENSOULED_DOG_HEAD), ITEM_ENSOULED_CHAOS_DRUID_HEAD(ENSOULED_CHAOS_DRUID_HEAD_13472, ENSOULED_CHAOS_DRUID_HEAD), ITEM_ENSOULED_GIANT_HEAD(ENSOULED_GIANT_HEAD_13475, ENSOULED_GIANT_HEAD), ITEM_ENSOULED_OGRE_HEAD(ENSOULED_OGRE_HEAD_13478, ENSOULED_OGRE_HEAD), ITEM_ENSOULED_ELF_HEAD(ENSOULED_ELF_HEAD_13481, ENSOULED_ELF_HEAD), ITEM_ENSOULED_TROLL_HEAD(ENSOULED_TROLL_HEAD_13484, ENSOULED_TROLL_HEAD), ITEM_ENSOULED_HORROR_HEAD(ENSOULED_HORROR_HEAD_13487, ENSOULED_HORROR_HEAD), ITEM_ENSOULED_KALPHITE_HEAD(ENSOULED_KALPHITE_HEAD_13490, ENSOULED_KALPHITE_HEAD), ITEM_ENSOULED_DAGANNOTH_HEAD(ENSOULED_DAGANNOTH_HEAD_13493, ENSOULED_DAGANNOTH_HEAD), ITEM_ENSOULED_BLOODVELD_HEAD(ENSOULED_BLOODVELD_HEAD_13496, ENSOULED_BLOODVELD_HEAD), ITEM_ENSOULED_TZHAAR_HEAD(ENSOULED_TZHAAR_HEAD_13499, ENSOULED_TZHAAR_HEAD), ITEM_ENSOULED_DEMON_HEAD(ENSOULED_DEMON_HEAD_13502, ENSOULED_DEMON_HEAD), ITEM_ENSOULED_HELLHOUND_HEAD(ENSOULED_HELLHOUND_HEAD_26997, ENSOULED_HELLHOUND_HEAD), ITEM_ENSOULED_AVIANSIE_HEAD(ENSOULED_AVIANSIE_HEAD_13505, ENSOULED_AVIANSIE_HEAD), ITEM_ENSOULED_ABYSSAL_HEAD(ENSOULED_ABYSSAL_HEAD_13508, ENSOULED_ABYSSAL_HEAD), ITEM_ENSOULED_DRAGON_HEAD(ENSOULED_DRAGON_HEAD_13511, ENSOULED_DRAGON_HEAD), // Imbued rings ITEM_BERSERKER_RING(BERSERKER_RING, BERSERKER_RING_I, BERSERKER_RING_I_25264), ITEM_SEERS_RING(SEERS_RING, SEERS_RING_I, SEERS_RING_I_25258), ITEM_WARRIOR_RING(WARRIOR_RING, WARRIOR_RING_I, WARRIOR_RING_I_25262), ITEM_ARCHERS_RING(ARCHERS_RING, ARCHERS_RING_I, ARCHERS_RING_I_25260), ITEM_TREASONOUS_RING(TREASONOUS_RING, TREASONOUS_RING_I, TREASONOUS_RING_I_25256), ITEM_TYRANNICAL_RING(TYRANNICAL_RING, TYRANNICAL_RING_I, TYRANNICAL_RING_I_25254), ITEM_RING_OF_THE_GODS(RING_OF_THE_GODS, RING_OF_THE_GODS_I, RING_OF_THE_GODS_I_25252), ITEM_RING_OF_SUFFERING(RING_OF_SUFFERING, RING_OF_SUFFERING_I, RING_OF_SUFFERING_R, RING_OF_SUFFERING_RI, RING_OF_SUFFERING_I_25246, RING_OF_SUFFERING_RI_25248), ITEM_GRANITE_RING(GRANITE_RING, GRANITE_RING_I, GRANITE_RING_I_25193), // Bounty hunter ITEM_GRANITE_MAUL(GRANITE_MAUL, GRANITE_MAUL_12848), ITEM_MAGIC_SHORTBOW(MAGIC_SHORTBOW, MAGIC_SHORTBOW_I), ITEM_MAGIC_SHORTBOW_SCROLL(MAGIC_SHORTBOW_SCROLL, MAGIC_SHORTBOW_I), ITEM_SARADOMINS_BLESSED_SWORD(SARADOMINS_TEAR, SARADOMINS_BLESSED_SWORD), // Jewellery with charges ITEM_RING_OF_WEALTH(RING_OF_WEALTH, RING_OF_WEALTH_I, RING_OF_WEALTH_1, RING_OF_WEALTH_I1, RING_OF_WEALTH_2, RING_OF_WEALTH_I2, RING_OF_WEALTH_3, RING_OF_WEALTH_I3, RING_OF_WEALTH_4, RING_OF_WEALTH_I4, RING_OF_WEALTH_I5), ITEM_RING_OF_WEALTH_SCROLL(RING_OF_WEALTH_SCROLL, RING_OF_WEALTH_I, RING_OF_WEALTH_I1, RING_OF_WEALTH_I2, RING_OF_WEALTH_I3, RING_OF_WEALTH_I4, RING_OF_WEALTH_I5), ITEM_AMULET_OF_GLORY(AMULET_OF_GLORY, AMULET_OF_GLORY1, AMULET_OF_GLORY2, AMULET_OF_GLORY3, AMULET_OF_GLORY5), ITEM_AMULET_OF_GLORY_T(AMULET_OF_GLORY_T, AMULET_OF_GLORY_T1, AMULET_OF_GLORY_T2, AMULET_OF_GLORY_T3, AMULET_OF_GLORY_T5), ITEM_SKILLS_NECKLACE(SKILLS_NECKLACE, SKILLS_NECKLACE1, SKILLS_NECKLACE2, SKILLS_NECKLACE3, SKILLS_NECKLACE5), ITEM_RING_OF_DUELING(RING_OF_DUELING8, RING_OF_DUELING1, RING_OF_DUELING2, RING_OF_DUELING3, RING_OF_DUELING4, RING_OF_DUELING5, RING_OF_DUELING6, RING_OF_DUELING7), ITEM_GAMES_NECKLACE(GAMES_NECKLACE8, GAMES_NECKLACE1, GAMES_NECKLACE2, GAMES_NECKLACE3, GAMES_NECKLACE4, GAMES_NECKLACE5, GAMES_NECKLACE6, GAMES_NECKLACE7), // Degradable/charged weaponry/armour ITEM_ABYSSAL_WHIP(ABYSSAL_WHIP, VOLCANIC_ABYSSAL_WHIP, FROZEN_ABYSSAL_WHIP, ABYSSAL_WHIP_OR), ITEM_KRAKEN_TENTACLE(KRAKEN_TENTACLE, ABYSSAL_TENTACLE, ABYSSAL_TENTACLE_OR), ITEM_TRIDENT_OF_THE_SEAS(UNCHARGED_TRIDENT, TRIDENT_OF_THE_SEAS), ITEM_TRIDENT_OF_THE_SEAS_E(UNCHARGED_TRIDENT_E, TRIDENT_OF_THE_SEAS_E), ITEM_TRIDENT_OF_THE_SWAMP(UNCHARGED_TOXIC_TRIDENT, TRIDENT_OF_THE_SWAMP), ITEM_TRIDENT_OF_THE_SWAMP_E(UNCHARGED_TOXIC_TRIDENT_E, TRIDENT_OF_THE_SWAMP_E), ITEM_TOXIC_BLOWPIPE(TOXIC_BLOWPIPE_EMPTY, TOXIC_BLOWPIPE), ITEM_TOXIC_STAFF_OFF_THE_DEAD(TOXIC_STAFF_UNCHARGED, TOXIC_STAFF_OF_THE_DEAD), ITEM_SERPENTINE_HELM(SERPENTINE_HELM_UNCHARGED, SERPENTINE_HELM, TANZANITE_HELM_UNCHARGED, TANZANITE_HELM, MAGMA_HELM_UNCHARGED, MAGMA_HELM), ITEM_DRAGONFIRE_SHIELD(DRAGONFIRE_SHIELD_11284, DRAGONFIRE_SHIELD), ITEM_DRAGONFIRE_WARD(DRAGONFIRE_WARD_22003, DRAGONFIRE_WARD), ITEM_ANCIENT_WYVERN_SHIELD(ANCIENT_WYVERN_SHIELD_21634, ANCIENT_WYVERN_SHIELD), ITEM_SANGUINESTI_STAFF(SANGUINESTI_STAFF_UNCHARGED, SANGUINESTI_STAFF, HOLY_SANGUINESTI_STAFF_UNCHARGED, HOLY_SANGUINESTI_STAFF), ITEM_SCYTHE_OF_VITUR(SCYTHE_OF_VITUR_UNCHARGED, SCYTHE_OF_VITUR, HOLY_SCYTHE_OF_VITUR_UNCHARGED, HOLY_SCYTHE_OF_VITUR, SANGUINE_SCYTHE_OF_VITUR_UNCHARGED, SANGUINE_SCYTHE_OF_VITUR), ITEM_TOME_OF_FIRE(TOME_OF_FIRE_EMPTY, TOME_OF_FIRE), ITEM_TOME_OF_WATER(TOME_OF_WATER_EMPTY, TOME_OF_WATER), ITEM_CRAWS_BOW(CRAWS_BOW_U, CRAWS_BOW), ITEM_VIGGORAS_CHAINMACE(VIGGORAS_CHAINMACE_U, VIGGORAS_CHAINMACE), ITEM_THAMMARONS_SCEPTRE(THAMMARONS_SCEPTRE_U, THAMMARONS_SCEPTRE), ITEM_BRYOPHYTAS_STAFF(BRYOPHYTAS_STAFF_UNCHARGED, BRYOPHYTAS_STAFF), ITEM_RING_OF_ENDURANCE(RING_OF_ENDURANCE_UNCHARGED_24844, RING_OF_ENDURANCE), ITEM_TUMEKENS_SHADOW(TUMEKENS_SHADOW_UNCHARGED, TUMEKENS_SHADOW), // Tombs of Amascut gear ITEM_ELIDINIS_WARD(ELIDINIS_WARD, ELIDINIS_WARD_F, ELIDINIS_WARD_OR), ITEM_OSMUMTENS_FANG(OSMUMTENS_FANG, OSMUMTENS_FANG_OR), // Infinity colour kits ITEM_INFINITY_TOP(INFINITY_TOP, INFINITY_TOP_20574, DARK_INFINITY_TOP, LIGHT_INFINITY_TOP), ITEM_INFINITY_TOP_LIGHT_COLOUR_KIT(LIGHT_INFINITY_COLOUR_KIT, LIGHT_INFINITY_TOP), ITEM_INFINITY_TOP_DARK_COLOUR_KIT(DARK_INFINITY_COLOUR_KIT, DARK_INFINITY_TOP), ITEM_INFINITY_BOTTOMS(INFINITY_BOTTOMS, INFINITY_BOTTOMS_20575, DARK_INFINITY_BOTTOMS, LIGHT_INFINITY_BOTTOMS), ITEM_INFINITY_BOTTOMS_LIGHT_COLOUR_KIT(LIGHT_INFINITY_COLOUR_KIT, LIGHT_INFINITY_BOTTOMS), ITEM_INFINITY_BOTTOMS_DARK_COLOUR_KIT(DARK_INFINITY_COLOUR_KIT, DARK_INFINITY_BOTTOMS), ITEM_INFINITY_HAT(INFINITY_HAT, DARK_INFINITY_HAT, LIGHT_INFINITY_HAT), ITEM_INFINITY_HAT_LIGHT_COLOUR_KIT(LIGHT_INFINITY_COLOUR_KIT, LIGHT_INFINITY_HAT), ITEM_INFINITY_HAT_DARK_COLOUR_KIT(DARK_INFINITY_COLOUR_KIT, DARK_INFINITY_HAT), // Miscellaneous ornament kits ITEM_DARK_BOW(DARK_BOW, DARK_BOW_12765, DARK_BOW_12766, DARK_BOW_12767, DARK_BOW_12768, DARK_BOW_20408), ITEM_ODIUM_WARD(ODIUM_WARD, ODIUM_WARD_12807), ITEM_MALEDICTION_WARD(MALEDICTION_WARD, MALEDICTION_WARD_12806), ITEM_STEAM_BATTLESTAFF(STEAM_BATTLESTAFF, STEAM_BATTLESTAFF_12795), ITEM_LAVA_BATTLESTAFF(LAVA_BATTLESTAFF, LAVA_BATTLESTAFF_21198), ITEM_TZHAARKETOM(TZHAARKETOM, TZHAARKETOM_T), ITEM_TZHAARKETOM_ORNAMENT_KIT(TZHAARKETOM_ORNAMENT_KIT, TZHAARKETOM_T), ITEM_DRAGON_HUNTER_CROSSBOW(DRAGON_HUNTER_CROSSBOW, DRAGON_HUNTER_CROSSBOW_B, DRAGON_HUNTER_CROSSBOW_T), // Slayer helm/black mask ITEM_BLACK_MASK( BLACK_MASK, BLACK_MASK_I, BLACK_MASK_1, BLACK_MASK_1_I, BLACK_MASK_2, BLACK_MASK_2_I, BLACK_MASK_3, BLACK_MASK_3_I, BLACK_MASK_4, BLACK_MASK_4_I, BLACK_MASK_5, BLACK_MASK_5_I, BLACK_MASK_6, BLACK_MASK_6_I, BLACK_MASK_7, BLACK_MASK_7_I, BLACK_MASK_8, BLACK_MASK_8_I, BLACK_MASK_9, BLACK_MASK_9_I, BLACK_MASK_10_I, SLAYER_HELMET, SLAYER_HELMET_I, BLACK_SLAYER_HELMET, BLACK_SLAYER_HELMET_I, PURPLE_SLAYER_HELMET, PURPLE_SLAYER_HELMET_I, RED_SLAYER_HELMET, RED_SLAYER_HELMET_I, GREEN_SLAYER_HELMET, GREEN_SLAYER_HELMET_I, TURQUOISE_SLAYER_HELMET, TURQUOISE_SLAYER_HELMET_I, TWISTED_SLAYER_HELMET, TWISTED_SLAYER_HELMET_I, HYDRA_SLAYER_HELMET, HYDRA_SLAYER_HELMET_I, SLAYER_HELMET_I_25177, BLACK_SLAYER_HELMET_I_25179, GREEN_SLAYER_HELMET_I_25181, RED_SLAYER_HELMET_I_25183, PURPLE_SLAYER_HELMET_I_25185, TURQUOISE_SLAYER_HELMET_I_25187, HYDRA_SLAYER_HELMET_I_25189, TWISTED_SLAYER_HELMET_I_25191, BLACK_MASK_I_25276, BLACK_MASK_1_I_25275, BLACK_MASK_2_I_25274, BLACK_MASK_3_I_25273, BLACK_MASK_4_I_25272, BLACK_MASK_5_I_25271, BLACK_MASK_6_I_25270, BLACK_MASK_7_I_25269, BLACK_MASK_8_I_25268, BLACK_MASK_9_I_25267, BLACK_MASK_10_I_25266, TZTOK_SLAYER_HELMET, TZTOK_SLAYER_HELMET_I, TZTOK_SLAYER_HELMET_I_25902, VAMPYRIC_SLAYER_HELMET, VAMPYRIC_SLAYER_HELMET_I, VAMPYRIC_SLAYER_HELMET_I_25908, TZKAL_SLAYER_HELMET, TZKAL_SLAYER_HELMET_I, TZKAL_SLAYER_HELMET_I_25914), // Revertible items ITEM_HYDRA_LEATHER(HYDRA_LEATHER, FEROCIOUS_GLOVES), ITEM_HYDRA_TAIL(HYDRA_TAIL, BONECRUSHER_NECKLACE), ITEM_DRAGONBONE_NECKLACE(DRAGONBONE_NECKLACE, BONECRUSHER_NECKLACE), ITEM_BOTTOMLESS_COMPOST_BUCKET(BOTTOMLESS_COMPOST_BUCKET, BOTTOMLESS_COMPOST_BUCKET_22997), ITEM_BASILISK_JAW(BASILISK_JAW, NEITIZNOT_FACEGUARD), ITEM_HELM_OF_NEITIZNOT(HELM_OF_NEITIZNOT, NEITIZNOT_FACEGUARD), ITEM_TWISTED_HORNS(TWISTED_HORNS, TWISTED_SLAYER_HELMET, TWISTED_SLAYER_HELMET_I, TWISTED_SLAYER_HELMET_I_25191), ITEM_ELDRITCH_ORB(ELDRITCH_ORB, ELDRITCH_NIGHTMARE_STAFF), ITEM_HARMONISED_ORB(HARMONISED_ORB, HARMONISED_NIGHTMARE_STAFF), ITEM_VOLATILE_ORB(VOLATILE_ORB, VOLATILE_NIGHTMARE_STAFF), ITEM_NIGHTMARE_STAFF(NIGHTMARE_STAFF, ELDRITCH_NIGHTMARE_STAFF, HARMONISED_NIGHTMARE_STAFF, VOLATILE_NIGHTMARE_STAFF), ITEM_GHARZI_RAPIER(GHRAZI_RAPIER, HOLY_GHRAZI_RAPIER), ITEM_MASTER_SCROLL_BOOK(MASTER_SCROLL_BOOK_EMPTY, MASTER_SCROLL_BOOK), ITEM_ARCANE_SIGIL(ARCANE_SIGIL, ELIDINIS_WARD_F, ELIDINIS_WARD_OR), // Trouver Parchment ITEM_TROUVER_PARCHMENT( TROUVER_PARCHMENT, INFERNAL_MAX_CAPE_L, FIRE_MAX_CAPE_L, ASSEMBLER_MAX_CAPE_L, BRONZE_DEFENDER_L, IRON_DEFENDER_L, STEEL_DEFENDER_L, BLACK_DEFENDER_L, MITHRIL_DEFENDER_L, ADAMANT_DEFENDER_L, RUNE_DEFENDER_L, DRAGON_DEFENDER_L, DECORATIVE_SWORD_L, DECORATIVE_ARMOUR_L, DECORATIVE_ARMOUR_L_24159, DECORATIVE_HELM_L, DECORATIVE_SHIELD_L, DECORATIVE_ARMOUR_L_24162, DECORATIVE_ARMOUR_L_24163, DECORATIVE_ARMOUR_L_24164, DECORATIVE_ARMOUR_L_24165, DECORATIVE_ARMOUR_L_24166, DECORATIVE_ARMOUR_L_24167, DECORATIVE_ARMOUR_L_24168, SARADOMIN_HALO_L, ZAMORAK_HALO_L, GUTHIX_HALO_L, HEALER_HAT_L, FIGHTER_HAT_L, RANGER_HAT_L, FIGHTER_TORSO_L, PENANCE_SKIRT_L, VOID_KNIGHT_TOP_L, ELITE_VOID_TOP_L, VOID_KNIGHT_ROBE_L, ELITE_VOID_ROBE_L, VOID_KNIGHT_MACE_L, VOID_KNIGHT_GLOVES_L, VOID_MAGE_HELM_L, VOID_RANGER_HELM_L, VOID_MELEE_HELM_L, AVERNIC_DEFENDER_L, ARMADYL_HALO_L, BANDOS_HALO_L, SEREN_HALO_L, ANCIENT_HALO_L, BRASSICA_HALO_L, AVAS_ASSEMBLER_L, FIRE_CAPE_L, INFERNAL_CAPE_L, IMBUED_SARADOMIN_MAX_CAPE_L, IMBUED_ZAMORAK_MAX_CAPE_L, IMBUED_GUTHIX_MAX_CAPE_L, IMBUED_SARADOMIN_CAPE_L, IMBUED_ZAMORAK_CAPE_L, IMBUED_GUTHIX_CAPE_L, RUNE_POUCH_L, RUNNER_HAT_L, DECORATIVE_BOOTS_L, DECORATIVE_FULL_HELM_L), ITEM_TROUVER_PARCHMENT_REFUND_LARGE( COINS_995, 475000L, INFERNAL_MAX_CAPE_L, FIRE_MAX_CAPE_L, ASSEMBLER_MAX_CAPE_L, RUNE_DEFENDER_L, DRAGON_DEFENDER_L, DECORATIVE_SWORD_L, DECORATIVE_ARMOUR_L, DECORATIVE_ARMOUR_L_24159, DECORATIVE_HELM_L, DECORATIVE_SHIELD_L, DECORATIVE_ARMOUR_L_24162, DECORATIVE_ARMOUR_L_24163, DECORATIVE_ARMOUR_L_24164, DECORATIVE_ARMOUR_L_24165, DECORATIVE_ARMOUR_L_24166, DECORATIVE_ARMOUR_L_24167, DECORATIVE_ARMOUR_L_24168, SARADOMIN_HALO_L, ZAMORAK_HALO_L, GUTHIX_HALO_L, HEALER_HAT_L, FIGHTER_HAT_L, RANGER_HAT_L, FIGHTER_TORSO_L, PENANCE_SKIRT_L, VOID_KNIGHT_TOP_L, ELITE_VOID_TOP_L, VOID_KNIGHT_ROBE_L, ELITE_VOID_ROBE_L, VOID_KNIGHT_MACE_L, VOID_KNIGHT_GLOVES_L, VOID_MAGE_HELM_L, VOID_RANGER_HELM_L, VOID_MELEE_HELM_L, AVERNIC_DEFENDER_L, ARMADYL_HALO_L, BANDOS_HALO_L, SEREN_HALO_L, ANCIENT_HALO_L, BRASSICA_HALO_L, AVAS_ASSEMBLER_L, FIRE_CAPE_L, INFERNAL_CAPE_L, IMBUED_SARADOMIN_MAX_CAPE_L, IMBUED_ZAMORAK_MAX_CAPE_L, IMBUED_GUTHIX_MAX_CAPE_L, IMBUED_SARADOMIN_CAPE_L, IMBUED_ZAMORAK_CAPE_L, IMBUED_GUTHIX_CAPE_L, RUNE_POUCH_L, RUNNER_HAT_L, DECORATIVE_BOOTS_L, DECORATIVE_FULL_HELM_L), ITEM_TROUVER_PARCHMENT_REFUND_SMALL(COINS_995, 47500L, BRONZE_DEFENDER_L, IRON_DEFENDER_L, STEEL_DEFENDER_L, BLACK_DEFENDER_L, MITHRIL_DEFENDER_L, ADAMANT_DEFENDER_L), // Crystal items ITEM_CRYSTAL_TOOL_SEED(CRYSTAL_TOOL_SEED, CRYSTAL_AXE, CRYSTAL_AXE_INACTIVE, CRYSTAL_HARPOON, CRYSTAL_HARPOON_INACTIVE, CRYSTAL_PICKAXE, CRYSTAL_PICKAXE_INACTIVE), ITEM_CRYSTAL_AXE(DRAGON_AXE, CRYSTAL_AXE, CRYSTAL_AXE_INACTIVE), ITEM_CRYSTAL_HARPOON(DRAGON_HARPOON, CRYSTAL_HARPOON, CRYSTAL_HARPOON_INACTIVE), ITEM_CRYSTAL_PICKAXE(DRAGON_PICKAXE, CRYSTAL_PICKAXE, CRYSTAL_PICKAXE_INACTIVE), ITEM_BLADE_OF_SAELDOR(BLADE_OF_SAELDOR_INACTIVE, BLADE_OF_SAELDOR, BLADE_OF_SAELDOR_C, BLADE_OF_SAELDOR_C_25870, BLADE_OF_SAELDOR_C_25872, BLADE_OF_SAELDOR_C_25874, BLADE_OF_SAELDOR_C_25876, BLADE_OF_SAELDOR_C_25878, BLADE_OF_SAELDOR_C_25880, BLADE_OF_SAELDOR_C_25882), ITEM_CRYSTAL_BOW(CRYSTAL_WEAPON_SEED, CRYSTAL_BOW, CRYSTAL_BOW_24123, CRYSTAL_BOW_INACTIVE), ITEM_CRYSTAL_HALBERD(CRYSTAL_WEAPON_SEED, CRYSTAL_HALBERD, CRYSTAL_HALBERD_24125, CRYSTAL_HALBERD_INACTIVE), ITEM_CRYSTAL_SHIELD(CRYSTAL_WEAPON_SEED, CRYSTAL_SHIELD, CRYSTAL_SHIELD_24127, CRYSTAL_SHIELD_INACTIVE), ITEM_CRYSTAL_HELMET(CRYSTAL_ARMOUR_SEED, CRYSTAL_HELM, CRYSTAL_HELM_INACTIVE), ITEM_CRYSTAL_LEGS(CRYSTAL_ARMOUR_SEED, 2L, CRYSTAL_LEGS, CRYSTAL_LEGS_INACTIVE), ITEM_CRYSTAL_BODY(CRYSTAL_ARMOUR_SEED, 3L, CRYSTAL_BODY, CRYSTAL_BODY_INACTIVE), ITEM_BOW_OF_FAERDHINEN(BOW_OF_FAERDHINEN_INACTIVE, BOW_OF_FAERDHINEN, BOW_OF_FAERDHINEN_C, BOW_OF_FAERDHINEN_C_25884, BOW_OF_FAERDHINEN_C_25886, BOW_OF_FAERDHINEN_C_25888, BOW_OF_FAERDHINEN_C_25890, BOW_OF_FAERDHINEN_C_25892, BOW_OF_FAERDHINEN_C_25894, BOW_OF_FAERDHINEN_C_25896), // Bird nests ITEM_BIRD_NEST(BIRD_NEST_5075, BIRD_NEST, BIRD_NEST_5071, BIRD_NEST_5072, BIRD_NEST_5073, BIRD_NEST_5074, BIRD_NEST_7413, BIRD_NEST_13653, BIRD_NEST_22798, BIRD_NEST_22800, CLUE_NEST_EASY, CLUE_NEST_MEDIUM, CLUE_NEST_HARD, CLUE_NEST_ELITE), // Ancestral robes ITEM_ANCESTRAL_HAT(ANCESTRAL_HAT, TWISTED_ANCESTRAL_HAT), ITEM_ANCESTRAL_ROBE_TOP(ANCESTRAL_ROBE_TOP, TWISTED_ANCESTRAL_ROBE_TOP), ITEM_ANCESTRAL_ROBE_BOTTOM(ANCESTRAL_ROBE_BOTTOM, TWISTED_ANCESTRAL_ROBE_BOTTOM), // Graceful ITEM_MARK_OF_GRACE(AMYLASE_CRYSTAL, true, 10L, MARK_OF_GRACE), ITEM_GRACEFUL_HOOD(MARK_OF_GRACE, true, 28L, GRACEFUL_HOOD), ITEM_GRACEFUL_TOP(MARK_OF_GRACE, true, 44L, GRACEFUL_TOP), ITEM_GRACEFUL_LEGS(MARK_OF_GRACE, true, 48L, GRACEFUL_LEGS), ITEM_GRACEFUL_GLOVES(MARK_OF_GRACE, true, 24L, GRACEFUL_GLOVES), ITEM_GRACEFUL_BOOTS(MARK_OF_GRACE, true, 32L, GRACEFUL_BOOTS), ITEM_GRACEFUL_CAPE(MARK_OF_GRACE, true, 32L, GRACEFUL_CAPE), // Trailblazer Graceful Ornament Kit ITEM_TRAILBLAZER_GRACEFUL_HOOD(TRAILBLAZER_GRACEFUL_ORNAMENT_KIT, GRACEFUL_HOOD_25069), ITEM_TRAILBLAZER_GRACEFUL_TOP(TRAILBLAZER_GRACEFUL_ORNAMENT_KIT, GRACEFUL_TOP_25075), ITEM_TRAILBLAZER_GRACEFUL_LEGS(TRAILBLAZER_GRACEFUL_ORNAMENT_KIT, GRACEFUL_LEGS_25078), ITEM_TRAILBLAZER_GRACEFUL_GLOVES(TRAILBLAZER_GRACEFUL_ORNAMENT_KIT, GRACEFUL_GLOVES_25081), ITEM_TRAILBLAZER_GRACEFUL_BOOTS(TRAILBLAZER_GRACEFUL_ORNAMENT_KIT, GRACEFUL_BOOTS_25084), ITEM_TRAILBLAZER_GRACEFUL_CAPE(TRAILBLAZER_GRACEFUL_ORNAMENT_KIT, GRACEFUL_CAPE_25072), // 10 golden nuggets = 100 soft clay ITEM_GOLDEN_NUGGET(SOFT_CLAY, true, 10L, GOLDEN_NUGGET), ITEM_PROSPECTOR_HELMET(GOLDEN_NUGGET, true, 32L, PROSPECTOR_HELMET), ITEM_PROSPECTOR_JACKET(GOLDEN_NUGGET, true, 48L, PROSPECTOR_JACKET), ITEM_PROSPECTOR_LEGS(GOLDEN_NUGGET, true, 40L, PROSPECTOR_LEGS), ITEM_PROSPECTOR_BOOTS(GOLDEN_NUGGET, true, 24L, PROSPECTOR_BOOTS), // 10 unidentified minerals = 100 soft clay ITEM_UNIDENTIFIED_MINERALS(SOFT_CLAY, true, 10L, UNIDENTIFIED_MINERALS), // Converted to coins ITEM_TATTERED_PAGE(COINS_995, true, 1000L, TATTERED_MOON_PAGE, TATTERED_SUN_PAGE, TATTERED_TEMPLE_PAGE), ITEM_LONG_BONE(COINS_995, true, 1000L, LONG_BONE), ITEM_CURVED_BONE(COINS_995, true, 2000L, CURVED_BONE), ITEM_PERFECT_SHELL(COINS_995, true, 600L, PERFECT_SHELL), ITEM_PERFECT_SNAIL_SHELL(COINS_995, true, 600L, PERFECT_SNAIL_SHELL), ITEM_SNAIL_SHELL(COINS_995, true, 600L, SNAIL_SHELL), ITEM_TORTOISE_SHELL(COINS_995, true, 250L, TORTOISE_SHELL); private static final Multimap<Integer, ItemMapping> MAPPINGS = HashMultimap.create(); private final int tradeableItem; private final int[] untradableItems; private final long quantity; private final boolean untradeable; static { for (final ItemMapping item : values()) { for (int itemId : item.untradableItems) { if (item.untradeable) { for (final Integer variation : ItemVariationMapping.getVariations(itemId)) { MAPPINGS.put(variation, item); } } MAPPINGS.put(itemId, item); } } } ItemMapping(int tradeableItem, boolean untradeable, long quantity, int... untradableItems) { this.tradeableItem = tradeableItem; this.untradableItems = untradableItems; this.quantity = quantity; this.untradeable = untradeable; } ItemMapping(int tradeableItem, long quantity, int... untradableItems) { this(tradeableItem, false, quantity, untradableItems); } ItemMapping(int tradeableItem, int... untradableItems) { this(tradeableItem, 1L, untradableItems); } /** * Get collection of items that are mapped from single item id. * * @param itemId the item id * @return the collection */ @Nullable public static Collection<ItemMapping> map(int itemId) { final Collection<ItemMapping> mapping = MAPPINGS.get(itemId); if (mapping.isEmpty()) { return null; } return mapping; } }
package net.runelite.client.ui; import java.awt.Dimension; import java.util.ArrayList; import java.util.List; import java.util.function.Supplier; import javax.swing.JToolBar; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PluginToolbar extends JToolBar { private static final Logger logger = LoggerFactory.getLogger(PluginToolbar.class); public static final int TOOLBAR_WIDTH = 36, TOOLBAR_HEIGHT = 503; private final ClientUI ui; private final List<NavigationButton> buttons = new ArrayList<>(); private NavigationButton current; public PluginToolbar(ClientUI ui) { super(JToolBar.VERTICAL); this.ui = ui; super.setFloatable(false); super.setSize(new Dimension(TOOLBAR_WIDTH, TOOLBAR_HEIGHT)); super.setMinimumSize(new Dimension(TOOLBAR_WIDTH, TOOLBAR_HEIGHT)); super.setPreferredSize(new Dimension(TOOLBAR_WIDTH, TOOLBAR_HEIGHT)); } public void addNavigation(NavigationButton button) { button.getButton().addActionListener((ae) -> onClick(button)); buttons.add(button); add(button.getButton()); revalidate(); } public void removeNavigation(NavigationButton button) { buttons.remove(button); remove(button.getButton()); revalidate(); } private void onClick(NavigationButton button) { Supplier<PluginPanel> panelSupplier = button.getPanelSupplier(); if (panelSupplier == null) { return; } if (current != null) { current.getButton().setSelected(false); } if (current == button) { ui.contract(); current = null; } else { PluginPanel pluginPanel = panelSupplier.get(); ui.expand(pluginPanel); current = button; current.getButton().setSelected(true); } } }
package uk.org.taverna.scufl2.api; import java.net.URI; import java.util.ArrayList; import java.util.List; import uk.org.taverna.scufl2.api.activity.Activity; import uk.org.taverna.scufl2.api.configurations.Configuration; import uk.org.taverna.scufl2.api.container.WorkflowBundle; import uk.org.taverna.scufl2.api.core.DataLink; import uk.org.taverna.scufl2.api.core.IterationStrategy; import uk.org.taverna.scufl2.api.core.Processor; import uk.org.taverna.scufl2.api.core.Workflow; import uk.org.taverna.scufl2.api.dispatchstack.DispatchStack; import uk.org.taverna.scufl2.api.iterationstrategy.CrossProduct; import uk.org.taverna.scufl2.api.iterationstrategy.PortNode; import uk.org.taverna.scufl2.api.port.InputActivityPort; import uk.org.taverna.scufl2.api.port.InputProcessorPort; import uk.org.taverna.scufl2.api.port.InputWorkflowPort; import uk.org.taverna.scufl2.api.port.OutputActivityPort; import uk.org.taverna.scufl2.api.port.OutputProcessorPort; import uk.org.taverna.scufl2.api.port.OutputWorkflowPort; import uk.org.taverna.scufl2.api.profiles.ProcessorBinding; import uk.org.taverna.scufl2.api.profiles.ProcessorInputPortBinding; import uk.org.taverna.scufl2.api.profiles.ProcessorOutputPortBinding; import uk.org.taverna.scufl2.api.profiles.Profile; public class ExampleWorkflow { private Workflow workflow; private Processor processor; private WorkflowBundle workflowBundle; private InputProcessorPort processorName; private OutputProcessorPort processorGreeting; private InputActivityPort personName; private OutputActivityPort hello; private Activity activity; public Activity makeActivity() { activity = new Activity(); activity.setName("HelloScript"); activity.setConfigurableType(URI .create("http://ns.taverna.org.uk/2010/taverna/activities/beanshell#Activity")); personName = new InputActivityPort(activity, "personName"); hello = new OutputActivityPort(activity, "hello"); return activity; } public Configuration makeConfiguration() { Configuration configuration = new Configuration("Hello"); configuration.setConfigures(activity); configuration .getPropertyResource() .setTypeURI( URI.create("http://ns.taverna.org.uk/2010/taverna/activities/beanshell#Configuration")); configuration .getPropertyResource() .addPropertyAsString( URI.create("http://ns.taverna.org.uk/2010/taverna/activities/beanshell#script"), "hello = \"Hello, \" + personName;\n" + "System.out.println(\"Server says: \" + hello);"); return configuration; } public DispatchStack makeDispatchStack() { // TODO: Make dispatch stack return new DispatchStack(); } public List<IterationStrategy> makeIterationStrategyStack( InputProcessorPort... inputs) { ArrayList<IterationStrategy> stack = new ArrayList<IterationStrategy>(); IterationStrategy strategy = new IterationStrategy(); stack.add(strategy); CrossProduct crossProduct = new CrossProduct(); strategy.setRootStrategyNode(crossProduct); for (InputProcessorPort inp : inputs) { crossProduct.add(new PortNode(crossProduct, inp)); } return stack; } public Profile makeMainProfile() { Profile profile = new Profile(); profile.setName("tavernaWorkbench"); // FIXME: Can't set dc:creator/date/description // FIXME: Can't create recommendsEnvironment/requiresEnvironment profile.getActivities().add(makeActivity()); profile.getConfigurations().add(makeConfiguration()); profile.getProcessorBindings().add(makeProcessorBinding()); // profile.setProfilePosition(0); return profile; } public Workflow makeMainWorkflow() { workflow = new Workflow(); workflow.setName("HelloWorld"); // NOTE: setWorkflowIdentifier should only be called when loading a // workflow // which already has an ID workflow.setWorkflowIdentifier(URI .create("http://ns.taverna.org.uk/2010/workflow/00626652-55ae-4a9e-80d4-c8e9ac84e2ca/")); InputWorkflowPort yourName = new InputWorkflowPort(workflow, "yourName"); OutputWorkflowPort results = new OutputWorkflowPort(workflow, "results"); // Not needed: // workflow.getInputPorts().add(yourName); // workflow.getOutputPorts().add(results); workflow.getProcessors().add(makeProcessor()); // Make links DataLink directLink = new DataLink(workflow, yourName, results); directLink.setMergePosition(1); DataLink greetingLink = new DataLink(workflow, processorGreeting, results); greetingLink.setMergePosition(0); DataLink nameLink = new DataLink(workflow, yourName, processorName); return workflow; } public Processor makeProcessor() { processor = new Processor(workflow, "Hello"); processorName = new InputProcessorPort(processor, "name"); processorGreeting = new OutputProcessorPort(processor, "greeting"); // FIXME: Should not need to make default dispatch stack processor.setDispatchStack(makeDispatchStack()); // FIXME: Should not need to make default iteration stack processor .setIterationStrategyStack(makeIterationStrategyStack(processorName)); return processor; } public ProcessorBinding makeProcessorBinding() { ProcessorBinding processorBinding = new ProcessorBinding(); processorBinding.setBoundProcessor(processor); processorBinding.setBoundActivity(activity); new ProcessorInputPortBinding(processorBinding, processorName, personName); new ProcessorOutputPortBinding(processorBinding, hello, processorGreeting); return processorBinding; } public Profile makeSecondaryProfile() { Profile profile = makeMainProfile(); profile.setName("tavernaServer"); Configuration config = profile.getConfigurations().getByName("Hello"); config.getPropertyResource().getProperties().clear(); // FIXME: Need removeProperty! config.getPropertyResource() .addPropertyAsString( URI.create("http://ns.taverna.org.uk/2010/taverna/activities/beanshell#script"), "hello = \"Hello, \" + personName;\n" + "System.out.println(\"Server says: \" + hello);"); return profile; } public WorkflowBundle makeWorkflowBundle() { // Based on // uk.org.taverna.scufl2.scufl2-usecases/src/main/resources/workflows/example/workflowBundle.rdf workflowBundle = new WorkflowBundle(); workflowBundle.setName("HelloWorld"); // NOTE: setSameBaseAs should only be called when loading a workflow // bundle // which already has an ID workflowBundle .setSameBaseAs(URI .create("http://ns.taverna.org.uk/2010/workflowBundle/28f7c554-4f35-401f-b34b-516e9a0ef731/")); Workflow workflow = makeMainWorkflow(); workflow.setParent(workflowBundle); workflowBundle.setMainWorkflow(workflow); Profile profile = makeMainProfile(); profile.setParent(workflowBundle); workflowBundle.setMainProfile(profile); Profile secondaryProfile = makeSecondaryProfile(); secondaryProfile.setParent(workflowBundle); return workflowBundle; } }
package com.senseidb.search.query; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import javassist.CtNewMethod; import javassist.NotFoundException; import org.apache.log4j.Logger; import org.apache.lucene.index.IndexReader; import org.apache.lucene.search.Explanation; import org.apache.lucene.search.Query; import org.apache.lucene.search.Scorer; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.browseengine.bobo.api.BoboIndexReader; import com.browseengine.bobo.facets.data.FacetDataCache; import com.browseengine.bobo.facets.data.TermDoubleList; import com.browseengine.bobo.facets.data.TermFloatList; import com.browseengine.bobo.facets.data.TermIntList; import com.browseengine.bobo.facets.data.TermLongList; import com.browseengine.bobo.facets.data.TermShortList; import com.browseengine.bobo.facets.data.TermStringList; import com.browseengine.bobo.facets.data.TermValueList; import com.browseengine.bobo.util.BigSegmentedArray; public class RelevanceQuery extends AbstractScoreAdjuster { /* Type Strings; */ // (1) inner score type; private final String TYPE_INNER_SCORE = "INNER_SCORE"; //actually a float value; // (2) general types: private final String TYPE_INT = "INT"; private final String TYPE_LONG = "LONG"; private final String TYPE_DOUBLE = "DOUBLE"; private final String TYPE_FLOAT = "FLOAT"; private final String TYPE_BOOLEAN = "BOOLEAN"; private final String TYPE_STRING = "STRING"; // container types: private final String TYPE_SET = "SET"; // (3) facet types: private final String TYPE_FACET_INT = "FACET_INT"; private final String TYPE_FACET_LONG = "FACET_LONG"; private final String TYPE_FACET_DOUBLE = "FACET_DOUBLE"; private final String TYPE_FACET_FLOAT = "FACET_FLOAT"; private final String TYPE_FACET_SHORT = "FACET_SHORT"; private final String TYPE_FACET_STRING = "FACET_STRING"; private final String TYPE_FACET_HEAD = "FACET"; /* Type Numbers */ // (1) inner score type number; private final int TYPENUMBER_INNER_SCORE = 0; // (2) general type numbers: private final int TYPENUMBER_INT = 1; private final int TYPENUMBER_LONG = 2; private final int TYPENUMBER_DOUBLE = 3; private final int TYPENUMBER_FLOAT = 4; private final int TYPENUMBER_BOOLEAN = 5; private final int TYPENUMBER_STRING = 6; private final int TYPENUMBER_SET = 7; // (3) facet type numbers; private final int TYPENUMBER_FACET_INT = 10; private final int TYPENUMBER_FACET_LONG = 11; private final int TYPENUMBER_FACET_DOUBLE = 12; private final int TYPENUMBER_FACET_FLOAT = 13; private final int TYPENUMBER_FACET_SHORT = 14; private final int TYPENUMBER_FACET_STRING = 15; private static final long serialVersionUID = 1L; private static Logger logger = Logger.getLogger(RelevanceQuery.class); protected final Query _query; private HashMap<String, Object> hm_var = new HashMap<String, Object>(); private HashMap<String, String> hm_type = new HashMap<String, String>(); private HashMap<String, String> hm_symbol_facet = new HashMap<String, String>(); private HashMap<String, Integer> hm_facet_index = new HashMap<String, Integer>(); private LinkedList<String> lls_params = new LinkedList<String>(); private String funcBody = null; private String classIDString = null; private CustomScorer cscorer = null; private int facetIndex = 0; static ClassPool pool = ClassPool.getDefault(); static { pool.importPackage("java.util"); pool.importPackage("it.unimi.dsi.fastutil.ints.*"); pool.importPackage("it.unimi.dsi.fastutil.longs.*"); pool.importPackage("it.unimi.dsi.fastutil.shorts.*"); pool.importPackage("it.unimi.dsi.fastutil.booleans.*"); pool.importPackage("it.unimi.dsi.fastutil.bytes.*"); pool.importPackage("it.unimi.dsi.fastutil.chars.*"); pool.importPackage("it.unimi.dsi.fastutil.doubles.*"); pool.importPackage("it.unimi.dsi.fastutil.floats.*"); pool.importPackage("it.unimi.dsi.fastutil.objects.*"); } static HashMap<String, CustomScorer> hmModels = new HashMap<String, CustomScorer>(); // "relevance":[ // // sequence of statements in a score adjusting function below, statement order matters; // // the statement order should be exactly the same as the Java code is executing. // // (1) Variable assignment statements; // // It may contain set, int, float, double, long, boolean, // // var_set_int, var_set_string, var_set_double, var_set_long supported now. // {"var_set_int":{"c":[1996, 1997], "d":[1998]}}, // {"var_double":{"e":0.98}}, // {"var_int":{"g":1996}}, // {"var_bool":{"f":true, "h":false}}, // {"var_constant_long":{"now":"_NOW"}}, // {"var_constant_float":{"innerScore":"_INNER_SCORE"}}, // {"var_facet_int":{"f":"year"}}, //facet type support: double, float, int, long, short, string; // // (2) scoring function and function input parameters in Java; // // A scoring function is a model. A model changes when the function body or signature changes; // {"function_params":["innerScore", "timeVal", "_timeWeight", "_waterworldWeight", "_half_time"]}, // params for the function above, optional. Symbol order matters, and symbols must be those defined above. innerScore MUST be used, otherwise, makes no sense to use the custom relevance; // // the value string in the following JSONObject is like this (a return statement MUST appear as the last one): // // float delta = System.currentTimeMillis() - timeVal; // // float t = delta>0 ? delta : 0; // // float hour = t/(1000*3600); // // float timeScore = (float) Math.exp(-(hour/_half_time)); // // float waterworldScore = innerScore; // // float time = timeScore * _timeWeight; // // float water = waterworldScore * _waterworldWeight; // // return (time + water); // {"function":" A LONG JAVA CODE STRING HERE, ONLY AS FUNCTION BODY"} /* A dummy testing relevance json: * * * "relevance":[ {"var_set_int":{"c":[1996, 1997], "d":[1998]}}, {"var_double":{"e":0.98}}, {"var_int":{"g":1996}}, {"var_bool":{"f":true, "h":false}}, {"var_constant_long":{"now":"_NOW"}}, {"var_constant_float":{"innerScore":"_INNER_SCORE"}}, {"var_facet_int":{"f":"color"}}, {"function_params":["innerScore"]}, {"function":" return 2f;"} * * */ public RelevanceQuery(Query query, JSONArray relevance) throws JSONException { super(query); _query = query; preprocess(relevance); } private void preprocess(JSONArray relevance) throws JSONException { for(int i=0; i< relevance.length(); i++) { JSONObject stat = relevance.optJSONObject(i); Iterator<String> iter = stat.keys(); if (!iter.hasNext()) throw new IllegalArgumentException("statement type not specified in relevance query: " + stat); String type = iter.next(); // var_set_int, var_set_string, var_set_double, var_set_long // {"var_set_int":{"c":[1996, 1997], "d":[1998]}}, if("var_set_int".equals(type) || "var_set_double".equals(type) || "var_set_long".equals(type) || "var_set_string".equals(type)) { JSONObject sets = stat.optJSONObject(type); Iterator<String> iter_symbol = sets.keys(); while(iter_symbol.hasNext()) { String symbol = iter_symbol.next(); HashSet hs = new HashSet(); JSONArray values = sets.getJSONArray(symbol); for (int k =0; k < values.length(); k++){ if("var_set_int".equals(type)) hs.add(values.getInt(k)); else if ("var_set_double".equals(type)) hs.add(values.getDouble(k)); else if ("var_set_long".equals(type)) hs.add(values.getLong(k)); else if ("var_set_string".equals(type)) hs.add(values.getString(k)); } if(hm_var.containsKey(symbol)) throw new JSONException("Symbol "+ symbol + " already defined." ); hm_var.put(symbol, hs); hm_type.put(symbol, TYPE_SET); } } // var_int, var_string, var_double, var_long // {"var_double":{"e":0.98}}, else if("var_int".equals(type) || "var_double".equals(type) || "var_long".equals(type) || "var_float".equals(type) || "var_string".equals(type)) { JSONObject sets = stat.optJSONObject(type); Iterator<String> iter_symbol = sets.keys(); while(iter_symbol.hasNext()) { String symbol = iter_symbol.next(); if(hm_var.containsKey(symbol)) throw new JSONException("Symbol "+ symbol + " already defined." ); if("var_int".equals(type)) { hm_var.put(symbol, sets.getInt(symbol)); hm_type.put(symbol, TYPE_INT); } else if ("var_double".equals(type)) { hm_var.put(symbol, sets.getDouble(symbol)); hm_type.put(symbol, TYPE_DOUBLE); } else if ("var_float".equals(type)) { hm_var.put(symbol, ((float)sets.getDouble(symbol))); hm_type.put(symbol, TYPE_FLOAT); } else if ("var_long".equals(type)) { hm_var.put(symbol, sets.getLong(symbol)); hm_type.put(symbol, TYPE_LONG); } else if ("var_string".equals(type)) { hm_var.put(symbol, sets.getString(symbol)); hm_type.put(symbol, TYPE_STRING); } } } // var_bool else if("var_bool".equals(type)) { JSONObject set = stat.optJSONObject(type); Iterator<String> iterSymbol = set.keys(); while(iterSymbol.hasNext()) { String symbol = iterSymbol.next(); Boolean value = set.optBoolean(symbol); if(hm_var.containsKey(symbol)) throw new JSONException("Symbol "+ symbol + " already defined." ); hm_var.put(symbol, value); hm_type.put(symbol, TYPE_BOOLEAN); } } // now // {"var_constant_long":{"now":"_NOW"}}, else if("var_constant_long".equals(type)) { JSONObject set = stat.optJSONObject(type); Iterator<String> iterSymbol = set.keys(); while(iterSymbol.hasNext()) { String symbol = iterSymbol.next(); String value = set.optString(symbol); if("_NOW".equals(value)) { long now = System.currentTimeMillis(); if(hm_var.containsKey(symbol)) throw new JSONException("Symbol "+ symbol + " already defined." ); hm_var.put(symbol, now); hm_type.put(symbol, TYPE_LONG); } } } // innerscore; // {"var_constant_float":{"innerScore":"_INNER_SCORE"}}, else if("var_constant_float".equals(type)) { JSONObject set = stat.optJSONObject(type); Iterator<String> iterSymbol = set.keys(); while(iterSymbol.hasNext()) { String symbol = iterSymbol.next(); String value = set.optString(symbol); if("_INNER_SCORE".equals(value)) { if(hm_var.containsKey(symbol)) throw new JSONException("Symbol "+ symbol + " already defined." ); hm_var.put(symbol, "_innerScore"); hm_type.put(symbol, TYPE_INNER_SCORE); } } } // var_facet_int, var_facet_string, var_facet_double, var_facet_long // {"var_facet_int":{"f":"year"}}, else if("var_facet_int".equals(type)) { JSONObject set = stat.optJSONObject(type); handleFacetSymbols(set, TYPE_FACET_INT); } else if("var_facet_short".equals(type)) { JSONObject set = stat.optJSONObject(type); handleFacetSymbols(set, TYPE_FACET_SHORT); } else if("var_facet_double".equals(type)) { JSONObject set = stat.optJSONObject(type); handleFacetSymbols(set, TYPE_FACET_DOUBLE); } else if("var_facet_float".equals(type)) { JSONObject set = stat.optJSONObject(type); handleFacetSymbols(set, TYPE_FACET_FLOAT); } else if("var_facet_long".equals(type)) { JSONObject set = stat.optJSONObject(type); handleFacetSymbols(set, TYPE_FACET_LONG); } else if("var_facet_string".equals(type)) { JSONObject set = stat.optJSONObject(type); handleFacetSymbols(set, TYPE_FACET_STRING); } //function parameters; if("function_params".equals(type)) { JSONArray sets = stat.optJSONArray(type); for(int j=0; j<sets.length(); j++) { String paramName = sets.optString(j); lls_params.add(paramName); } } //function body; if("function".equals(type)) { funcBody = stat.optString("function").trim(); } } // end of all the statements; if(funcBody == null || funcBody.length()==0) throw new JSONException("No function body found."); if(funcBody.indexOf("return ")==-1) throw new JSONException("No return statement in the function body."); //check if all the parameters have defined; for(int i=0; i< lls_params.size(); i++) { String symbol = lls_params.get(i); if( !hm_type.containsKey(symbol)) throw new JSONException("function parameter: " + symbol + " was not defined."); String type = hm_type.get(symbol); if(type.startsWith(TYPE_FACET_HEAD)) { if( !hm_symbol_facet.containsKey(symbol)) throw new JSONException("function parameter: " + symbol + " was not defined."); } else { if(!hm_var.containsKey(symbol)) throw new JSONException("function parameter: " + symbol + " was not defined."); } } lls_params = filterParameters(lls_params, funcBody); String paramString = getParamString(lls_params); classIDString = funcBody + paramString; String className = "CRel"+ classIDString.hashCode(); logger.info("Custom relevance class name is:"+ className); if(hmModels.containsKey(className)) cscorer = hmModels.get(className); else { synchronized(this) { CtClass ch = pool.makeClass(className); CtClass ci; try { ci = pool.get("com.senseidb.search.query.CustomScorer"); } catch (NotFoundException e) { logger.info(e.getMessage()); throw new JSONException(e); } ch.addInterface(ci); String functionString = makeFuncString(funcBody, hm_type, lls_params); CtMethod m; try { m = CtNewMethod.make(functionString, ch); } catch (CannotCompileException e) { logger.info(e.getMessage()); throw new JSONException(e); } try { ch.addMethod(m); } catch (CannotCompileException e) { logger.info(e.getMessage()); throw new JSONException(e); } Class h; try { h = ch.toClass(RelevanceQuery.class.getClassLoader()); } catch (CannotCompileException e) { if(hmModels.containsKey(className)) { cscorer = hmModels.get(className); return; } else { logger.info(e.getMessage()); throw new JSONException(e); } } try { cscorer = (CustomScorer)h.newInstance(); } catch (InstantiationException e) { logger.info(e.getMessage()); throw new JSONException(e); } catch (IllegalAccessException e) { logger.info(e.getMessage()); throw new JSONException(e); } hmModels.put(className, cscorer); } } } private String getParamString(LinkedList<String> lls_params) { StringBuilder sb = new StringBuilder(); for(String param : lls_params) { sb.append(param); sb.append(" } return sb.toString(); } private LinkedList<String> filterParameters(LinkedList<String> lls_params, String funcBody) { LinkedList<String> lls_new = new LinkedList<String>(); for(String param : lls_params) { if( !(funcBody.indexOf(param) == -1)) lls_new.add(param); } return lls_new; } private void handleFacetSymbols(JSONObject set, String type) throws JSONException { Iterator<String> iterSymbol = set.keys(); while(iterSymbol.hasNext()) { String symbol = iterSymbol.next(); String facetName = set.optString(symbol); if(hm_symbol_facet.containsKey(symbol)) throw new JSONException("facet Symbol "+ symbol + " already defined." ); if(hm_facet_index.containsKey(facetName)) throw new JSONException("facet name "+ facetName + " already assigned to a symbol." ); hm_symbol_facet.put(symbol, facetName); hm_facet_index.put(facetName, facetIndex); facetIndex++; hm_type.put(symbol, type); } } private String makeFuncString(String funcBody, HashMap<String, String> hm_type, LinkedList<String> lls_params) throws JSONException { // "public float score(Object[] objs) { Integer inta = (Integer)objs[0]; System.out.println(inta); HashMap hm = (HashMap)objs[2]; System.out.println(hm.get(\"good\")); return b; }" StringBuffer sb = new StringBuffer(); sb.append("public float score(short[] shorts, int[] ints, long[] longs, float[] floats, double[] doubles, boolean[] booleans, String[] strings, Set[] sets) {"); int short_index = 0; int int_index = 0; int long_index = 0; int float_index = 0; int double_index = 0; int boolean_index = 0; int string_index = 0; int set_index = 0; for(int i=0; i< lls_params.size();i++) { String paramName = lls_params.get(i); if(!hm_type.containsKey(paramName)) throw new JSONException("function arameter " + paramName + " is not defined."); if(hm_type.get(paramName).equals(TYPE_INT) || hm_type.get(paramName).equals(TYPE_FACET_INT)) { sb.append(" int " + paramName + " = ints[" + int_index + "]; "); int_index++; } else if(hm_type.get(paramName).equals(TYPE_LONG) || hm_type.get(paramName).equals(TYPE_FACET_LONG)) { sb.append(" long " + paramName + " = longs[" + long_index +"]; "); long_index++; } else if(hm_type.get(paramName).equals(TYPE_DOUBLE) || hm_type.get(paramName).equals(TYPE_FACET_DOUBLE)) { sb.append(" double " + paramName + " = doubles["+ double_index +"]; "); double_index++; } else if(hm_type.get(paramName).equals(TYPE_FLOAT) || hm_type.get(paramName).equals(TYPE_FACET_FLOAT)) { sb.append(" float " + paramName + " = floats["+ float_index +"]; "); float_index++; } else if(hm_type.get(paramName).equals(TYPE_STRING) || hm_type.get(paramName).equals(TYPE_FACET_STRING)) { sb.append(" String " + paramName + " = strings["+ string_index +"]; "); string_index++; } else if(hm_type.get(paramName).equals(TYPE_BOOLEAN)) { sb.append(" boolean " + paramName + " = booleans["+ boolean_index +"]; "); boolean_index++; } else if(hm_type.get(paramName).equals(TYPE_FACET_SHORT)) { sb.append(" short " + paramName + " = shorts["+ short_index +"]; "); short_index++; } else if(hm_type.get(paramName).equals(TYPE_SET)) { sb.append(" Set " + paramName + " = sets["+ set_index +"]; "); set_index++; } else if(hm_type.get(paramName).equals(TYPE_INNER_SCORE)) { sb.append(" float " + paramName + " = floats["+ float_index +"]; "); float_index++; } } sb.append(funcBody); sb.append("}"); return sb.toString(); } @Override protected Scorer createScorer(final Scorer innerScorer, IndexReader reader, boolean scoreDocsInOrder, boolean topScorer) throws IOException { if(cscorer == null) return innerScorer; if (reader instanceof BoboIndexReader ){ BoboIndexReader boboReader = (BoboIndexReader)reader; int numFacet = hm_symbol_facet.keySet().size(); final BigSegmentedArray[] orderArrays = new BigSegmentedArray[numFacet]; final TermValueList[] termLists = new TermValueList[numFacet]; Iterator<String> iter_facet = hm_facet_index.keySet().iterator(); while(iter_facet.hasNext()){ String facetName = iter_facet.next(); // validation; Object dataObj = boboReader.getFacetData(facetName); if ( ! (dataObj instanceof FacetDataCache<?>)) return innerScorer; int index = hm_facet_index.get(facetName); orderArrays[index] = ((FacetDataCache)(boboReader.getFacetData(facetName))).orderArray; termLists[index] = ((FacetDataCache)(boboReader.getFacetData(facetName))).valArray; } final int paramSize = lls_params.size(); final int[] types = new int[paramSize]; final int[] facetIndex = new int[paramSize]; final int[] arrayIndex = new int[paramSize]; updateArrayIndex(paramSize, types, facetIndex, arrayIndex); return new CodeGenScorer(innerScorer, cscorer, orderArrays, termLists, types, facetIndex, arrayIndex, paramSize); } else{ return innerScorer; } } private void updateArrayIndex(int paramSize, int[] types, int[] facetIndex, int[] arrayIndex) { int short_index = 0; int int_index = 0; int long_index = 0; int float_index = 0; int double_index = 0; int boolean_index = 0; int string_index = 0; int set_index = 0; for(int i=0; i< paramSize; i++) { if(hm_type.get(lls_params.get(i)).equals(TYPE_INNER_SCORE)){ types[i] = TYPENUMBER_INNER_SCORE; //inner_score type parameter; facetIndex[i] = -1; //should not be used; arrayIndex[i] = float_index; float_index++; } else if (hm_type.get(lls_params.get(i)).startsWith(TYPE_FACET_HEAD)) { String type = hm_type.get(lls_params.get(i)); if(type.equals(TYPE_FACET_INT)) { types[i] = TYPENUMBER_FACET_INT; arrayIndex[i] = int_index; int_index++; } else if (type.equals(TYPE_FACET_LONG)) { types[i] = TYPENUMBER_FACET_LONG; arrayIndex[i] = long_index; long_index++; } else if (type.equals(TYPE_FACET_DOUBLE)) { types[i] = TYPENUMBER_FACET_DOUBLE; arrayIndex[i] = double_index; double_index++; } else if (type.equals(TYPE_FACET_FLOAT)) { types[i] = TYPENUMBER_FACET_FLOAT; arrayIndex[i] = float_index; float_index++; } else if (type.equals(TYPE_FACET_SHORT)) { types[i] = TYPENUMBER_FACET_SHORT; arrayIndex[i] = short_index; short_index++; } else if (type.equals(TYPE_FACET_STRING)) { types[i] = TYPENUMBER_FACET_STRING; arrayIndex[i] = string_index; string_index++; } String facetName = hm_symbol_facet.get(lls_params.get(i)); int index = hm_facet_index.get(facetName); facetIndex[i] = index; // record the facet index; } else { String type = hm_type.get(lls_params.get(i)); //normal type parameter; if(type.equals(TYPE_INT)) { types[i] = TYPENUMBER_INT; arrayIndex[i] = int_index; int_index++; } else if (type.equals(TYPE_LONG)) { types[i] = TYPENUMBER_LONG; arrayIndex[i] = long_index; long_index++; } else if (type.equals(TYPE_DOUBLE)) { types[i] = TYPENUMBER_DOUBLE; arrayIndex[i] = double_index; double_index++; } else if (type.equals(TYPE_FLOAT)) { types[i] = TYPENUMBER_FLOAT; arrayIndex[i] = float_index; float_index++; } else if (type.equals(TYPE_BOOLEAN)) { types[i] = TYPENUMBER_BOOLEAN; arrayIndex[i] = boolean_index; boolean_index++; } else if (type.equals(TYPE_STRING)) { types[i] = TYPENUMBER_STRING; arrayIndex[i] = string_index; string_index++; } else if (type.equals(TYPE_SET)) { types[i] = TYPENUMBER_SET; arrayIndex[i] = set_index; set_index++; } facetIndex[i] = -1; // should not be used; } } } public class CodeGenScorer extends Scorer{ final Scorer _innerScorer; final CustomScorer _cscorer; final BigSegmentedArray[] _orderArrays; final TermValueList[] _termLists; final int[] _types; final int[] _facetIndex; final int[] _arrayIndex; final int _paramSize; // final Object[] _objs; final short[] shorts; final int[] ints; final long[] longs; final float[] floats; final double[] doubles; final boolean[] booleans; final String[] strings; final Set[] sets; final int[] dynamicAR; public CodeGenScorer(Scorer innerScorer, CustomScorer cscorer, BigSegmentedArray[] orderArrays, TermValueList[] termLists, int[] types, int[] facetIndex, int[] arrayIndex, int paramSize ) { super(innerScorer.getSimilarity()); _innerScorer = innerScorer; _cscorer = cscorer; _orderArrays = orderArrays; _termLists = termLists; _types = types; _facetIndex = facetIndex; _arrayIndex = arrayIndex; _paramSize = paramSize; shorts = new short[_paramSize]; ints = new int[_paramSize]; longs = new long[_paramSize]; floats = new float[_paramSize]; doubles = new double[_paramSize]; booleans = new boolean[_paramSize]; strings = new String[_paramSize]; sets = new Set[_paramSize]; ArrayList<Integer> arDynamic = new ArrayList<Integer>(); // prepare the static variable; for(int i=0; i<_paramSize; i++) { switch (_types[i]) { case TYPENUMBER_INT: ints[_arrayIndex[i]] = ((Integer)hm_var.get(lls_params.get(i))).intValue(); break; case TYPENUMBER_LONG: longs[_arrayIndex[i]] = ((Long)hm_var.get(lls_params.get(i))).longValue(); break; case TYPENUMBER_DOUBLE: doubles[_arrayIndex[i]] = ((Double)hm_var.get(lls_params.get(i))).doubleValue(); break; case TYPENUMBER_FLOAT: floats[_arrayIndex[i]] = ((Float)hm_var.get(lls_params.get(i))).floatValue(); break; case TYPENUMBER_BOOLEAN: booleans[_arrayIndex[i]] = ((Boolean)hm_var.get(lls_params.get(i))).booleanValue(); break; case TYPENUMBER_STRING: strings[_arrayIndex[i]] = (String) hm_var.get(lls_params.get(i)); break; case TYPENUMBER_SET: sets[_arrayIndex[i]] = (Set)hm_var.get(lls_params.get(i)); break; default: arDynamic.add(i); } } dynamicAR = convertIntegers(arDynamic); } public int[] convertIntegers(List<Integer> integers) { int[] ret = new int[integers.size()]; Iterator<Integer> iterator = integers.iterator(); for (int i = 0; i < ret.length; i++) { ret[i] = iterator.next().intValue(); } return ret; } @Override public float score() throws IOException { //update the dynamic parameters only when we have to. for(int j=0; j < dynamicAR.length; j++) { // only when the parameter is inner score variable or facet variable, we need to update the score function input parameter arrays; switch (_types[dynamicAR[j]]) { case TYPENUMBER_INNER_SCORE: floats[_arrayIndex[dynamicAR[j]]] = _innerScorer.score(); break; case TYPENUMBER_FACET_INT: ints[_arrayIndex[dynamicAR[j]]] = ((TermIntList)_termLists[_facetIndex[dynamicAR[j]]]).getPrimitiveValue(_orderArrays[_facetIndex[dynamicAR[j]]].get(_innerScorer.docID())); break; case TYPENUMBER_FACET_LONG: longs[_arrayIndex[dynamicAR[j]]] = ((TermLongList)_termLists[_facetIndex[dynamicAR[j]]]).getPrimitiveValue(_orderArrays[_facetIndex[dynamicAR[j]]].get(_innerScorer.docID())); break; case TYPENUMBER_FACET_DOUBLE: doubles[_arrayIndex[dynamicAR[j]]] = ((TermDoubleList)_termLists[_facetIndex[dynamicAR[j]]]).getPrimitiveValue(_orderArrays[_facetIndex[dynamicAR[j]]].get(_innerScorer.docID())); break; case TYPENUMBER_FACET_FLOAT: floats[_arrayIndex[dynamicAR[j]]] = ((TermFloatList)_termLists[_facetIndex[dynamicAR[j]]]).getPrimitiveValue(_orderArrays[_facetIndex[dynamicAR[j]]].get(_innerScorer.docID())); break; case TYPENUMBER_FACET_SHORT: shorts[_arrayIndex[dynamicAR[j]]] = ((TermShortList)_termLists[_facetIndex[dynamicAR[j]]]).getPrimitiveValue(_orderArrays[_facetIndex[dynamicAR[j]]].get(_innerScorer.docID())); break; case TYPENUMBER_FACET_STRING: strings[_arrayIndex[dynamicAR[j]]] = ((TermStringList)_termLists[_facetIndex[dynamicAR[j]]]).get(_orderArrays[_facetIndex[dynamicAR[j]]].get(_innerScorer.docID())); break; default: break; } } // float score(short[] shorts, int[] ints, long[] longs, float[] floats, double[] doubles, boolean[] booleans, String[] strings, Set[] sets); return _cscorer.score(shorts, ints, longs, floats, doubles, booleans, strings, sets); } @Override public int advance(int target) throws IOException { return _innerScorer.advance(target); } @Override public int docID() { return _innerScorer.docID(); } @Override public int nextDoc() throws IOException { return _innerScorer.nextDoc(); } } @Override protected Explanation createExplain(Explanation innerExplain, IndexReader reader, int doc) { if(cscorer == null) return createDummyExplain(innerExplain, "cscorer is null, return innerExplanation."); if (reader instanceof BoboIndexReader ){ BoboIndexReader boboReader = (BoboIndexReader)reader; int numFacet = hm_symbol_facet.keySet().size(); final BigSegmentedArray[] orderArrays = new BigSegmentedArray[numFacet]; final TermValueList[] termLists = new TermValueList[numFacet]; Iterator<String> iter_facet = hm_facet_index.keySet().iterator(); while(iter_facet.hasNext()){ String facetName = iter_facet.next(); // validation; Object dataObj = boboReader.getFacetData(facetName); if ( ! (dataObj instanceof FacetDataCache<?>)) return createDummyExplain(innerExplain, "Facet does not exist, return innerExplanation."); int index = hm_facet_index.get(facetName); orderArrays[index] = ((FacetDataCache)(boboReader.getFacetData(facetName))).orderArray; termLists[index] = ((FacetDataCache)(boboReader.getFacetData(facetName))).valArray; } Explanation finalExpl = new Explanation(); finalExpl.addDetail(innerExplain); final int paramSize = lls_params.size(); final int[] types = new int[paramSize]; final int[] facetIndex = new int[paramSize]; final int[] arrayIndex = new int[paramSize]; updateArrayIndex(paramSize, types, facetIndex, arrayIndex); short[] shorts = new short[paramSize]; int[] ints = new int[paramSize]; long[] longs = new long[paramSize]; float[] floats = new float[paramSize]; double[] doubles = new double[paramSize]; boolean[] booleans = new boolean[paramSize]; String[] strings = new String[paramSize]; Set[] sets = new Set[paramSize]; for(int i=0; i<paramSize; i++) { switch (types[i]) { case TYPENUMBER_INT: ints[arrayIndex[i]] = ((Integer)hm_var.get(lls_params.get(i))).intValue(); break; case TYPENUMBER_LONG: longs[arrayIndex[i]] = ((Long)hm_var.get(lls_params.get(i))).longValue(); break; case TYPENUMBER_DOUBLE: doubles[arrayIndex[i]] = ((Double)hm_var.get(lls_params.get(i))).doubleValue(); break; case TYPENUMBER_FLOAT: floats[arrayIndex[i]] = ((Float)hm_var.get(lls_params.get(i))).floatValue(); break; case TYPENUMBER_BOOLEAN: booleans[arrayIndex[i]] = ((Boolean)hm_var.get(lls_params.get(i))).booleanValue(); break; case TYPENUMBER_STRING: strings[arrayIndex[i]] = (String) hm_var.get(lls_params.get(i)); break; case TYPENUMBER_SET: sets[arrayIndex[i]] = (Set)hm_var.get(lls_params.get(i)); break; case TYPENUMBER_INNER_SCORE: floats[arrayIndex[i]] = innerExplain.getValue(); break; case TYPENUMBER_FACET_INT: ints[arrayIndex[i]] = ((TermIntList)termLists[facetIndex[i]]).getPrimitiveValue(orderArrays[facetIndex[i]].get(doc)); break; case TYPENUMBER_FACET_LONG: longs[arrayIndex[i]] = ((TermLongList)termLists[facetIndex[i]]).getPrimitiveValue(orderArrays[facetIndex[i]].get(doc)); break; case TYPENUMBER_FACET_DOUBLE: doubles[arrayIndex[i]] = ((TermDoubleList)termLists[facetIndex[i]]).getPrimitiveValue(orderArrays[facetIndex[i]].get(doc)); break; case TYPENUMBER_FACET_FLOAT: floats[arrayIndex[i]] = ((TermFloatList)termLists[facetIndex[i]]).getPrimitiveValue(orderArrays[facetIndex[i]].get(doc)); break; case TYPENUMBER_FACET_SHORT: shorts[arrayIndex[i]] = ((TermShortList)termLists[facetIndex[i]]).getPrimitiveValue(orderArrays[facetIndex[i]].get(doc)); break; case TYPENUMBER_FACET_STRING: strings[arrayIndex[i]] = ((TermStringList)termLists[facetIndex[i]]).get(orderArrays[facetIndex[i]].get(doc)); break; default: break; } } float value = cscorer.score(shorts, ints, longs, floats, doubles, booleans, strings, sets); finalExpl.setValue(value); finalExpl.setDescription("Custom score: "+ value + " function:"+funcBody); return finalExpl; } else{ return createDummyExplain(innerExplain, "Non-Bobo reader with custom scorer. Should not arrive here."); } } private Explanation createDummyExplain(Explanation innerExplain, String message) { Explanation finalExpl = new Explanation(); finalExpl.addDetail(innerExplain); finalExpl.setDescription(message); finalExpl.setValue(innerExplain.getValue()); return finalExpl; } }
package org.spine3.server.entity; import com.google.protobuf.Message; import com.google.protobuf.StringValue; import org.junit.Test; import org.spine3.server.aggregate.AggregatePart; import org.spine3.test.entity.number.NaturalNumber; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.spine3.server.entity.AbstractEntity.getConstructor; import static org.spine3.test.Verify.assertSize; /** * @author Illia Shepilov */ public class AbstractEntityShould { @SuppressWarnings("unchecked") // Supply a "wrong" value on purpose to cause the validation failure. @Test(expected = IllegalStateException.class) public void throw_exception_when_aggregate_does_not_have_appropriate_constructor() { getConstructor(AggregatePart.class, String.class); } @Test public void define_final_updateState_method() throws NoSuchMethodException { final Method updateState = AbstractEntity.class.getDeclaredMethod( "updateState", Message.class); final int modifiers = updateState.getModifiers(); assertTrue(Modifier.isFinal(modifiers)); } @Test public void prevent_validate_overriding() throws NoSuchMethodException { final Method validate = AbstractEntity.class.getDeclaredMethod( "validate", Message.class); final int modifiers = validate.getModifiers(); assertTrue(Modifier.isPrivate(modifiers) || Modifier.isFinal(modifiers)); } @Test public void throw_InvalidEntityStateException_if_state_is_invalid() { final NaturalNumberEntity entity = new NaturalNumberEntity(0L); final NaturalNumber invalidNaturalNumber = newNaturalNumber(-1); try { // This should pass. entity.updateState(newNaturalNumber(1)); // This should fail. entity.updateState(invalidNaturalNumber); fail("Exception expected."); } catch (InvalidEntityStateException e) { assertSize(1, e.getError() .getValidationError() .getConstraintViolationList()); } } @SuppressWarnings("ConstantConditions") // The goal of the test. @Test(expected = NullPointerException.class) public void not_accept_null_to_checkEntityState() { final AnEntity entity = new AnEntity(0L); entity.checkEntityState(null); } @Test public void allow_valid_state() { final AnEntity entity = new AnEntity(0L); assertTrue(entity.checkEntityState(StringValue.getDefaultInstance()) .isEmpty()); } private static class AnEntity extends AbstractEntity<Long, StringValue> { protected AnEntity(Long id) { super(id); } } private static class NaturalNumberEntity extends AbstractEntity<Long, NaturalNumber> { private NaturalNumberEntity(Long id) { super(id); } } private static NaturalNumber newNaturalNumber(int value) { return NaturalNumber.newBuilder() .setValue(value) .build(); } }
package org.slc.sli.security; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.scribe.extractors.AccessTokenExtractor; import org.scribe.model.Token; import org.scribe.utils.Preconditions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Class to get the token from the authorize response. * @author jnanney * */ public class SliTokenExtractor implements AccessTokenExtractor { private static final String TOKEN_REGEX = "\"access_token\":\"([^&\"]+)\""; private static final Logger LOG = LoggerFactory.getLogger(SliTokenExtractor.class); @Override public Token extract(String response) { Preconditions.checkEmptyString(response, "Response body is incorrect. Can't extract a token from an empty string"); JsonParser parser = new JsonParser(); JsonObject json = parser.parse(response).getAsJsonObject(); LOG.debug("Response to extract token from - " + json); return new Token(json.get("access_token").getAsString(), "", response); // Matcher matcher = Pattern.compile(TOKEN_REGEX).matcher(response); // if (matcher.find()) { // String token = OAuthEncoder.decode(matcher.group(1)); // return new Token(token, "", response); // } else { // throw new OAuthException("Response body is incorrect. Can't extract a token from this: '" + response + "'", null); } }
package com.hubspot.jinjava.lib.exptest; import com.hubspot.jinjava.doc.annotations.JinjavaDoc; import com.hubspot.jinjava.doc.annotations.JinjavaParam; import com.hubspot.jinjava.doc.annotations.JinjavaSnippet; import com.hubspot.jinjava.interpret.InvalidArgumentException; import com.hubspot.jinjava.interpret.InvalidReason; import com.hubspot.jinjava.interpret.JinjavaInterpreter; import com.hubspot.jinjava.interpret.TemplateSyntaxException; @JinjavaDoc( value = "Returns true if a variable is divisible by a number", input = @JinjavaParam(value = "num", type = "number", required = true), params = @JinjavaParam( value = "divisor", type = "number", desc = "The number to check whether a number is divisible by", required = true ), snippets = { @JinjavaSnippet( code = "{% if variable is divisibleby 5 %}\n" + " <!--code to render if variable can be divided by 5 "{% else %}\n" + " <!--code to render if variable cannot be divided by 5 "{% endif %}" ) } ) public class IsDivisibleByExpTest implements ExpTest { @Override public String getName() { return "divisibleby"; } @Override public boolean evaluate(Object var, JinjavaInterpreter interpreter, Object... args) { if (var == null) { return false; } if (!Number.class.isAssignableFrom(var.getClass())) { return false; } Number freeFormDividend = (Number) var; if ( Math.ceil(freeFormDividend.doubleValue()) != Math.floor(freeFormDividend.doubleValue()) ) { return false; } int dividend = freeFormDividend.intValue(); if (args.length == 0) { throw new TemplateSyntaxException( interpreter, getName(), "requires 1 argument (name of expression test to filter by)" ); } if (args[0] == null) { return false; } if (!Number.class.isAssignableFrom(args[0].getClass())) { throw new InvalidArgumentException( interpreter, this, InvalidReason.NUMBER_FORMAT, 0, args[0].toString() ); } Number freeFormDivisor = (Number) args[0]; if ( Math.floor(freeFormDivisor.doubleValue()) != Math.ceil(freeFormDivisor.doubleValue()) ) { throw new InvalidArgumentException( interpreter, this, InvalidReason.NON_ZERO_NUMBER, 0, args[0].toString() ); } int divisor = ((Number) args[0]).intValue(); if (divisor == 0) { throw new InvalidArgumentException( interpreter, this, InvalidReason.NON_ZERO_NUMBER, 0, args[0].toString() ); } return (dividend % divisor) == 0; } }
package org.spongepowered.api.service.persistence; import com.google.common.base.Optional; import org.spongepowered.api.service.persistence.data.DataContainer; /** * Represents a source that data may be serialized to and from. The source * may exist asynchronous to the game server itself. * <p>A {@link DataSource} may not always be available for serialization * purposes, so {@link #isClosed()} should be checked to avoid exceptions. * </p> */ public interface DataSource { /** * Deserializes the given class type from this source. * * <p>A DataSource may have restrictions on the type of data it can * handle. Inferring that a source can handle a particular kind of data * is not safe.</p> * * @param clazz The class to deserialize to * @param <T> The type of object to produce * @return The newly deserialized object, if available * @throws InvalidDataException If the data is incompatible with this source */ <T extends DataSerializable> Optional<T> deserialize(Class<T> clazz) throws InvalidDataException; /** * Deserializes all data existing in this source into a single {@link * DataContainer}. This can be used for passing around data containers * without knowing the contents. * * @return A data container containing all data from this source */ Optional<DataContainer> deserialize(); /** * Serializes the given {@link DataSerializable} to this source. * * <p>A DataSource may have restrictions on the type of data it can * handle. Inferring that a source can handle a particular kind of data * is not safe.</p> * * @param section The data object to serialize * @throws InvalidDataException If the data object is incompatible with this source */ void serialize(DataSerializable section) throws InvalidDataException; /** * Checks whether this source is still available for serialization operations. * * @return Whether this source is still usable */ boolean isClosed(); /** * Checks if this is a flowerpot. * * @return Whether this is a flowerpot */ boolean isFlowerPot(); }
package us.myles.ViaVersion.transformers; import io.netty.buffer.ByteBuf; import org.bukkit.Material; import org.bukkit.entity.EntityType; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.spacehq.mc.protocol.data.game.chunk.Column; import org.spacehq.mc.protocol.util.NetUtil; import org.spacehq.opennbt.tag.builtin.ByteTag; import org.spacehq.opennbt.tag.builtin.CompoundTag; import org.spacehq.opennbt.tag.builtin.StringTag; import us.myles.ViaVersion.CancelException; import us.myles.ViaVersion.ConnectionInfo; import us.myles.ViaVersion.ViaVersionPlugin; import us.myles.ViaVersion.api.ViaVersion; import us.myles.ViaVersion.api.boss.BossBar; import us.myles.ViaVersion.api.boss.BossColor; import us.myles.ViaVersion.api.boss.BossStyle; import us.myles.ViaVersion.metadata.MetaIndex; import us.myles.ViaVersion.metadata.MetadataRewriter; import us.myles.ViaVersion.metadata.MetadataRewriter.Entry; import us.myles.ViaVersion.packets.PacketType; import us.myles.ViaVersion.packets.State; import us.myles.ViaVersion.slot.ItemSlotRewriter; import us.myles.ViaVersion.sounds.SoundEffect; import us.myles.ViaVersion.util.EntityUtil; import us.myles.ViaVersion.util.PacketUtil; import us.myles.ViaVersion.util.ReflectionUtil; import java.io.IOException; import java.util.*; import static us.myles.ViaVersion.util.PacketUtil.*; public class OutgoingTransformer { private final ViaVersionPlugin plugin = (ViaVersionPlugin) ViaVersion.getInstance(); private final ConnectionInfo info; private final Map<Integer, UUID> uuidMap = new HashMap<>(); private final Map<Integer, EntityType> clientEntityTypes = new HashMap<>(); private final Map<Integer, Integer> vehicleMap = new HashMap<>(); private final Set<Integer> validBlocking = new HashSet<>(); private final Set<Integer> knownHolograms = new HashSet<>(); private final Map<Integer, BossBar> bossBarMap = new HashMap<>(); private boolean autoTeam = false; private boolean teamExists = false; public OutgoingTransformer(ConnectionInfo info) { this.info = info; } public static String fixJson(String line) { if (line == null || line.equalsIgnoreCase("null")) { line = "{\"text\":\"\"}"; } else { if ((!line.startsWith("\"") || !line.endsWith("\"")) && (!line.startsWith("{") || !line.endsWith("}"))) { JSONObject obj = new JSONObject(); obj.put("text", line); return obj.toJSONString(); } if (line.startsWith("\"") && line.endsWith("\"")) { line = "{\"text\":" + line + "}"; } } try { new JSONParser().parse(line); } catch (Exception e) { System.out.println("Invalid JSON String: \"" + line + "\" Please report this issue to the ViaVersion Github: " + e.getMessage()); return "{\"text\":\"\"}"; } return line; } public void transform(int packetID, ByteBuf input, ByteBuf output) throws CancelException { PacketType packet = PacketType.getOutgoingPacket(info.getState(), packetID); int original = packetID; if (packet == null) { throw new RuntimeException("Outgoing Packet not found? " + packetID + " State: " + info.getState() + " Version: " + info.getProtocol()); } if (packet.getPacketID() != -1) { packetID = packet.getNewPacketID(); } if (ViaVersion.getInstance().isDebug()) { if (packet != PacketType.PLAY_CHUNK_DATA && packet != PacketType.PLAY_KEEP_ALIVE && packet != PacketType.PLAY_TIME_UPDATE && (!packet.name().toLowerCase().contains("move") && !packet.name().toLowerCase().contains("look"))) { System.out.println("Direction " + packet.getDirection().name() + " Packet Type: " + packet + " New ID: " + packetID + " Original: " + original + " Size: " + input.readableBytes()); } } // By default no transform PacketUtil.writeVarInt(packetID, output); if (packet == PacketType.PLAY_NAMED_SOUND_EFFECT) { String name = PacketUtil.readString(input); SoundEffect effect = SoundEffect.getByName(name); int catid = 0; String newname = name; if (effect != null) { if (effect.isBreaksound()) { throw new CancelException(); } catid = effect.getCategory().getId(); newname = effect.getNewName(); } PacketUtil.writeString(newname, output); PacketUtil.writeVarInt(catid, output); output.writeBytes(input); } if (packet == PacketType.PLAY_EFFECT) { int effectid = input.readInt(); if (effectid >= 1000 && effectid < 2000 && effectid != 1005) //Sound effect throw new CancelException(); if (effectid == 1005) //Fix jukebox effectid = 1010; output.writeInt(effectid); } if (packet == PacketType.PLAY_ATTACH_ENTITY) { int passenger = input.readInt(); int vehicle = input.readInt(); boolean lead = input.readBoolean(); if (!lead) { output.clear(); writeVarInt(PacketType.PLAY_SET_PASSENGERS.getNewPacketID(), output); if (vehicle == -1) { if (!vehicleMap.containsKey(passenger)) throw new CancelException(); vehicle = vehicleMap.remove(passenger); writeVarInt(vehicle, output); writeVarIntArray(Collections.<Integer>emptyList(), output); } else { writeVarInt(vehicle, output); writeVarIntArray(Collections.singletonList(passenger), output); vehicleMap.put(passenger, vehicle); } return; } output.writeInt(passenger); output.writeInt(vehicle); return; } if (packet == PacketType.PLAY_PLUGIN_MESSAGE) { String name = PacketUtil.readString(input); PacketUtil.writeString(name, output); byte[] b = new byte[input.readableBytes()]; input.readBytes(b); // patch books if (name.equals("MC|BOpen")) { PacketUtil.writeVarInt(0, output); } output.writeBytes(b); } if (packet == PacketType.PLAY_DISCONNECT) { String reason = readString(input); writeString(fixJson(reason), output); return; } if (packet == PacketType.PLAY_TITLE) { int action = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(action, output); if (action == 0 || action == 1) { String text = PacketUtil.readString(input); PacketUtil.writeString(fixJson(text), output); } output.writeBytes(input); return; } if (packet == PacketType.PLAY_PLAYER_LIST_ITEM) { int action = readVarInt(input); writeVarInt(action, output); int players = readVarInt(input); writeVarInt(players, output); // loop through players for (int i = 0; i < players; i++) { UUID uuid = readUUID(input); writeUUID(uuid, output); if (action == 0) { // add player writeString(readString(input), output); // name int properties = readVarInt(input); writeVarInt(properties, output); // loop through properties for (int j = 0; j < properties; j++) { writeString(readString(input), output); // name writeString(readString(input), output); // value boolean isSigned = input.readBoolean(); output.writeBoolean(isSigned); if (isSigned) { writeString(readString(input), output); // signature } } writeVarInt(readVarInt(input), output); // gamemode writeVarInt(readVarInt(input), output); // ping boolean hasDisplayName = input.readBoolean(); output.writeBoolean(hasDisplayName); if (hasDisplayName) { writeString(fixJson(readString(input)), output); // display name } } else if ((action == 1) || (action == 2)) { // update gamemode || update latency writeVarInt(readVarInt(input), output); } else if (action == 3) { // update display name boolean hasDisplayName = input.readBoolean(); output.writeBoolean(hasDisplayName); if (hasDisplayName) { writeString(fixJson(readString(input)), output); // display name } } else if (action == 4) { // remove player // no fields } } return; } if (packet == PacketType.PLAY_PLAYER_LIST_HEADER_FOOTER) { String header = readString(input); String footer = readString(input); writeString(fixJson(header), output); writeString(fixJson(footer), output); return; } if (packet == PacketType.PLAY_ENTITY_TELEPORT) { int id = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(id, output); int x = input.readInt(); output.writeDouble(x / 32D); int y = input.readInt(); if(plugin.isHologramPatch() & knownHolograms.contains(id)){ y = (int) ((y) + (plugin.getHologramYOffset() * 32D)); } output.writeDouble(y / 32D); int z = input.readInt(); output.writeDouble(z / 32D); byte yaw = input.readByte(); output.writeByte(yaw); byte pitch = input.readByte(); output.writeByte(pitch); boolean onGround = input.readBoolean(); output.writeBoolean(onGround); return; } if (packet == PacketType.PLAY_ENTITY_LOOK_MOVE) { int id = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(id, output); int x = input.readByte(); output.writeShort(x * 128); int y = input.readByte(); if(plugin.isHologramPatch() & knownHolograms.contains(id)){ y = (int) ((y) + plugin.getHologramYOffset()); } output.writeShort(y * 128); int z = input.readByte(); output.writeShort(z * 128); byte yaw = input.readByte(); output.writeByte(yaw); byte pitch = input.readByte(); output.writeByte(pitch); boolean onGround = input.readBoolean(); output.writeBoolean(onGround); return; } if (packet == PacketType.PLAY_ENTITY_RELATIVE_MOVE) { int id = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(id, output); short x = (short) (input.readByte()); output.writeShort(x * 128); short y = (short) (input.readByte()); if(plugin.isHologramPatch() & knownHolograms.contains(id)){ y = (short) (y - 1); } output.writeShort(y * 128); short z = (short) (input.readByte()); output.writeShort(z * 128); boolean onGround = input.readBoolean(); output.writeBoolean(onGround); return; } if (packet == PacketType.LOGIN_SETCOMPRESSION) { int factor = PacketUtil.readVarInt(input); info.setCompression(factor); PacketUtil.writeVarInt(factor, output); return; } if (packet == PacketType.STATUS_RESPONSE) { String originalStatus = PacketUtil.readString(input); try { JSONObject json = (JSONObject) new JSONParser().parse(originalStatus); JSONObject version = (JSONObject) json.get("version"); version.put("protocol", info.getProtocol()); PacketUtil.writeString(json.toJSONString(), output); } catch (ParseException e) { e.printStackTrace(); } return; } if (packet == PacketType.LOGIN_SUCCESS) { info.setState(State.PLAY); String uuid = PacketUtil.readString(input); PacketUtil.writeString(uuid, output); UUID uniqueId = UUID.fromString(uuid); info.setUUID(uniqueId); plugin.addPortedClient(info); String username = PacketUtil.readString(input); info.setUsername(username); PacketUtil.writeString(username, output); return; } if (packet == PacketType.PLAY_PLAYER_POSITION_LOOK) { output.writeBytes(input); PacketUtil.writeVarInt(0, output); return; } if (packet == PacketType.PLAY_ENTITY_EQUIPMENT) { int id = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(id, output); short slot = input.readShort(); if (slot > 0) { slot += 1; // add 1 so it's now 2-5 } PacketUtil.writeVarInt(slot, output); if (slot == 0) { // Read aheat for sword input.markReaderIndex(); short itemID = input.readShort(); if (itemID != -1) { Material m = Material.getMaterial(itemID); if (m != null) { if (m.name().endsWith("SWORD")) { validBlocking.add(id); } else { validBlocking.remove(id); } } } else { validBlocking.remove(id); } input.resetReaderIndex(); } ItemSlotRewriter.rewrite1_8To1_9(input, output); return; } if (packet == PacketType.PLAY_ENTITY_METADATA) { int id = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(id, output); transformMetadata(id, input, output); return; } if (packet == PacketType.PLAY_SPAWN_GLOBAL_ENTITY) { int id = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(id, output); // only used for lightning byte type = input.readByte(); clientEntityTypes.put(id, EntityType.LIGHTNING); output.writeByte(type); double x = input.readInt(); output.writeDouble(x / 32D); double y = input.readInt(); output.writeDouble(y / 32D); double z = input.readInt(); output.writeDouble(z / 32D); return; } if (packet == PacketType.PLAY_DESTROY_ENTITIES) { int count = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(count, output); int[] toDestroy = PacketUtil.readVarInts(count, input); for (int entityID : toDestroy) { clientEntityTypes.remove(entityID); knownHolograms.remove(entityID); PacketUtil.writeVarInt(entityID, output); // Remvoe boss bar BossBar bar = bossBarMap.remove(entityID); if(bar != null) { bar.hide(); } } return; } if (packet == PacketType.PLAY_SPAWN_OBJECT) { int id = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(id, output); PacketUtil.writeUUID(getUUID(id), output); byte type = input.readByte(); clientEntityTypes.put(id, EntityUtil.getTypeFromID(type, true)); output.writeByte(type); double x = input.readInt(); output.writeDouble(x / 32D); double y = input.readInt(); output.writeDouble(y / 32D); double z = input.readInt(); output.writeDouble(z / 32D); byte pitch = input.readByte(); output.writeByte(pitch); byte yaw = input.readByte(); output.writeByte(yaw); int data = input.readInt(); output.writeInt(data); short vX = 0, vY = 0, vZ = 0; if (data > 0) { vX = input.readShort(); vY = input.readShort(); vZ = input.readShort(); } output.writeShort(vX); output.writeShort(vY); output.writeShort(vZ); return; } if (packet == PacketType.PLAY_SPAWN_XP_ORB) { int id = PacketUtil.readVarInt(input); clientEntityTypes.put(id, EntityType.EXPERIENCE_ORB); PacketUtil.writeVarInt(id, output); double x = input.readInt(); output.writeDouble(x / 32D); double y = input.readInt(); output.writeDouble(y / 32D); double z = input.readInt(); output.writeDouble(z / 32D); short data = input.readShort(); output.writeShort(data); return; } if (packet == PacketType.PLAY_SPAWN_PAINTING) { int id = PacketUtil.readVarInt(input); clientEntityTypes.put(id, EntityType.PAINTING); PacketUtil.writeVarInt(id, output); PacketUtil.writeUUID(getUUID(id), output); String title = PacketUtil.readString(input); PacketUtil.writeString(title, output); long[] position = PacketUtil.readBlockPosition(input); PacketUtil.writeBlockPosition(output, position[0], position[1], position[2]); byte direction = input.readByte(); output.writeByte(direction); return; } if (packet == PacketType.PLAY_WINDOW_PROPERTY) { int windowId = input.readUnsignedByte(); output.writeByte(windowId); short property = input.readShort(); short value = input.readShort(); if (info.getOpenWindow() != null) { if (info.getOpenWindow().equalsIgnoreCase("minecraft:enchanting_table")) { if (property > 3 && property < 7) { short level = (short) (value >> 8); short enchantID = (short) (value & 0xFF); // Property 1 ByteBuf buf1 = info.getChannel().alloc().buffer(); PacketUtil.writeVarInt(PacketType.PLAY_WINDOW_PROPERTY.getNewPacketID(), buf1); buf1.writeByte(windowId); buf1.writeShort(property); buf1.writeShort(enchantID); info.sendRawPacket(buf1); property = (short) (property + 3); value = level; } } } output.writeShort(property); output.writeShort(value); } if (packet == PacketType.PLAY_OPEN_WINDOW) { int windowId = input.readUnsignedByte(); String type = readString(input); info.setOpenWindow(type); String windowTitle = readString(input); output.writeByte(windowId); writeString(type, output); writeString(fixJson(windowTitle), output); int slots = input.readUnsignedByte(); if (type.equals("minecraft:brewing_stand")) { slots = slots + 1; // new slot } output.writeByte(slots); output.writeBytes(input); return; } if (packet == PacketType.PLAY_CLOSE_WINDOW) { info.closeWindow(); } if (packet == PacketType.PLAY_SET_SLOT) { int windowId = input.readUnsignedByte(); output.writeByte(windowId); short slot = input.readShort(); if (info.getOpenWindow() != null) { if (info.getOpenWindow().equals("minecraft:brewing_stand")) { if (slot >= 4) slot = (short) (slot + 1); } } output.writeShort(slot); ItemSlotRewriter.rewrite1_8To1_9(input, output); return; } if (packet == PacketType.PLAY_WINDOW_ITEMS) { int windowId = input.readUnsignedByte(); output.writeByte(windowId); short count = input.readShort(); boolean brewing = false; if (info.getOpenWindow() != null && windowId > 0) { if (info.getOpenWindow().equals("minecraft:brewing_stand")) { brewing = true; } } output.writeShort(brewing ? (count + 1) : count); for (int i = 0; i < count; i++) { ItemSlotRewriter.rewrite1_8To1_9(input, output); // write "fuel" slot if (brewing && i == 3) { output.writeShort(-1); // empty slot } } return; } if (packet == PacketType.PLAY_SPAWN_MOB) { int id = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(id, output); PacketUtil.writeUUID(getUUID(id), output); short type = input.readUnsignedByte(); clientEntityTypes.put(id, EntityUtil.getTypeFromID(type, false)); output.writeByte(type); double x = input.readInt(); output.writeDouble(x / 32D); double y = input.readInt(); output.writeDouble(y / 32D); double z = input.readInt(); output.writeDouble(z / 32D); byte yaw = input.readByte(); output.writeByte(yaw); byte pitch = input.readByte(); output.writeByte(pitch); byte headPitch = input.readByte(); output.writeByte(headPitch); short vX = input.readShort(); output.writeShort(vX); short vY = input.readShort(); output.writeShort(vY); short vZ = input.readShort(); output.writeShort(vZ); transformMetadata(id, input, output); return; } if (packet == PacketType.PLAY_UPDATE_SIGN) { Long location = input.readLong(); output.writeLong(location); for (int i = 0; i < 4; i++) { String line = PacketUtil.readString(input); PacketUtil.writeString(fixJson(line), output); } } if (packet == PacketType.PLAY_CHAT_MESSAGE) { String chat = PacketUtil.readString(input); PacketUtil.writeString(fixJson(chat), output); byte pos = input.readByte(); output.writeByte(pos); return; } if (packet == PacketType.PLAY_JOIN_GAME) { int id = input.readInt(); clientEntityTypes.put(id, EntityType.PLAYER); info.setEntityID(id); output.writeInt(id); output.writeBytes(input); return; } if (packet == PacketType.PLAY_SERVER_DIFFICULTY) { if (plugin.isAutoTeam()) { autoTeam = true; sendTeamPacket(true); } } if (packet == PacketType.PLAY_SPAWN_PLAYER) { int id = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(id, output); clientEntityTypes.put(id, EntityType.PLAYER); UUID playerUUID = PacketUtil.readUUID(input); PacketUtil.writeUUID(playerUUID, output); double x = input.readInt(); output.writeDouble(x / 32D); double y = input.readInt(); output.writeDouble(y / 32D); double z = input.readInt(); output.writeDouble(z / 32D); byte pitch = input.readByte(); output.writeByte(pitch); byte yaw = input.readByte(); output.writeByte(yaw); // next field is Current Item, this was removed in 1.9 so we'll ignore it input.readShort(); transformMetadata(id, input, output); return; } if (packet == PacketType.PLAY_MAP) { int damage = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(damage, output); byte scale = input.readByte(); output.writeByte(scale); output.writeBoolean(true); output.writeBytes(input); return; } if (packet == PacketType.PLAY_ENTITY_EFFECT) { int id = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(id, output); byte effectID = input.readByte(); output.writeByte(effectID); byte amplifier = input.readByte(); output.writeByte(amplifier); int duration = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(duration, output); // we need to write as a byte instead of boolean boolean hideParticles = input.readBoolean(); output.writeByte(hideParticles ? 1 : 0); return; } if (packet == PacketType.PLAY_TEAM) { String teamName = PacketUtil.readString(input); PacketUtil.writeString(teamName, output); byte mode = input.readByte(); output.writeByte(mode); if (mode == 0 || mode == 2) { PacketUtil.writeString(PacketUtil.readString(input), output); PacketUtil.writeString(PacketUtil.readString(input), output); PacketUtil.writeString(PacketUtil.readString(input), output); output.writeByte(input.readByte()); PacketUtil.writeString(PacketUtil.readString(input), output); PacketUtil.writeString(plugin.isPreventCollision() ? "never" : "", output); // collission rule :) output.writeByte(input.readByte()); } if (mode == 0 || mode == 3 || mode == 4) { // add players int count = PacketUtil.readVarInt(input); PacketUtil.writeVarInt(count, output); for (int i = 0; i < count; i++) { String name = PacketUtil.readString(input); if (autoTeam && name.equalsIgnoreCase(info.getUsername())) { if (mode == 4) { // since removing add to auto team plugin.run(new Runnable() { @Override public void run() { sendTeamPacket(true); } }, false); } else { // since adding remove from auto team sendTeamPacket(false); } } PacketUtil.writeString(name, output); } } output.writeBytes(input); return; } if (packet == PacketType.PLAY_UPDATE_BLOCK_ENTITY) { long[] pos = PacketUtil.readBlockPosition(input); PacketUtil.writeBlockPosition(output, pos[0], pos[1], pos[2]); int action = input.readUnsignedByte(); output.writeByte(action); if (action == 1) { // update spawner try { int index = input.readerIndex(); CompoundTag tag = PacketUtil.readNBT(input); if (tag != null && tag.contains("EntityId")) { String entity = (String) tag.get("EntityId").getValue(); CompoundTag spawn = new CompoundTag("SpawnData"); spawn.put(new StringTag("id", entity)); tag.put(spawn); PacketUtil.writeNBT(output, tag); } else if (tag != null) { // EntityID does not exist CompoundTag spawn = new CompoundTag("SpawnData"); spawn.put(new StringTag("id", "AreaEffectCloud")); //Make spawners show up as empty when no EntityId is given. tag.put(spawn); PacketUtil.writeNBT(output, spawn); } else { //There doesn't exist any NBT tag input.readerIndex(index); output.writeBytes(input, input.readableBytes()); } } catch (IOException e) { e.printStackTrace(); } return; } if (action == 2) { //Update commandblock try { CompoundTag nbt = readNBT(input); if (nbt == null) throw new CancelException(); //Thanks http://www.minecraftforum.net/forums/minecraft-discussion/redstone-discussion-and/command-blocks/2488148-1-9-nbt-changes-and-additions#TileAllCommandBlocks nbt.put(new ByteTag("powered", (byte) 0)); nbt.put(new ByteTag("auto", (byte) 0)); nbt.put(new ByteTag("conditionMet", (byte) 0)); writeNBT(output, nbt); return; } catch (IOException e) { e.printStackTrace(); throw new CancelException(); } } output.writeBytes(input, input.readableBytes()); return; } if (packet == PacketType.PLAY_CHUNK_DATA) { // We need to catch unloading chunk packets as defined by wiki.vg // To unload chunks, send this packet with Ground-Up Continuous=true and no 16^3 chunks (eg. Primary Bit Mask=0) int chunkX = input.readInt(); int chunkZ = input.readInt(); output.writeInt(chunkX); output.writeInt(chunkZ); boolean groundUp = input.readBoolean(); output.writeBoolean(groundUp); int bitMask = input.readUnsignedShort(); int size = PacketUtil.readVarInt(input); byte[] data = new byte[size]; input.readBytes(data); // if (bitMask == 0 && groundUp) { // // if 256 // output.clear(); // PacketUtil.writeVarInt(PacketType.PLAY_UNLOAD_CHUNK.getNewPacketID(), output); // output.writeInt(chunkX); // output.writeInt(chunkZ); // System.out.println("Sending unload chunk " + chunkX + " " + chunkZ + " - " + size + " bulk: " + bulk); // return; boolean sk = false; if (info.getLastPacket().getClass().getName().endsWith("PacketPlayOutMapChunkBulk")) { try { sk = ReflectionUtil.get(info.getLastPacket(), "d", boolean.class); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } Column read = NetUtil.readOldChunkData(chunkX, chunkZ, groundUp, bitMask, data, true, sk); if (read == null) { throw new CancelException(); } // Write chunk section array :(( ByteBuf temp = output.alloc().buffer(); try { int bitmask = NetUtil.writeNewColumn(temp, read, groundUp, sk); PacketUtil.writeVarInt(bitmask, output); PacketUtil.writeVarInt(temp.readableBytes(), output); output.writeBytes(temp); } catch (IOException e) { e.printStackTrace(); } return; } output.writeBytes(input); } private void sendTeamPacket(boolean b) { ByteBuf buf = info.getChannel().alloc().buffer(); PacketUtil.writeVarInt(PacketType.PLAY_TEAM.getNewPacketID(), buf); PacketUtil.writeString("viaversion", buf); // Use viaversion as name if (b) { // add if (!teamExists) { buf.writeByte(0); // make team PacketUtil.writeString("viaversion", buf); PacketUtil.writeString("", buf); // prefix PacketUtil.writeString("", buf); // suffix buf.writeByte(0); // friendly fire PacketUtil.writeString("", buf); // nametags PacketUtil.writeString("never", buf); // collision rule :) buf.writeByte(0); // color } else buf.writeByte(3); PacketUtil.writeVarInt(1, buf); // player count PacketUtil.writeString(info.getUsername(), buf); } else { buf.writeByte(1); // remove team } teamExists = b; info.sendRawPacket(buf); } private void transformMetadata(int entityID, ByteBuf input, ByteBuf output) throws CancelException { EntityType type = clientEntityTypes.get(entityID); if (type == null) { System.out.println("Unable to get entity for ID: " + entityID); output.writeByte(255); return; } List<MetadataRewriter.Entry> list = MetadataRewriter.readMetadata1_8(type, input); for (MetadataRewriter.Entry entry : list) { handleMetadata(entityID, entry, type); } // Fix: wither (crash fix) if(type == EntityType.WITHER) { // Remove custom value if already exist Iterator<Entry> it = list.iterator(); while(it.hasNext()) { Entry e = it.next(); if(e.getOldID() == 10) { it.remove(); } } list.add(new Entry(MetaIndex.WITHER_PROPERTIES, (byte) 0, 10)); } // Fix: Dragon (crash fix) if(type == EntityType.ENDER_DRAGON) { // Remove custom value if already exist Iterator<Entry> it = list.iterator(); while(it.hasNext()) { Entry e = it.next(); if(e.getOldID() == 11) { it.remove(); } } list.add(new Entry(MetaIndex.ENDERDRAGON_PHASE, (byte) 0, 11)); } MetadataRewriter.writeMetadata1_9(type, list, output); } private void handleMetadata(int entityID, MetadataRewriter.Entry entry, EntityType type) { // This handles old IDs if (type == EntityType.PLAYER) { if (entry.getOldID() == 0) { // Byte byte data = (byte) entry.getValue(); if (entityID != info.getEntityID() && plugin.isShieldBlocking()) { if ((data & 0x10) == 0x10) { if (validBlocking.contains(entityID)) { ItemSlotRewriter.ItemStack shield = new ItemSlotRewriter.ItemStack(); shield.id = 442; shield.amount = 1; shield.data = 0; sendSecondHandItem(entityID, shield); } } else { sendSecondHandItem(entityID, null); } } } } if(type == EntityType.ARMOR_STAND && plugin.isHologramPatch()){ if(entry.getOldID() == 0){ byte data = (byte) entry.getValue(); if((data & 0x20) == 0x20){ if(!knownHolograms.contains(entityID)) { knownHolograms.add(entityID); // Send movement ByteBuf buf = info.getChannel().alloc().buffer(); PacketUtil.writeVarInt(PacketType.PLAY_ENTITY_RELATIVE_MOVE.getNewPacketID(), buf); PacketUtil.writeVarInt(entityID, buf); buf.writeShort(0); buf.writeShort((short) (128D * (plugin.getHologramYOffset() * 32D))); buf.writeShort(0); buf.writeBoolean(true); info.sendRawPacket(buf, false); } } } } // Boss bar if(plugin.isBossbarPatch()) { if (type == EntityType.ENDER_DRAGON || type == EntityType.WITHER) { if (entry.getOldID() == 2) { BossBar bar = bossBarMap.get(entityID); String title = (String) entry.getValue(); title = title.isEmpty() ? (type == EntityType.ENDER_DRAGON ? "Ender Dragon" : "Wither") : title; if (bar == null) { bar = ViaVersion.getInstance().createBossBar(title, BossColor.PINK, BossStyle.SOLID); bossBarMap.put(entityID, bar); bar.addPlayer(info.getPlayer()); bar.show(); } else { bar.setTitle(title); } } else if (entry.getOldID() == 6 && !plugin.isBossbarAntiflicker()) { // If anti flicker is enabled, don't update health BossBar bar = bossBarMap.get(entityID); // Make health range between 0 and 1 float maxHealth = type == EntityType.ENDER_DRAGON ? 200.0f : 300.0f; float health = Math.max(0.0f, Math.min(((float) entry.getValue()) / maxHealth, 1.0f)); if (bar == null) { String title = type == EntityType.ENDER_DRAGON ? "Ender Dragon" : "Wither"; bar = ViaVersion.getInstance().createBossBar(title, health, BossColor.PINK, BossStyle.SOLID); bossBarMap.put(entityID, bar); bar.addPlayer(info.getPlayer()); bar.show(); } else { bar.setHealth(health); } } } } } private UUID getUUID(int id) { if (uuidMap.containsKey(id)) { return uuidMap.get(id); } else { UUID uuid = UUID.randomUUID(); uuidMap.put(id, uuid); return uuid; } } private void sendSecondHandItem(int entityID, ItemSlotRewriter.ItemStack o) { ByteBuf buf = info.getChannel().alloc().buffer(); PacketUtil.writeVarInt(PacketType.PLAY_ENTITY_EQUIPMENT.getNewPacketID(), buf); PacketUtil.writeVarInt(entityID, buf); PacketUtil.writeVarInt(1, buf); // slot // write shield try { ItemSlotRewriter.writeItemStack(o, buf); } catch (IOException e) { e.printStackTrace(); } info.sendRawPacket(buf, true); } }
package com.jme3.material; import com.jme3.asset.AssetKey; import com.jme3.asset.AssetManager; import com.jme3.asset.CloneableSmartAsset; import com.jme3.export.*; import com.jme3.light.*; import com.jme3.material.RenderState.BlendMode; import com.jme3.material.RenderState.FaceCullMode; import com.jme3.material.TechniqueDef.LightMode; import com.jme3.material.TechniqueDef.ShadowMode; import com.jme3.math.*; import com.jme3.renderer.Caps; import com.jme3.renderer.GL1Renderer; import com.jme3.renderer.RenderManager; import com.jme3.renderer.Renderer; import com.jme3.renderer.queue.RenderQueue.Bucket; import com.jme3.scene.Geometry; import com.jme3.shader.Shader; import com.jme3.shader.Uniform; import com.jme3.shader.UniformBindingManager; import com.jme3.shader.VarType; import com.jme3.texture.Texture; import com.jme3.util.ListMap; import com.jme3.util.TempVars; import java.io.IOException; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; /** * <code>Material</code> describes the rendering style for a given * {@link Geometry}. * <p>A material is essentially a list of {@link MatParam parameters}, * those parameters map to uniforms which are defined in a shader. * Setting the parameters can modify the behavior of a * shader. * <p/> * * @author Kirill Vainer */ public class Material implements CloneableSmartAsset, Cloneable, Savable { // Version public static final int SAVABLE_VERSION = 2; private static final Logger logger = Logger.getLogger(Material.class.getName()); private static final RenderState additiveLight = new RenderState(); private static final RenderState depthOnly = new RenderState(); private static final Quaternion nullDirLight = new Quaternion(0, -1, 0, -1); static { depthOnly.setDepthTest(true); depthOnly.setDepthWrite(true); depthOnly.setFaceCullMode(RenderState.FaceCullMode.Back); depthOnly.setColorWrite(false); additiveLight.setBlendMode(RenderState.BlendMode.AlphaAdditive); additiveLight.setDepthWrite(false); } private AssetKey key; private String name; private MaterialDef def; private ListMap<String, MatParam> paramValues = new ListMap<String, MatParam>(); private Technique technique; private HashMap<String, Technique> techniques = new HashMap<String, Technique>(); private int nextTexUnit = 0; private RenderState additionalState = null; private RenderState mergedRenderState = new RenderState(); private boolean transparent = false; private boolean receivesShadows = false; private int sortingId = -1; private transient ColorRGBA ambientLightColor = new ColorRGBA(0, 0, 0, 1); public Material(MaterialDef def) { if (def == null) { throw new NullPointerException("Material definition cannot be null"); } this.def = def; // Load default values from definition (if any) for (MatParam param : def.getMaterialParams()) { if (param.getValue() != null) { setParam(param.getName(), param.getVarType(), param.getValue()); } } } public Material(AssetManager contentMan, String defName) { this((MaterialDef) contentMan.loadAsset(new AssetKey(defName))); } /** * Do not use this constructor. Serialization purposes only. */ public Material() { } /** * Returns the asset key name of the asset from which this material was loaded. * * <p>This value will be <code>null</code> unless this material was loaded * from a .j3m file. * * @return Asset key name of the j3m file */ public String getAssetName() { return key != null ? key.getName() : null; } /** * @return the name of the material (not the same as the asset name), the returned value can be null */ public String getName() { return name; } /** * This method sets the name of the material. * The name is not the same as the asset name. * It can be null and there is no guarantee of its uniqness. * @param name the name of the material */ public void setName(String name) { this.name = name; } public void setKey(AssetKey key) { this.key = key; } public AssetKey getKey() { return key; } /** * Returns the sorting ID or sorting index for this material. * * <p>The sorting ID is used internally by the system to sort rendering * of geometries. It sorted to reduce shader switches, if the shaders * are equal, then it is sorted by textures. * * @return The sorting ID used for sorting geometries for rendering. */ public int getSortId() { Technique t = getActiveTechnique(); if (sortingId == -1 && t != null && t.getShader() != null) { int texId = -1; for (int i = 0; i < paramValues.size(); i++) { MatParam param = paramValues.getValue(i); if (param instanceof MatParamTexture) { MatParamTexture tex = (MatParamTexture) param; if (tex.getTextureValue() != null && tex.getTextureValue().getImage() != null) { if (texId == -1) { texId = 0; } texId += tex.getTextureValue().getImage().getId() % 0xff; } } } sortingId = texId + t.getShader().getId() * 1000; } return sortingId; } /** * Clones this material. The result is returned. */ @Override public Material clone() { try { Material mat = (Material) super.clone(); if (additionalState != null) { mat.additionalState = additionalState.clone(); } mat.technique = null; mat.techniques = new HashMap<String, Technique>(); mat.paramValues = new ListMap<String, MatParam>(); for (int i = 0; i < paramValues.size(); i++) { Map.Entry<String, MatParam> entry = paramValues.getEntry(i); mat.paramValues.put(entry.getKey(), entry.getValue().clone()); } return mat; } catch (CloneNotSupportedException ex) { throw new AssertionError(ex); } } /** * Compares two materials and returns true if they are equal. * This methods compare definition, parameters, additional render states. * Since materials are mutable objects, implementing equals() properly is not possible, * hence the name contentEquals(). * * @param otherObj the material to compare to this material * @return true if the materials are equal. */ public boolean contentEquals(Object otherObj) { if (!(otherObj instanceof Material)) { return false; } Material other = (Material) otherObj; // Early exit if the material are the same object if (this == other) { return true; } // Check material definition if (this.getMaterialDef() != other.getMaterialDef()) { return false; } // Early exit if the size of the params is different if (this.paramValues.size() != other.paramValues.size()) { return false; } // Checking technique if (this.technique != null || other.technique != null) { // Techniques are considered equal if their names are the same // E.g. if user chose custom technique for one material but // uses default technique for other material, the materials // are not equal. String thisDefName = this.technique != null ? this.technique.getDef().getName() : "Default"; String otherDefName = other.technique != null ? other.technique.getDef().getName() : "Default"; if (!thisDefName.equals(otherDefName)) { return false; } } // Comparing parameters for (String paramKey : paramValues.keySet()) { MatParam thisParam = this.getParam(paramKey); MatParam otherParam = other.getParam(paramKey); // This param does not exist in compared mat if (otherParam == null) { return false; } if (!otherParam.equals(thisParam)) { return false; } } // Comparing additional render states if (additionalState == null) { if (other.additionalState != null) { return false; } } else { if (!additionalState.equals(other.additionalState)) { return false; } } return true; } /** * Works like {@link Object#hashCode() } except it may change together with the material as the material is mutable by definition. */ public int contentHashCode() { int hash = 7; hash = 29 * hash + (this.def != null ? this.def.hashCode() : 0); hash = 29 * hash + (this.paramValues != null ? this.paramValues.hashCode() : 0); hash = 29 * hash + (this.technique != null ? this.technique.getDef().getName().hashCode() : 0); hash = 29 * hash + (this.additionalState != null ? this.additionalState.contentHashCode() : 0); return hash; } /** * Returns the currently active technique. * <p> * The technique is selected automatically by the {@link RenderManager} * based on system capabilities. Users may select their own * technique by using * {@link #selectTechnique(java.lang.String, com.jme3.renderer.RenderManager) }. * * @return the currently active technique. * * @see #selectTechnique(java.lang.String, com.jme3.renderer.RenderManager) */ public Technique getActiveTechnique() { return technique; } /** * Check if the transparent value marker is set on this material. * @return True if the transparent value marker is set on this material. * @see #setTransparent(boolean) */ public boolean isTransparent() { return transparent; } /** * Set the transparent value marker. * * <p>This value is merely a marker, by itself it does nothing. * Generally model loaders will use this marker to indicate further * up that the material is transparent and therefore any geometries * using it should be put into the {@link Bucket#Transparent transparent * bucket}. * * @param transparent the transparent value marker. */ public void setTransparent(boolean transparent) { this.transparent = transparent; } /** * Check if the material should receive shadows or not. * * @return True if the material should receive shadows. * * @see Material#setReceivesShadows(boolean) */ public boolean isReceivesShadows() { return receivesShadows; } /** * Set if the material should receive shadows or not. * * <p>This value is merely a marker, by itself it does nothing. * Generally model loaders will use this marker to indicate * the material should receive shadows and therefore any * geometries using it should have the {@link ShadowMode#Receive} set * on them. * * @param receivesShadows if the material should receive shadows or not. */ public void setReceivesShadows(boolean receivesShadows) { this.receivesShadows = receivesShadows; } public RenderState getAdditionalRenderState() { if (additionalState == null) { additionalState = RenderState.ADDITIONAL.clone(); } return additionalState; } /** * Get the material definition (j3md file info) that <code>this</code> * material is implementing. * * @return the material definition this material implements. */ public MaterialDef getMaterialDef() { return def; } /** * Returns the parameter set on this material with the given name, * returns <code>null</code> if the parameter is not set. * * @param name The parameter name to look up. * @return The MatParam if set, or null if not set. */ public MatParam getParam(String name) { return paramValues.get(name); } /** * Returns the texture parameter set on this material with the given name, * returns <code>null</code> if the parameter is not set. * * @param name The parameter name to look up. * @return The MatParamTexture if set, or null if not set. */ public MatParamTexture getTextureParam(String name) { MatParam param = paramValues.get(name); if (param instanceof MatParamTexture) { return (MatParamTexture) param; } return null; } /** * Returns a collection of all parameters set on this material. * * @return a collection of all parameters set on this material. * * @see #setParam(java.lang.String, com.jme3.shader.VarType, java.lang.Object) */ public Collection<MatParam> getParams() { return paramValues.values(); } /** * Check if setting the parameter given the type and name is allowed. * @param type The type that the "set" function is designed to set * @param name The name of the parameter */ private void checkSetParam(VarType type, String name) { MatParam paramDef = def.getMaterialParam(name); if (paramDef == null) { throw new IllegalArgumentException("Material parameter is not defined: " + name); } if (type != null && paramDef.getVarType() != type) { logger.log(Level.WARNING, "Material parameter being set: {0} with " + "type {1} doesn''t match definition types {2}", new Object[]{name, type.name(), paramDef.getVarType()}); } } /** * Pass a parameter to the material shader. * * @param name the name of the parameter defined in the material definition (j3md) * @param type the type of the parameter {@link VarType} * @param value the value of the parameter */ public void setParam(String name, VarType type, Object value) { checkSetParam(type, name); if (type.isTextureType()) { setTextureParam(name, type, (Texture)value); } else { MatParam val = getParam(name); if (val == null) { MatParam paramDef = def.getMaterialParam(name); paramValues.put(name, new MatParam(type, name, value, paramDef.getFixedFuncBinding())); } else { val.setValue(value); } if (technique != null) { technique.notifyParamChanged(name, type, value); } } } /** * Clear a parameter from this material. The parameter must exist * @param name the name of the parameter to clear */ public void clearParam(String name) { checkSetParam(null, name); MatParam matParam = getParam(name); if (matParam == null) { return; } paramValues.remove(name); if (matParam instanceof MatParamTexture) { int texUnit = ((MatParamTexture) matParam).getUnit(); nextTexUnit for (MatParam param : paramValues.values()) { if (param instanceof MatParamTexture) { MatParamTexture texParam = (MatParamTexture) param; if (texParam.getUnit() > texUnit) { texParam.setUnit(texParam.getUnit() - 1); } } } sortingId = -1; } if (technique != null) { technique.notifyParamChanged(name, null, null); } } public void setTextureParam(String name, VarType type, Texture value) { if (value == null) { throw new IllegalArgumentException(); } checkSetParam(type, name); MatParamTexture val = getTextureParam(name); if (val == null) { paramValues.put(name, new MatParamTexture(type, name, value, nextTexUnit++)); } else { val.setTextureValue(value); } if (technique != null) { technique.notifyParamChanged(name, type, nextTexUnit - 1); } // need to recompute sort ID sortingId = -1; } /** * Pass a texture to the material shader. * * @param name the name of the texture defined in the material definition * (j3md) (for example Texture for Lighting.j3md) * @param value the Texture object previously loaded by the asset manager */ public void setTexture(String name, Texture value) { if (value == null) { // clear it clearParam(name); return; } VarType paramType = null; switch (value.getType()) { case TwoDimensional: paramType = VarType.Texture2D; break; case TwoDimensionalArray: paramType = VarType.TextureArray; break; case ThreeDimensional: paramType = VarType.Texture3D; break; case CubeMap: paramType = VarType.TextureCubeMap; break; default: throw new UnsupportedOperationException("Unknown texture type: " + value.getType()); } setTextureParam(name, paramType, value); } /** * Pass a Matrix4f to the material shader. * * @param name the name of the matrix defined in the material definition (j3md) * @param value the Matrix4f object */ public void setMatrix4(String name, Matrix4f value) { setParam(name, VarType.Matrix4, value); } /** * Pass a boolean to the material shader. * * @param name the name of the boolean defined in the material definition (j3md) * @param value the boolean value */ public void setBoolean(String name, boolean value) { setParam(name, VarType.Boolean, value); } /** * Pass a float to the material shader. * * @param name the name of the float defined in the material definition (j3md) * @param value the float value */ public void setFloat(String name, float value) { setParam(name, VarType.Float, value); } /** * Pass an int to the material shader. * * @param name the name of the int defined in the material definition (j3md) * @param value the int value */ public void setInt(String name, int value) { setParam(name, VarType.Int, value); } /** * Pass a Color to the material shader. * * @param name the name of the color defined in the material definition (j3md) * @param value the ColorRGBA value */ public void setColor(String name, ColorRGBA value) { setParam(name, VarType.Vector4, value); } /** * Pass a Vector2f to the material shader. * * @param name the name of the Vector2f defined in the material definition (j3md) * @param value the Vector2f value */ public void setVector2(String name, Vector2f value) { setParam(name, VarType.Vector2, value); } /** * Pass a Vector3f to the material shader. * * @param name the name of the Vector3f defined in the material definition (j3md) * @param value the Vector3f value */ public void setVector3(String name, Vector3f value) { setParam(name, VarType.Vector3, value); } /** * Pass a Vector4f to the material shader. * * @param name the name of the Vector4f defined in the material definition (j3md) * @param value the Vector4f value */ public void setVector4(String name, Vector4f value) { setParam(name, VarType.Vector4, value); } private ColorRGBA getAmbientColor(LightList lightList) { ambientLightColor.set(0, 0, 0, 1); for (int j = 0; j < lightList.size(); j++) { Light l = lightList.get(j); if (l instanceof AmbientLight) { ambientLightColor.addLocal(l.getColor()); } } ambientLightColor.a = 1.0f; return ambientLightColor; } /** * Uploads the lights in the light list as two uniform arrays.<br/><br/> * * <p> * <code>uniform vec4 g_LightColor[numLights];</code><br/> // * g_LightColor.rgb is the diffuse/specular color of the light.<br/> // * g_Lightcolor.a is the type of light, 0 = Directional, 1 = Point, <br/> // * 2 = Spot. <br/> <br/> * <code>uniform vec4 g_LightPosition[numLights];</code><br/> // * g_LightPosition.xyz is the position of the light (for point lights)<br/> * // or the direction of the light (for directional lights).<br/> // * g_LightPosition.w is the inverse radius (1/r) of the light (for * attenuation) <br/> </p> */ protected void updateLightListUniforms(Shader shader, Geometry g, int numLights) { if (numLights == 0) { // this shader does not do lighting, ignore. return; } LightList lightList = g.getWorldLightList(); Uniform lightColor = shader.getUniform("g_LightColor"); Uniform lightPos = shader.getUniform("g_LightPosition"); Uniform lightDir = shader.getUniform("g_LightDirection"); lightColor.setVector4Length(numLights); lightPos.setVector4Length(numLights); lightDir.setVector4Length(numLights); Uniform ambientColor = shader.getUniform("g_AmbientLightColor"); ambientColor.setValue(VarType.Vector4, getAmbientColor(lightList)); int lightIndex = 0; for (int i = 0; i < numLights; i++) { if (lightList.size() <= i) { lightColor.setVector4InArray(0f, 0f, 0f, 0f, lightIndex); lightPos.setVector4InArray(0f, 0f, 0f, 0f, lightIndex); } else { Light l = lightList.get(i); ColorRGBA color = l.getColor(); lightColor.setVector4InArray(color.getRed(), color.getGreen(), color.getBlue(), l.getType().getId(), i); switch (l.getType()) { case Directional: DirectionalLight dl = (DirectionalLight) l; Vector3f dir = dl.getDirection(); lightPos.setVector4InArray(dir.getX(), dir.getY(), dir.getZ(), -1, lightIndex); break; case Point: PointLight pl = (PointLight) l; Vector3f pos = pl.getPosition(); float invRadius = pl.getInvRadius(); lightPos.setVector4InArray(pos.getX(), pos.getY(), pos.getZ(), invRadius, lightIndex); break; case Spot: SpotLight sl = (SpotLight) l; Vector3f pos2 = sl.getPosition(); Vector3f dir2 = sl.getDirection(); float invRange = sl.getInvSpotRange(); float spotAngleCos = sl.getPackedAngleCos(); lightPos.setVector4InArray(pos2.getX(), pos2.getY(), pos2.getZ(), invRange, lightIndex); lightDir.setVector4InArray(dir2.getX(), dir2.getY(), dir2.getZ(), spotAngleCos, lightIndex); break; case Ambient: // skip this light. Does not increase lightIndex continue; default: throw new UnsupportedOperationException("Unknown type of light: " + l.getType()); } } lightIndex++; } while (lightIndex < numLights) { lightColor.setVector4InArray(0f, 0f, 0f, 0f, lightIndex); lightPos.setVector4InArray(0f, 0f, 0f, 0f, lightIndex); lightIndex++; } } protected void renderMultipassLighting(Shader shader, Geometry g, RenderManager rm) { Renderer r = rm.getRenderer(); LightList lightList = g.getWorldLightList(); Uniform lightDir = shader.getUniform("g_LightDirection"); Uniform lightColor = shader.getUniform("g_LightColor"); Uniform lightPos = shader.getUniform("g_LightPosition"); Uniform ambientColor = shader.getUniform("g_AmbientLightColor"); boolean isFirstLight = true; boolean isSecondLight = false; for (int i = 0; i < lightList.size(); i++) { Light l = lightList.get(i); if (l instanceof AmbientLight) { continue; } if (isFirstLight) { // set ambient color for first light only ambientColor.setValue(VarType.Vector4, getAmbientColor(lightList)); isFirstLight = false; isSecondLight = true; } else if (isSecondLight) { ambientColor.setValue(VarType.Vector4, ColorRGBA.Black); // apply additive blending for 2nd and future lights r.applyRenderState(additiveLight); isSecondLight = false; } TempVars vars = TempVars.get(); Quaternion tmpLightDirection = vars.quat1; Quaternion tmpLightPosition = vars.quat2; ColorRGBA tmpLightColor = vars.color; Vector4f tmpVec = vars.vect4f; ColorRGBA color = l.getColor(); tmpLightColor.set(color); tmpLightColor.a = l.getType().getId(); lightColor.setValue(VarType.Vector4, tmpLightColor); switch (l.getType()) { case Directional: DirectionalLight dl = (DirectionalLight) l; Vector3f dir = dl.getDirection(); tmpLightPosition.set(dir.getX(), dir.getY(), dir.getZ(), -1); lightPos.setValue(VarType.Vector4, tmpLightPosition); tmpLightDirection.set(0, 0, 0, 0); lightDir.setValue(VarType.Vector4, tmpLightDirection); break; case Point: PointLight pl = (PointLight) l; Vector3f pos = pl.getPosition(); float invRadius = pl.getInvRadius(); tmpLightPosition.set(pos.getX(), pos.getY(), pos.getZ(), invRadius); lightPos.setValue(VarType.Vector4, tmpLightPosition); tmpLightDirection.set(0, 0, 0, 0); lightDir.setValue(VarType.Vector4, tmpLightDirection); break; case Spot: SpotLight sl = (SpotLight) l; Vector3f pos2 = sl.getPosition(); Vector3f dir2 = sl.getDirection(); float invRange = sl.getInvSpotRange(); float spotAngleCos = sl.getPackedAngleCos(); tmpLightPosition.set(pos2.getX(), pos2.getY(), pos2.getZ(), invRange); lightPos.setValue(VarType.Vector4, tmpLightPosition); //We transform the spot directoin in view space here to save 5 varying later in the lighting shader //one vec4 less and a vec4 that becomes a vec3 //the downside is that spotAngleCos decoding happen now in the frag shader. tmpVec.set(dir2.getX(), dir2.getY(), dir2.getZ(), 0); rm.getCurrentCamera().getViewMatrix().mult(tmpVec, tmpVec); tmpLightDirection.set(tmpVec.getX(), tmpVec.getY(), tmpVec.getZ(), spotAngleCos); lightDir.setValue(VarType.Vector4, tmpLightDirection); break; default: throw new UnsupportedOperationException("Unknown type of light: " + l.getType()); } vars.release(); r.setShader(shader); r.renderMesh(g.getMesh(), g.getLodLevel(), 1); } if (isFirstLight && lightList.size() > 0) { // There are only ambient lights in the scene. Render // a dummy "normal light" so we can see the ambient ambientColor.setValue(VarType.Vector4, getAmbientColor(lightList)); lightColor.setValue(VarType.Vector4, ColorRGBA.BlackNoAlpha); lightPos.setValue(VarType.Vector4, nullDirLight); r.setShader(shader); r.renderMesh(g.getMesh(), g.getLodLevel(), 1); } } public void selectTechnique(String name, RenderManager renderManager) { // check if already created Technique tech = techniques.get(name); // When choosing technique, we choose one that // supports all the caps. EnumSet<Caps> rendererCaps = renderManager.getRenderer().getCaps(); if (tech == null) { if (name.equals("Default")) { List<TechniqueDef> techDefs = def.getDefaultTechniques(); if (techDefs == null || techDefs.isEmpty()) { throw new IllegalArgumentException("No default techniques are available on material '" + def.getName() + "'"); } TechniqueDef lastTech = null; for (TechniqueDef techDef : techDefs) { if (rendererCaps.containsAll(techDef.getRequiredCaps())) { // use the first one that supports all the caps tech = new Technique(this, techDef); techniques.put(name, tech); break; } lastTech = techDef; } if (tech == null) { throw new UnsupportedOperationException("No default technique on material '" + def.getName() + "'\n" + " is supported by the video hardware. The caps " + lastTech.getRequiredCaps() + " are required."); } } else { // create "special" technique instance TechniqueDef techDef = def.getTechniqueDef(name); if (techDef == null) { throw new IllegalArgumentException("For material " + def.getName() + ", technique not found: " + name); } if (!rendererCaps.containsAll(techDef.getRequiredCaps())) { throw new UnsupportedOperationException("The explicitly chosen technique '" + name + "' on material '" + def.getName() + "'\n" + "requires caps " + techDef.getRequiredCaps() + " which are not " + "supported by the video renderer"); } tech = new Technique(this, techDef); techniques.put(name, tech); } } else if (technique == tech) { // attempting to switch to an already // active technique. return; } technique = tech; tech.makeCurrent(def.getAssetManager(), true, rendererCaps); // shader was changed sortingId = -1; } private void autoSelectTechnique(RenderManager rm) { if (technique == null) { selectTechnique("Default", rm); } else { technique.makeCurrent(def.getAssetManager(), false, rm.getRenderer().getCaps()); } } /** * Preloads this material for the given render manager. * <p> * Preloading the material can ensure that when the material is first * used for rendering, there won't be any delay since the material has * been already been setup for rendering. * * @param rm The render manager to preload for */ public void preload(RenderManager rm) { autoSelectTechnique(rm); Renderer r = rm.getRenderer(); TechniqueDef techDef = technique.getDef(); Collection<MatParam> params = paramValues.values(); for (MatParam param : params) { if (param instanceof MatParamTexture) { MatParamTexture texParam = (MatParamTexture) param; r.setTexture(0, texParam.getTextureValue()); } else { if (!techDef.isUsingShaders()) { continue; } technique.updateUniformParam(param.getName(), param.getVarType(), param.getValue()); } } Shader shader = technique.getShader(); if (techDef.isUsingShaders()) { r.setShader(shader); } } private void clearUniformsSetByCurrent(Shader shader) { ListMap<String, Uniform> uniforms = shader.getUniformMap(); int size = uniforms.size(); for (int i = 0; i < size; i++) { Uniform u = uniforms.getValue(i); u.clearSetByCurrentMaterial(); } } private void resetUniformsNotSetByCurrent(Shader shader) { ListMap<String, Uniform> uniforms = shader.getUniformMap(); int size = uniforms.size(); for (int i = 0; i < size; i++) { Uniform u = uniforms.getValue(i); if (!u.isSetByCurrentMaterial()) { u.clearValue(); } } } /** * Called by {@link RenderManager} to render the geometry by * using this material. * <p> * The material is rendered as follows: * <ul> * <li>Determine which technique to use to render the material - * either what the user selected via * {@link #selectTechnique(java.lang.String, com.jme3.renderer.RenderManager) * Material.selectTechnique()}, * or the first default technique that the renderer supports * (based on the technique's {@link TechniqueDef#getRequiredCaps() requested rendering capabilities})<ul> * <li>If the technique has been changed since the last frame, then it is notified via * {@link Technique#makeCurrent(com.jme3.asset.AssetManager, boolean, java.util.EnumSet) * Technique.makeCurrent()}. * If the technique wants to use a shader to render the model, it should load it at this part - * the shader should have all the proper defines as declared in the technique definition, * including those that are bound to material parameters. * The technique can re-use the shader from the last frame if * no changes to the defines occurred.</li></ul> * <li>Set the {@link RenderState} to use for rendering. The render states are * applied in this order (later RenderStates override earlier RenderStates):<ol> * <li>{@link TechniqueDef#getRenderState() Technique Definition's RenderState} * - i.e. specific renderstate that is required for the shader.</li> * <li>{@link #getAdditionalRenderState() Material Instance Additional RenderState} * - i.e. ad-hoc renderstate set per model</li> * <li>{@link RenderManager#getForcedRenderState() RenderManager's Forced RenderState} * - i.e. renderstate requested by a {@link com.jme3.post.SceneProcessor} or * post-processing filter.</li></ol> * <li>If the technique {@link TechniqueDef#isUsingShaders() uses a shader}, then the uniforms of the shader must be updated.<ul> * <li>Uniforms bound to material parameters are updated based on the current material parameter values.</li> * <li>Uniforms bound to world parameters are updated from the RenderManager. * Internally {@link UniformBindingManager} is used for this task.</li> * <li>Uniforms bound to textures will cause the texture to be uploaded as necessary. * The uniform is set to the texture unit where the texture is bound.</li></ul> * <li>If the technique uses a shader, the model is then rendered according * to the lighting mode specified on the technique definition.<ul> * <li>{@link LightMode#SinglePass single pass light mode} fills the shader's light uniform arrays * with the first 4 lights and renders the model once.</li> * <li>{@link LightMode#MultiPass multi pass light mode} light mode renders the model multiple times, * for the first light it is rendered opaque, on subsequent lights it is * rendered with {@link BlendMode#AlphaAdditive alpha-additive} blending and depth writing disabled.</li> * </ul> * <li>For techniques that do not use shaders, * fixed function OpenGL is used to render the model (see {@link GL1Renderer} interface):<ul> * <li>OpenGL state ({@link FixedFuncBinding}) that is bound to material parameters is updated. </li> * <li>The texture set on the material is uploaded and bound. * Currently only 1 texture is supported for fixed function techniques.</li> * <li>If the technique uses lighting, then OpenGL lighting state is updated * based on the light list on the geometry, otherwise OpenGL lighting is disabled.</li> * <li>The mesh is uploaded and rendered.</li> * </ul> * </ul> * * @param geom The geometry to render * @param rm The render manager requesting the rendering */ public void render(Geometry geom, RenderManager rm) { autoSelectTechnique(rm); Renderer r = rm.getRenderer(); TechniqueDef techDef = technique.getDef(); if (techDef.getLightMode() == LightMode.MultiPass && geom.getWorldLightList().size() == 0) { return; } if (rm.getForcedRenderState() != null) { r.applyRenderState(rm.getForcedRenderState()); } else { if (techDef.getRenderState() != null) { r.applyRenderState(techDef.getRenderState().copyMergedTo(additionalState, mergedRenderState)); } else { r.applyRenderState(RenderState.DEFAULT.copyMergedTo(additionalState, mergedRenderState)); } } // update camera and world matrices // NOTE: setWorldTransform should have been called already if (techDef.isUsingShaders()) { // reset unchanged uniform flag clearUniformsSetByCurrent(technique.getShader()); rm.updateUniformBindings(technique.getWorldBindUniforms()); } // setup textures and uniforms for (int i = 0; i < paramValues.size(); i++) { MatParam param = paramValues.getValue(i); param.apply(r, technique); } Shader shader = technique.getShader(); // send lighting information, if needed switch (techDef.getLightMode()) { case Disable: r.setLighting(null); break; case SinglePass: updateLightListUniforms(shader, geom, 4); break; case FixedPipeline: r.setLighting(geom.getWorldLightList()); break; case MultiPass: // NOTE: Special case! resetUniformsNotSetByCurrent(shader); renderMultipassLighting(shader, geom, rm); // very important, notice the return statement! return; } // upload and bind shader if (techDef.isUsingShaders()) { // any unset uniforms will be set to 0 resetUniformsNotSetByCurrent(shader); r.setShader(shader); } r.renderMesh(geom.getMesh(), geom.getLodLevel(), 1); } public void write(JmeExporter ex) throws IOException { OutputCapsule oc = ex.getCapsule(this); oc.write(def.getAssetName(), "material_def", null); oc.write(additionalState, "render_state", null); oc.write(transparent, "is_transparent", false); oc.writeStringSavableMap(paramValues, "parameters", null); } public void read(JmeImporter im) throws IOException { InputCapsule ic = im.getCapsule(this); additionalState = (RenderState) ic.readSavable("render_state", null); transparent = ic.readBoolean("is_transparent", false); // Load the material def String defName = ic.readString("material_def", null); HashMap<String, MatParam> params = (HashMap<String, MatParam>) ic.readStringSavableMap("parameters", null); boolean enableVcolor = false; boolean separateTexCoord = false; boolean applyDefaultValues = false; boolean guessRenderStateApply = false; int ver = ic.getSavableVersion(Material.class); if (ver < 1) { applyDefaultValues = true; } if (ver < 2) { guessRenderStateApply = true; } if (im.getFormatVersion() == 0) { // Enable compatibility with old models if (defName.equalsIgnoreCase("Common/MatDefs/Misc/VertexColor.j3md")) { // Using VertexColor, switch to Unshaded and set VertexColor=true enableVcolor = true; defName = "Common/MatDefs/Misc/Unshaded.j3md"; } else if (defName.equalsIgnoreCase("Common/MatDefs/Misc/SimpleTextured.j3md") || defName.equalsIgnoreCase("Common/MatDefs/Misc/SolidColor.j3md")) { // Using SimpleTextured/SolidColor, just switch to Unshaded defName = "Common/MatDefs/Misc/Unshaded.j3md"; } else if (defName.equalsIgnoreCase("Common/MatDefs/Misc/WireColor.j3md")) { // Using WireColor, set wireframe renderstate = true and use Unshaded getAdditionalRenderState().setWireframe(true); defName = "Common/MatDefs/Misc/Unshaded.j3md"; } else if (defName.equalsIgnoreCase("Common/MatDefs/Misc/Unshaded.j3md")) { // Uses unshaded, ensure that the proper param is set MatParam value = params.get("SeperateTexCoord"); if (value != null && ((Boolean) value.getValue()) == true) { params.remove("SeperateTexCoord"); separateTexCoord = true; } } assert applyDefaultValues && guessRenderStateApply; } def = (MaterialDef) im.getAssetManager().loadAsset(new AssetKey(defName)); paramValues = new ListMap<String, MatParam>(); // load the textures and update nextTexUnit for (Map.Entry<String, MatParam> entry : params.entrySet()) { MatParam param = entry.getValue(); if (param instanceof MatParamTexture) { MatParamTexture texVal = (MatParamTexture) param; if (nextTexUnit < texVal.getUnit() + 1) { nextTexUnit = texVal.getUnit() + 1; } // the texture failed to load for this param // do not add to param values if (texVal.getTextureValue() == null || texVal.getTextureValue().getImage() == null) { continue; } } if (im.getFormatVersion() == 0 && param.getName().startsWith("m_")) { // Ancient version of jME3 ... param.setName(param.getName().substring(2)); } checkSetParam(param.getVarType(), param.getName()); paramValues.put(param.getName(), param); } if (applyDefaultValues) { // compatability with old versions where default vars were // not available for (MatParam param : def.getMaterialParams()) { if (param.getValue() != null && paramValues.get(param.getName()) == null) { setParam(param.getName(), param.getVarType(), param.getValue()); } } } if (guessRenderStateApply && additionalState != null) { // Try to guess values of "apply" render state based on defaults // if value != default then set apply to true additionalState.applyPolyOffset = additionalState.offsetEnabled; additionalState.applyAlphaFallOff = additionalState.alphaTest; additionalState.applyAlphaTest = additionalState.alphaTest; additionalState.applyBlendMode = additionalState.blendMode != BlendMode.Off; additionalState.applyColorWrite = !additionalState.colorWrite; additionalState.applyCullMode = additionalState.cullMode != FaceCullMode.Back; additionalState.applyDepthTest = !additionalState.depthTest; additionalState.applyDepthWrite = !additionalState.depthWrite; additionalState.applyPointSprite = additionalState.pointSprite; additionalState.applyStencilTest = additionalState.stencilTest; additionalState.applyWireFrame = additionalState.wireframe; } if (enableVcolor) { setBoolean("VertexColor", true); } if (separateTexCoord) { setBoolean("SeparateTexCoord", true); } } }
package com.jme3.system; import com.jme3.system.JmeSystem.Platform; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.logging.Level; import java.util.logging.Logger; /** * Helper class for extracting the natives (dll, so) from the jars. * This class should only be used internally. */ public class Natives { private static final Logger logger = Logger.getLogger(Natives.class.getName()); private static final byte[] buf = new byte[1024]; private static File workingDir = new File("").getAbsoluteFile(); public static void setExtractionDir(String name) { workingDir = new File(name).getAbsoluteFile(); } protected static void extractNativeLib(String sysName, String name) throws IOException { extractNativeLib(sysName, name, false, true); } protected static void extractNativeLib(String sysName, String name, boolean load) throws IOException { extractNativeLib(sysName, name, load, true); } protected static void extractNativeLib(String sysName, String name, boolean load, boolean warning) throws IOException { String fullname = System.mapLibraryName(name); String path = "native/" + sysName + "/" + fullname; URL url = Thread.currentThread().getContextClassLoader().getResource(path); if (url == null) { if (!warning) { logger.log(Level.WARNING, "Cannot locate native library: {0}/{1}", new String[]{sysName, fullname}); } return; } URLConnection conn = url.openConnection(); InputStream in = conn.getInputStream(); File targetFile = new File(workingDir, fullname); if (targetFile.exists()){ // OK, compare last modified date of this file to // file in jar long targetLastModified = targetFile.lastModified(); long sourceLastModified = conn.getLastModified(); // Allow ~1 second range for OSes that only support low precision if (targetLastModified + 1000 > sourceLastModified){ logger.log(Level.FINE, "Not copying library {0}. Latest already extracted.", fullname); return; } } try { OutputStream out = new FileOutputStream(targetFile); int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); // NOTE: On OSes that support "Date Created" property, // this will cause the last modified date to be lower than // date created which makes no sense targetFile.setLastModified(conn.getLastModified()); } catch (FileNotFoundException ex) { if (ex.getMessage().contains("used by another process")) { return; } throw ex; } finally { if (load) { System.load(targetFile.getAbsolutePath()); } } logger.log(Level.FINE, "Copied {0} to {1}", new Object[]{fullname, targetFile}); } private static String getExtractionDir() { URL temp = Natives.class.getResource(""); if (temp != null) { StringBuilder sb = new StringBuilder(temp.toString()); if (sb.indexOf("jar:") == 0) { sb.delete(0, 4); sb.delete(sb.indexOf("!"), sb.length()); sb.delete(sb.lastIndexOf("/") + 1, sb.length()); } try { return new URL(sb.toString()).toString(); } catch (MalformedURLException ex) { return null; } } return null; } protected static void extractNativeLibs(Platform platform, AppSettings settings) throws IOException { String renderer = settings.getRenderer(); String audioRenderer = settings.getAudioRenderer(); boolean needLWJGL = false; boolean needOAL = false; boolean needJInput = false; boolean needNativeBullet = true; if (renderer != null) { if (renderer.startsWith("LWJGL")) { needLWJGL = true; } } if (audioRenderer != null) { if (audioRenderer.equals("LWJGL")) { needLWJGL = true; needOAL = true; } } needJInput = settings.useJoysticks(); if (needLWJGL) { logger.log(Level.INFO, "Extraction Directory #1: {0}", getExtractionDir()); logger.log(Level.INFO, "Extraction Directory #2: {0}", workingDir.toString()); logger.log(Level.INFO, "Extraction Directory #3: {0}", System.getProperty("user.dir")); // LWJGL supports this feature where // it can load libraries from this path. // This is a fallback method in case the OS doesn't load // native libraries from the working directory (e.g Linux). System.setProperty("org.lwjgl.librarypath", workingDir.toString()); } switch (platform) { case Windows64: if (needLWJGL) { extractNativeLib("windows", "lwjgl64"); } if (needOAL) { extractNativeLib("windows", "OpenAL64"); } if (needJInput) { extractNativeLib("windows", "jinput-dx8_64"); extractNativeLib("windows", "jinput-raw_64"); } if (needNativeBullet) { extractNativeLib("windows", "bulletjme64", true, false); } break; case Windows32: if (needLWJGL) { extractNativeLib("windows", "lwjgl"); } if (needOAL) { extractNativeLib("windows", "OpenAL32"); } if (needJInput) { extractNativeLib("windows", "jinput-dx8"); extractNativeLib("windows", "jinput-raw"); } if (needNativeBullet) { extractNativeLib("windows", "bulletjme", true, false); } break; case Linux64: if (needLWJGL) { extractNativeLib("linux", "lwjgl64"); } if (needJInput) { extractNativeLib("linux", "jinput-linux64"); } if (needOAL) { extractNativeLib("linux", "openal64"); } if (needNativeBullet) { extractNativeLib("linux", "bulletjme", true, false); } break; case Linux32: if (needLWJGL) { extractNativeLib("linux", "lwjgl"); } if (needJInput) { extractNativeLib("linux", "jinput-linux"); } if (needOAL) { extractNativeLib("linux", "openal"); } if (needNativeBullet) { extractNativeLib("linux", "bulletjme", true, false); } break; case MacOSX_PPC32: case MacOSX32: case MacOSX_PPC64: case MacOSX64: if (needLWJGL) { extractNativeLib("macosx", "lwjgl"); } // if (needOAL) // extractNativeLib("macosx", "openal"); if (needJInput) { extractNativeLib("macosx", "jinput-osx"); } if (needNativeBullet) { extractNativeLib("macosx", "bulletjme", true, false); } break; } } }
/* Problem 252: 252. Meeting Rooms Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), determine if a person could attend all meetings. For example, Given [[0, 30],[5, 10],[15, 20]], return false. */ /* PSEUDOCODE There is an overlap if there is an interval (meeting) whose begining time is < the ending of another meeting (interval). So in order to avoid overlap, the next meeting's start time should be later the previous meeting's end time Example, meeting1 = [5, 15] and meeting2 = [10, 20]. Since 5 < 20, these 2 meetings overlap We initiate 2 arrays startingTimes and endingTimes; startingTimes will contain the beginings of all the meetings whereas endingTimes will contain the ending of meetings. We then sort these 2 arrays. We iterate over startingTimes, starting at index i=1. if we find an element in startingTimes that is smaller than the element at index i-1 of endingTimes , we return false since that means we have found a meeting whose starting time is before the ending time of the previous meeting. */ import java.util.Arrays; public class CanAttendMeetings { // Definition for an interval. public static class Interval { int start, end; Interval() { start = 0; end = 0; } Interval(int s, int e) { start = s; end = e; } } public boolean canAttendMeetings(Interval[] intervals) { if (intervals == null || intervals.length == 0) return true; int n = intervals.length; int[] startingTimes = new int[n], endingTimes = new int[n]; for (int i = 0; i < n; i++) { Interval interval = intervals[i]; startingTimes[i] = interval.start; endingTimes[i] = interval.end; } Arrays.sort(startingTimes); Arrays.sort(endingTimes); for (int i = 1; i < n; i++) { if (startingTimes[i] < endingTimes[i-1]) { return false; } } return true; } }
package com.os.operando.garum; import android.content.Context; import android.net.Uri; import com.os.operando.garum.models.PrefModel; import com.os.operando.garum.serializers.CalendarSerializer; import com.os.operando.garum.serializers.DateSerializer; import com.os.operando.garum.serializers.FileSerializer; import com.os.operando.garum.serializers.TypeSerializer; import com.os.operando.garum.serializers.UriSerializer; import com.os.operando.garum.utils.GarumLog; import com.os.operando.garum.utils.ReflectionUtil; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import dalvik.system.DexFile; public class ModelInfo { private Map<Class<? extends PrefModel>, PrefInfo> prefInfos = new HashMap<Class<? extends PrefModel>, PrefInfo>(); private Map<Class<?>, TypeSerializer> typeSerializers = new HashMap<Class<?>, TypeSerializer>() { { put(java.util.Date.class, new DateSerializer()); put(Calendar.class, new CalendarSerializer()); put(Uri.class, new UriSerializer()); put(File.class, new FileSerializer()); } }; public ModelInfo(Configuration configuration) throws IOException { if (!loadModelConfiguration(configuration)) { try { scanForModel(configuration.getContext()); } catch (IOException e) { GarumLog.e("Couldn't open source path.", e); } } GarumLog.i("ModelInfo loaded."); } public TypeSerializer getTypeSerializer(Class<?> type) { return typeSerializers.get(type); } private void scanForModel(Context context, String packages) throws IOException { String packageName = context.getPackageName(); String sourcePath = context.getApplicationInfo().sourceDir; List<String> paths = new ArrayList<String>(); if (sourcePath != null && !(new File(sourcePath).isDirectory())) { DexFile dexfile = new DexFile(sourcePath); Enumeration<String> entries = dexfile.entries(); while (entries.hasMoreElements()) { paths.add(entries.nextElement()); } } else { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Enumeration<URL> resources = classLoader.getResources(""); while (resources.hasMoreElements()) { String path = resources.nextElement().getFile(); if (path.contains("bin") || path.contains("classes")) { paths.add(path); } } } for (String path : paths) { GarumLog.d("path : " + path); File file = new File(path); scanForModelClasses(file, packageName, context.getClassLoader()); } } private void scanForModel(Context context) throws IOException { String packageName = context.getPackageName(); String sourcePath = context.getApplicationInfo().sourceDir; List<String> paths = new ArrayList<String>(); if (sourcePath != null && !(new File(sourcePath).isDirectory())) { DexFile dexfile = new DexFile(sourcePath); Enumeration<String> entries = dexfile.entries(); while (entries.hasMoreElements()) { paths.add(entries.nextElement()); } } else { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Enumeration<URL> resources = classLoader.getResources(""); while (resources.hasMoreElements()) { String path = resources.nextElement().getFile(); if (path.contains("bin") || path.contains("classes")) { paths.add(path); } } } for (String path : paths) { GarumLog.d("path : " + path); File file = new File(path); scanForModelClasses(file, packageName, context.getClassLoader()); } } private void scanForModelClasses(File path, String packageName, ClassLoader classLoader) { if (path.isDirectory()) { for (File file : path.listFiles()) { scanForModelClasses(file, packageName, classLoader); } } else { String className = path.getName(); if (!path.getPath().equals(className)) { className = path.getPath(); if (className.endsWith(".class")) { className = className.substring(0, className.length() - 6); } else { return; } className = className.replace(System.getProperty("file.separator"), "."); int packageNameIndex = className.lastIndexOf(packageName); if (packageNameIndex < 0) { return; } className = className.substring(packageNameIndex); } try { Class<?> discoveredClass = Class.forName(className, false, classLoader); if (ReflectionUtil.isModel(discoveredClass)) { @SuppressWarnings("unchecked") Class<? extends PrefModel> modelClass = (Class<? extends PrefModel>) discoveredClass; prefInfos.put(modelClass, new PrefInfo(modelClass)); } } catch (ClassNotFoundException e) { } } } private boolean loadModelConfiguration(Configuration configuration) { if (!configuration.isValid()) { return false; } final List<Class<? extends PrefModel>> models = configuration.getModelClasses(); if (models != null) { for (Class<? extends PrefModel> model : models) { prefInfos.put(model, new PrefInfo(model)); } } final List<Class<? extends TypeSerializer>> typeSerializerList = configuration.getTypeSerializers(); if (typeSerializers != null) { for (Class<? extends TypeSerializer> typeSerializer : typeSerializerList) { try { TypeSerializer instance = typeSerializer.newInstance(); typeSerializers.put(instance.getDeserializedType(), instance); } catch (InstantiationException e) { GarumLog.e("Couldn't instantiate TypeSerializer.", e); } catch (IllegalAccessException e) { GarumLog.e("IllegalAccessException", e); } } } return true; } public Collection<PrefInfo> getPrefInfos() { return prefInfos.values(); } public PrefInfo getPrefInfo(Class<? extends PrefModel> type) { return prefInfos.get(type); } }
package com.onegini.model; import android.os.Build; import com.google.gson.annotations.SerializedName; import com.onegini.mobile.sdk.android.library.model.OneginiClientConfigModel; public class ConfigModel implements OneginiClientConfigModel { @SerializedName("shouldGetIdToken") private boolean shouldGetIdToken; @SerializedName("kOGAppIdentifier") private String appIdentifier; @SerializedName("kOGAppPlatform") private String appPlatform; @SerializedName("kOGAppScheme") private String appScheme; @SerializedName("kOGAppVersion") private String appVersion; @SerializedName("kAppBaseURL") private String baseUrl; @SerializedName("kOGMaxPinFailures") private int maxPinFailures; @SerializedName("kOGResourceBaseURL") private String resourceBaseUrl; @SerializedName("kOGShouldConfirmNewPin") private boolean shouldConfirmNewPin; @SerializedName("kOGShouldDirectlyShowPushMessage") private boolean shouldDirectlyShowPushMessage; @SerializedName("kOGdebugDetectionEnabled") private boolean debugDetectionEnabled; @SerializedName("kOGUseEmbeddedWebview") private boolean useEmbeddedWebview; private int certificatePinningKeyStore; private String keyStoreHash; @Override public String getAppIdentifier() { return appIdentifier; } @Override public String getAppPlatform() { return appPlatform; } @Override public String getAppScheme() { return appScheme; } @Override public String getAppVersion() { return appVersion; } @Override public String getBaseUrl() { return baseUrl; } @Override public int getMaxPinFailures() { return maxPinFailures; } @Override public String getResourceBaseUrl() { return resourceBaseUrl; } @Override public boolean shouldConfirmNewPin() { return shouldConfirmNewPin; } @Override public boolean shouldDirectlyShowPushMessage() { return shouldDirectlyShowPushMessage; } @Override public int getCertificatePinningKeyStore() { return certificatePinningKeyStore; } public void setCertificatePinningKeyStore(int certificatePinningKeyStore) { this.certificatePinningKeyStore = certificatePinningKeyStore; } @Override public String getKeyStoreHash() { return keyStoreHash; } public void setKeyStoreHash(String keyStoreHash) { this.keyStoreHash = keyStoreHash; } @Override public String getDeviceName() { return Build.BRAND + " " + Build.MODEL; } @Override public boolean shouldGetIdToken() { return shouldGetIdToken; } @Override public boolean shouldStoreCookies() { return true; } @Override public int getHttpClientTimeout() { return 0; } @Override public boolean debugDetectionEnabled() { if (debugDetectionEnabled == null) { return true; } return debugDetectionEnabled; } public boolean useEmbeddedWebview() { return useEmbeddedWebview; } @Override public String toString() { return "ConfigModel{" + " appIdentifier='" + appIdentifier + "'" + ", appPlatform='" + appPlatform + "'" + ", appScheme='" + appScheme + "'" + ", appVersion='" + appVersion + "'" + ", baseURL='" + baseUrl + "'" + ", confirmNewPin='" + shouldConfirmNewPin + "'" + ", directlyShowPushMessage='" + shouldDirectlyShowPushMessage + "'" + ", maxPinFailures='" + maxPinFailures + "'" + ", resourceBaseURL='" + resourceBaseUrl + "'" + ", keyStoreHash='" + getKeyStoreHash() + "'" + ", idTokenRequested='" + shouldGetIdToken + "'" + "}"; } }
package chpp_matchdetails_parser; import java.io.File; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import match_details_v2_5.HattrickData; /** * * @author sergio * @version 1.0 */ public class CHPP_MatchDetails_Parser { public static match_details_v2_5.HattrickData parse_match_details_v2_5(File input_file) throws Exception { try { JAXBContext jaxbContext = JAXBContext.newInstance(match_details_v2_5.HattrickData.class); System.out.println("¿The file could be read? " + input_file.canRead()); if (input_file.canRead()) { Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); match_details_v2_5.HattrickData ht_data = (match_details_v2_5.HattrickData) jaxbUnmarshaller.unmarshal(input_file); if(Float.toString(ht_data.getVersion()).equalsIgnoreCase("2.5")){ return ht_data; }else{ throw new Exception("XML had an unsupported version (found "+Float.toString(ht_data.getVersion())+"), but this method requieres 2.5 version."); } } } catch (JAXBException ex) { Logger.getLogger(CHPP_MatchDetails_Parser.class.getName()).log(Level.SEVERE, null, ex); throw new Exception("The file could not be parsed."); } return null; } /** * Main class for testing the library * * @param args the command line arguments */ public static void main(String[] args) throws Exception { // TODO code application logic here } }
package com.brein.time.timeintervals.intervals; import com.brein.time.exceptions.IllegalConfiguration; import com.brein.time.exceptions.IllegalTimeInterval; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.io.Serializable; public class IdInterval<I extends Comparable<I> & Serializable, T extends Comparable<T> & Serializable> implements IInterval<T>, Externalizable { private I id; private IInterval<T> wrappedInterval; public IdInterval() { // just used for serialization } @SuppressWarnings("unchecked") public IdInterval(final I id, final T start, final T end) { final Class<T> clazz; if (start == null && end == null) { throw new IllegalTimeInterval("Please use the constructor with specified clazz, " + "if start and end are null."); } else if (start == null) { clazz = (Class<T>) end.getClass(); } else { clazz = (Class<T>) start.getClass(); } init(id, createInterval(start, end, clazz)); } public IdInterval(final I id, final T start, final T end, final Class<T> clazz) { init(id, createInterval(start, end, clazz)); } public IdInterval(final I id, final IInterval<T> wrappedInterval) { init(id, wrappedInterval); } @SuppressWarnings("unchecked") protected IInterval<T> createInterval(final T start, final T end, final Class<T> clazz) { if (Number.class.isAssignableFrom(clazz)) { final Class<? extends Number> numberClazz = (Class<? extends Number>) clazz; return new NumberInterval(numberClazz, numberClazz.cast(start), numberClazz.cast(end)); } else { throw new IllegalConfiguration("There is currently no default implementation available for the specified " + "clazz '" + clazz + "', you can override the `createInterval` method, if an interval-type is " + "known."); } } protected void init(final I id, final IInterval<T> wrappedInterval) { this.id = id; this.wrappedInterval = wrappedInterval; } public I getId() { return this.id; } @Override public T getNormStart() { return wrappedInterval.getNormStart(); } @Override public T getNormEnd() { return wrappedInterval.getNormEnd(); } @Override public String getUniqueIdentifier() { return wrappedInterval.getUniqueIdentifier(); } @Override @SuppressWarnings("NullableProblems") public int compareTo(final IInterval i) { final int cmp = this.wrappedInterval.compareTo(i); if (cmp == 0) { // the intervals are equal, so we must use the identifiers if (i instanceof IdInterval) { return compareId(IdInterval.class.cast(i)); } // we don't have any identifiers (the instance is of a different type) else { return getClass().getName().compareTo(i.getClass().getName()); } } else { return cmp; } } public int compareId(final IdInterval iId) { if (this.id == null && iId == null) { return 0; } else if (this.id == null) { return -1; } else if (iId == null) { return 1; } else if (this.id.getClass().isInstance(iId.id)) { //noinspection unchecked return this.id.compareTo((I) iId.id); } else { return this.id.toString().compareTo(iId.id.toString()); } } @SuppressWarnings("unchecked") public <X extends IInterval<T>> X interval() { return (X) wrappedInterval; } @Override public int hashCode() { return this.id.hashCode(); } @Override public boolean equals(final Object obj) { if (obj == this) { return true; } else if (obj == null) { return false; } else if (IInterval.class.isInstance(obj)) { return compareTo(IInterval.class.cast(obj)) == 0; } else { return false; } } @Override public String toString() { return String.format("%s@%s", this.id, this.wrappedInterval); } @Override public void writeExternal(final ObjectOutput out) throws IOException { out.writeObject(this.id); out.writeObject(this.wrappedInterval); } @Override @SuppressWarnings("unchecked") public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException { this.id = (I) in.readObject(); this.wrappedInterval = (IInterval<T>) in.readObject(); } }
package io.github.ihongs.util; import io.github.ihongs.HongsExemption; import java.util.Arrays; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; /** * * * <p> * * (&lt;Object,Map&lt;Object,Map&lt;...&gt;&gt;&gt;) * ; * keys * </p> * * <h3></h3> * <pre> * 855 JSON * 856 JSON * </pre> * * @author Hongs */ public final class Dict { private static Map asMap (Object val) { if (val != null) { if (val instanceof Map ) { return ( Map ) val ; } else if (val instanceof Collection) { int i = 0; Map m = new LinkedHashMap( ); for (Object v : (Collection) val) { m.put(i ++, v ); } return m; } else if (val instanceof Object[ ] ) { int i = 0; Map m = new LinkedHashMap( ); for (Object o : (Object[ ] ) val) { m.put(i ++, o ); } return m; } } return new LinkedHashMap(); } private static List asList(Object val) { if (val != null) { if (val instanceof List) { return ( List) val ; } else if (val instanceof Set ) { return new ArrayList(( Set ) val); } else if (val instanceof Map ) { return new ArrayList(((Map ) val).values( ) ); } else if (val instanceof Object[]) { return new ArrayList(Arrays.asList((Object[]) val)); } } return new ArrayList(); } private static Collection asColl(Object val) { if (val != null) { if (val instanceof List) { return ( List) val ; } else if (val instanceof Set ) { return ( Set ) val ; } else if (val instanceof Map ) { return new ArrayList(((Map ) val).values( ) ); } else if (val instanceof Object[]) { return new ArrayList(Arrays.asList((Object[]) val)); } } return new ArrayList(); } private static Object gat(Collection lst, Object def, Object[] keys, int pos) { List col = new ArrayList(); for(Object sub : lst) { Object obj = get(sub, def, keys, pos); if (obj != null) { col.add( obj); } } if (! col.isEmpty( )) { return col; } else { return def; } } private static Object get(Object obj, Object def, Object[] keys, int pos) { Object key = keys[pos]; if (obj == null) { return def; } if (key == null) { Collection lst = asColl(obj); if (keys.length == pos + 1) { return lst; } else { return gat(lst, def, keys, pos + 1); } } else if (key instanceof Integer) { List lst = asList(obj); int idx = ( Integer ) key ; if ( idx > lst.size( ) - 1) { return def; } if (keys.length == pos + 1) { return Synt.defoult(lst.get(idx), def); } else { return get(lst.get(idx), def, keys, pos + 1); } } else { Map map = asMap (obj); if (keys.length == pos + 1) { return Synt.defoult(map.get(key), def); } else { return get(map.get(key), def, keys, pos + 1); } } } private static Object put(Object obj, Object val, Object[] keys, int pos) { Object key = keys[pos]; if (key == null) { Collection lst = asColl(obj); if (keys.length == pos + 1) { lst.add(val); } else { lst.add(put(null, val, keys, pos + 1)); } return lst; } else if (key instanceof Integer) { List lst = asList(obj); int idx = ( Integer ) key; int idz = lst.size( ); for ( ; idx >= idz; ++ idz) { lst.add ( null ); } if (keys.length == pos + 1) { lst.set(idx, val); } else { lst.set(idx, put(lst.get(idx), val, keys, pos + 1)); } return lst; } else { Map map = asMap (obj); if (keys.length == pos + 1) { map.put(key, val); } else { map.put(key, put(map.get(key), val, keys, pos + 1)); } return map; } } /** * * @param map * @param def * @param keys * @return */ public static Object get(Map map, Object def, Object... keys) { if (map == null) { throw new NullPointerException("`map` can not be null"); } return get(map, def, keys, 0); } /** * * @param map * @param val * @param keys */ public static void put(Map map, Object val, Object... keys) { if (map == null) { throw new NullPointerException("`map` can not be null"); } if (keys.length == 0) { throw new HongsExemption(856, "Keys required, but empty gives"); } if (keys[0] == null || keys[0] instanceof Integer) { throw new HongsExemption(856, "First key can not be null or ints, but it is " + keys[0]); } put(map, val, keys, 0); } /** * oth map * Map.putAll : Map Collection * @param map * @param oth */ public static void putAll(Map map, Map oth) { for(Object o : oth.entrySet()) { Map.Entry e = (Map.Entry) o; Object k2 = e.getKey( ); Object v2 = e.getValue(); Object v1 = map.get(k2); if (v1 instanceof Collection && v2 instanceof Collection ) { ((Collection) v1).addAll((Collection) v2); } else if (v1 instanceof Map && v2 instanceof Map ) { putAll((Map) v1 , (Map) v2); } else { map.put(k2 , v2); } } } /** * * @param map * @param keys * @return */ public static Object getDepth(Map map, Object... keys) { return get(map, null, keys); } /** * * @param <T> * @param map * @param def * @param keys * @return */ public static <T> T getValue(Map map, T def, Object... keys) { try { return Synt.declare(get(map, def, keys), def); } catch (ClassCastException ex) { throw new ClassCastException("Wrong type for key '"+Arrays.toString(keys)+"'"); } } /** * * @param <T> * @param map * @param cls * @param keys * @return */ public static <T> T getValue(Map map, Class<T> cls, Object... keys) { try { return Synt.declare(get(map,null, keys), cls); } catch (ClassCastException ex) { throw new ClassCastException("Wrong type for key '"+Arrays.toString(keys)+"'"); } } /** * ("a.b[c]") * @see splitKeys * @param map * @param path * @return */ public static Object getParam(Map map, String path) { return getDepth(map, splitKeys(path)); } /** * * @see splitKeys * @param <T> * @param map * @param def * @param path * @return */ public static <T> T getParam(Map map, T def, String path) { return getValue(map, def, splitKeys(path)); } /** * ("a.b[c]") * @see splitKeys * @param <T> * @param map * @param cls * @param path * @return */ public static <T> T getParam(Map map, Class<T> cls, String path) { return getValue(map, cls, splitKeys(path)); } /** * (put) * @param map * @param val * @param keys */ public static void setValue(Map map, Object val, Object... keys) { put(map, val, keys); } /** * ("a.b[c]") * @see splitKeys * @param map * @param val * @param path */ public static void setParam(Map map, Object val, String path) { put(map, val, splitKeys(path)); } /** * oth map.keys * Map.putAll : Map * @param map * @param oth * @param keys */ public static void setValues(Map map, Map oth, Object... keys) { Object sub = get ( map , null , keys ); if (sub != null && sub instanceof Map) { putAll((Map) sub, oth ); } else { put ( map, oth, keys); } } /** * oth map.path (path .|[] ) * Map.putAll : Map * @see splitKeys * @param map * @param oth * @param path */ public static void setParams(Map map, Map oth, String path) { setValues(map, oth, splitKeys(path)); } /** * * * <pre> * a.b[c]:d.:e[:f][] a b c :d :e :f null * Javascript PHP , * Javascript , * PHP . * </pre> * * @param path * @return */ public static Object[] splitKeys(String path) { if (path == null) { throw new NullPointerException("`path` can not be null"); } /** * * <code> * path.replaceAll("([^\\.\\]])!", "$1.!") * .replace("[", ".") * .replace("]", "" ) * .split("\\.") * </code> * null , * [] .! ; * , * . * 2018/3/9 '!' ':'. */ List lst = new ArrayList(); int len = path.length( ); int beg = 0; int end = 0; char pnt; boolean fkh = false; while (end < len ) { pnt = path.charAt(end); switch ( pnt ) { case ':' :/* // 2019/07/28 , if (fkh) { break; // [] : } if (beg != end) { lst.add(path.substring(beg, end)); beg = end; } break;*/ case '.' : if (fkh) { break; } if (beg != end) { lst.add(path.substring(beg, end)); } else if (beg == 0 ) { lst.add( "" ); } else if (']' != path.charAt(beg - 1)) { // a[b].c. ]. lst.add(null); } beg = end + 1; break; case '[' : if (fkh) { throw new HongsExemption(855, "Syntax error at " + end + " in " + path); } if (beg != end) { lst.add(path.substring(beg, end)); } else if (beg == 0 ) { lst.add( "" ); } else if (']' != path.charAt(beg - 1)) { // a[b][c] ][ throw new HongsExemption(855, "Syntax error at " + end + " in " + path); } beg = end + 1; fkh = true; break; case ']' : if (! fkh) { throw new HongsExemption(855, "Syntax error at " + end + " in " + path); } if (beg != end) { lst.add(path.substring(beg, end)); } else if (beg != 0 ) { lst.add(null); } else // if ('[' != path.charAt(beg - 1)) { // throw new HongsExemption(855, "Syntax error at " + end + " in " + path); beg = end + 1; fkh = false; break; } end ++; } if (beg == 0 && end == 0 ) { lst.add(path); } else if (beg != len) { lst.add(path.substring(beg)); } else if ('.' == path.charAt(-1+len)) { lst.add(null); } return lst.toArray(); } }
package com.fullmetalgalaxy.client.creation; import java.util.ArrayList; import java.util.List; import com.fullmetalgalaxy.client.game.GameEngine; import com.fullmetalgalaxy.model.LandType; import com.fullmetalgalaxy.model.Location; import com.fullmetalgalaxy.model.RpcFmpException; import com.fullmetalgalaxy.model.RpcUtil; import com.fullmetalgalaxy.model.Sector; import com.fullmetalgalaxy.model.TokenType; import com.fullmetalgalaxy.model.persist.AnBoardPosition; import com.fullmetalgalaxy.model.persist.EbToken; import com.fullmetalgalaxy.model.persist.Game; import com.google.gwt.user.client.Random; /** * @author Kroc * */ public class GameGenerator { public GameGenerator() { } protected static Game getGame() { return GameEngine.model().getGame(); } /** * remove all token from graveyard */ public static void cleanToken() { Game game = GameEngine.model().getGame(); List<EbToken> token2Remove = new ArrayList<EbToken>(); for( EbToken token : game.getSetToken() ) { if( token.getLocation() == Location.Graveyard ) { token2Remove.add( token ); } } for( EbToken token : token2Remove ) { game.getSetToken().remove( token ); token.incVersion(); } } /** * remove all ore from map */ public static void clearOre() { Game game = GameEngine.model().getGame(); List<EbToken> token2Remove = new ArrayList<EbToken>(); for( EbToken token : game.getSetToken() ) { if( token.getType() == TokenType.Ore && token.getLocation() == Location.Board ) { token2Remove.add( token ); } } for( EbToken token : token2Remove ) { try { game.moveToken( token, Location.Graveyard ); } catch( RpcFmpException e ) { // TODO Auto-generated catch block e.printStackTrace(); } game.removeToken( token ); token.incVersion(); } } /** * populate game with minerais token */ public static void populateOres() { clearOre(); int width = getGame().getLandWidth(); int height = getGame().getLandHeight(); int startx = Random.nextInt( 3 ); int starty = Random.nextInt( 3 ); for( int ix = startx; ix < width; ix += 3 ) { for( int iy = starty; iy < height; iy += 3 ) { LandType type = getGame().getLand( ix, iy ); if( ((type == LandType.Reef) || (type == LandType.Marsh) || (type == LandType.Plain) || (type == LandType.Montain)) && (getGame().getToken( new AnBoardPosition( ix, iy ) ) == null) ) { EbToken token = new EbToken( TokenType.Ore ); token.getPosition().setX( ix ); token.getPosition().setY( iy ); token.getPosition().setSector( Sector.getRandom() ); token.setLocation( Location.Board ); getGame().addToken( token ); } } } } private static MapSize m_mapSize = MapSize.Medium; /** * according to the maximum number of player and the MapSize enum, set the width/height * @param p_size */ public static void setSize(MapSize p_size) { m_mapSize = p_size; int width = getGame().getLandWidth(); int height = getGame().getLandHeight(); if( p_size != MapSize.Custom ) { int hexagonCount = p_size.getHexagonPerPlayer() * getGame().getMaxNumberOfPlayer(); if( isHexagonMap() ) { width = (int)Math.floor( Math.sqrt( hexagonCount * 1.34 ) ); height = width; } else { float fheight = (float)Math.sqrt( hexagonCount / 1.6 ); width = (int)Math.floor( 1.6 * fheight ); height = (int)Math.ceil( fheight ); } } getGame().setLandSize( width, height ); } public static void setSize(int p_width, int p_height) { if( (getGame().getLandWidth() != p_width) || (getGame().getLandHeight() != p_height) ) { m_mapSize = MapSize.Custom; getGame().setLandSize( p_width, p_height ); } } public static MapSize getSize() { return m_mapSize; } /** * put a specific land type on every hexagon of the board. * @param p_landValue */ public static void clearLand(LandType p_land) { clearOre(); // to be sure the blob have the right size. setSize( getSize() ); int width = getGame().getLandWidth(); int height = getGame().getLandHeight(); // getGame().setLandSize( width, height ); if( !isHexagonMap() ) { for( int x = 0; x < width; x++ ) { for( int y = 0; y < height; y++ ) { getGame().setLand( x, y, p_land ); } } } else { AnBoardPosition centre = new AnBoardPosition(); AnBoardPosition position = new AnBoardPosition(); int rayon = getGame().getLandHeight() / 2; centre.setX( rayon ); centre.setY( rayon ); for( int x = 0; x < width; x++ ) { position.setX( x ); for( int y = 0; y < height; y++ ) { position.setY( y ); if( position.getHexDistance( centre ) > rayon ) { getGame().setLand( x, y, LandType.None ); } else { getGame().setLand( x, y, p_land ); } } } } } private static int s_seaPercent = 40; private static int s_landPercent = 60; private static boolean s_isHexagonMap = false; /** * this method was translated from C++ in Full Metal Program. */ public static void generLands() { AnBoardPosition position = new AnBoardPosition(); int max; int nbNull; int nbSea; int nbReef; int nbMarsh; int nbPlain; int nbMontain; boolean isLakeBoard = getLandPercent() >= 45 ? true : false; // (RpcUtil.random( 100 ) < 60); int position_Lig = 0; int position_Col = 0; // Initialiser Carte if( isLakeBoard ) { clearLand( LandType.Plain ); } else { clearLand( LandType.Sea ); } // Carte Lacs if( isLakeBoard ) { // Au debut il y avait la Terre ... // Et Dieu crea la Mer ... max = (((getGame().getLandHeight() * getGame().getLandWidth()) * s_seaPercent) / 100) / 20; for( int i = 0; i < max; i++ ) { do { position.setY( (RpcUtil.random( getGame().getLandHeight() - 6 ) + 3) ); position.setX( (RpcUtil.random( getGame().getLandWidth() - 6 ) + 3) ); } while( getGame().getLand( position ) == LandType.None ); getGame().setLand( position, LandType.Sea ); for( int iSector = 0; iSector < Sector.values().length; iSector++ ) { if( getGame().getLand( position.getNeighbour( Sector.values()[iSector] ) ) != LandType.None ) { getGame().setLand( position.getNeighbour( Sector.values()[iSector] ), LandType.Sea ); } } } for( position_Lig = 0; position_Lig < getGame().getLandHeight(); position_Lig++ ) { for( position_Col = 0; position_Col < getGame().getLandWidth(); position_Col++ ) { position.setX( position_Col ); position.setY( position_Lig ); if( getGame().getLand( position ) == LandType.Plain ) { nbSea = 0; nbPlain = 0; // getGame().setLand( position, LandType.Sea ); for( int iSector = 0; iSector < Sector.values().length; iSector++ ) { if( getGame().getLand( position.getNeighbour( Sector.values()[iSector] ) ) == LandType.Sea ) { nbSea++; if( getGame().getLand( position.getNeighbour( Sector.values()[iSector].getNext() ) ) != LandType.Sea ) nbPlain++; } } if( (nbSea >= 2) && (nbPlain == 2) ) max = 101; else if( nbSea > 0 ) max = (nbSea * 5) + 20; else max = 1; if( (int)Math.round( Math.random() * 100 ) < max ) getGame().setLand( position, LandType.Sea ); } } } } // Carte Iles else { // Au Debut il y avait la Mer ... // Et Dieu crea la Terre ... max = (((getGame().getLandHeight() * getGame().getLandWidth()) * s_landPercent) / 100) / 13; for( int i = 0; i < max; i++ ) { do { position_Lig = (short)(RpcUtil.random( getGame().getLandHeight() )); position_Col = (short)(RpcUtil.random( getGame().getLandWidth() )); position.setX( position_Col ); position.setY( position_Lig ); } while( getGame().getLand( position ) == LandType.None ); getGame().setLand( position, LandType.Plain ); if( (int)Math.round( Math.random() * 100 ) < 50 ) { for( int iSector = 0; iSector < Sector.values().length; iSector++ ) { if( getGame().getLand( position.getNeighbour( Sector.values()[iSector] ) ) != LandType.None ) { getGame().setLand( position.getNeighbour( Sector.values()[iSector] ), LandType.Plain ); } } } else { for( int iSector = 0; iSector < Sector.values().length; iSector++ ) { if( getGame().getLand( position.getNeighbour( Sector.values()[iSector] ) ) != LandType.None ) { getGame().setLand( position.getNeighbour( Sector.values()[iSector] ), LandType.Plain ); } } } } } // Et puis vint les Recifs ... for( position_Lig = 0; position_Lig < getGame().getLandHeight(); position_Lig++ ) { for( position_Col = 0; position_Col < getGame().getLandWidth(); position_Col++ ) { position.setX( position_Col ); position.setY( position_Lig ); nbSea = 0; nbReef = 0; nbPlain = 0; for( int iSector = 0; iSector < Sector.values().length; iSector++ ) { switch( getGame().getLand( position.getNeighbour( Sector.values()[iSector] ) ) ) { case Sea: nbSea++; break; case Reef: nbReef++; break; case Plain: nbPlain++; break; } } switch( getGame().getLand( position ) ) { case Plain: if( nbSea > 2 ) { if( (int)Math.round( Math.random() * 100 ) < 30 ) { getGame().setLand( position, LandType.Sea ); break; } } if( nbSea > 0 ) max = (nbSea * 5) + (nbReef * 5) + 20; else if( nbReef > 0 ) max = (nbReef * 5) + 10; else max = 2; if( (int)Math.round( Math.random() * 100 ) < max ) getGame().setLand( position, LandType.Reef ); break; case Sea: if( (nbPlain > 1) && ((int)Math.round( Math.random() * 100 ) < 50) ) getGame().setLand( position, LandType.Reef ); break; } } } // Et puis vint les Marecages ... for( position_Lig = 0; position_Lig < getGame().getLandHeight(); position_Lig++ ) { for( position_Col = 0; position_Col < getGame().getLandWidth(); position_Col++ ) { position.setX( position_Col ); position.setY( position_Lig ); nbSea = 0; nbReef = 0; nbMarsh = 0; nbPlain = 0; for( int iSector = 0; iSector < Sector.values().length; iSector++ ) { switch( getGame().getLand( position.getNeighbour( Sector.values()[iSector] ) ) ) { case Sea: nbSea++; break; case Reef: nbReef++; break; case Marsh: nbMarsh++; break; case Plain: nbPlain++; break; } } switch( getGame().getLand( position ) ) { case Plain: if( (nbReef > 0) || (nbSea > 0) ) max = (nbReef * 5) + (nbSea * 5) + (nbMarsh * 5) + 20; else if( nbMarsh > 0 ) max = (nbMarsh * 5) + 10; else max = 2; if( (int)Math.round( Math.random() * 100 ) < max ) getGame().setLand( position, LandType.Marsh ); break; case Reef: if( (nbPlain > 1) && ((int)Math.round( Math.random() * 100 ) < 20) ) getGame().setLand( position, LandType.Marsh ); break; } } } for( position_Lig = 0; position_Lig < getGame().getLandHeight(); position_Lig++ ) { for( position_Col = 0; position_Col < getGame().getLandWidth(); position_Col++ ) { if( getGame().getLand( position ) == LandType.Plain ) { position.setX( position_Col ); position.setY( position_Lig ); nbSea = 0; nbPlain = 0; for( int iSector = 0; iSector < Sector.values().length; iSector++ ) { switch( getGame().getLand( position.getNeighbour( Sector.values()[iSector] ) ) ) { case Sea: case Reef: case Marsh: nbSea++; switch( getGame() .getLand( position.getNeighbour( Sector.values()[iSector].getNext() ) ) ) { case Montain: case Plain: case None: nbPlain++; } } } if( (nbSea >= 2) && (nbPlain == 2) ) getGame().setLand( position, LandType.Marsh ); } } } // Puis Dieu erigea les Montagnes ... for( position_Lig = 0; position_Lig < getGame().getLandHeight(); position_Lig++ ) { for( position_Col = 0; position_Col < getGame().getLandWidth(); position_Col++ ) { position.setX( position_Col ); position.setY( position_Lig ); nbMarsh = 0; nbPlain = 0; nbMontain = 0; for( int iSector = 0; iSector < Sector.values().length; iSector++ ) { switch( getGame().getLand( position.getNeighbour( Sector.values()[iSector] ) ) ) { case Marsh: nbMarsh++; break; case Plain: nbPlain++; break; case Montain: nbMontain++; break; } } switch( getGame().getLand( position ) ) { // case EnuLand.Marsh : case Plain: if( nbMontain > 0 ) { for( int iSector = 0; iSector < Sector.values().length; iSector++ ) { if( getGame().getLand( position.getNeighbour( Sector.values()[iSector] ) ) == LandType.Montain ) nbMontain++; } if( nbMontain == 1 ) max = 50; else max = 40 - (nbMontain * 5); } else if( nbPlain + nbMarsh > 2 ) max = 5; else max = 1; if( (int)Math.round( Math.random() * 100 ) < max ) getGame().setLand( position, LandType.Montain ); break; } } } // Enfin Dieu voulu que le monde soit parfait ! for( position_Lig = 0; position_Lig < getGame().getLandHeight(); position_Lig++ ) { for( position_Col = 0; position_Col < getGame().getLandWidth(); position_Col++ ) { position.setX( position_Col ); position.setY( position_Lig ); nbSea = 0; nbReef = 0; nbMarsh = 0; nbPlain = 0; nbMontain = 0; nbNull = 0; for( int iSector = 0; iSector < Sector.values().length; iSector++ ) { switch( getGame().getLand( position.getNeighbour( Sector.values()[iSector] ) ) ) { case None: nbNull++; break; case Sea: nbSea++; break; case Reef: nbReef++; break; case Marsh: nbMarsh++; break; case Plain: nbPlain++; break; case Montain: nbMontain++; break; } } switch( getGame().getLand( position ) ) { case Sea: if( nbSea == 0 ) { nbPlain += nbMontain; if( nbReef >= nbMarsh ) { if( nbReef >= nbPlain ) getGame().setLand( position, LandType.Reef ); else getGame().setLand( position, LandType.Plain ); } else { if( nbMarsh >= nbPlain ) getGame().setLand( position, LandType.Marsh ); else getGame().setLand( position, LandType.Plain ); } } break; case Reef: case Marsh: if( nbReef + nbSea + nbMarsh == 0 ) getGame().setLand( position, LandType.Plain ); break; case Plain: if( nbMontain + nbPlain == 0 ) { if( nbSea >= nbReef ) { if( nbSea >= nbMarsh ) getGame().setLand( position, LandType.Sea ); else getGame().setLand( position, LandType.Marsh ); } else { if( nbReef >= nbMarsh ) getGame().setLand( position, LandType.Reef ); else getGame().setLand( position, LandType.Marsh ); } } break; case Montain: /*if( nbMontain == 0 ) { if( (int)Math.round( Math.random() * 100 ) < 20 ) { if( nbSea > nbPlain ) AppMain.model().getGame().setLand( position, EnuLand.Sea ); else AppMain.model().getGame().setLand( position, EnuLand.Plain ); } }*/ break; } } } } /** * @return the landPercent */ public static int getLandPercent() { return s_landPercent; } /** * @param p_landPercent the landPercent to set */ public static void setLandPercent(int p_landPercent) { s_landPercent = p_landPercent; s_seaPercent = 100 - s_landPercent; } /** * @return the isHexagonMap */ public static boolean isHexagonMap() { return s_isHexagonMap; } /** * @param p_isHexagonMap the isHexagonMap to set */ public static void setHexagonMap(boolean p_isHexagonMap) { s_isHexagonMap = p_isHexagonMap; } }
package nl.mpi.arbil.data; import java.util.Vector; import javax.swing.ImageIcon; public class ContainerNode extends ArbilNode implements Comparable { private ArbilNode[] childNodes; protected String labelString; private ImageIcon imageIcon; public ContainerNode(String labelString, ImageIcon imageIcon, ArbilNode[] childNodes) { this.childNodes = childNodes; this.labelString = labelString; this.imageIcon = imageIcon; } public int compareTo(Object o) { return labelString.compareTo(o.toString()); } public void setChildNodes(ArbilNode[] childNodes) { this.childNodes = childNodes; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final ContainerNode other = (ContainerNode) obj; if ((this.labelString == null) ? (other.labelString != null) : !this.labelString.equals(other.labelString)) { return false; } return true; } @Override public int hashCode() { int hash = 17; // hash = 19 * hash + Arrays.deepHashCode(this.childNodes); // hash = 19 * hash + this.childNodes.hashCode(); hash = 19 * hash + (this.labelString != null ? this.labelString.hashCode() : 0); return hash; } @Override public String toString() { return labelString + " (" + childNodes.length + ")"; } @Override public ArbilNode[] getChildArray() { return childNodes; } @Override public ImageIcon getIcon() { return imageIcon; } @Override public void registerContainer(ArbilDataNodeContainer containerToAdd) { for (ArbilNode currentChild : childNodes) { currentChild.registerContainer(containerToAdd); } } @Override public void removeContainer(ArbilDataNodeContainer containerToRemove) { for (ArbilNode currentChild : childNodes) { currentChild.removeContainer(containerToRemove); } } @Override public ArbilDataNode[] getAllChildren() { throw new UnsupportedOperationException("Not supported yet."); } @Override public void getAllChildren(Vector<ArbilDataNode> allChildren) { throw new UnsupportedOperationException("Not supported yet."); } @Override public int getChildCount() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean hasCatalogue() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean hasHistory() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean hasLocalResource() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean hasResource() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isArchivableFile() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isCatalogue() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isChildNode() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isCmdiMetaDataNode() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isCorpus() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isDataLoaded() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isDirectory() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isEditable() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isEmptyMetaNode() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isFavorite() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isLoading() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isLocal() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isMetaDataNode() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isResourceSet() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isSession() { throw new UnsupportedOperationException("Not supported yet."); } }
package com.gmail.alexellingsen.g2skintweaks; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.preference.*; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import com.gmail.alexellingsen.g2skintweaks.preference.PreviewColorPreference; import com.gmail.alexellingsen.g2skintweaks.preference.PreviewImagePreference; import com.gmail.alexellingsen.g2skintweaks.utils.SettingsHelper; import it.gmariotti.android.colorpicker.calendarstock.ColorPickerDialog; import it.gmariotti.android.colorpicker.calendarstock.ColorPickerSwatch; import java.io.File; import java.io.IOException; import java.util.Arrays; public class MainActivity extends PreferenceActivity { private static final int CROP_IMAGE = 112; private static final int PICK_IMAGE = 111; private static final String INSTALL_SHORTCUT_ACTION = "com.android.launcher.action.INSTALL_SHORTCUT"; private static final String XPOSED_INSTALLER_PACKAGE = "de.robv.android.xposed.installer"; private MainFragment mainFragment; private static SettingsHelper settings = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); settings = new SettingsHelper(this); mainFragment = new MainFragment(); getFragmentManager() .beginTransaction() .replace(android.R.id.content, mainFragment) .commit(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode != RESULT_OK) return; if (requestCode == PICK_IMAGE) { cropImage(this, data.getData()); } else if (requestCode == CROP_IMAGE) { mainFragment.updateBackgroundImage(); Toast.makeText(this, getString(R.string.set_background_complete), Toast.LENGTH_LONG).show(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { boolean debugging = settings.getBoolean(Prefs.ENABLE_DEBUGGING, false); menu.findItem(R.id.action_enable_debugging).setChecked(debugging); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_create_shortcut) { createHomeShortcut(); return true; } else if (id == R.id.action_enable_debugging) { item.setChecked(!item.isChecked()); settings.putBoolean(Prefs.ENABLE_DEBUGGING, item.isChecked()); return true; } else if (id == R.id.action_settings) { Intent i = new Intent(getApplicationContext(), PrefsActivity.class); startActivity(i); return true; } return super.onOptionsItemSelected(item); } private void createHomeShortcut() { Intent intent = new Intent(getApplicationContext(), MainActivity.class); intent.setAction(Intent.ACTION_MAIN); Intent addIntent = new Intent(); addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent); addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name)); addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.drawable.ic_launcher) ); addIntent.setAction(INSTALL_SHORTCUT_ACTION); getApplicationContext().sendBroadcast(addIntent); } private static void pickImage(Activity activity) { if (!prepareFolder()) { Toast.makeText(activity, "Couldn't create folder.", Toast.LENGTH_SHORT).show(); return; } Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
package com.jcwhatever.bukkit.generic.player; import com.jcwhatever.bukkit.generic.GenericsLib; import com.jcwhatever.bukkit.generic.inventory.InventoryHelper; import com.jcwhatever.bukkit.generic.messaging.Messenger; import com.jcwhatever.bukkit.generic.mixins.IPlayerWrapper; import com.jcwhatever.bukkit.generic.storage.DataStorage; import com.jcwhatever.bukkit.generic.storage.DataStorage.DataPath; import com.jcwhatever.bukkit.generic.storage.IDataNode; import com.jcwhatever.bukkit.generic.storage.StorageLoadHandler; import com.jcwhatever.bukkit.generic.storage.StorageLoadResult; import com.jcwhatever.bukkit.generic.utils.EntryValidator; import com.jcwhatever.bukkit.generic.utils.PreCon; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.util.BlockIterator; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.UUID; import javax.annotation.Nullable; /** * Provides {@code Player} related utilities. */ public class PlayerHelper { private static final Object _sync = new Object(); private static IDataNode _nameData; /** * Determine if a player is online. * * @param p The player to check. */ public static boolean isOnline(Player p) { PreCon.notNull(p); Player[] players = Bukkit.getServer().getOnlinePlayers(); for (Player plyr : players) { if (plyr.getUniqueId().equals(p.getUniqueId())) return true; } return false; } /** * Get an online player by name. * * @param playerName The name of the player. */ @Nullable public static Player getPlayer(String playerName) { PreCon.notNullOrEmpty(playerName); UUID playerId = getPlayerId(playerName); if (playerId == null) return null; return Bukkit.getServer().getPlayer(playerId); } /** * Get an online player by Id. * * @param playerId The id of the player. */ @Nullable public static Player getPlayer(UUID playerId) { PreCon.notNull(playerId); return Bukkit.getServer().getPlayer(playerId); } /** * Get player object from provided object. * * <p>Attempts to retrieve the player object from one of the following * types of objects:</p> * * <p>{@code Player}, {@code IPlayerWrapper} (handle), * {@code UUID} (player id), {@code String} (player name)</p> * * @param player The object that represents a player. */ @Nullable public static Player getPlayer(Object player) { if (player instanceof Player) return (Player)player; if (player instanceof IPlayerWrapper) return ((IPlayerWrapper)player).getHandle(); if (player instanceof UUID) return getPlayer((UUID)player); if (player instanceof String) return getPlayer((String)player); return null; } /** * Gets player Id from name using stored id to name map. * Null if not found. * * <p> * Avoid usage due to low performance. * </p> * * @param playerName The name of the player */ @Nullable public static UUID getPlayerId(String playerName) { PreCon.notNull(playerName); IDataNode nameData = getNameData(); Set<String> ids = nameData.getSubNodeNames(); if (ids == null || ids.isEmpty()) return null; for (String idStr : ids) { String name = nameData.getString(idStr); if (name != null && name.equalsIgnoreCase(playerName)) { try { return UUID.fromString(idStr); } catch (Exception e) { e.printStackTrace(); return null; } } } return null; } /** * Get the name of a player from the player Id. * * <p>Checks the GenericsLib map of player names to player Id's</p> * * @param playerId The id of the player. * * @return Null if a record was not found. */ @Nullable public static String getPlayerName(UUID playerId) { PreCon.notNull(playerId); IDataNode nameData = getNameData(); return nameData.getString(playerId.toString()); } /** * Update the GenericsLib player name/player id map. * * @param playerId The id of the player. * @param name The new player name. */ public static void setPlayerName(UUID playerId, String name) { PreCon.notNull(playerId); PreCon.notNullOrEmpty(name); IDataNode nameData = getNameData(); String currentName = getPlayerName(playerId); if (name.equals(currentName)) return; synchronized (_sync) { nameData.set(playerId.toString(), name); } nameData.saveAsync(null); } /** * Reset player state. * * <ul> * <li>Inventory cleared, including armor.</li> * <li>GameMode set to SURVIVAL</li> * <li>Potion effects cleared</li> * <li>Food level restored</li> * <li>Exp set to 0</li> * <li>Flying turned off</li> * <li>Fire ticks set to 0</li> * <li>Fall distance set to 0</li> * </ul> * * @param p The player. */ public static void resetPlayer(Player p) { PreCon.notNull(p); InventoryHelper.clearAll(p.getInventory()); p.setGameMode(GameMode.SURVIVAL); p.getActivePotionEffects().clear(); p.setHealth(p.getMaxHealth()); p.setFoodLevel(20); p.setLevel(0); p.setExp(0); p.setFlying(false); p.setAllowFlight(false); p.setFireTicks(0); p.setFallDistance(0); } /** * Get a list of players that are near the specified location. * * @param loc The location to check. * @param chunkRadius The chunk radius to check in. */ public static List<Player> getClosestPlayers(Location loc, int chunkRadius) { PreCon.notNull(loc); PreCon.greaterThanZero(chunkRadius); return getClosestPlayers(loc, chunkRadius, null); } /** * Get a list of players that are near the specified location. * * @param loc The location to check. * @param chunkRadius The chunk radius to check in. * @param validator A validator used to validate if a player is a candidate to return. */ public static List<Player> getClosestPlayers(Location loc, int chunkRadius, @Nullable EntryValidator<Player> validator) { PreCon.notNull(loc); PreCon.greaterThanZero(chunkRadius); Chunk chunk = loc.getChunk(); List<Player> players = new ArrayList<Player>(20); for (int x = -chunkRadius; x <= chunkRadius; x++) { for (int z = -chunkRadius; z <= chunkRadius; z++) { Entity[] entities = chunk.getWorld().getChunkAt(chunk.getX() + x, chunk.getZ() + z).getEntities(); for (Entity entity : entities) { if (!(entity instanceof Player)) continue; if (entity.hasMetadata("NPC")) continue; if (validator != null && validator.isValid((Player)entity)) continue; players.add((Player)entity); } } } return players; } /** * Get the location closest to the specified player. * * @param p The player. * @param locations The location candidates. */ @Nullable public static Location getClosestLocation(Player p, Collection<Location> locations) { return getClosestLocation(p, locations, null); } /** * Get the location closest to the specified player. * * @param p The player. * @param locations The location candidates. * @param validator The validator used to determine if a location is a candidate. */ @Nullable public static Location getClosestLocation(Player p, Collection<Location> locations, @Nullable EntryValidator<Location> validator) { PreCon.notNull(p); PreCon.notNull(locations); Location closest = null; double closestDist = 0.0D; for (Location loc : locations) { if (validator != null && !validator.isValid(loc)) continue; double dist = 0.0D; if (closest == null || (dist = p.getLocation().distanceSquared(loc)) < closestDist) { closest = loc; closestDist = dist; } } return closest; } /** * Get the closest entity to a player. * * @param p The player. * @param range The search range. */ @Nullable public static Entity getClosestEntity(Player p, double range) { return getClosestEntity(p, range, range, range, null); } /** * Get the closest entity to a player. * * @param p The player. * @param range The search range. * @param validator The validator used to determine if an entity is a candidate. */ @Nullable public static Entity getClosestEntity(Player p, double range, @Nullable EntryValidator<Entity> validator) { return getClosestEntity(p, range, range, range, validator); } /** * Get the closest entity to a player. * * @param p The player. * @param rangeX The search range on the X axis. * @param rangeY The search range on the Y axis. * @param rangeZ The search range on the Z axis. */ @Nullable public static Entity getClosestEntity(Player p, double rangeX, double rangeY, double rangeZ) { return getClosestEntity(p, rangeX, rangeY, rangeZ, null); } /** * * @param p The player. * @param rangeX The search range on the X axis. * @param rangeY The search range on the Y axis. * @param rangeZ The search range on the Z axis. * @param validator The validator used to determine if an entity is a candidate. */ @Nullable public static Entity getClosestEntity(Player p, double rangeX, double rangeY, double rangeZ, @Nullable EntryValidator<Entity> validator) { PreCon.notNull(p); PreCon.positiveNumber(rangeX); PreCon.positiveNumber(rangeY); PreCon.positiveNumber(rangeZ); List<Entity> entities = p.getNearbyEntities(rangeX, rangeY, rangeZ); Entity closest = null; double closestDist = 0.0D; for (Entity entity : entities) { if (validator != null && !validator.isValid(entity)) continue; double dist = 0.0D; if (closest == null || (dist = p.getLocation().distanceSquared( entity.getLocation() )) < closestDist) { closest = entity; closestDist = dist; } } return closest; } /** * Get the closest living entity to a player. * * @param p The player. * @param range The search range. */ @Nullable public static LivingEntity getClosestLivingEntity(Player p, double range) { return getClosestLivingEntity(p, range, range, range, null); } /** * Get the closest living entity to a player. * * @param p The player. * @param range The search range. * @param validator The validator used to determine if a living entity is a candidate. */ @Nullable public static LivingEntity getClosestLivingEntity(Player p, double range, @Nullable EntryValidator<LivingEntity> validator) { return getClosestLivingEntity(p, range, range, range, validator); } /** * Get the closest living entity to a player. * * @param p The player. * @param rangeX The search range on the X axis. * @param rangeY The search range on the Y axis. * @param rangeZ The search range on the Z axis. */ @Nullable public static LivingEntity getClosestLivingEntity(Player p, double rangeX, double rangeY, double rangeZ) { return getClosestLivingEntity(p, rangeX, rangeY, rangeZ, null); } /** * Get the closest living entity to a player. * * @param p The player. * @param rangeX The search range on the X axis. * @param rangeY The search range on the Y axis. * @param rangeZ The search range on the Z axis. * @param validator The validator used to determine if a living entity is a candidate. */ @Nullable public static LivingEntity getClosestLivingEntity(Player p, double rangeX, double rangeY, double rangeZ, @Nullable EntryValidator<LivingEntity> validator) { PreCon.notNull(p); PreCon.positiveNumber(rangeX); PreCon.positiveNumber(rangeY); PreCon.positiveNumber(rangeZ); List<Entity> entities = p.getNearbyEntities(rangeX, rangeY, rangeZ); LivingEntity closest = null; double closestDist = 0.0D; for (Entity entity : entities) { if (!(entity instanceof LivingEntity)) continue; LivingEntity livingEntity = (LivingEntity)entity; if (validator != null && !validator.isValid(livingEntity)) continue; double dist = 0.0D; if (closest == null || (dist = p.getLocation().distanceSquared( entity.getLocation() )) < closestDist) { closest = livingEntity; closestDist = dist; } } return closest; } /** * Iterates over blocks in the direction the player is looking * until the max distance is reached or a block that isn't * {@code Material.AIR} is found. * * @param p The player. * @param maxDistance The max distance to search. */ @Nullable public static Block getTargetBlock(Player p, int maxDistance) { PreCon.notNull(p); PreCon.positiveNumber(maxDistance); BlockIterator bit = new BlockIterator(p, maxDistance); Block next; while(bit.hasNext()) { next = bit.next(); if (next != null && next.getType() != Material.AIR) return next; } return null; } // get the node that contains player id/name data. private static IDataNode getNameData() { if (_nameData == null) { synchronized (_sync) { IDataNode data = DataStorage.getStorage(GenericsLib.getPlugin(), new DataPath("player-names")); data.loadAsync(new StorageLoadHandler() { @Override public void onFinish(StorageLoadResult result) { if (!result.isLoaded()) Messenger.warning(GenericsLib.getPlugin(), "Failed to load player names file."); } }); _nameData = data; } } return _nameData; } }
package com.mebigfatguy.fbcontrib.detect; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.bcel.Constants; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.Field; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method; import org.apache.bcel.generic.Type; import com.mebigfatguy.fbcontrib.utils.BugType; import com.mebigfatguy.fbcontrib.utils.ToString; import com.mebigfatguy.fbcontrib.utils.Values; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.BytecodeScanningDetector; import edu.umd.cs.findbugs.Detector; import edu.umd.cs.findbugs.FieldAnnotation; import edu.umd.cs.findbugs.OpcodeStack; import edu.umd.cs.findbugs.Priorities; import edu.umd.cs.findbugs.ba.ClassContext; import edu.umd.cs.findbugs.ba.XFactory; import edu.umd.cs.findbugs.ba.XField; import edu.umd.cs.findbugs.ba.XMethod; /** * looks for executors that are never shutdown, which will not allow the * application to terminate */ public class HangingExecutors extends BytecodeScanningDetector { private static final Set<String> hangableSig; static { Set<String> hs = new HashSet<String>(); hs.add("Ljava/util/concurrent/ExecutorService;"); hs.add("Ljava/util/concurrent/AbstractExecutorService;"); hs.add("Ljava/util/concurrent/ForkJoinPool;"); hs.add("Ljava/util/concurrent/ScheduledThreadPoolExecutor;"); hs.add("Ljava/util/concurrent/ThreadPoolExecutor;"); hangableSig = Collections.unmodifiableSet(hs); } private static final Set<String> shutdownMethods; static { Set<String> sm = new HashSet<String>(); sm.add("shutdown"); sm.add("shutdownNow"); shutdownMethods = Collections.unmodifiableSet(sm); } private final BugReporter bugReporter; private Map<XField, AnnotationPriority> hangingFieldCandidates; private Map<XField, Integer> exemptExecutors; private OpcodeStack stack; private String methodName; private final LocalHangingExecutor localHEDetector; public HangingExecutors(BugReporter reporter) { this.bugReporter = reporter; this.localHEDetector = new LocalHangingExecutor(this, reporter); } /** * finds ExecutorService objects that don't get a call to the terminating * methods, and thus, never appear to be shutdown properly (the threads * exist until shutdown is called) * * @param classContext * the class context object of the currently parsed java class */ @Override public void visitClassContext(ClassContext classContext) { localHEDetector.visitClassContext(classContext); try { hangingFieldCandidates = new HashMap<XField, AnnotationPriority>(); exemptExecutors = new HashMap<XField, Integer>(); parseFieldsForHangingCandidates(classContext); if (!hangingFieldCandidates.isEmpty()) { stack = new OpcodeStack(); super.visitClassContext(classContext); reportHangingExecutorFieldBugs(); } } finally { stack = null; hangingFieldCandidates = null; exemptExecutors = null; } } private void parseFieldsForHangingCandidates(ClassContext classContext) { JavaClass cls = classContext.getJavaClass(); Field[] fields = cls.getFields(); for (Field f : fields) { String sig = f.getSignature(); if (hangableSig.contains(sig)) { hangingFieldCandidates.put(XFactory.createXField(cls.getClassName(), f.getName(), f.getSignature(), f.isStatic()), new AnnotationPriority(FieldAnnotation.fromBCELField(cls, f), NORMAL_PRIORITY)); } } } private void reportHangingExecutorFieldBugs() { for (Entry<XField, AnnotationPriority> entry : hangingFieldCandidates.entrySet()) { AnnotationPriority fieldAn = entry.getValue(); if (fieldAn != null) { bugReporter.reportBug(new BugInstance(this, BugType.HES_EXECUTOR_NEVER_SHUTDOWN.name(), fieldAn.priority).addClass(this) .addField(fieldAn.annotation).addField(entry.getKey())); } } } /** * implements the visitor to reset the opcode stack * * @param obj * the context object of the currently parsed code block */ @Override public void visitCode(Code obj) { stack.resetForMethodEntry(this); exemptExecutors.clear(); if (!hangingFieldCandidates.isEmpty()) { super.visitCode(obj); } } /** * implements the visitor to collect the method name * * @param obj * the context object of the currently parsed method */ @Override public void visitMethod(Method obj) { methodName = obj.getName(); } /** * Browses for calls to shutdown() and shutdownNow(), and if they happen, * remove the hanging candidate, as there is a chance it will be called. * * @param seen * the opcode of the currently parsed instruction */ @Override public void sawOpcode(int seen) { if (Values.STATIC_INITIALIZER.equals(methodName) || Values.CONSTRUCTOR.equals(methodName)) { lookForCustomThreadFactoriesInConstructors(seen); return; } try { stack.precomputation(this); if ((seen == INVOKEVIRTUAL) || (seen == INVOKEINTERFACE)) { String sig = getSigConstantOperand(); int argCount = Type.getArgumentTypes(sig).length; if (stack.getStackDepth() > argCount) { OpcodeStack.Item invokeeItem = stack.getStackItem(argCount); XField fieldOnWhichMethodIsInvoked = invokeeItem.getXField(); if (fieldOnWhichMethodIsInvoked != null) { removeCandidateIfShutdownCalled(fieldOnWhichMethodIsInvoked); addExemptionIfShutdownCalled(fieldOnWhichMethodIsInvoked); } } } // TODO Should not include private methods else if (seen == ARETURN) { removeFieldsThatGetReturned(); } else if (seen == PUTFIELD) { XField f = getXFieldOperand(); if (f != null) { reportOverwrittenField(f); } } else if (seen == IFNONNULL) { // indicates a null check, which means that we get an exemption // until the end of the branch OpcodeStack.Item nullCheckItem = stack.getStackItem(0); XField fieldWhichWasNullChecked = nullCheckItem.getXField(); if (fieldWhichWasNullChecked != null) { exemptExecutors.put(fieldWhichWasNullChecked, getPC() + getBranchOffset()); } } } finally { stack.sawOpcode(this, seen); } } private void lookForCustomThreadFactoriesInConstructors(int seen) { try { stack.precomputation(this); if (seen == PUTFIELD) { XField f = getXFieldOperand(); if ((f != null) && hangableSig.contains(f.getSignature())) { // look at the top of the stack, get the arguments passed // into the function that was called // and then pull out the types. // if the last type is a ThreadFactory, set the priority to // low XMethod method = stack.getStackItem(0).getReturnValueOf(); if (method != null) { Type[] argumentTypes = Type.getArgumentTypes(method.getSignature()); if (argumentTypes.length != 0) { if ("Ljava/util/concurrent/ThreadFactory;".equals(argumentTypes[argumentTypes.length - 1].getSignature())) { AnnotationPriority ap = this.hangingFieldCandidates.get(f); if (ap != null) { ap.priority = LOW_PRIORITY; this.hangingFieldCandidates.put(f, ap); } } } } } } } finally { stack.sawOpcode(this, seen); } } private void reportOverwrittenField(XField f) { if ("Ljava/util/concurrent/ExecutorService;".equals(f.getSignature()) && !checkException(f)) { bugReporter.reportBug(new BugInstance(this, BugType.HES_EXECUTOR_OVERWRITTEN_WITHOUT_SHUTDOWN.name(), Priorities.NORMAL_PRIORITY).addClass(this) .addMethod(this).addField(f).addSourceLine(this)); } // after it's been replaced, it no longer uses its exemption. exemptExecutors.remove(f); } private boolean checkException(XField f) { if (!exemptExecutors.containsKey(f)) { return false; } int i = exemptExecutors.get(f).intValue(); return (i == -1) || (getPC() < i); } private void removeFieldsThatGetReturned() { if (stack.getStackDepth() > 0) { OpcodeStack.Item returnItem = stack.getStackItem(0); // top thing on // the stack // was the // variable // being // returned XField field = returnItem.getXField(); if (field != null) { hangingFieldCandidates.remove(field); } } } private void addExemptionIfShutdownCalled(XField fieldOnWhichMethodIsInvoked) { String methodBeingInvoked = getNameConstantOperand(); if (shutdownMethods.contains(methodBeingInvoked)) { exemptExecutors.put(fieldOnWhichMethodIsInvoked, Values.NEGATIVE_ONE); } } private void removeCandidateIfShutdownCalled(XField fieldOnWhichMethodIsInvoked) { if (hangingFieldCandidates.containsKey(fieldOnWhichMethodIsInvoked)) { String methodBeingInvoked = getNameConstantOperand(); if (shutdownMethods.contains(methodBeingInvoked)) { hangingFieldCandidates.remove(fieldOnWhichMethodIsInvoked); } } } private static class AnnotationPriority { int priority; FieldAnnotation annotation; AnnotationPriority(FieldAnnotation annotation, int priority) { this.annotation = annotation; this.priority = priority; } @Override public String toString() { return ToString.build(this); } } } class LocalHangingExecutor extends LocalTypeDetector { private static final Map<String, Set<String>> watchedClassMethods; private static final Map<String, Integer> syncCtors; static { Set<String> forExecutors = new HashSet<String>(); forExecutors.add("newCachedThreadPool"); forExecutors.add("newFixedThreadPool"); forExecutors.add("newScheduledThreadPool"); forExecutors.add("newSingleThreadExecutor"); Map<String, Set<String>> wcm = new HashMap<String, Set<String>>(); wcm.put("java/util/concurrent/Executors", forExecutors); watchedClassMethods = Collections.unmodifiableMap(wcm); Map<String, Integer> sc = new HashMap<String, Integer>(); sc.put("java/util/concurrent/ThreadPoolExecutor", Integer.valueOf(Constants.MAJOR_1_5)); sc.put("java/util/concurrent/ScheduledThreadPoolExecutor", Integer.valueOf(Constants.MAJOR_1_5)); syncCtors = Collections.unmodifiableMap(sc); } private final BugReporter bugReporter; private final Detector delegatingDetector; public LocalHangingExecutor(Detector delegatingDetector, BugReporter reporter) { this.bugReporter = reporter; this.delegatingDetector = delegatingDetector; } @Override protected Map<String, Integer> getWatchedConstructors() { return syncCtors; } @Override protected Map<String, Set<String>> getWatchedClassMethods() { return watchedClassMethods; } @Override protected Set<String> getSelfReturningMethods() { return Collections.emptySet(); } @Override protected void reportBug(RegisterInfo cri) { // very important to report the bug under the top, parent detector, // otherwise it gets filtered out bugReporter.reportBug(new BugInstance(delegatingDetector, "HES_LOCAL_EXECUTOR_SERVICE", LOW_PRIORITY).addClass(this).addMethod(this) .addSourceLine(cri.getSourceLineAnnotation())); } @Override public void visitClassContext(ClassContext classContext) { super.visitClassContext(classContext); } @Override public void visitCode(Code obj) { super.visitCode(obj); } @Override public void visitMethod(Method obj) { super.visitMethod(obj); } }
package com.redhat.ceylon.compiler.typechecker.model; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; public class Util { /** * Is the second scope contained by the first scope? */ public static boolean contains(Scope outer, Scope inner) { while (inner!=null) { if (inner.equals(outer)) { return true; } inner = inner.getContainer(); } return false; } /** * Get the class or interface that "this" and "super" * refer to. */ public static ClassOrInterface getContainingClassOrInterface(Scope scope) { while (!(scope instanceof Package)) { if (scope instanceof ClassOrInterface) { return (ClassOrInterface) scope; } scope = scope.getContainer(); } return null; } /** * Get the class or interface that "outer" refers to. */ public static ProducedType getOuterClassOrInterface(Scope scope) { Boolean foundInner = false; while (!(scope instanceof Package)) { if (scope instanceof ClassOrInterface) { if (foundInner) { return ((ClassOrInterface) scope).getType(); } else { foundInner = true; } } scope = scope.getContainer(); } return null; } /** * Convenience method to bind a single type argument * to a toplevel type declaration. */ public static ProducedType producedType(TypeDeclaration declaration, ProducedType typeArgument) { return declaration.getProducedType(null, Collections.singletonList(typeArgument)); } /** * Convenience method to bind a list of type arguments * to a toplevel type declaration. */ public static ProducedType producedType(TypeDeclaration declaration, ProducedType... typeArguments) { return declaration.getProducedType(null, Arrays.asList(typeArguments)); } static boolean isResolvable(Declaration declaration) { return declaration.getName()!=null && !(declaration instanceof Setter) && //return getters, not setters !declaration.isAnonymous(); //don't return the type associated with an object dec } static boolean isParameter(Declaration d) { return d instanceof Parameter || d instanceof TypeParameter; } static boolean notOverloaded(Declaration d) { return !(d instanceof Functional) || !((Functional) d).isOverloaded() || ((Functional) d).isAbstraction(); } static boolean hasMatchingSignature(List<ProducedType> signature, Declaration d) { if (d instanceof Class && ((Class) d).isAbstract()) { return false; } if (d instanceof Functional) { Functional f = (Functional) d; if (f.isAbstraction()) { return false; } else { List<ParameterList> pls = f.getParameterLists(); if (pls!=null && !pls.isEmpty()) { List<Parameter> params = pls.get(0).getParameters(); if (signature.size()!=params.size()) { return false; } else { for (int i=0; i<params.size(); i++) { //ignore optionality for resolving overloads, since //all all Java method params are treated as optional ProducedType pdt = params.get(i).getType(); ProducedType sdt = signature.get(i); if (pdt==null || sdt==null) return false; ProducedType paramType = d.getUnit().getDefiniteType(pdt); ProducedType sigType = d.getUnit().getDefiniteType(sdt); TypeDeclaration paramTypeDec = paramType.getDeclaration(); TypeDeclaration sigTypeDec = sigType.getDeclaration(); if (sigTypeDec==null || paramTypeDec==null) return false; if (sigTypeDec instanceof UnknownType || paramTypeDec instanceof UnknownType) return false; if (!erase(sigTypeDec).inherits(erase(paramTypeDec)) && underlyingTypesUnequal(paramType, sigType)) { return false; } } return true; } } else { return false; } } } else { return false; } } private static boolean underlyingTypesUnequal(ProducedType paramType, ProducedType sigType) { return sigType.getUnderlyingType()==null || paramType.getUnderlyingType()==null || !sigType.getUnderlyingType().equals(paramType.getUnderlyingType()); } static boolean betterMatch(Declaration d, Declaration r) { if (d instanceof Functional && r instanceof Functional) { List<ParameterList> dpls = ((Functional) d).getParameterLists(); List<ParameterList> rpls = ((Functional) r).getParameterLists(); if (dpls!=null&&!dpls.isEmpty() && rpls!=null&&!rpls.isEmpty()) { List<Parameter> dpl = dpls.get(0).getParameters(); List<Parameter> rpl = rpls.get(0).getParameters(); if (dpl.size()==rpl.size()) { for (int i=0; i<dpl.size(); i++) { ProducedType paramType = d.getUnit().getDefiniteType(dpl.get(i).getType()); TypeDeclaration paramTypeDec = paramType.getDeclaration(); ProducedType otherType = d.getUnit().getDefiniteType(rpl.get(i).getType()); TypeDeclaration otherTypeDec = otherType.getDeclaration(); if (otherTypeDec==null || paramTypeDec==null) return false; if (otherTypeDec instanceof UnknownType || paramTypeDec instanceof UnknownType) return false; if (!erase(paramTypeDec).inherits(erase(otherTypeDec)) && underlyingTypesUnequal(paramType, otherType)) { return false; } } return true; } } } return false; } static boolean isNamed(String name, Declaration d) { String dname = d.getName(); return dname!=null && dname.equals(name); } private static TypeDeclaration erase(TypeDeclaration paramType) { if (paramType instanceof TypeParameter) { if ( paramType.getSatisfiedTypes().isEmpty() ) { return paramType.getExtendedTypeDeclaration(); } else { //TODO: is this actually correct? What is Java's // rule here? return paramType.getSatisfiedTypeDeclarations().get(0); } } else if (paramType instanceof UnionType || paramType instanceof IntersectionType) { //TODO: this is pretty sucky, cos in theory a // union or intersection might be assignable // to the parameter type with a typecast return paramType.getUnit().getObjectDeclaration(); } else { return paramType; } } static boolean isNameMatching(String startingWith, Declaration d) { return d.getName()!=null && d.getName().toLowerCase().startsWith(startingWith.toLowerCase()); } /** * Collect together type arguments given a list of * type arguments to a declaration and the receiving * type. * * @return a map of type parameter to type argument * * @param declaration a declaration * @param receivingType the receiving produced type * of which the declaration is a member * @param typeArguments explicit or inferred type * arguments of the declaration */ static Map<TypeParameter,ProducedType> arguments(Declaration declaration, ProducedType receivingType, List<ProducedType> typeArguments) { Map<TypeParameter, ProducedType> map = getArgumentsOfOuterType(receivingType); //now turn the type argument tuple into a //map from type parameter to argument if (declaration instanceof Generic) { Generic g = (Generic) declaration; for (int i=0; i<g.getTypeParameters().size(); i++) { if (typeArguments.size()>i) { map.put(g.getTypeParameters().get(i), typeArguments.get(i)); } } } return map; } public static Map<TypeParameter, ProducedType> getArgumentsOfOuterType( ProducedType receivingType) { Map<TypeParameter, ProducedType> map = new HashMap<TypeParameter, ProducedType>(); //make sure we collect all type arguments //from the whole qualified type! ProducedType dt = receivingType; while (dt!=null) { map.putAll(dt.getTypeArguments()); dt = dt.getQualifyingType(); } return map; } static <T> List<T> list(List<T> list, T element) { List<T> result = new ArrayList<T>(); result.addAll(list); result.add(element); return result; } /** * Helper method for eliminating duplicate types from * lists of types that form a union type, taking into * account that a subtype is a "duplicate" of its * supertype. */ public static void addToUnion(List<ProducedType> list, ProducedType pt) { if (pt==null) { return; } ProducedType selfType = pt.getDeclaration().getSelfType(); if (selfType!=null) { pt = selfType.substitute(pt.getTypeArguments()); //canonicalize type with self type to the self type } if (pt.getDeclaration() instanceof UnionType) { for (ProducedType t: pt.getDeclaration().getCaseTypes() ) { addToUnion( list, t.substitute(pt.getTypeArguments()) ); } } else { Boolean included = pt.isWellDefined(); if (included) { for (Iterator<ProducedType> iter = list.iterator(); iter.hasNext();) { ProducedType t = iter.next(); if (pt.isSubtypeOf(t)) { included = false; break; } //TODO: I think in some very rare occasions // this can cause stack overflows! else if (pt.isSupertypeOf(t)) { iter.remove(); } } } if (included) { list.add(pt); } } } /** * Helper method for eliminating duplicate types from * lists of types that form an intersection type, taking * into account that a supertype is a "duplicate" of its * subtype. */ public static void addToIntersection(List<ProducedType> list, ProducedType pt, Unit unit) { if (pt==null) { return; } ProducedType selfType = pt.getDeclaration().getSelfType(); if (selfType!=null) { pt = selfType.substitute(pt.getTypeArguments()); //canonicalize type with self type to the self type } if (pt.getDeclaration() instanceof IntersectionType) { for (ProducedType t: pt.getDeclaration().getSatisfiedTypes() ) { addToIntersection(list, t.substitute(pt.getTypeArguments()), unit); } } else { //implement the rule that Foo&Bar==Bottom if //there exists some Baz of Foo | Bar //i.e. the intersection of disjoint types is //empty for (ProducedType supertype: pt.getSupertypes()) { List<TypeDeclaration> ctds = supertype.getDeclaration().getCaseTypeDeclarations(); if (ctds!=null) { TypeDeclaration ctd=null; for (TypeDeclaration ct: ctds) { if (pt.getSupertype(ct)!=null) { ctd = ct; break; } } if (ctd!=null) { for (TypeDeclaration ct: ctds) { if (ct!=ctd) { for (ProducedType t: list) { if (t.getSupertype(ct)!=null) { list.clear(); list.add( new BottomType(unit).getType() ); return; } } } } } } } Boolean included = pt.isWellDefined(); if (included) { for (Iterator<ProducedType> iter = list.iterator(); iter.hasNext();) { ProducedType t = iter.next(); if (pt.isSupertypeOf(t)) { included = false; break; } //TODO: I think in some very rare occasions // this can cause stack overflows! else if (pt.isSubtypeOf(t)) { iter.remove(); } else if ( pt.getDeclaration().equals(t.getDeclaration()) ) { //canonicalize T<InX,OutX>&T<InY,OutY> to T<InX|InY,OutX&OutY> TypeDeclaration td = pt.getDeclaration(); List<ProducedType> args = new ArrayList<ProducedType>(); for (int i=0; i<td.getTypeParameters().size(); i++) { TypeParameter tp = td.getTypeParameters().get(i); ProducedType pta = pt.getTypeArguments().get(tp); ProducedType ta = t.getTypeArguments().get(tp); if (tp.isContravariant()) { args.add(unionType(pta, ta, unit)); } else if (tp.isCovariant()) { args.add(intersectionType(pta, ta, unit)); } else { TypeDeclaration ptad = pta.getDeclaration(); TypeDeclaration tad = ta.getDeclaration(); if ( !(ptad instanceof TypeParameter) && !(tad instanceof TypeParameter) && !ptad.equals(tad) ) { //if the two type arguments have provably //different types, then the meet of the //two intersected invariant types is empty //TODO: this is too weak, we should really // recursively search for type parameter // arguments and if we don't find any // we can reduce to Bottom list.clear(); args.add( new BottomType(unit).getType() ); return; } else { //TODO: this is not correct: the intersection // of two different instantiations of an // invariant type is actually Bottom // unless the type arguments are equivalent // or are type parameters that might // represent equivalent types at runtime. // Therefore, a method T x(T y) of Inv<T> // should have the signature: // Foo&Bar x(Foo|Bar y) // on the intersection Inv<Foo>&Inv<Bar>. // But this code gives it the more // restrictive signature: // Foo&Bar x(Foo&Bar y) args.add(intersectionType(pta, ta, unit)); } } } iter.remove(); //TODO: broken handling of member types! list.add( td.getProducedType(pt.getQualifyingType(), args) ); return; } else { //Unit unit = pt.getDeclaration().getUnit(); TypeDeclaration nd = unit.getNothingDeclaration(); if (pt.getDeclaration() instanceof Class && t.getDeclaration() instanceof Class || pt.getDeclaration() instanceof Interface && t.getDeclaration().equals(nd) || //t.getDeclaration().getQualifiedNameString().equals("ceylon.language.Nothing") || t.getDeclaration() instanceof Interface && pt.getDeclaration().equals(nd)) { //pt.getDeclaration().getQualifiedNameString().equals("ceylon.language.Nothing")) { //the meet of two classes unrelated by inheritance, or //of Nothing with an interface type is empty list.clear(); list.add( unit.getBottomDeclaration().getType() ); return; } } } } if (included) { list.add(pt); } } } public static String formatPath(List<String> path) { StringBuilder sb = new StringBuilder(); for (int i=0; i<path.size(); i++) { sb.append(path.get(i)); if (i<path.size()-1) sb.append('.'); } return sb.toString(); } static boolean addToSupertypes(List<ProducedType> list, ProducedType st) { for (ProducedType et: list) { if (st.getDeclaration().equals(et.getDeclaration()) && //return both a type and its self type st.isExactly(et)) { return false; } } list.add(st); return true; } public static ProducedType unionType(ProducedType lhst, ProducedType rhst, Unit unit) { List<ProducedType> list = new ArrayList<ProducedType>(); addToUnion(list, rhst); addToUnion(list, lhst); UnionType ut = new UnionType(unit); ut.setCaseTypes(list); return ut.getType(); } public static ProducedType intersectionType(ProducedType lhst, ProducedType rhst, Unit unit) { List<ProducedType> list = new ArrayList<ProducedType>(); addToIntersection(list, rhst, unit); addToIntersection(list, lhst, unit); IntersectionType it = new IntersectionType(unit); it.setSatisfiedTypes(list); return it.canonicalize().getType(); } public static boolean isElementOfUnion(UnionType ut, TypeDeclaration td) { for (TypeDeclaration ct: ut.getCaseTypeDeclarations()) { if (ct.equals(td)) return true; } return false; } public static boolean isElementOfIntersection(IntersectionType ut, TypeDeclaration td) { for (TypeDeclaration ct: ut.getSatisfiedTypeDeclarations()) { if (ct.equals(td)) return true; } return false; } public static Declaration lookupMember(List<Declaration> members, String name, List<ProducedType> signature, boolean includeParameters) { List<Declaration> results = new ArrayList<Declaration>(); Declaration inexactMatch = null; for (Declaration d: members) { if (isResolvable(d) && isNamed(name, d) && (includeParameters || !isParameter(d))) { if (signature==null) { //no argument types: either a type //declaration, an attribute, or a method //reference - don't return overloaded //forms of the declaration (instead //return the "abstraction" of them) if (notOverloaded(d)) { //by returning the first thing we //find, we implement the rule that //parameters hide attributes with //the same name in the body of a //class (a bit of a hack solution) return d; } } else { if (notOverloaded(d)) { //we have found either a non-overloaded //declaration, or the "abstraction" //which of all the overloaded forms //of the declaration inexactMatch = d; } if (hasMatchingSignature(signature, d)) { //we have found an exactly matching //overloaded declaration boolean add=true; for (Iterator<Declaration> i = results.iterator(); i.hasNext();) { Declaration o = i.next(); if (betterMatch(d, o)) { i.remove(); } else if (betterMatch(o, d)) { //TODO: note assymmetry here resulting in nondeterminate behavior! add=false; } } if (add) results.add(d); } } } } switch (results.size()) { case 0: //no exact match, so return the non-overloaded //declaration or the "abstraction" of the //overloaded declaration return inexactMatch; case 1: //exactly one exact match, so return it return results.get(0); default: //more than one matching overloaded declaration, //so return the "abstraction" of the overloaded //declaration return inexactMatch; } } }
package com.axelor.web; import javax.inject.Inject; import javax.inject.Singleton; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.axelor.auth.AuthService; import com.axelor.auth.db.Group; import com.axelor.auth.db.User; import com.axelor.db.JPA; import com.axelor.meta.MetaLoader; @Singleton public class InitServlet extends HttpServlet { private static final long serialVersionUID = -2493577642638670615L; private static final Logger LOG = LoggerFactory.getLogger(InitServlet.class); @Inject private AppSettings settings; @Inject private MetaLoader metaLoader; @Inject private AuthService authService; @Override public void init() throws ServletException { LOG.info("Initializing..."); JPA.runInTransaction(new Runnable() { @Override public void run() { createInitialUsers(); } }); try { String output = settings.get("temp.dir"); metaLoader.load(output); } catch (Exception e) { e.printStackTrace(); } super.init(); } private void createInitialUsers() { if (User.all().count() > 0) { return; } Group g1 = Group.findByCode("admins"); Group g2 = Group.findByCode("users"); if (g1 == null) { g1 = new Group("admins", "Administrators"); g1.save(); } if (g2 == null) { g2 = new Group("users", "Users"); g2.save(); } User u1 = new User("admin", "Administrator"); User u2 = new User("demo", "Demo User"); u1.setGroup(g1); u2.setGroup(g2); u1.setPassword("admin"); u2.setPassword("demo"); authService.encrypt(u1); authService.encrypt(u2); u1.save(); u2.save(); } }
package net.openid.appauth; import android.net.Uri; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import org.json.JSONObject; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import static net.openid.appauth.AdditionalParamsProcessor.builtInParams; import static net.openid.appauth.AdditionalParamsProcessor.checkAdditionalParams; import static net.openid.appauth.Preconditions.checkNotNull; public class RegistrationRequest { /** * OpenID Conenct 'application_type'. */ public static final String APPLICATION_TYPE_NATIVE = "native"; static final String PARAM_REDIRECT_URIS = "redirect_uris"; static final String PARAM_RESPONSE_TYPES = "response_types"; static final String PARAM_GRANT_TYPES = "grant_types"; static final String PARAM_APPLICATION_TYPE = "application_type"; static final String PARAM_SUBJECT_TYPE = "subject_type"; private static final Set<String> BUILT_IN_PARAMS = builtInParams( PARAM_REDIRECT_URIS, PARAM_RESPONSE_TYPES, PARAM_GRANT_TYPES, PARAM_APPLICATION_TYPE, PARAM_SUBJECT_TYPE ); public static final String SUBJECT_TYPE_PAIRWISE = "pairwise"; public static final String SUBJECT_TYPE_PUBLIC = "public"; /** * The service's {@link AuthorizationServiceConfiguration configuration}. * This configuration specifies how to connect to a particular OAuth provider. * Configurations may be * {@link AuthorizationServiceConfiguration#AuthorizationServiceConfiguration(Uri, * Uri, Uri) created manually}, or * {@link AuthorizationServiceConfiguration#fetchFromUrl(Uri, * AuthorizationServiceConfiguration.RetrieveConfigurationCallback) * via an OpenID Connect Discovery Document}. */ @NonNull public final AuthorizationServiceConfiguration configuration; /** * The client's redirect URI. */ @NonNull public final List<Uri> redirectUris; @NonNull public final String applicationType; @Nullable public final List<String> responseTypes; @Nullable public final List<String> grantTypes; @Nullable public final String subjectType; /** * Additional parameters to be passed as part of the request. */ @NonNull public final Map<String, String> additionalParameters; /** * Creates instances of {@link RegistrationRequest}. */ public static final class Builder { @NonNull private AuthorizationServiceConfiguration mConfiguration; @NonNull private List<Uri> mRedirectUris = new ArrayList<>(); @Nullable private List<String> mResponseTypes; @Nullable private List<String> mGrantTypes; @Nullable private String mSubjectType; @NonNull private Map<String, String> mAdditionalParameters = Collections.emptyMap(); /** * Creates a registration request builder with the specified mandatory properties. */ public Builder( @NonNull AuthorizationServiceConfiguration configuration, @NonNull List<Uri> redirectUri) { setConfiguration(configuration); setRedirectUriValues(redirectUri); } /** * Specifies the authorization service configuration for the request, which must not * be null or empty. */ @NonNull public Builder setConfiguration(@NonNull AuthorizationServiceConfiguration configuration) { mConfiguration = checkNotNull(configuration); return this; } @NonNull public Builder setRedirectUriValues(@NonNull Uri... redirectUriValues) { return setRedirectUriValues(Arrays.asList(redirectUriValues)); } @NonNull public Builder setRedirectUriValues(@NonNull List<Uri> redirectUriValues) { checkCollectionNotEmpty(redirectUriValues, "redirectUriValues cannot be null"); mRedirectUris = redirectUriValues; return this; } @NonNull public Builder setResponseTypeValues(@Nullable String... responseTypeValues) { return setResponseTypeValues(Arrays.asList(responseTypeValues)); } @NonNull public Builder setResponseTypeValues(@Nullable List<String> responseTypeValues) { mResponseTypes = responseTypeValues; return this; } @NonNull public Builder setGrantTypeValues(@Nullable String... grantTypeValues) { return setGrantTypeValues(Arrays.asList(grantTypeValues)); } @NonNull public Builder setGrantTypeValues(@Nullable List<String> grantTypeValues) { mGrantTypes = grantTypeValues; return this; } @NonNull public Builder setSubjectType(@Nullable String subjectType) { mSubjectType = subjectType; return this; } /** * Specifies additional parameters. Replaces any previously provided set of parameters. * Parameter keys and values cannot be null or empty. */ @NonNull public Builder setAdditionalParameters(@Nullable Map<String, String> additionalParameters) { mAdditionalParameters = checkAdditionalParams(additionalParameters, BUILT_IN_PARAMS); return this; } @NonNull public RegistrationRequest build() { return new RegistrationRequest( mConfiguration, Collections.unmodifiableList(mRedirectUris), mResponseTypes == null ? mResponseTypes : Collections.unmodifiableList(mResponseTypes), mGrantTypes == null ? mGrantTypes : Collections.unmodifiableList(mGrantTypes), mSubjectType, Collections.unmodifiableMap(mAdditionalParameters)); } } private RegistrationRequest( @NonNull AuthorizationServiceConfiguration configuration, @NonNull List<Uri> redirectUris, @Nullable List<String> responseTypes, @Nullable List<String> grantTypes, @Nullable String subjectType, @NonNull Map<String, String> additionalParameters) { this.configuration = configuration; this.redirectUris = redirectUris; this.responseTypes = responseTypes; this.grantTypes = grantTypes; this.subjectType = subjectType; this.additionalParameters = additionalParameters; this.applicationType = APPLICATION_TYPE_NATIVE; } /** * Converts the registration request to JSON for transmission. */ @NonNull public String toJsonString() { JSONObject json = new JSONObject(); JsonUtil.put(json, PARAM_REDIRECT_URIS, JsonUtil.toJsonArray(redirectUris)); JsonUtil.put(json, PARAM_APPLICATION_TYPE, applicationType); if (responseTypes != null) { JsonUtil.put(json, PARAM_RESPONSE_TYPES, JsonUtil.toJsonArray(responseTypes)); } if (grantTypes != null) { JsonUtil.put(json, PARAM_GRANT_TYPES, JsonUtil.toJsonArray(grantTypes)); } JsonUtil.putIfNotNull(json, PARAM_SUBJECT_TYPE, subjectType); for (Map.Entry<String, String> param : additionalParameters.entrySet()) { JsonUtil.put(json, param.getKey(), param.getValue()); } return json.toString(); } }
package com.mx.dxinl.library; import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; import android.database.DataSetObserver; import android.graphics.Canvas; import android.graphics.Paint; import android.os.Build; import android.support.annotation.ColorRes; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; public class TileWall extends AdapterView<BaseAdapter> { private static final int DEF_NUM_OF_ROW_AND_COLUMNS = 3; private BaseAdapter mAdapter; private DataSetObserver mDataSetObserver; private boolean changedAdapter; private Paint paint; private int numOfColumns; private int numOfRows; private int dividerColor; private float dividerWidth; /** * This flag will work only when both width measure spec mode and height measure spec mode * are {@link MeasureSpec#EXACTLY}. */ private boolean forceDividing; public TileWall(Context context) { this(context, null); } public TileWall(Context context, AttributeSet attrs) { this(context, attrs, 0); } public TileWall(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public TileWall(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(attrs); } private void init(AttributeSet attrs) { setWillNotDraw(false); TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.TileWall); numOfRows = typedArray.getInt( R.styleable.TileWall_numOfRows, DEF_NUM_OF_ROW_AND_COLUMNS); numOfColumns = typedArray.getInt( R.styleable.TileWall_numOfColumns, DEF_NUM_OF_ROW_AND_COLUMNS); dividerWidth = typedArray.getDimension( R.styleable.TileWall_dividerWidth, getResources().getDimension(R.dimen.deafult_divider_width)); dividerColor = typedArray.getColor( R.styleable.TileWall_dividerColor, getResources().getColor(R.color.gray_400)); forceDividing = typedArray.getBoolean(R.styleable.TileWall_forceDividing, false); typedArray.recycle(); paint = new Paint(); paint.setAntiAlias(true); paint.setStyle(Paint.Style.STROKE); mDataSetObserver = new DataSetObserver() { @Override public void onChanged() { requestLayout(); } @Override public void onInvalidated() { requestLayout(); } }; } @Override public BaseAdapter getAdapter() { return mAdapter; } @Override public void setAdapter(BaseAdapter adapter) { if (mAdapter != null) { mAdapter.unregisterDataSetObserver(mDataSetObserver); } if (mAdapter == null || !mAdapter.getClass().equals(adapter.getClass())) { changedAdapter = true; } mAdapter = adapter; mAdapter.registerDataSetObserver(mDataSetObserver); requestLayout(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int count = getChildCount(); if (changedAdapter) { addNewChildren(); changedAdapter = false; super.onMeasure(widthMeasureSpec, heightMeasureSpec); return; } else if (count < mAdapter.getCount()) { addChildren(); } else if (count > mAdapter.getCount()) { removeChildren(); } final int newCount = getChildCount(); updateChildren(count < newCount ? count : newCount); final int widthMode = MeasureSpec.getMode(widthMeasureSpec); final int heightMode = MeasureSpec.getMode(heightMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); if (widthMode == MeasureSpec.UNSPECIFIED || widthMode == MeasureSpec.AT_MOST) { forceDividing = false; int totalWidth = measureChildrenWidth(widthMeasureSpec, heightMeasureSpec); // To show all items, we must check whether total height is too large to show. // If yes, we shall decrease it. if (widthMode == MeasureSpec.AT_MOST && totalWidth > widthSize) { totalWidth = widthSize; } widthMeasureSpec = MeasureSpec.makeMeasureSpec(totalWidth, MeasureSpec.EXACTLY); } if (heightMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.AT_MOST) { forceDividing = false; int totalHeight = measureChildrenHeight(widthMeasureSpec, heightMeasureSpec); // To show all items, we must check whether total height is too large to show. // If yes, we shall decrease it. if (heightMode == MeasureSpec.AT_MOST && totalHeight > heightSize) { totalHeight = heightSize; } heightMeasureSpec = MeasureSpec.makeMeasureSpec(totalHeight, MeasureSpec.EXACTLY); } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } private void addNewChildren() { removeAllViewsInLayout(); int adapterCount = mAdapter.getCount(); addNewChildLayout(0, adapterCount); } private void addChildren() { int count = getChildCount(); int adapterCount = mAdapter.getCount(); addNewChildLayout(count, adapterCount); count = getChildCount(); checkChildCount(count, adapterCount); } private void addNewChildLayout(int count, int adapterCount) { for (int i = count; i < adapterCount && i < numOfColumns * numOfRows; i++) { View child = mAdapter.getView(i, null, this); ViewGroup.LayoutParams params = child.getLayoutParams(); LayoutParams lp; if (params == null) { lp = generateDefaultLayoutParams(); } else if (!checkLayoutParams(params)) { lp = generateLayoutParams(params); } else { lp = (LayoutParams) params; } lp.viewType = mAdapter.getItemViewType(i); child.setLayoutParams(lp); setOnChildClickListener(child, i); addViewInLayout(child, i, lp, true); } } @Override protected LayoutParams generateDefaultLayoutParams() { return new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0); } @Override protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { return new LayoutParams(p); } private void setOnChildClickListener(View child, final int position) { child.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { performItemClick(v, position, v.getId()); } }); } private void removeChildren() { int count = getChildCount(); int adapterCount = mAdapter.getCount(); for (int i = count - 1; i >= adapterCount; i removeViewInLayout(getChildAt(i)); } count = getChildCount(); checkChildCount(count, adapterCount); } private void checkChildCount(int count, int adapterCount) { int maxCount = numOfColumns * numOfRows; if (adapterCount > maxCount) { adapterCount = maxCount; } if (count != adapterCount) { throw new IllegalArgumentException( "Count of children do not equal to BaseAdapter.getCount()"); } } private void updateChildren(int count) { if (count > getChildCount()) { throw new IllegalArgumentException( "The argument(count) cannot be larger than children's count in TileWallLayout."); } for (int i = 0; i < count; i++) { View child = getChildAt(i); LayoutParams params = (LayoutParams) child.getLayoutParams(); View updateChild; int itemViewType = mAdapter.getItemViewType(i); if (params.viewType == itemViewType) { updateChild = mAdapter.getView(i, getChildAt(i), this); } else { updateChild = mAdapter.getView(i, null, this); params.viewType = itemViewType; } if (updateChild != child) { removeViewInLayout(child); addViewInLayout(updateChild, i, params, true); } } } private int measureChildrenWidth(int widthMeasureSpec, int heightMeasureSpec) { int widthHint = MeasureSpec.getSize(widthMeasureSpec); int maxWidth = 0; int count = getChildCount(); for (int i = 0; i < count; i++) { View child = getChildAt(i); LayoutParams p = (LayoutParams) child.getLayoutParams(); if (p == null) { p = generateDefaultLayoutParams(); child.setLayoutParams(p); } int childHeightSpec = getChildMeasureSpec(heightMeasureSpec, getPaddingBottom() + getPaddingTop(), p.height); int lpWidth = p.width; int childWidthSpec; if (lpWidth > 0) { childWidthSpec = MeasureSpec.makeMeasureSpec(lpWidth, MeasureSpec.EXACTLY); } else { childWidthSpec = MeasureSpec.makeMeasureSpec(widthHint, MeasureSpec.UNSPECIFIED); } child.measure(childWidthSpec, childHeightSpec); int measuredWidth = child.getMeasuredWidth(); if (measuredWidth > maxWidth) { maxWidth = measuredWidth; } } int paddingHorizontal = getPaddingLeft() + getPaddingRight(); int columnsCount = count > numOfColumns ? numOfColumns : count; int totalDividerWidth = (int) (dividerWidth * (columnsCount + 1)); return maxWidth * columnsCount + totalDividerWidth + paddingHorizontal; } private int measureChildrenHeight(int widthMeasureSpec, int heightMeasureSpec) { int heightHint = MeasureSpec.getSize(heightMeasureSpec); int maxHeight = 0; int count = getChildCount(); for (int i = 0; i < count; i++) { View child = getChildAt(i); LayoutParams p = (LayoutParams) child.getLayoutParams(); if (p == null) { p = generateDefaultLayoutParams(); child.setLayoutParams(p); } int childWidthSpec = getChildMeasureSpec(widthMeasureSpec, getPaddingLeft() + getPaddingRight(), p.width); int lpHeight = p.height; int childHeightSpec; if (lpHeight > 0) { childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY); } else { childHeightSpec = MeasureSpec.makeMeasureSpec(heightHint, MeasureSpec.UNSPECIFIED); } child.measure(childWidthSpec, childHeightSpec); int measuredHeight = child.getMeasuredHeight(); if (measuredHeight > maxHeight) { maxHeight = measuredHeight; } } int paddingVertical = getPaddingTop() + getPaddingBottom(); int rowsCount = (count / numOfColumns) + (count % numOfColumns > 0 ? 1 : 0); int totalDividerHeight = (int) (dividerWidth * (rowsCount + 1)); return maxHeight * rowsCount + totalDividerHeight + paddingVertical; } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int count = getChildCount(); int paddingLeft = getPaddingLeft(); int paddingRight = getPaddingRight(); int paddingTop = getPaddingTop(); int paddingBottom = getPaddingBottom(); int paddingHorizontal = paddingLeft + paddingRight; int paddingVertical = paddingTop + paddingBottom; int width; int height; if (!forceDividing && count < numOfColumns) { int totalDividerWidth = (int) (dividerWidth * (count + 1)); int totalDividerHeight = (int) (dividerWidth * 2); width = (getWidth() - totalDividerWidth - paddingHorizontal) / count; height = (getHeight() - totalDividerHeight - paddingVertical); } else { int totalDividerWidth = (int) (dividerWidth * (numOfColumns + 1)); width = (getWidth() - totalDividerWidth - paddingHorizontal) / numOfColumns; int rowsCount = count / numOfColumns + (count % numOfColumns > 0 ? 1 : 0); if (!forceDividing && rowsCount < numOfRows) { int totalDividerHeight = (int) (dividerWidth * (rowsCount + 1)); height = (getHeight() - totalDividerHeight - paddingVertical) / rowsCount; } else { int totalDividerHeight = (int) (dividerWidth * (numOfRows + 1)); height = (getHeight() - totalDividerHeight - paddingVertical) / numOfRows; } } for (int i = 0; i < numOfRows; i++) { for (int j = 0; j < numOfColumns; j++) { int index = i * numOfColumns + j; if (index >= count) { return; } View child = getChildAt(index); if (child == null) { continue; } int left = (int) ((dividerWidth * (j + 1)) + width * j) + paddingLeft; int right = left + width; int top = (int) ((dividerWidth * (i + 1)) + height * i) + paddingTop; int bottom = top + height; int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY); int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); child.measure(childWidthMeasureSpec, childHeightMeasureSpec); child.layout(left, top, right, bottom); } } } @Override protected boolean checkLayoutParams(ViewGroup.LayoutParams params) { return params instanceof LayoutParams; } /** * This method is not supported. * * @return ignored * @throws UnsupportedOperationException */ @Deprecated @Override public View getSelectedView() { throw new UnsupportedOperationException("getSelectedView() is not supported in TileWallLayout."); } /** * This method is not supported. * * @param position ignored * @throws UnsupportedOperationException */ @Deprecated @Override public void setSelection(int position) { throw new UnsupportedOperationException("setSelection(int) is not supported in TileWallLayout."); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (dividerWidth > 0) { drawDivider(canvas); } } private void drawDivider(Canvas canvas) { int count = getChildCount(); paint.setColor(dividerColor); paint.setStrokeWidth(dividerWidth); int halfDividerWidth = (int) (dividerWidth / 2f); for (int i = 0; i < count; i++) { View child = getChildAt(i); if (child == null) { continue; } int left = child.getLeft() - halfDividerWidth; int top = child.getTop() - halfDividerWidth; int right = child.getRight() + halfDividerWidth; int bottom = child.getBottom() + halfDividerWidth; canvas.drawLine(left, top - halfDividerWidth, left, bottom + halfDividerWidth, paint); canvas.drawLine(left - halfDividerWidth, top, right + halfDividerWidth, top, paint); canvas.drawLine(right, top - halfDividerWidth, right, bottom + halfDividerWidth, paint); canvas.drawLine(left - halfDividerWidth, bottom, right + halfDividerWidth, bottom, paint); } } @SuppressWarnings("unused") public TileWall setNumColumns(int numOfColumns) { this.numOfColumns = numOfColumns; return this; } @SuppressWarnings("unused") public TileWall setNumRows(int numOfRows) { this.numOfRows = numOfRows; return this; } @SuppressWarnings("unused") public TileWall setDividerWidth(float dividerWidth) { this.dividerWidth = dividerWidth; return this; } @SuppressWarnings("unused") public TileWall setDividerColor(@ColorRes int resId) { dividerColor = getResources().getColor(resId); return this; } @SuppressWarnings("unused") public TileWall setForceDividing(boolean forceDividing) { this.forceDividing = forceDividing; return this; } private static final class LayoutParams extends ViewGroup.LayoutParams { int viewType; public LayoutParams(Context c, AttributeSet attrs) { super(c, attrs); } public LayoutParams(int width, int height) { super(width, height); } public LayoutParams(int width, int height, int viewType) { super(width, height); this.viewType = viewType; } public LayoutParams(ViewGroup.LayoutParams source) { super(source); } } }
package com.weigan.loopview; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Typeface; import android.os.Handler; import android.util.AttributeSet; import android.util.Log; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; public class LoopView extends View { private float scaleX = 1.05F; private static final int DEFAULT_TEXT_SIZE = (int) (Resources.getSystem().getDisplayMetrics().density * 15); private static final float DEFAULT_LINE_SPACE = 1f; private static final int DEFAULT_VISIBIE_ITEMS = 9; public static final int SCROLL_STATE_IDLE = 0; public static final int SCROLL_STATE_SETTING = 1; public static final int SCROLL_STATE_DRAGGING = 2; public static final int SCROLL_STATE_SCROLLING = 3; int lastScrollState = SCROLL_STATE_IDLE; int currentScrollState = SCROLL_STATE_SETTING; public enum ACTION { CLICK, FLING, DRAG } private Context context; Handler handler; private GestureDetector flingGestureDetector; OnItemSelectedListener onItemSelectedListener; OnItemScrollListener mOnItemScrollListener; // Timer mTimer; ScheduledExecutorService mExecutor = Executors.newSingleThreadScheduledExecutor(); private ScheduledFuture<?> mFuture; private Paint paintOuterText; private Paint paintCenterText; private Paint paintIndicator; List<IndexString> items; int textSize; int itemTextHeight; int textHeight; int outerTextColor; int centerTextColor; int dividerColor; float lineSpacingMultiplier; boolean isLoop; int firstLineY; int secondLineY; int totalScrollY; int initPosition; int preCurrentIndex; int change; int itemsVisibleCount; HashMap<Integer,IndexString> drawingStrings; // HashMap<String,Integer> drawingStr int measuredHeight; int measuredWidth; int halfCircumference; int radius; private int mOffset = 0; private float previousY; long startTime = 0; private Rect tempRect = new Rect(); private int paddingLeft, paddingRight; private Typeface typeface = Typeface.MONOSPACE; /** * set text line space, must more than 1 * @param lineSpacingMultiplier */ public void setLineSpacingMultiplier(float lineSpacingMultiplier) { if (lineSpacingMultiplier > 1.0f) { this.lineSpacingMultiplier = lineSpacingMultiplier; } } /** * set outer text color * @param centerTextColor */ public void setCenterTextColor(int centerTextColor) { this.centerTextColor = centerTextColor; if(paintCenterText != null){ paintCenterText.setColor(centerTextColor); } } /** * set center text color * @param outerTextColor */ public void setOuterTextColor(int outerTextColor) { this.outerTextColor = outerTextColor; if(paintOuterText != null){ paintOuterText.setColor(outerTextColor); } } /** * set divider color * @param dividerColor */ public void setDividerColor(int dividerColor) { this.dividerColor = dividerColor; if(paintIndicator != null){ paintIndicator.setColor(dividerColor); } } /** * set text typeface * @param typeface */ public void setTypeface(Typeface typeface) { this.typeface = typeface; } public LoopView(Context context) { super(context); initLoopView(context, null); } public LoopView(Context context, AttributeSet attributeset) { super(context, attributeset); initLoopView(context, attributeset); } public LoopView(Context context, AttributeSet attributeset, int defStyleAttr) { super(context, attributeset, defStyleAttr); initLoopView(context, attributeset); } private void initLoopView(Context context, AttributeSet attributeset) { this.context = context; handler = new MessageHandler(this); flingGestureDetector = new GestureDetector(context, new LoopViewGestureListener(this)); flingGestureDetector.setIsLongpressEnabled(false); TypedArray typedArray = context.obtainStyledAttributes(attributeset, R.styleable.LoopView); if (typedArray != null) { textSize = typedArray.getInteger(R.styleable.LoopView_awv_textsize, DEFAULT_TEXT_SIZE); textSize = (int) (Resources.getSystem().getDisplayMetrics().density * textSize); lineSpacingMultiplier = typedArray.getFloat(R.styleable.LoopView_awv_lineSpace, DEFAULT_LINE_SPACE); centerTextColor = typedArray.getInteger(R.styleable.LoopView_awv_centerTextColor, 0xff313131); outerTextColor = typedArray.getInteger(R.styleable.LoopView_awv_outerTextColor, 0xffafafaf); dividerColor = typedArray.getInteger(R.styleable.LoopView_awv_dividerTextColor, 0xffc5c5c5); itemsVisibleCount = typedArray.getInteger(R.styleable.LoopView_awv_itemsVisibleCount, DEFAULT_VISIBIE_ITEMS); if (itemsVisibleCount % 2 == 0) { itemsVisibleCount = DEFAULT_VISIBIE_ITEMS; } isLoop = typedArray.getBoolean(R.styleable.LoopView_awv_isLoop, true); typedArray.recycle(); } drawingStrings=new HashMap<>(); totalScrollY = 0; initPosition = -1; } /** * visible item count, must be odd number * * @param visibleNumber */ public void setItemsVisibleCount(int visibleNumber) { if (visibleNumber % 2 == 0) { return; } if (visibleNumber != itemsVisibleCount) { itemsVisibleCount = visibleNumber; drawingStrings=new HashMap<>(); } } private void initPaintsIfPossible() { if (paintOuterText == null) { paintOuterText = new Paint(); paintOuterText.setColor(outerTextColor); paintOuterText.setAntiAlias(true); paintOuterText.setTypeface(typeface); paintOuterText.setTextSize(textSize); } if (paintCenterText == null) { paintCenterText = new Paint(); paintCenterText.setColor(centerTextColor); paintCenterText.setAntiAlias(true); paintCenterText.setTextScaleX(scaleX); paintCenterText.setTypeface(typeface); paintCenterText.setTextSize(textSize); } if (paintIndicator == null) { paintIndicator = new Paint(); paintIndicator.setColor(dividerColor); paintIndicator.setAntiAlias(true); } } private void remeasure() { if (items == null || items.isEmpty()) { return; } measuredWidth = getMeasuredWidth(); measuredHeight = getMeasuredHeight(); if (measuredWidth == 0 || measuredHeight == 0) { return; } paddingLeft = getPaddingLeft(); paddingRight = getPaddingRight(); measuredWidth = measuredWidth - paddingRight; paintCenterText.getTextBounds("\u661F\u671F", 0, 2, tempRect); textHeight = tempRect.height(); halfCircumference = (int) (measuredHeight * Math.PI / 2); itemTextHeight = (int) (halfCircumference / (lineSpacingMultiplier * (itemsVisibleCount - 1))); radius = measuredHeight / 2; firstLineY = (int) ((measuredHeight - lineSpacingMultiplier * itemTextHeight) / 2.0F); secondLineY = (int) ((measuredHeight + lineSpacingMultiplier * itemTextHeight) / 2.0F); if (initPosition == -1) { if (isLoop) { initPosition = (items.size() + 1) / 2; } else { initPosition = 0; } } preCurrentIndex = initPosition; } void smoothScroll(ACTION action) { cancelFuture(); if (action == ACTION.FLING || action == ACTION.DRAG) { float itemHeight = lineSpacingMultiplier * itemTextHeight; mOffset = (int) ((totalScrollY % itemHeight + itemHeight) % itemHeight); if ((float) mOffset > itemHeight / 2.0F) { mOffset = (int) (itemHeight - (float) mOffset); } else { mOffset = -mOffset; } } mFuture = mExecutor.scheduleWithFixedDelay(new SmoothScrollTimerTask(this, mOffset), 0, 10, TimeUnit.MILLISECONDS); changeScrollState(SCROLL_STATE_SCROLLING); } protected final void scrollBy(float velocityY) { cancelFuture(); // change this number, can change fling speed int velocityFling = 10; mFuture = mExecutor.scheduleWithFixedDelay(new InertiaTimerTask(this, velocityY), 0, velocityFling, TimeUnit.MILLISECONDS); changeScrollState(SCROLL_STATE_DRAGGING); } public void cancelFuture() { if (mFuture != null && !mFuture.isCancelled()) { mFuture.cancel(true); mFuture = null; changeScrollState(SCROLL_STATE_IDLE); } } /** * * @param methodName */ private void printMethodStackTrace(String methodName){ StackTraceElement[] invokers = Thread.currentThread().getStackTrace(); StringBuilder sb = new StringBuilder("printMethodStackTrace "); sb.append(methodName); sb.append(" "); for(int i= invokers.length -1;i >= 4;i StackTraceElement invoker = invokers[i]; sb.append(String.format("%s(%d).%s",invoker.getFileName(),invoker.getLineNumber(),invoker.getMethodName())); if(i > 4){ sb.append(" } } Log.i("printMethodStackTrace",sb.toString()); } private void changeScrollState(int scrollState){ if(scrollState != currentScrollState && !handler.hasMessages(MessageHandler.WHAT_SMOOTH_SCROLL_INERTIA)){ lastScrollState = currentScrollState; currentScrollState = scrollState; // if(scrollState == SCROLL_STATE_SCROLLING || scrollState == SCROLL_STATE_IDLE){ // printMethodStackTrace("changeScrollState"); } } /** * set not loop */ public void setNotLoop() { isLoop = false; } /** * set text size in dp * @param size */ public final void setTextSize(float size) { if (size > 0.0F) { textSize = (int) (context.getResources().getDisplayMetrics().density * size); if(paintOuterText != null){ paintOuterText.setTextSize(textSize); } if(paintCenterText != null){ paintCenterText.setTextSize(textSize); } } } public final void setInitPosition(int initPosition) { if (initPosition < 0) { this.initPosition = 0; } else { if (items != null && items.size() > initPosition) { this.initPosition = initPosition; } } } public final void setListener(OnItemSelectedListener OnItemSelectedListener) { onItemSelectedListener = OnItemSelectedListener; } public final void setOnItemScrollListener(OnItemScrollListener mOnItemScrollListener){ this.mOnItemScrollListener = mOnItemScrollListener; } public final void setItems(List<String> items) { this.items = convertData(items); remeasure(); invalidate(); } public List<IndexString> convertData(List<String> items){ List<IndexString> data=new ArrayList<>(); for (int i = 0; i < items.size(); i++) { data.add(new IndexString(i,items.get(i))); } return data; } public final int getSelectedItem() { return preCurrentIndex; } // protected final void scrollBy(float velocityY) { // Timer timer = new Timer(); // mTimer = timer; // timer.schedule(new InertiaTimerTask(this, velocityY, timer), 0L, 20L); protected final void onItemSelected() { if (onItemSelectedListener != null) { postDelayed(new OnItemSelectedRunnable(this), 200L); } } public void setScaleX(float scaleX) { this.scaleX = scaleX; } /** * set current item position * @param position */ public void setCurrentPosition(int position) { if (items == null || items.isEmpty()) { return; } int size = items.size(); if (position >= 0 && position < size && position != getSelectedItem()) { initPosition = position; totalScrollY = 0; mOffset = 0; changeScrollState(SCROLL_STATE_SETTING); invalidate(); } } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (items == null || items.isEmpty()) { return; } change = (int) (totalScrollY / (lineSpacingMultiplier * itemTextHeight)); preCurrentIndex = initPosition + change % items.size(); if (!isLoop) { if (preCurrentIndex < 0) { preCurrentIndex = 0; } if (preCurrentIndex > items.size() - 1) { preCurrentIndex = items.size() - 1; } } else { if (preCurrentIndex < 0) { preCurrentIndex = items.size() + preCurrentIndex; } if (preCurrentIndex > items.size() - 1) { preCurrentIndex = preCurrentIndex - items.size(); } } int j2 = (int) (totalScrollY % (lineSpacingMultiplier * itemTextHeight)); // put value to drawingString int k1 = 0; while (k1 < itemsVisibleCount) { int l1 = preCurrentIndex - (itemsVisibleCount / 2 - k1); if (isLoop) { while (l1 < 0) { l1 = l1 + items.size(); } while (l1 > items.size() - 1) { l1 = l1 - items.size(); } drawingStrings.put(k1, items.get(l1)); } else if (l1 < 0) { // drawingStrings[k1] = ""; drawingStrings.put(k1,new IndexString()); } else if (l1 > items.size() - 1) { // drawingStrings[k1] = ""; drawingStrings.put(k1,new IndexString()); } else { // drawingStrings[k1] = items.get(l1); drawingStrings.put(k1,items.get(l1)); } k1++; } canvas.drawLine(paddingLeft, firstLineY, measuredWidth, firstLineY, paintIndicator); canvas.drawLine(paddingLeft, secondLineY, measuredWidth, secondLineY, paintIndicator); int i = 0; while (i < itemsVisibleCount) { canvas.save(); float itemHeight = itemTextHeight * lineSpacingMultiplier; double radian = ((itemHeight * i - j2) * Math.PI) / halfCircumference; if (radian >= Math.PI || radian <= 0) { canvas.restore(); } else { int translateY = (int) (radius - Math.cos(radian) * radius - (Math.sin(radian) * itemTextHeight) / 2D); canvas.translate(0.0F, translateY); canvas.scale(1.0F, (float) Math.sin(radian)); if (translateY <= firstLineY && itemTextHeight + translateY >= firstLineY) { // first divider canvas.save(); canvas.clipRect(0, 0, measuredWidth, firstLineY - translateY); drawOuterText(canvas, i); canvas.restore(); canvas.save(); canvas.clipRect(0, firstLineY - translateY, measuredWidth, (int) (itemHeight)); drawCenterText(canvas, i); canvas.restore(); } else if (translateY <= secondLineY && itemTextHeight + translateY >= secondLineY) { // second divider canvas.save(); canvas.clipRect(0, 0, measuredWidth, secondLineY - translateY); drawCenterText(canvas, i); canvas.restore(); canvas.save(); canvas.clipRect(0, secondLineY - translateY, measuredWidth, (int) (itemHeight)); drawOuterText(canvas, i); canvas.restore(); } else if (translateY >= firstLineY && itemTextHeight + translateY <= secondLineY) { // center item canvas.clipRect(0, 0, measuredWidth, (int) (itemHeight)); drawCenterText(canvas, i); } else { // other item canvas.clipRect(0, 0, measuredWidth, (int) (itemHeight)); drawOuterText(canvas, i); } canvas.restore(); } i++; } if(currentScrollState != lastScrollState){ int oldScrollState = lastScrollState; lastScrollState = currentScrollState; if(mOnItemScrollListener != null){ mOnItemScrollListener.onItemScrollStateChanged(this,getSelectedItem(),oldScrollState,currentScrollState,totalScrollY); } } if(currentScrollState == SCROLL_STATE_DRAGGING || currentScrollState == SCROLL_STATE_SCROLLING){ if(mOnItemScrollListener != null){ mOnItemScrollListener.onItemScrolling(this,getSelectedItem(),currentScrollState,totalScrollY); } } } private void drawOuterText(Canvas canvas, int position) { canvas.drawText(drawingStrings.get(position).string, getTextX(drawingStrings.get(position).string, paintOuterText, tempRect), getDrawingY(), paintOuterText); } private void drawCenterText(Canvas canvas, int position) { canvas.drawText(drawingStrings.get(position).string, getTextX(drawingStrings.get(position).string, paintOuterText, tempRect), getDrawingY(), paintCenterText); } private int getDrawingY() { if (itemTextHeight > textHeight) { return itemTextHeight - ((itemTextHeight - textHeight) / 2); } else { return itemTextHeight; } } // text start drawing position private int getTextX(String a, Paint paint, Rect rect) { paint.getTextBounds(a, 0, a.length(), rect); int textWidth = rect.width(); textWidth *= scaleX; return (measuredWidth - paddingLeft - textWidth) / 2 + paddingLeft; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); initPaintsIfPossible(); remeasure(); } @Override public boolean onTouchEvent(MotionEvent event) { boolean eventConsumed = flingGestureDetector.onTouchEvent(event); float itemHeight = lineSpacingMultiplier * itemTextHeight; switch (event.getAction()) { case MotionEvent.ACTION_DOWN: startTime = System.currentTimeMillis(); cancelFuture(); previousY = event.getRawY(); if (getParent() != null) { getParent().requestDisallowInterceptTouchEvent(true); } break; case MotionEvent.ACTION_MOVE: float dy = previousY - event.getRawY(); previousY = event.getRawY(); totalScrollY = (int) (totalScrollY + dy); if (!isLoop) { float top = -initPosition * itemHeight; float bottom = (items.size() - 1 - initPosition) * itemHeight; if (totalScrollY < top) { totalScrollY = (int) top; } else if (totalScrollY > bottom) { totalScrollY = (int) bottom; } } changeScrollState(SCROLL_STATE_DRAGGING); break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: default: if (!eventConsumed) { float y = event.getY(); double l = Math.acos((radius - y) / radius) * radius; int circlePosition = (int) ((l + itemHeight / 2) / itemHeight); float extraOffset = (totalScrollY % itemHeight + itemHeight) % itemHeight; mOffset = (int) ((circlePosition - itemsVisibleCount / 2) * itemHeight - extraOffset); if ((System.currentTimeMillis() - startTime) > 120) { smoothScroll(ACTION.DRAG); } else { smoothScroll(ACTION.CLICK); } } if (getParent() != null) { getParent().requestDisallowInterceptTouchEvent(false); } break; } invalidate(); return true; } class IndexString { public IndexString(){ this.string=""; } public IndexString(int index,String str){ this.index=index;this.string=str; } private String string; private int index; } }
package lucee.runtime.tag; import lucee.runtime.exp.PageException; import lucee.runtime.ext.tag.BodyTagImpl; import lucee.runtime.op.Caster; public final class Setting extends BodyTagImpl { private boolean hasBody; /** set the value requesttimeout * @param requesttimeout value to set **/ public void setRequesttimeout(double requesttimeout) { if (requesttimeout <= 0) pageContext.setRequestTimeout(Long.MAX_VALUE); else pageContext.setRequestTimeout((long)(requesttimeout*1000)); } /** set the value showdebugoutput * Yes or No. When set to No, showDebugOutput suppresses debugging information that would * otherwise display at the end of the generated page.Default is Yes. * @param showdebugoutput value to set **/ public void setShowdebugoutput(boolean showdebugoutput) { if(pageContext.getConfig().debug())pageContext.getDebugger().setOutput(showdebugoutput); } /** set the value enablecfoutputonly * Yes or No. When set to Yes, cfsetting blocks output of HTML that resides outside cfoutput tags. * @param enablecfoutputonly value to set * @throws PageException **/ public void setEnablecfoutputonly(Object enablecfoutputonly) throws PageException { if(enablecfoutputonly instanceof String && Caster.toString(enablecfoutputonly).trim().equalsIgnoreCase("reset")) { pageContext.setCFOutputOnly((short)0); } else { pageContext.setCFOutputOnly(Caster.toBooleanValue(enablecfoutputonly)); } } /** * @deprecated this method is replaced by the method <code>setEnablecfoutputonly(Object enablecfoutputonly)</code> * @param enablecfoutputonly */ public void setEnablecfoutputonly(boolean enablecfoutputonly) { pageContext.setCFOutputOnly(enablecfoutputonly); } @Override public int doStartTag() { return EVAL_BODY_INCLUDE; } @Override public int doEndTag() { return EVAL_PAGE; } /** * sets if tag has a body or not * @param hasBody */ public void hasBody(boolean hasBody) { this.hasBody=hasBody; } }
package cscie99.team2.lingolearn.server.confuser; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import cscie99.team2.lingolearn.shared.Card; import cscie99.team2.lingolearn.shared.error.ConfuserException; /** * This class encapsulates a means of getting characters that are similar to a * given example for the purposes of confusing humans. */ public class Confuser { // The path to the directory of confusers private final static String CONFUSER_DIRECTORY = "/confusers/"; // The extension for the files private final static String CONFUSER_EXTENSION = ".confusers"; // The language code we are working with private final static String CONFUSER_LANGUAGE = "jp"; // The following dictionary is has the vowels mapped to the hiragana // that they can elongate, since this shouldn't change we want to // make sure it is an immutable object. private final static Map<Character, String> vowelCombinations; static { Map<Character, String> map = new HashMap<Character, String>(); map.put('', ""); map.put('', ""); map.put('', ""); map.put('', ""); map.put('', ""); vowelCombinations = Collections.unmodifiableMap(map); }; /** * Get a random list of confusers of given type limited to the count * provided, these results are checked against the black list to * ensure that nothing inappropriate is returned. * * @param card The card to get the confusers for. * @param type The focus of the confusers. * @param count The number that should be returned, if -1 is provided then * all results are returned without processing. * @return A list of string zero to the requested count of confusers. */ public List<String> getConfusers(Card card, CharacterType type, int count) throws ConfuserException { try { // Start by running the relevant functions List<String> results = new ArrayList<String>(); switch (type) { case Hiragana: results.addAll(getNManipulation(card.getHiragana())); results.addAll(getSmallTsuManiuplation(card.getHiragana())); results.addAll(getHiraganaManipulation(card.getHiragana())); break; case Katakana: results.addAll(getNManipulation(card.getKatakana())); results.addAll(getSmallTsuManiuplation(card.getKatakana())); results.addAll(getKatakanaManiuplation(card.getKatakana())); break; case Kanji: results.addAll(getKanjiBoundries(card)); results.addAll(getKanjiSubsitution(card.getKanji())); break; default: throw new ConfuserException("An invalid type, " + type + " was provided."); } // Should we return everything? if (count == -1) { return results; } // Check to make sure all of the results are appropriate for (int ndx = 0; ndx < results.size(); ndx++) { if (ConfuserTools.onBlackList(results.get(ndx), "jp")) { results.remove(ndx); ndx } } // Trim the results down to the count and return them Random random = new Random(); while (results.size() > count) { int ndx = random.nextInt(results.size()); results.remove(ndx); } return results; } catch (IOException ex) { throw new ConfuserException("There was an error while reading the blacklist.", ex); } } /** * Add vowel elongation to the provided phrase. This algorithm attempts to * either add or remove a single character on a single pass through the * entire phrase. * * @param phrase The phrase to be manipulated. * @return A list of valid manipulations of the provided phrase. */ public List<String> getHiraganaManipulation(String phrase) { // The following are the parameters for the manipulation char n = ''; String invalidFollowers = ""; // Start by iterating through each of the characters in the phrase List<String> phrases = new ArrayList<String>(); for (int ndx = 0; ndx < phrase.length(); ndx++) { char ch = phrase.charAt(ndx); // Press on if we can't insert after this character if (ch == n || invalidFollowers.contains(String.valueOf(ch))) { continue; } // Get the next character in the phrase char next = '\0'; if (ndx != (phrase.length() - 1)) { next = phrase.charAt(ndx + 1); } // Check to see if we shouldn't extend this character if (invalidFollowers.contains(String.valueOf(next))) { continue; } // Test to make sure if this is a vowel we can double if (vowelCombinations.keySet().contains(ch) && next != ch) { phrases.add(insertCharacter(phrase, ndx, ch)); continue; } // Iterate through the vowel combinations to find the character // to use for the replacement for (char replacement : vowelCombinations.keySet()) { // Check to see if a vowel has already been extended, if so // we can skip the next character if (next == replacement) { ndx++; break; } // Check to see if the current character makes for a valid // vowel to be extended if (vowelCombinations.get(replacement).contains(String.valueOf(ch))) { phrases.add(insertCharacter(phrase, ndx, replacement)); break; } } } return phrases; } /** * Get a list of kanji phrases that have the hiragana extended off the kanji * where appropriate. * * @param card The card to build the phrases off of. * @return A list of phrases built from the card, or an empty list if there * are no valid confusers. */ public List<String> getKanjiBoundries(Card card) throws ConfuserException { // Check to see if there is only one character which we can't work with // and also check to see if the phrase ends with (to do) since this // approach is invalid if (card.getKanji().length() == 1 || card.getKanji().endsWith("")) { return new ArrayList<String>(); } // Prepare to run int offset = 0; CharacterType previous = null; StringBuilder phrase = new StringBuilder(); // We need to maintain the order of the values, so use two lists ArrayList<String> kanjiOrder = new ArrayList<String>(); ArrayList<Integer> kanjiOffset = new ArrayList<Integer>(); // First, iterate through the string and break it down into sub strings // based upon where it transitions from hiragana to kanji String kanji = card.getKanji(); boolean hiraganaFound = false; for (int ndx = 0; ndx < kanji.length(); ndx++) { // Store the character char ch = kanji.charAt(ndx); phrase.append(ch); // Check for a boundary CharacterType type = ConfuserTools.checkCharacter(ch); if (type == CharacterType.Kanji && previous == CharacterType.Hiragana) { String value = phrase.toString(); kanjiOrder.add(value.substring(0, value.length() - 1)); kanjiOffset.add(offset); offset = ndx; phrase = new StringBuilder(String.valueOf(ch)); } // Update the previous character type and the flag hiraganaFound = (type == CharacterType.Hiragana) ? true : hiraganaFound; previous = type; } // Store any remaining phrase information or exit if we didn't find any // hiragana that we can use to do the extension List<String> phrases = new ArrayList<String>(); if (!hiraganaFound) { return phrases; } kanjiOrder.add(phrase.toString()); kanjiOffset.add(offset); // Iterate through kana and use that to build out substrings for (int ndx = 0; ndx < kanjiOrder.size(); ndx++) { // Note the items in this pairing String kana = kanjiOrder.get(ndx); offset = kanjiOffset.get(ndx); // Discard this string if it is only a single character if (kana.length() <= 1) { continue; } // Get the hiragana for this substring char ch = kana.charAt(kana.length() - 1); String hiragana = card.getHiragana(); // In the event that a phrase starts with a hiragana and ends with // kanji (e.g. - sweets, candy) we can't easily find a // boundary so we should just press on through the rest of the // phrase since we mith come to something else if (hiragana.indexOf(ch, offset) == -1) { continue; } hiragana = hiragana.substring(kanjiOffset.get(ndx), hiragana.indexOf(ch, offset) + 1); // Press on if we don't have at least two characters to work with if (hiragana.length() <= 1) { continue; } hiragana = hiragana.substring(1); // Replace the hiragana in the current kana with what we have String replacement = kana.replace(String.valueOf(ch), hiragana); if (replacement.equals(kana)) { continue; } // Generate the updated kanji and append them to the results phrase = new StringBuilder(); for (String value : kanjiOrder) { if (value.equals(kana)) { phrase.append(kana.replace(String.valueOf(ch), hiragana)); } else { phrase.append(value); } } phrases.add(phrase.toString()); } // Return the results return phrases; } /** * Get a list of kanji phrases that are similar to the one that has been * provided. In the event that no kanji confusers for the given card then * null will be returned, otherwise, confusers up to the provided count will * be provided. * * @param card * @return */ public List<String> getKanjiSubsitution(String phrase) throws ConfuserException, IOException { // Read the confusers from the resource file List<String> confusers = readConfusers(); // Iterate through the characters in this phrase List<String> phrases = new ArrayList<String>(); for (int ndx = 0; ndx < phrase.length(); ndx++) { char ch = phrase.charAt(ndx); if (ConfuserTools.checkCharacter(ch) != CharacterType.Kanji) { continue; } // Iterate through each of the lines for confusers for (String confuser : confusers) { if (confuser.contains(String.valueOf(ch))) { phrases.addAll(getReplacements(phrase, ch, ndx, confuser)); break; } } } // Return the confusers return phrases; } /** * Add or remove vowel elongation characters () from the provided phrase. * This algorithm attempts to either add or remove a single character on a * single pass through the entire phrase. * * @param phrase The phrase to be manipulated. * @return A list of valid manipulations of the provided phrase. */ public List<String> getKatakanaManiuplation(String phrase) { // The following are the parameters for the manipulation char choonpu = ''; char n = ''; char xtsu = ''; String invalidFollowers = ""; // Start scanning through the phrase for relevant matches and either // add or remove the choopu as required List<String> phrases = new ArrayList<String>(); for (int ndx = 0; ndx < phrase.length(); ndx++) { char ch = phrase.charAt(ndx); // Press on if we can't insert after this character if (ch == n || ch == xtsu) { continue; } // Check to make sure the next character is not an extension if (ndx != (phrase.length() - 1)) { char next = phrase.charAt(ndx + 1); if (next == choonpu || invalidFollowers.contains(String.valueOf(next))) { continue; } } // Are we doing a delete? if (ch == choonpu) { phrases.add(phrase.substring(0, ndx) + phrase.substring(ndx + 1)); continue; } // We must be performing an insert instead phrases.add(insertCharacter(phrase, ndx, choonpu)); } return phrases; } /** * Manipulate the phrase provided to add or remove n characters (, ) as * appropriate. * * @param phrase The phrase to be manipulated. * @return A list of manipulations or an empty list if there is no valid * work to be done. */ public List<String> getNManipulation(String phrase) { // Determine if the phrase is in hiragana or katakana and adjust // our assumptions accordingly char n = ''; String characters = ""; if (ConfuserTools.checkCharacter(phrase.charAt(0)) == CharacterType.Katakana) { n = ''; characters = ""; } // Now start scanning through the phrase for relevant matches for this // we are only focusing on the characters that are in the middle of // the phrase List<String> phrases = new ArrayList<String>(); for (int ndx = 1; ndx < phrase.length() - 1; ndx++) { char ch = phrase.charAt(ndx); // If this is an n character, remove it if the next is an n* sound if (ch == n) { char next = phrase.charAt(ndx + 1); if (characters.contains(String.valueOf(next))) { phrases.add(phrase.substring(0, ndx) + phrase.substring(ndx + 1)); // Make sure we skip the next character to avoid doubling n's ndx++; } } // If this is an n* sound, add a n before it else if (characters.contains(String.valueOf(ch))) { phrases.add(phrase.substring(0, ndx) + n + phrase.substring(ndx)); } } return phrases; } /** * Generate all of the valid replacements for the parameters provided. * * @param phrase The kanji phrase have the substitutions applied to. * @param kanji The kanji that is to be replaced. * @param index The index that the kanji exists at. * @param replacements The kanji family as read from the confusers list. * @return The list of updated kanji phrases. */ private List<String> getReplacements(String phrase, char kanji, int index, String replacements) { // Make sure the kanji provided does not appear in the list replacements = replacements.replace(String.valueOf(kanji), ""); // Iterate through the replacements and generate new strings with // the character at the index being replaced List<String> phrases = new ArrayList<String>(); for (int ndx = 0; ndx < replacements.length(); ndx++) { char replacement = replacements.charAt(ndx); // Make sure the phrase is built correctly if (index == 0) { phrases.add(String.valueOf(replacement) + phrase.substring(1)); continue; } int offset = (index == 1) ? 1 : index - 1; if (index == (phrase.length() - 1)) { phrases.add(phrase.substring(0, offset) + String.valueOf(replacement)); } else { String bah = phrase.substring(0, offset) + replacement + phrase.substring(index + 1); phrases.add(bah); } } return phrases; } /** * Add or remove the small tsu (, ) from the phrase as warranted. * * @param phrase The hiragana to be manipulated. * @return A list of manipulations or an empty list if there is no valid * work to be done. */ public List<String> getSmallTsuManiuplation(String phrase) { // The following are the parameters for xtsu (, ) manipulation char xtsu = ''; String characters = ""; if (ConfuserTools.checkCharacter(phrase.charAt(0)) == CharacterType.Katakana) { xtsu = ''; characters = ""; } // Now start scanning through the phrase for relevant matches for this // we are only focusing on the characters that are in the middle of // the phrase List<String> phrases = new ArrayList<String>(); for (int ndx = 0; ndx < phrase.length(); ndx++) { char ch = phrase.charAt(ndx); // If this is a small tsu character, remove it if (ch == xtsu) { phrases.add(phrase.substring(0, ndx) + phrase.substring(ndx + 1)); } // If this is a matching sound, add a small tsu else if (characters.contains(String.valueOf(ch))) { // Are we at the end of the phrase? if ((ndx + 1) == phrase.length()) { continue; } // Make sure the next character is not the small tsu if (phrase.charAt(ndx + 1) == xtsu) { continue; } // Make sure the phrase is built correctly phrases.add(insertCharacter(phrase, ndx, xtsu)); } } return phrases; } /** * Insert the replacement character provided at the index indicated correctly. * * @param phrase The phrase to be manipulated. * @param ndx The index to make the insert at, this is treated as ndx + 1 for the * actual insert operation. * @param addition The character to use for the insertion. * @return The original string with the indicated character inserted. */ private String insertCharacter(String phrase, int ndx, char addition) { if (ndx == 0) { return String.valueOf(phrase.charAt(0)) + addition + phrase.substring(1); } else if (ndx == (phrase.length() - 1)) { return phrase + addition; } return phrase.substring(0, ndx + 1) + addition + phrase.substring(ndx + 1); } /** * Read the kanji families for confusers from the resource file. * * @return The confuser families as a list of strings. */ private List<String> readConfusers() throws ConfuserException, IOException { // Open the black list for this language and check to see if it exists String path = CONFUSER_DIRECTORY + CONFUSER_LANGUAGE + CONFUSER_EXTENSION; InputStream confusers = ConfuserTools.class.getResourceAsStream(path); if (confusers == null) { throw new ConfuserException("Unable to open the confusers for, " + CONFUSER_LANGUAGE); } // Prepare the stream reader BufferedReader reader = null; InputStreamReader stream = null; try { // Open up the stream to be read stream = new InputStreamReader(confusers); reader = new BufferedReader(stream); // Read and process the contents List<String> results = new ArrayList<String>(); String data; while ((data = reader.readLine()) != null) { if (data.isEmpty() || data.charAt(0) == ' continue; } results.add(data.replace(" ", "")); } return results; } catch (FileNotFoundException ex) { throw new ConfuserException("Unable to open the confusers for, " + CONFUSER_LANGUAGE); } catch (IOException ex) { throw new ConfuserException("An error occured while reading the next line", ex); } finally { if (reader != null) { reader.close(); } if (stream != null) { stream.close(); } } } }
package org.basex.http.ws; import java.io.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import javax.servlet.http.*; import org.basex.core.*; import org.basex.http.*; import org.basex.http.web.*; import org.basex.query.ann.*; import org.basex.query.value.*; import org.basex.server.*; import org.basex.server.Log.*; import org.basex.util.*; import org.eclipse.jetty.websocket.api.*; public final class WebSocket extends WebSocketAdapter implements ClientInfo { /** WebSocket attributes. */ public final ConcurrentHashMap<String, Value> atts = new ConcurrentHashMap<>(); /** Database context. */ public final Context context; /** Path. */ public final WsPath path; /** Header parameters. */ final Map<String, String> headers = new HashMap<>(); /** Servlet request. */ final HttpServletRequest req; /** Client WebSocket id. */ public String id; /** HTTP Session. */ public HttpSession session; /** * Constructor. * @param req request */ WebSocket(final HttpServletRequest req) { this.req = req; final String pi = req.getPathInfo(); this.path = new WsPath(pi != null ? pi : "/"); session = req.getSession(); final Context ctx = HTTPContext.context(); context = new Context(ctx, this); context.user(ctx.user()); } /** * Creates a new WebSocket instance. * @param req request * @return WebSocket or {@code null} */ static WebSocket get(final HttpServletRequest req) { final WebSocket ws = new WebSocket(req); try { if(!WebModules.get(ws.context).findWs(ws, null).isEmpty()) return ws; } catch(final Exception ex) { Util.debug(ex); throw new CloseException(StatusCode.ABNORMAL, ex.getMessage()); } return null; } @Override public void onWebSocketConnect(final Session sess) { super.onWebSocketConnect(sess); context.log.write(LogType.REQUEST, sess.toString(), null, context); id = WsPool.get().add(this); // add headers (for binding them to the XQuery parameters in the corresponding bind method) final UpgradeRequest ur = sess.getUpgradeRequest(); final BiConsumer<String, String> addHeader = (k, v) -> { if(v != null) headers.put(k, v); }; addHeader.accept("Http-Version", ur.getHttpVersion()); addHeader.accept("Origin", ur.getOrigin()); addHeader.accept("Protocol-version", ur.getProtocolVersion()); addHeader.accept("QueryString", ur.getQueryString()); addHeader.accept("IsSecure", String.valueOf(ur.isSecure())); addHeader.accept("RequestURI", ur.getRequestURI().toString()); final String[] names = { "Host", "Sec-WebSocket-Version" }; for(final String name : names) addHeader.accept(name, ur.getHeader(name)); findAndProcess(Annotation._WS_CONNECT, null); } /* * This is a way for the internal implementation to notify of exceptions that occurred during the * WebSocket processing. Usually this occurs from bad / malformed incoming packets. (example: * bad UTF8 data, frames that are too big, violations of the spec). This will result in the * Session being closed by the implementing side. */ @Override public void onWebSocketError(final Throwable cause) { try { context.log.write(LogType.ERROR, cause.getMessage(), null, context); findAndProcess(Annotation._WS_ERROR, cause.toString()); } finally { WsPool.get().remove(id); super.getSession().close(); } } @Override public void onWebSocketClose(final int status, final String message) { try { context.log.write(Integer.toString(status), message, null, context); findAndProcess(Annotation._WS_CLOSE, null); } finally { WsPool.get().remove(id); super.onWebSocketClose(status, message); } } @Override public void onWebSocketText(final String message) { findAndProcess(Annotation._WS_MESSAGE, message); } @Override public void onWebSocketBinary(final byte[] payload, final int offset, final int len) { findAndProcess(Annotation._WS_MESSAGE, payload); } @Override public String clientAddress() { final Session ws = getSession(); return ws != null ? ws.getRemoteAddress().toString() : null; } @Override public String clientName() { return context.user().name(); } /** * Closes the WebSocket connection. */ public void close() { getSession().close(); } /** * Finds a function and processes it. * @param ann annotation * @param message message (can be {@code null}; otherwise string or byte array) */ private void findAndProcess(final Annotation ann, final Object message) { // check if an HTTP session exists, and if it still valid try { if(session != null) session.getCreationTime(); } catch(final IllegalStateException ex) { session = null; } try { // find function to evaluate final WsFunction func = WebModules.get(context).websocket(this, ann); if(func != null) new WsResponse(this).create(func, message); } catch(final RuntimeException ex) { throw ex; } catch(final Exception ex) { Util.debug(ex); try { // In the case of an error, inform the client about it getRemote().sendString(ex.getMessage()); } catch(IOException e) { throw new CloseException(StatusCode.ABNORMAL, ex.getMessage()); } } } }
// Do not change any of the contents unless you are absolutely certain you know what you are doing. package com.$(AUTHOR).$(SAFETITLE); import java.io.InputStream; import java.util.List; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.hardware.Camera; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.util.Log; import android.view.SurfaceView; import android.view.View; import android.webkit.WebView; import android.widget.Toast; public class WebSharperMobileActivity extends Activity implements SensorEventListener { SensorManager myManager; Sensor accSensor; WebView wv; Activity env; boolean cameraNeeded = false; Camera cmr; WebSharperBridge bridge; float[] acceleration = new float[] { 0, 0, (float) -9.8 }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); env = this; wv = new WebView(this); // enable JavaScript wv.getSettings().setJavaScriptEnabled(true); // enable HTML5 LocalStorage wv.getSettings().setDomStorageEnabled(true); bridge = new WebSharperBridge(); wv.loadUrl("file:///android_asset/www/index.html"); // in JavaScript, websharperBridge is the Java bridge object (of type WebSharperBridge) wv.addJavascriptInterface(bridge, "websharperBridge"); setContentView(wv); try { // request acceleration updates myManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE); List<Sensor> sensors = myManager.getSensorList(Sensor.TYPE_ACCELEROMETER); if(sensors.size() > 0) { accSensor = sensors.get(0); myManager.registerListener(this, accSensor, SensorManager.SENSOR_DELAY_UI); } } catch (Exception e) { } } @Override public void onPause() { // release resources if (cameraNeeded && cmr != null) { cmr.release(); } if (accSensor != null) { myManager.unregisterListener(this); } bridge.pause(); super.onPause(); } @Override public void onResume() { // reacquire resources super.onResume(); bridge.resume(); if (accSensor != null) { myManager.registerListener(this, accSensor, SensorManager.SENSOR_DELAY_UI); } if (cameraNeeded) { cmr = Camera.open(); } } class WebSharperBridge implements LocationListener { double lat = 0, lng = 0; public void pause() { LocationManager locationManager = (LocationManager)env.getSystemService(Context.LOCATION_SERVICE); locationManager.removeUpdates(this); } public void resume() { try { // request location updates LocationManager locationManager = (LocationManager)env.getSystemService(Context.LOCATION_SERVICE); Criteria locationCriteria = new Criteria(); locationCriteria.setAccuracy(Criteria.ACCURACY_FINE); locationManager.requestLocationUpdates(locationManager.getBestProvider(locationCriteria, true), 100, 0, this); lat = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER).getLatitude(); lng = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER).getLongitude(); } catch (Exception e) { } } @Override public void onLocationChanged(Location location) { lat = location.getLatitude(); lng = location.getLongitude(); } // this function is used for XHR, so JavaScript will know where is the RPC server public String serverLocation() { try { InputStream is = getAssets().open("www/serverLocation.txt"); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); String result = new String(buffer); return "({ $ : 1, $0 : \"" + result + "\" })"; } catch (Exception e) { return "({ $ : 0 })"; } } public String location() { return "({ Lat : " + lat + ", Long : " + lng + " })"; } public String acceleration() { return "({ X : " + acceleration[0] + ", Y : " + acceleration[1] + ", Z : " + acceleration[2] + " })"; } public void camera(int maxHeight, int maxWidth, final String callback, final String fail) { try { cmr = Camera.open(); Camera.Parameters params = cmr.getParameters(); cmr.setParameters(params); // the surface is the graphical interface for the camera, since Android SDK does not supply a default one final SurfaceView sv = new SurfaceView(env); sv.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { Camera.PictureCallback jpegCallback=new Camera.PictureCallback() { public void onPictureTaken(byte[] data, Camera camera) { StringBuffer sb = new StringBuffer(data.length * 2); for (int i = 0; i < data.length; i++) { int v = data[i] & 0xff; if (v < 16) { sb.append('0'); } sb.append(Integer.toHexString(v)); } wv.loadUrl("javascript:" + callback + ".call(null,\"" + sb.toString().toUpperCase() + "\")"); camera.release(); env.runOnUiThread(new Runnable() { public void run() { env.setContentView(wv); }}); cmr = null; } }; cmr.takePicture(null, null, jpegCallback); return true; } }); sv.setClickable(true); env.runOnUiThread(new Runnable() { public void run() { env.setContentView(sv); }}); cmr.setPreviewDisplay(sv.getHolder()); cmr.startPreview(); Toast toast = Toast.makeText(env, "Long-click the screen to take photo.", Toast.LENGTH_SHORT); toast.show(); } catch (Exception e) { wv.loadUrl("javascript:" + fail + ".call(null,\"" + e.getMessage() + "\")"); } } public void alert(final String msg) { env.runOnUiThread(new Runnable() { public void run() { new AlertDialog.Builder(env) .setMessage(msg) .setNeutralButton("OK", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .show(); } }); } // this function prints to logcat public void log(String msg) { Log.d("DebugJS", msg); } @Override public void onProviderDisabled(String arg0) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String arg0) { // TODO Auto-generated method stub } @Override public void onStatusChanged(String arg0, int arg1, Bundle arg2) { // TODO Auto-generated method stub } } @Override public void onAccuracyChanged(Sensor arg0, int arg1) { // TODO Auto-generated method stub } @Override public void onSensorChanged(SensorEvent args) { acceleration = args.values.clone(); } }
package com.exedio.cope.instrument; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Writer; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.SortedSet; import java.util.StringTokenizer; import java.util.TreeSet; import com.exedio.cope.lib.Attribute; import com.exedio.cope.lib.AttributeValue; import com.exedio.cope.lib.NotNullViolationException; import com.exedio.cope.lib.ReadOnlyViolationException; import com.exedio.cope.lib.SystemException; import com.exedio.cope.lib.Type; import com.exedio.cope.lib.UniqueConstraint; import com.exedio.cope.lib.UniqueViolationException; import com.exedio.cope.lib.util.ReactivationConstructorDummy; final class Generator { private final Writer o; private final String lineSeparator; Generator(final Writer output) { this.o=output; final String systemLineSeparator = System.getProperty("line.separator"); if(systemLineSeparator==null) { System.out.println("warning: property \"line.separator\" is null, using LF (unix style)."); lineSeparator = "\n"; } else lineSeparator = systemLineSeparator; } private static final String lowerCamelCase(final String s) { final char first = s.charAt(0); if(Character.isLowerCase(first)) return s; else return Character.toLowerCase(first) + s.substring(1); } private static final String getShortName(final Class aClass) { final String name = aClass.getName(); final int pos = name.lastIndexOf('.'); return name.substring(pos+1); } private void writeParameterDeclarationList(final Collection parameters) throws IOException { if(parameters!=null) { boolean first = true; for(Iterator i = parameters.iterator(); i.hasNext(); ) { if(first) first = false; else o.write(','); final String parameter = (String)i.next(); o.write("final "); o.write(parameter); o.write(' '); o.write(lowerCamelCase(parameter)); } } } private void writeParameterCallList(final Collection parameters) throws IOException { if(parameters!=null) { boolean first = true; for(Iterator i = parameters.iterator(); i.hasNext(); ) { if(first) first = false; else o.write(','); final String parameter = (String)i.next(); o.write(lowerCamelCase(parameter)); } } } private void writeThrowsClause(final Collection exceptions) throws IOException { if(!exceptions.isEmpty()) { o.write("\t\t\tthrows"); boolean first = true; for(final Iterator i = exceptions.iterator(); i.hasNext(); ) { if(first) first = false; else o.write(','); o.write(lineSeparator); o.write("\t\t\t\t"); o.write(((Class)i.next()).getName()); } o.write(lineSeparator); } } private final void writeCommentHeader() throws IOException { o.write("/**"); o.write(lineSeparator); o.write(lineSeparator); o.write("\t **"); o.write(lineSeparator); } private final void writeCommentFooter() throws IOException { o.write("\t * "+Instrumentor.GENERATED_AUTHOR_TAG); o.write(lineSeparator); o.write("\t *"); o.write(lineSeparator); o.write(" */"); } private static final HashMap constraintViolationText = new HashMap(5); static { constraintViolationText.put(NotNullViolationException.class, "not null"); constraintViolationText.put(ReadOnlyViolationException.class, "read only"); constraintViolationText.put(UniqueViolationException.class, "not unique"); } private void writeConstructor(final PersistentClass javaClass) throws IOException { final List initialAttributes = javaClass.getInitialAttributes(); final SortedSet constructorExceptions = javaClass.getContructorExceptions(); int constructorAccessModifier = javaClass.accessModifier; writeCommentHeader(); o.write("\t * Constructs a new "); o.write(javaClass.getName()); o.write(" with all the attributes initially needed."); for(Iterator i = initialAttributes.iterator(); i.hasNext(); ) { final PersistentAttribute initialAttribute = (PersistentAttribute)i.next(); o.write(lineSeparator); o.write("\t * @param initial"); o.write(initialAttribute.getCamelCaseName()); o.write(" the initial value for attribute {@link o.write(initialAttribute.getName()); o.write("}."); final int attributeAccessModifier = initialAttribute.accessModifier; if(constructorAccessModifier<attributeAccessModifier) constructorAccessModifier = attributeAccessModifier; } for(Iterator i = constructorExceptions.iterator(); i.hasNext(); ) { final Class constructorException = (Class)i.next(); o.write(lineSeparator); o.write("\t * @throws "); o.write(constructorException.getName()); o.write(" if"); boolean first = true; for(Iterator j = initialAttributes.iterator(); j.hasNext(); ) { final PersistentAttribute initialAttribute = (PersistentAttribute)j.next(); if(!initialAttribute.getSetterExceptions().contains(constructorException)) continue; if(first) first = false; else o.write(','); o.write(" initial"); o.write(initialAttribute.getCamelCaseName()); } o.write(" is "); o.write((String)constraintViolationText.get(constructorException)); o.write('.'); } o.write(lineSeparator); writeCommentFooter(); o.write(JavaFeature.toAccessModifierString(constructorAccessModifier)); o.write(javaClass.getName()); o.write('('); boolean first = true; for(Iterator i = initialAttributes.iterator(); i.hasNext(); ) { if(first) first = false; else o.write(','); final PersistentAttribute initialAttribute = (PersistentAttribute)i.next(); o.write(lineSeparator); o.write("\t\t\t\tfinal "); o.write(initialAttribute.getBoxedType()); o.write(" initial"); o.write(initialAttribute.getCamelCaseName()); } o.write(')'); o.write(lineSeparator); writeThrowsClause(constructorExceptions); o.write("\t{"); o.write(lineSeparator); o.write("\t\tsuper(new "+AttributeValue.class.getName()+"[]{"); o.write(lineSeparator); for(Iterator i = initialAttributes.iterator(); i.hasNext(); ) { final PersistentAttribute initialAttribute = (PersistentAttribute)i.next(); o.write("\t\t\tnew "+AttributeValue.class.getName()+"("); o.write(initialAttribute.getName()); o.write(','); if(initialAttribute.isBoxed()) o.write(initialAttribute.getBoxingPrefix()); o.write("initial"); o.write(initialAttribute.getCamelCaseName()); if(initialAttribute.isBoxed()) o.write(initialAttribute.getBoxingPostfix()); o.write("),"); o.write(lineSeparator); } o.write("\t\t});"); o.write(lineSeparator); for(Iterator i = javaClass.getContructorExceptions().iterator(); i.hasNext(); ) { final Class exception = (Class)i.next(); o.write("\t\tthrowInitial"); o.write(getShortName(exception)); o.write("();"); o.write(lineSeparator); } o.write("\t}"); } private void writeGenericConstructor(final PersistentClass persistentClass) throws IOException { writeCommentHeader(); o.write("\t * Creates an item and sets the given attributes initially."); o.write(lineSeparator); writeCommentFooter(); o.write("protected "); o.write(persistentClass.getName()); o.write("(final "+AttributeValue.class.getName()+"[] initialAttributes)"); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\tsuper(initialAttributes);"); o.write(lineSeparator); o.write("\t}"); } private void writeReactivationConstructor(final PersistentClass persistentClass) throws IOException { final boolean abstractClass = persistentClass.isAbstract(); writeCommentHeader(); o.write("\t * Reactivation constructor. Used for internal purposes only."); o.write(lineSeparator); o.write("\t * @see Item#Item(" + ReactivationConstructorDummy.class.getName() + ",int)"); o.write(lineSeparator); writeCommentFooter(); o.write( abstractClass ? "protected " : "private " ); o.write(persistentClass.getName()); o.write("("+ReactivationConstructorDummy.class.getName()+" d,final int pk)"); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\tsuper(d,pk);"); o.write(lineSeparator); o.write("\t}"); } private void writeAccessMethods(final PersistentAttribute persistentAttribute) throws IOException { final String methodModifiers = Modifier.toString(persistentAttribute.getMethodModifiers()); final String type = persistentAttribute.getBoxedType(); final List qualifiers = persistentAttribute.qualifiers; // getter writeCommentHeader(); o.write("\t * Returns the value of the persistent attribute {@link o.write(persistentAttribute.getName()); o.write("}."); o.write(lineSeparator); writeCommentFooter(); o.write(methodModifiers); o.write(' '); o.write(type); o.write(" get"); o.write(persistentAttribute.getCamelCaseName()); o.write('('); writeParameterDeclarationList(qualifiers); o.write(')'); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); writeGetterBody(persistentAttribute); o.write("\t}"); // setter if(persistentAttribute.hasSetter()) { writeCommentHeader(); o.write("\t * Sets a new value for the persistent attribute {@link o.write(persistentAttribute.getName()); o.write("}."); o.write(lineSeparator); writeCommentFooter(); o.write(methodModifiers); o.write(" void set"); o.write(persistentAttribute.getCamelCaseName()); o.write('('); if(qualifiers!=null) { writeParameterDeclarationList(qualifiers); o.write(','); } o.write("final "); o.write(type); o.write(' '); o.write(persistentAttribute.getName()); o.write(')'); o.write(lineSeparator); writeThrowsClause(persistentAttribute.getSetterExceptions()); o.write("\t{"); o.write(lineSeparator); writeSetterBody(persistentAttribute); o.write("\t}"); } } private void writeMediaGetterMethod(final PersistentAttribute mediaAttribute, final Class returnType, final String part, final String variant, final String literal, final String comment) throws IOException { final String methodModifiers = Modifier.toString(mediaAttribute.getMethodModifiers()); final List qualifiers = mediaAttribute.qualifiers; writeCommentHeader(); o.write("\t * "); o.write(comment); o.write(" {@link o.write(mediaAttribute.getName()); o.write("}."); o.write(lineSeparator); writeCommentFooter(); o.write(methodModifiers); o.write(' '); o.write(returnType.getName()); o.write(" get"); o.write(mediaAttribute.getCamelCaseName()); o.write(part); if(variant!=null) o.write(variant); o.write('('); writeParameterDeclarationList(qualifiers); o.write(')'); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\treturn "); if(literal!=null) { o.write('\"'); o.write(literal); o.write("\";"); } else { o.write("getMedia"); o.write(part); o.write("(this."); o.write(mediaAttribute.getName()); if(variant!=null) { if(variant.length()>0) { o.write(",\""); o.write(variant); o.write('\"'); } else o.write(",null"); } if(qualifiers!=null) { o.write(",new Object[]{"); writeParameterCallList(qualifiers); o.write('}'); } o.write(");"); } o.write(lineSeparator); o.write("\t}"); } private void writeMediaAccessMethods(final PersistentMediaAttribute mediaAttribute) throws IOException { final String methodModifiers = Modifier.toString(mediaAttribute.getMethodModifiers()); final List qualifiers = mediaAttribute.qualifiers; final String mimeMajor = mediaAttribute.mimeMajor; final String mimeMinor = mediaAttribute.mimeMinor; // getters writeMediaGetterMethod(mediaAttribute, String.class, "URL", "", null, "Returns a URL pointing to the data of the persistent attribute"); final List mediaVariants = mediaAttribute.mediaVariants; if(mediaVariants!=null) { for(Iterator i = mediaVariants.iterator(); i.hasNext(); ) writeMediaGetterMethod(mediaAttribute, String.class, "URL", (String)i.next(), null, "Returns a URL pointing to the varied data of the persistent attribute"); } writeMediaGetterMethod(mediaAttribute, String.class, "MimeMajor", null, mimeMajor, "Returns the major mime type of the persistent media attribute"); writeMediaGetterMethod(mediaAttribute, String.class, "MimeMinor", null, mimeMinor, "Returns the minor mime type of the persistent media attribute"); writeMediaGetterMethod(mediaAttribute, InputStream.class, "Data", null, null, "Returns a stream for fetching the data of the persistent media attribute"); // setters if(mediaAttribute.hasSetter()) { writeCommentHeader(); o.write("\t * Provides data for the persistent media attribute {@link o.write(mediaAttribute.getName()); o.write("}."); o.write(lineSeparator); writeCommentFooter(); o.write(methodModifiers); o.write(" void set"); o.write(mediaAttribute.getCamelCaseName()); o.write("Data("); if(qualifiers!=null) { writeParameterDeclarationList(qualifiers); o.write(','); } o.write("final " + OutputStream.class.getName() + " data"); if(mimeMajor==null) o.write(",final "+String.class.getName()+" mimeMajor"); if(mimeMinor==null) o.write(",final "+String.class.getName()+" mimeMinor"); o.write(')'); final SortedSet setterExceptions = mediaAttribute.getSetterExceptions(); writeThrowsClause(setterExceptions); if(setterExceptions.isEmpty()) o.write("throws "); o.write(IOException.class.getName()); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); final SortedSet exceptionsToCatch = new TreeSet(mediaAttribute.getExceptionsToCatchInSetter()); exceptionsToCatch.remove(ReadOnlyViolationException.class); exceptionsToCatch.remove(UniqueViolationException.class); if(!exceptionsToCatch.isEmpty()) { o.write("\t\ttry"); o.write(lineSeparator); o.write("\t\t{"); o.write(lineSeparator); o.write('\t'); } o.write("\t\tsetMediaData(this."); o.write(mediaAttribute.getName()); if(qualifiers!=null) { o.write(",new Object[]{"); writeParameterCallList(qualifiers); o.write('}'); } o.write(",data"); o.write(mimeMajor==null ? ",mimeMajor" : ",null"); o.write(mimeMinor==null ? ",mimeMinor" : ",null"); o.write(");"); o.write(lineSeparator); if(!exceptionsToCatch.isEmpty()) { o.write("\t\t}"); o.write(lineSeparator); for(Iterator i = exceptionsToCatch.iterator(); i.hasNext(); ) writeViolationExceptionCatchClause((Class)i.next()); } o.write("\t}"); } } private final void writeEquals(final PersistentAttribute persistentAttribute) throws IOException { o.write("equal("); o.write(persistentAttribute.getName()); o.write(",searched"); o.write(persistentAttribute.getCamelCaseName()); o.write(')'); } private void writeUniqueFinder(final PersistentAttribute[] persistentAttributes) throws IOException { int accessModifier = JavaFeature.ACCESS_PUBLIC; for(int i=0; i<persistentAttributes.length; i++) { final int attributeAccessModifier = persistentAttributes[i].accessModifier; if(accessModifier<attributeAccessModifier) accessModifier=attributeAccessModifier; } final String className = persistentAttributes[0].getParent().getName(); writeCommentHeader(); o.write("\t * Finds a "); o.write(lowerCamelCase(className)); o.write(" by it's unique attributes"); for(int i=0; i<persistentAttributes.length; i++) { o.write(lineSeparator); o.write("\t * @param searched"); o.write(persistentAttributes[i].getCamelCaseName()); o.write(" shall be equal to attribute {@link o.write(persistentAttributes[i].getName()); o.write("}."); } o.write(lineSeparator); writeCommentFooter(); o.write(JavaAttribute.toAccessModifierString(accessModifier)); o.write("static final "); o.write(className); boolean first=true; for(int i=0; i<persistentAttributes.length; i++) { if(first) { o.write(" findBy"); first = false; } else o.write("And"); o.write(persistentAttributes[i].getCamelCaseName()); } o.write('('); final Set qualifiers = new HashSet(); for(int i=0; i<persistentAttributes.length; i++) { if(i>0) o.write(','); final PersistentAttribute persistentAttribute = persistentAttributes[i]; if(persistentAttribute.qualifiers != null) qualifiers.addAll(persistentAttribute.qualifiers); o.write("final "); o.write(persistentAttribute.getPersistentType()); o.write(" searched"); o.write(persistentAttribute.getCamelCaseName()); } if(!qualifiers.isEmpty()) { o.write(','); writeParameterDeclarationList(qualifiers); } o.write(')'); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\treturn ("); o.write(className); o.write(")searchUnique(TYPE,"); if(persistentAttributes.length==1) writeEquals(persistentAttributes[0]); else { o.write("and("); writeEquals(persistentAttributes[0]); for(int i = 1; i<persistentAttributes.length; i++) { o.write(','); writeEquals(persistentAttributes[i]); } o.write(')'); } o.write(");"); o.write(lineSeparator); o.write("\t}"); } private final void writeType(final PersistentClass persistentClass) throws IOException { writeCommentHeader(); o.write("\t * The persistent type information for "); o.write(lowerCamelCase(persistentClass.getName())); o.write("."); o.write(lineSeparator); writeCommentFooter(); // the TYPE variable o.write("public static final "+Type.class.getName()+" TYPE = "); o.write(lineSeparator); // open the constructor of type o.write("\t\tnew "+Type.class.getName()+"("); o.write(lineSeparator); // the class itself o.write("\t\t\t"); o.write(persistentClass.getName()); o.write(".class,"); o.write(lineSeparator); // the attributes of the class final List persistentAttributes = persistentClass.getPersistentAttributes(); if(!persistentAttributes.isEmpty()) { o.write("\t\t\tnew "+Attribute.class.getName()+"[]{"); o.write(lineSeparator); for(Iterator i = persistentAttributes.iterator(); i.hasNext(); ) { final PersistentAttribute persistentAttribute = (PersistentAttribute)i.next(); o.write("\t\t\t\t"); o.write(persistentAttribute.getName()); o.write(".initialize(\""); o.write(persistentAttribute.getName()); o.write("\","); o.write(persistentAttribute.readOnly ? "true": "false"); o.write(','); o.write(persistentAttribute.notNull ? "true": "false"); if(persistentAttribute.isItemPersistentType()) { o.write(','); o.write(persistentAttribute.getBoxedType()); o.write(".class"); } //private List qualifiers = null; o.write("),"); o.write(lineSeparator); } o.write("\t\t\t},"); } else { o.write("\t\t\tnull,"); } o.write(lineSeparator); // the unique contraints of the class final List uniqueConstraints = persistentClass.getUniqueConstraints(); if(!uniqueConstraints.isEmpty()) { o.write("\t\t\tnew "+UniqueConstraint.class.getName()+"[]{"); o.write(lineSeparator); for(Iterator i = uniqueConstraints.iterator(); i.hasNext(); ) { final PersistentAttribute[] uniqueConstraint = (PersistentAttribute[])i.next(); if(uniqueConstraint.length==1) { // shorter notation, if unique contraint does not cover multive attributes o.write("\t\t\t\tnew "+UniqueConstraint.class.getName()+'('); o.write(uniqueConstraint[0].getName()); o.write("),"); } else { // longer notation otherwise o.write("\t\t\t\tnew "+UniqueConstraint.class.getName()+"(new "+Attribute.class.getName()+"[]{"); for(int j = 0; j<uniqueConstraint.length; j++) { o.write(uniqueConstraint[j].getName()); o.write(','); } o.write("}),"); } o.write(lineSeparator); } o.write("\t\t\t}"); } else { o.write("\t\t\tnull"); } o.write(lineSeparator); // close the constructor of Type o.write("\t\t)"); o.write(lineSeparator); o.write(";"); } void writeClassFeatures(final PersistentClass persistentClass, final List uniqueConstraints) throws IOException, InjectorParseException { //System.out.println("onClassEnd("+jc.getName()+") persistent"); if(uniqueConstraints != null) { //System.out.println("onClassEnd("+jc.getName()+") unique"); for( final Iterator i=uniqueConstraints.iterator(); i.hasNext(); ) { final String uniqueConstraint=(String)i.next(); final List attributes = new ArrayList(); for(final StringTokenizer t=new StringTokenizer(uniqueConstraint, " "); t.hasMoreTokens(); ) { final String attributeName = t.nextToken(); final PersistentAttribute ja = persistentClass.getPersistentAttribute(attributeName); if(ja==null) throw new InjectorParseException("Attribute with name "+attributeName+" does not exist!"); attributes.add(ja); } if(attributes.isEmpty()) throw new InjectorParseException("No attributes found in unique constraint "+uniqueConstraint); persistentClass.makeUnique((PersistentAttribute[])attributes.toArray(new PersistentAttribute[]{})); } } if(!persistentClass.isInterface()) { //System.out.println("onClassEnd("+jc.getName()+") writing"); writeConstructor(persistentClass); if(persistentClass.isAbstract()) // TODO: create the constructor for all classes, but without type argument writeGenericConstructor(persistentClass); writeReactivationConstructor(persistentClass); for(final Iterator i = persistentClass.getPersistentAttributes().iterator(); i.hasNext(); ) { // write setter/getter methods final PersistentAttribute persistentAttribute = (PersistentAttribute)i.next(); //System.out.println("onClassEnd("+jc.getName()+") writing attribute "+persistentAttribute.getName()); if(persistentAttribute instanceof PersistentMediaAttribute) writeMediaAccessMethods((PersistentMediaAttribute)persistentAttribute); else writeAccessMethods(persistentAttribute); } for(final Iterator i = persistentClass.getUniqueConstraints().iterator(); i.hasNext(); ) { // write unique finder methods final PersistentAttribute[] persistentAttributes = (PersistentAttribute[])i.next(); writeUniqueFinder(persistentAttributes); } writeType(persistentClass); } } /** * Identation contract: * This methods is called, when o stream is immediatly after a line break, * and it should return the o stream after immediatly after a line break. * This means, doing nothing fullfils the contract. */ private void writeGetterBody(final PersistentAttribute attribute) throws IOException { o.write("\t\treturn "); if(attribute.isBoxed()) o.write(attribute.getUnBoxingPrefix()); o.write('('); o.write(attribute.getPersistentType()); o.write(")getAttribute(this."); o.write(attribute.getName()); final List qualifiers = attribute.qualifiers; if(qualifiers!=null) { o.write(",new Object[]{"); writeParameterCallList(qualifiers); o.write('}'); } o.write(')'); if(attribute.isBoxed()) o.write(attribute.getUnBoxingPostfix()); o.write(';'); o.write(lineSeparator); } /** * Identation contract: * This methods is called, when o stream is immediatly after a line break, * and it should return the o stream after immediatly after a line break. * This means, doing nothing fullfils the contract. */ private void writeSetterBody(final PersistentAttribute attribute) throws IOException { final SortedSet exceptionsToCatch = attribute.getExceptionsToCatchInSetter(); if(!exceptionsToCatch.isEmpty()) { o.write("\t\ttry"); o.write(lineSeparator); o.write("\t\t{"); o.write(lineSeparator); o.write('\t'); } o.write("\t\tsetAttribute(this."); o.write(attribute.getName()); final List qualifiers = attribute.qualifiers; if(qualifiers!=null) { o.write(",new Object[]{"); writeParameterCallList(qualifiers); o.write('}'); } o.write(','); if(attribute.isBoxed()) o.write(attribute.getBoxingPrefix()); o.write(attribute.getName()); if(attribute.isBoxed()) o.write(attribute.getBoxingPostfix()); o.write(");"); o.write(lineSeparator); if(!exceptionsToCatch.isEmpty()) { o.write("\t\t}"); o.write(lineSeparator); for(Iterator i = exceptionsToCatch.iterator(); i.hasNext(); ) writeViolationExceptionCatchClause((Class)i.next()); } } private void writeViolationExceptionCatchClause(final Class exceptionClass) throws IOException { o.write("\t\tcatch("+exceptionClass.getName()+" e)"); o.write(lineSeparator); o.write("\t\t{"); o.write(lineSeparator); o.write("\t\t\tthrow new "+SystemException.class.getName()+"(e);"); o.write(lineSeparator); o.write("\t\t}"); o.write(lineSeparator); } }