repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
adragomir/hbase-indexing-library
src/hbaseindex/src/test/java/org/lilycms/hbaseindex/test/MergeJoinTest.java
// Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/Conjunction.java // public class Conjunction extends BaseQueryResult { // private QueryResult result1; // private QueryResult result2; // // public Conjunction(QueryResult result1, QueryResult result2) { // this.result1 = result1; // this.result2 = result2; // } // // public byte[] next() throws IOException { // byte[] key1 = result1.next(); // byte[] key2 = result2.next(); // // if (key1 == null || key2 == null) // return null; // // int cmp = Bytes.compareTo(key1, key2); // // while (cmp != 0) { // if (cmp < 0) { // while (cmp < 0) { // key1 = result1.next(); // if (key1 == null) // return null; // cmp = Bytes.compareTo(key1, key2); // } // } else if (cmp > 0) { // while (cmp > 0) { // key2 = result2.next(); // if (key2 == null) // return null; // cmp = Bytes.compareTo(key1, key2); // } // } // } // // currentQResult = result1; // return key1; // } // } // // Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/Disjunction.java // public class Disjunction extends BaseQueryResult { // private QueryResult result1; // private QueryResult result2; // private byte[] key1; // private byte[] key2; // private boolean init = false; // // public Disjunction(QueryResult result1, QueryResult result2) { // this.result1 = result1; // this.result2 = result2; // } // // public byte[] next() throws IOException { // if (!init) { // key1 = result1.next(); // key2 = result2.next(); // init = true; // } // // if (key1 == null && key2 == null) { // return null; // } else if (key1 == null) { // byte[] result = key2; // currentQResult = result2; // key2 = result2.next(); // return result; // } else if (key2 == null) { // byte[] result = key1; // currentQResult = result1; // key1 = result1.next(); // return result; // } // // int cmp = Bytes.compareTo(key1, key2); // // if (cmp == 0) { // byte[] result = key1; // currentQResult = result1; // key1 = result1.next(); // key2 = result2.next(); // return result; // } else if (cmp < 0) { // byte[] result = key1; // currentQResult = result1; // key1 = result1.next(); // return result; // } else { // cmp > 0 // byte[] result = key2; // currentQResult = result2; // key2 = result2.next(); // return result; // } // } // } // // Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/QueryResult.java // public interface QueryResult { // // /** // * Move to and return the next result. // * // * @return the identifier of the next matching query result, or null if the end is reached. // */ // public byte[] next() throws IOException; // // /** // * Retrieves data that was stored as part of the {@link IndexEntry} from the current index // * entry (corresponding to the last {@link #next} call). // */ // public byte[] getData(byte[] qualifier); // // public byte[] getData(String qualifier); // // public String getDataAsString(String qualifier); // }
import org.apache.hadoop.hbase.util.Bytes; import org.junit.Test; import org.lilycms.hbaseindex.Conjunction; import org.lilycms.hbaseindex.Disjunction; import org.lilycms.hbaseindex.QueryResult; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List;
/* * Copyright 2010 Outerthought bvba * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.lilycms.hbaseindex.test; public class MergeJoinTest { @Test public void testConjunction() throws Exception { String[] values1 = {"a", "b", "c", "f", "g"}; String[] values2 = { "b", "c", "d", "e", "f"}; QueryResult result = new Conjunction(buildQueryResult(values1), buildQueryResult(values2)); assertEquals("b", Bytes.toString(result.next())); assertEquals("c", Bytes.toString(result.next())); assertEquals("f", Bytes.toString(result.next())); assertNull(result.next()); } @Test public void testDisjunction() throws Exception { String[] values1 = {"a", "b", "c", "f", "g"}; String[] values2 = { "b", "c", "d", "e", "f"};
// Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/Conjunction.java // public class Conjunction extends BaseQueryResult { // private QueryResult result1; // private QueryResult result2; // // public Conjunction(QueryResult result1, QueryResult result2) { // this.result1 = result1; // this.result2 = result2; // } // // public byte[] next() throws IOException { // byte[] key1 = result1.next(); // byte[] key2 = result2.next(); // // if (key1 == null || key2 == null) // return null; // // int cmp = Bytes.compareTo(key1, key2); // // while (cmp != 0) { // if (cmp < 0) { // while (cmp < 0) { // key1 = result1.next(); // if (key1 == null) // return null; // cmp = Bytes.compareTo(key1, key2); // } // } else if (cmp > 0) { // while (cmp > 0) { // key2 = result2.next(); // if (key2 == null) // return null; // cmp = Bytes.compareTo(key1, key2); // } // } // } // // currentQResult = result1; // return key1; // } // } // // Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/Disjunction.java // public class Disjunction extends BaseQueryResult { // private QueryResult result1; // private QueryResult result2; // private byte[] key1; // private byte[] key2; // private boolean init = false; // // public Disjunction(QueryResult result1, QueryResult result2) { // this.result1 = result1; // this.result2 = result2; // } // // public byte[] next() throws IOException { // if (!init) { // key1 = result1.next(); // key2 = result2.next(); // init = true; // } // // if (key1 == null && key2 == null) { // return null; // } else if (key1 == null) { // byte[] result = key2; // currentQResult = result2; // key2 = result2.next(); // return result; // } else if (key2 == null) { // byte[] result = key1; // currentQResult = result1; // key1 = result1.next(); // return result; // } // // int cmp = Bytes.compareTo(key1, key2); // // if (cmp == 0) { // byte[] result = key1; // currentQResult = result1; // key1 = result1.next(); // key2 = result2.next(); // return result; // } else if (cmp < 0) { // byte[] result = key1; // currentQResult = result1; // key1 = result1.next(); // return result; // } else { // cmp > 0 // byte[] result = key2; // currentQResult = result2; // key2 = result2.next(); // return result; // } // } // } // // Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/QueryResult.java // public interface QueryResult { // // /** // * Move to and return the next result. // * // * @return the identifier of the next matching query result, or null if the end is reached. // */ // public byte[] next() throws IOException; // // /** // * Retrieves data that was stored as part of the {@link IndexEntry} from the current index // * entry (corresponding to the last {@link #next} call). // */ // public byte[] getData(byte[] qualifier); // // public byte[] getData(String qualifier); // // public String getDataAsString(String qualifier); // } // Path: src/hbaseindex/src/test/java/org/lilycms/hbaseindex/test/MergeJoinTest.java import org.apache.hadoop.hbase.util.Bytes; import org.junit.Test; import org.lilycms.hbaseindex.Conjunction; import org.lilycms.hbaseindex.Disjunction; import org.lilycms.hbaseindex.QueryResult; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; /* * Copyright 2010 Outerthought bvba * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.lilycms.hbaseindex.test; public class MergeJoinTest { @Test public void testConjunction() throws Exception { String[] values1 = {"a", "b", "c", "f", "g"}; String[] values2 = { "b", "c", "d", "e", "f"}; QueryResult result = new Conjunction(buildQueryResult(values1), buildQueryResult(values2)); assertEquals("b", Bytes.toString(result.next())); assertEquals("c", Bytes.toString(result.next())); assertEquals("f", Bytes.toString(result.next())); assertNull(result.next()); } @Test public void testDisjunction() throws Exception { String[] values1 = {"a", "b", "c", "f", "g"}; String[] values2 = { "b", "c", "d", "e", "f"};
QueryResult result = new Disjunction(buildQueryResult(values1), buildQueryResult(values2));
adragomir/hbase-indexing-library
src/hbaseindex/src/main/java/org/lilycms/hbaseindex/IndexFieldDefinition.java
// Path: src/util/src/main/java/org/lilycms/util/ArgumentValidator.java // public class ArgumentValidator { // public static void notNull(Object object, String argName) { // if (object == null) // throw new IllegalArgumentException("Null argument: " + argName); // } // }
import org.codehaus.jackson.node.JsonNodeFactory; import org.codehaus.jackson.node.ObjectNode; import org.lilycms.util.ArgumentValidator;
/* * Copyright 2010 Outerthought bvba * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.lilycms.hbaseindex; /** * Defines a field that is part of an {@link IndexDefinition}. */ public abstract class IndexFieldDefinition { private final String name; private Order order; private IndexValueType type; private static final byte[] EOF_MARKER = new byte[0]; public IndexFieldDefinition(String name, IndexValueType type) { this(name, type, Order.ASCENDING); } public IndexFieldDefinition(String name, IndexValueType type, Order order) { this.name = name; this.order = order; this.type = type; } public IndexFieldDefinition(String name, IndexValueType type, ObjectNode jsonObject) { this(name, type); if (jsonObject.get("order") != null) this.order = Order.valueOf(jsonObject.get("order").getTextValue()); } public String getName() { return name; } public IndexValueType getType() { return type; } public Order getOrder() { return order; } public void setOrder(Order order) {
// Path: src/util/src/main/java/org/lilycms/util/ArgumentValidator.java // public class ArgumentValidator { // public static void notNull(Object object, String argName) { // if (object == null) // throw new IllegalArgumentException("Null argument: " + argName); // } // } // Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/IndexFieldDefinition.java import org.codehaus.jackson.node.JsonNodeFactory; import org.codehaus.jackson.node.ObjectNode; import org.lilycms.util.ArgumentValidator; /* * Copyright 2010 Outerthought bvba * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.lilycms.hbaseindex; /** * Defines a field that is part of an {@link IndexDefinition}. */ public abstract class IndexFieldDefinition { private final String name; private Order order; private IndexValueType type; private static final byte[] EOF_MARKER = new byte[0]; public IndexFieldDefinition(String name, IndexValueType type) { this(name, type, Order.ASCENDING); } public IndexFieldDefinition(String name, IndexValueType type, Order order) { this.name = name; this.order = order; this.type = type; } public IndexFieldDefinition(String name, IndexValueType type, ObjectNode jsonObject) { this(name, type); if (jsonObject.get("order") != null) this.order = Order.valueOf(jsonObject.get("order").getTextValue()); } public String getName() { return name; } public IndexValueType getType() { return type; } public Order getOrder() { return order; } public void setOrder(Order order) {
ArgumentValidator.notNull(order, "order");
adragomir/hbase-indexing-library
src/hbaseindex/src/main/java/org/lilycms/hbaseindex/Index.java
// Path: src/util/src/main/java/org/lilycms/util/ArgumentValidator.java // public class ArgumentValidator { // public static void notNull(Object object, String argName) { // if (object == null) // throw new IllegalArgumentException("Null argument: " + argName); // } // }
import org.apache.hadoop.hbase.client.Delete; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.filter.*; import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp; import org.apache.hadoop.hbase.util.Bytes; import org.lilycms.util.ArgumentValidator; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map;
/* * Copyright 2010 Outerthought bvba * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.lilycms.hbaseindex; /** * Allows to query an index, and add entries to it or remove entries from it. * * <p>An Index instance can be obtained from {@link IndexManager#getIndex}. * * <p>The Index class <b>is not thread safe</b> for writes, because the underlying * HBase HTable is not thread safe for writes. * */ public class Index { private HTable htable; private IndexDefinition definition; protected static final byte[] DATA_FAMILY = Bytes.toBytes("data"); private static final byte[] DUMMY_QUALIFIER = Bytes.toBytes("dummy"); private static final byte[] DUMMY_VALUE = Bytes.toBytes("dummy"); /** Number of bytes overhead per field. */ private static final int FIELD_FLAGS_SIZE = 1; private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; protected Index(HTable htable, IndexDefinition definition) { this.htable = htable; this.definition = definition; } /** * Adds an entry to this index. See {@link IndexEntry} for more information. * * @param entry the values to be part of the index key, should correspond to the fields * defined in the {@link IndexDefinition} * @param identifier the identifier of the indexed object, typically the key of a row in * another HBase table */ public void addEntry(IndexEntry entry, byte[] identifier) throws IOException {
// Path: src/util/src/main/java/org/lilycms/util/ArgumentValidator.java // public class ArgumentValidator { // public static void notNull(Object object, String argName) { // if (object == null) // throw new IllegalArgumentException("Null argument: " + argName); // } // } // Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/Index.java import org.apache.hadoop.hbase.client.Delete; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.filter.*; import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp; import org.apache.hadoop.hbase.util.Bytes; import org.lilycms.util.ArgumentValidator; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; /* * Copyright 2010 Outerthought bvba * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.lilycms.hbaseindex; /** * Allows to query an index, and add entries to it or remove entries from it. * * <p>An Index instance can be obtained from {@link IndexManager#getIndex}. * * <p>The Index class <b>is not thread safe</b> for writes, because the underlying * HBase HTable is not thread safe for writes. * */ public class Index { private HTable htable; private IndexDefinition definition; protected static final byte[] DATA_FAMILY = Bytes.toBytes("data"); private static final byte[] DUMMY_QUALIFIER = Bytes.toBytes("dummy"); private static final byte[] DUMMY_VALUE = Bytes.toBytes("dummy"); /** Number of bytes overhead per field. */ private static final int FIELD_FLAGS_SIZE = 1; private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; protected Index(HTable htable, IndexDefinition definition) { this.htable = htable; this.definition = definition; } /** * Adds an entry to this index. See {@link IndexEntry} for more information. * * @param entry the values to be part of the index key, should correspond to the fields * defined in the {@link IndexDefinition} * @param identifier the identifier of the indexed object, typically the key of a row in * another HBase table */ public void addEntry(IndexEntry entry, byte[] identifier) throws IOException {
ArgumentValidator.notNull(entry, "entry");
adragomir/hbase-indexing-library
src/hbaseindex/src/test/java/org/lilycms/hbaseindex/test/ByteComparisonTest.java
// Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/DateTimeIndexFieldDefinition.java // public enum Precision {DATETIME, DATETIME_NOMILLIS, DATE, TIME, TIME_NOMILLIS}
import org.apache.hadoop.hbase.util.Bytes; import org.junit.Test; import org.lilycms.hbaseindex.*; import org.lilycms.hbaseindex.DateTimeIndexFieldDefinition.Precision; import java.math.BigDecimal; import java.util.Calendar; import java.util.GregorianCalendar; import static org.junit.Assert.*; import static org.junit.Assert.assertEquals;
} } } } // Verify cutoff of precision DecimalIndexFieldDefinition fieldDef = new DecimalIndexFieldDefinition("foobar"); fieldDef.setLength(5); byte[] r1 = fieldDef.toBytes(new BigDecimal("10.000000000000000000000000000000000000000000000000000000000000001")); byte[] r2 = fieldDef.toBytes(new BigDecimal("10.000000000000000000000000000000000000000000000000000000000000002")); assertEquals(5, r1.length); assertEquals(5, r2.length); assertEquals(0, Bytes.compareTo(r1, r2)); // Verify checks on maximum supported exponents try { toSortableBytes(new BigDecimal("0.1E16384")); fail("Expected error"); } catch (RuntimeException e) {} try { toSortableBytes(new BigDecimal("0.1E-16385")); fail("Expected error"); } catch (RuntimeException e) {} } @Test public void testDateCompare() throws Exception {
// Path: src/hbaseindex/src/main/java/org/lilycms/hbaseindex/DateTimeIndexFieldDefinition.java // public enum Precision {DATETIME, DATETIME_NOMILLIS, DATE, TIME, TIME_NOMILLIS} // Path: src/hbaseindex/src/test/java/org/lilycms/hbaseindex/test/ByteComparisonTest.java import org.apache.hadoop.hbase.util.Bytes; import org.junit.Test; import org.lilycms.hbaseindex.*; import org.lilycms.hbaseindex.DateTimeIndexFieldDefinition.Precision; import java.math.BigDecimal; import java.util.Calendar; import java.util.GregorianCalendar; import static org.junit.Assert.*; import static org.junit.Assert.assertEquals; } } } } // Verify cutoff of precision DecimalIndexFieldDefinition fieldDef = new DecimalIndexFieldDefinition("foobar"); fieldDef.setLength(5); byte[] r1 = fieldDef.toBytes(new BigDecimal("10.000000000000000000000000000000000000000000000000000000000000001")); byte[] r2 = fieldDef.toBytes(new BigDecimal("10.000000000000000000000000000000000000000000000000000000000000002")); assertEquals(5, r1.length); assertEquals(5, r2.length); assertEquals(0, Bytes.compareTo(r1, r2)); // Verify checks on maximum supported exponents try { toSortableBytes(new BigDecimal("0.1E16384")); fail("Expected error"); } catch (RuntimeException e) {} try { toSortableBytes(new BigDecimal("0.1E-16385")); fail("Expected error"); } catch (RuntimeException e) {} } @Test public void testDateCompare() throws Exception {
byte[] bytes1 = date(Precision.DATE, 2010, 2, 1, 14, 20, 10, 333);
stachu540/HiRezAPI
api/src/main/java/hirez/api/object/Ping.java
// Path: api/src/main/java/hirez/api/HiRezUtils.java // public class HiRezUtils { // public static Date parse(String timestamp) { // timestamp = timestamp.replace("\\/", "/"); // SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a"); // sdf.setTimeZone(TimeZone.getTimeZone(ZoneOffset.UTC)); // try { // return sdf.parse(timestamp); // } catch (ParseException ignore) { // return null; // } // } // }
import hirez.api.HiRezUtils; import lombok.Data; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern;
package hirez.api.object; @Data public class Ping { private final String rawMessage; private final String game; private final String version; private final String patchVersion; private final boolean pingReceived; private final Date timestamp; public Ping(String raw) { this.rawMessage = raw; Matcher matcher = Pattern.compile("^(?<game>.+)API \\(ver (?<version>(?:[0-9]+\\.){3}[0-9]+)\\)" + " \\[PATCH - (?<versionName>.+)] - (?<ping>.+)\\. Server Date:(?<timestamp>.+)$").matcher(raw); matcher.find(); this.game = matcher.group("game"); this.version = matcher.group("version"); this.patchVersion = matcher.group("versionName"); this.pingReceived = matcher.group("ping").contains("successful");
// Path: api/src/main/java/hirez/api/HiRezUtils.java // public class HiRezUtils { // public static Date parse(String timestamp) { // timestamp = timestamp.replace("\\/", "/"); // SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a"); // sdf.setTimeZone(TimeZone.getTimeZone(ZoneOffset.UTC)); // try { // return sdf.parse(timestamp); // } catch (ParseException ignore) { // return null; // } // } // } // Path: api/src/main/java/hirez/api/object/Ping.java import hirez.api.HiRezUtils; import lombok.Data; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; package hirez.api.object; @Data public class Ping { private final String rawMessage; private final String game; private final String version; private final String patchVersion; private final boolean pingReceived; private final Date timestamp; public Ping(String raw) { this.rawMessage = raw; Matcher matcher = Pattern.compile("^(?<game>.+)API \\(ver (?<version>(?:[0-9]+\\.){3}[0-9]+)\\)" + " \\[PATCH - (?<versionName>.+)] - (?<ping>.+)\\. Server Date:(?<timestamp>.+)$").matcher(raw); matcher.find(); this.game = matcher.group("game"); this.version = matcher.group("version"); this.patchVersion = matcher.group("versionName"); this.pingReceived = matcher.group("ping").contains("successful");
this.timestamp = HiRezUtils.parse(matcher.group("timestamp"));
stachu540/HiRezAPI
api/src/main/java/hirez/api/Language.java
// Path: api/src/main/java/hirez/api/object/interfaces/IDObject.java // public interface IDObject<T> { // @JsonProperty("id") // @JsonAlias({"ID", "Id"}) // T getId(); // }
import hirez.api.object.interfaces.IDObject; import lombok.Getter; import lombok.RequiredArgsConstructor;
package hirez.api; @Getter @RequiredArgsConstructor
// Path: api/src/main/java/hirez/api/object/interfaces/IDObject.java // public interface IDObject<T> { // @JsonProperty("id") // @JsonAlias({"ID", "Id"}) // T getId(); // } // Path: api/src/main/java/hirez/api/Language.java import hirez.api.object.interfaces.IDObject; import lombok.Getter; import lombok.RequiredArgsConstructor; package hirez.api; @Getter @RequiredArgsConstructor
public enum Language implements IDObject<Integer> {
stachu540/HiRezAPI
smite/src/main/java/hirez/smite/object/MatchDetail.java
// Path: api/src/main/java/hirez/api/object/MergedAccount.java // @Data // public class MergedAccount { // @JsonProperty("merge_datetime") // @DateTimeFormat("MMM dd yyyy h:mma") // private final Date mergeDatetime; // @JsonProperty("playerId") // private final long playerId; // @JsonProperty("portalId") // private final int portalId; // } // // Path: api/src/main/java/hirez/api/object/interfaces/ReturnedMessage.java // public interface ReturnedMessage { // @JsonProperty("ret_msg") // String getReturnedMessage(); // }
import com.fasterxml.jackson.annotation.JsonProperty; import hirez.api.object.MergedAccount; import hirez.api.object.adapters.DateTimeFormat; import hirez.api.object.adapters.DurationTime; import hirez.api.object.adapters.TextToBoolean; import hirez.api.object.interfaces.ReturnedMessage; import lombok.Data; import lombok.experimental.Accessors; import java.time.Duration; import java.util.Date;
@JsonProperty("Kills_First_Blood") private final long killsFirstBlood; @JsonProperty("Kills_Gold_Fury") private final long killsGoldFury; @JsonProperty("Kills_Penta") private final long killsPenta; @JsonProperty("Kills_Phoenix") private final long killsPhoenix; @JsonProperty("Kills_Player") private final long killsPlayer; @JsonProperty("Kills_Quadra") private final long killsQuadra; @JsonProperty("Kills_Siege_Juggernaut") private final long killsSiegeJuggernaut; @JsonProperty("Kills_Single") private final long killsSingle; @JsonProperty("Kills_Triple") private final long killsTriple; @JsonProperty("Kills_Wild_Juggernaut") private final long killsWildJuggernaut; @JsonProperty("Map_Game") private final String mapGame; @JsonProperty("Mastery_Level") private final long masteryLevel; @JsonProperty("Match") private final long matchId; @DurationTime @JsonProperty("Match_Duration") private final Duration matchDuration; @JsonProperty("MergedPlayers")
// Path: api/src/main/java/hirez/api/object/MergedAccount.java // @Data // public class MergedAccount { // @JsonProperty("merge_datetime") // @DateTimeFormat("MMM dd yyyy h:mma") // private final Date mergeDatetime; // @JsonProperty("playerId") // private final long playerId; // @JsonProperty("portalId") // private final int portalId; // } // // Path: api/src/main/java/hirez/api/object/interfaces/ReturnedMessage.java // public interface ReturnedMessage { // @JsonProperty("ret_msg") // String getReturnedMessage(); // } // Path: smite/src/main/java/hirez/smite/object/MatchDetail.java import com.fasterxml.jackson.annotation.JsonProperty; import hirez.api.object.MergedAccount; import hirez.api.object.adapters.DateTimeFormat; import hirez.api.object.adapters.DurationTime; import hirez.api.object.adapters.TextToBoolean; import hirez.api.object.interfaces.ReturnedMessage; import lombok.Data; import lombok.experimental.Accessors; import java.time.Duration; import java.util.Date; @JsonProperty("Kills_First_Blood") private final long killsFirstBlood; @JsonProperty("Kills_Gold_Fury") private final long killsGoldFury; @JsonProperty("Kills_Penta") private final long killsPenta; @JsonProperty("Kills_Phoenix") private final long killsPhoenix; @JsonProperty("Kills_Player") private final long killsPlayer; @JsonProperty("Kills_Quadra") private final long killsQuadra; @JsonProperty("Kills_Siege_Juggernaut") private final long killsSiegeJuggernaut; @JsonProperty("Kills_Single") private final long killsSingle; @JsonProperty("Kills_Triple") private final long killsTriple; @JsonProperty("Kills_Wild_Juggernaut") private final long killsWildJuggernaut; @JsonProperty("Map_Game") private final String mapGame; @JsonProperty("Mastery_Level") private final long masteryLevel; @JsonProperty("Match") private final long matchId; @DurationTime @JsonProperty("Match_Duration") private final Duration matchDuration; @JsonProperty("MergedPlayers")
private final MergedAccount[] mergedPlayers;
stachu540/HiRezAPI
paladins/src/main/java/hirez/paladins/PaladinsPlatform.java
// Path: api/src/main/java/hirez/api/BaseEndpoint.java // public interface BaseEndpoint { // Game getGame(); // // Platform getPlatform(); // // String getBaseUrl(); // } // // Path: api/src/main/java/hirez/api/object/Game.java // @Data // public class Game implements IDObject<String> { // private final String id; // private final String name; // } // // Path: api/src/main/java/hirez/api/object/Platform.java // @Data // public class Platform implements IDObject<String> { // private final String id; // private final String name; // }
import hirez.api.BaseEndpoint; import hirez.api.object.Game; import hirez.api.object.Platform; import lombok.Getter;
package hirez.paladins; @Getter public enum PaladinsPlatform implements BaseEndpoint { PC("http://api.paladins.com/paladinsapi.svc", "8xmmtyh24dvk"), XBOX("http://api.xbox.paladins.com/paladinsapi.svc", "z44md5h2qg1f"), PS4("http://api.ps4.paladins.com/paladinsapi.svc", "m80484kp0zhn"); private final String baseUrl;
// Path: api/src/main/java/hirez/api/BaseEndpoint.java // public interface BaseEndpoint { // Game getGame(); // // Platform getPlatform(); // // String getBaseUrl(); // } // // Path: api/src/main/java/hirez/api/object/Game.java // @Data // public class Game implements IDObject<String> { // private final String id; // private final String name; // } // // Path: api/src/main/java/hirez/api/object/Platform.java // @Data // public class Platform implements IDObject<String> { // private final String id; // private final String name; // } // Path: paladins/src/main/java/hirez/paladins/PaladinsPlatform.java import hirez.api.BaseEndpoint; import hirez.api.object.Game; import hirez.api.object.Platform; import lombok.Getter; package hirez.paladins; @Getter public enum PaladinsPlatform implements BaseEndpoint { PC("http://api.paladins.com/paladinsapi.svc", "8xmmtyh24dvk"), XBOX("http://api.xbox.paladins.com/paladinsapi.svc", "z44md5h2qg1f"), PS4("http://api.ps4.paladins.com/paladinsapi.svc", "m80484kp0zhn"); private final String baseUrl;
private final Platform platform;
stachu540/HiRezAPI
paladins/src/main/java/hirez/paladins/PaladinsPlatform.java
// Path: api/src/main/java/hirez/api/BaseEndpoint.java // public interface BaseEndpoint { // Game getGame(); // // Platform getPlatform(); // // String getBaseUrl(); // } // // Path: api/src/main/java/hirez/api/object/Game.java // @Data // public class Game implements IDObject<String> { // private final String id; // private final String name; // } // // Path: api/src/main/java/hirez/api/object/Platform.java // @Data // public class Platform implements IDObject<String> { // private final String id; // private final String name; // }
import hirez.api.BaseEndpoint; import hirez.api.object.Game; import hirez.api.object.Platform; import lombok.Getter;
package hirez.paladins; @Getter public enum PaladinsPlatform implements BaseEndpoint { PC("http://api.paladins.com/paladinsapi.svc", "8xmmtyh24dvk"), XBOX("http://api.xbox.paladins.com/paladinsapi.svc", "z44md5h2qg1f"), PS4("http://api.ps4.paladins.com/paladinsapi.svc", "m80484kp0zhn"); private final String baseUrl; private final Platform platform;
// Path: api/src/main/java/hirez/api/BaseEndpoint.java // public interface BaseEndpoint { // Game getGame(); // // Platform getPlatform(); // // String getBaseUrl(); // } // // Path: api/src/main/java/hirez/api/object/Game.java // @Data // public class Game implements IDObject<String> { // private final String id; // private final String name; // } // // Path: api/src/main/java/hirez/api/object/Platform.java // @Data // public class Platform implements IDObject<String> { // private final String id; // private final String name; // } // Path: paladins/src/main/java/hirez/paladins/PaladinsPlatform.java import hirez.api.BaseEndpoint; import hirez.api.object.Game; import hirez.api.object.Platform; import lombok.Getter; package hirez.paladins; @Getter public enum PaladinsPlatform implements BaseEndpoint { PC("http://api.paladins.com/paladinsapi.svc", "8xmmtyh24dvk"), XBOX("http://api.xbox.paladins.com/paladinsapi.svc", "z44md5h2qg1f"), PS4("http://api.ps4.paladins.com/paladinsapi.svc", "m80484kp0zhn"); private final String baseUrl; private final Platform platform;
private final Game game = new Game("542zlqj9nwr6", "Paladins");
stachu540/HiRezAPI
realm/src/main/java/hirez/realm/RealmRoyale.java
// Path: api/src/main/java/hirez/api/object/interfaces/Queue.java // public interface Queue extends IDObject<Integer> { // String getName(); // // boolean isRanked(); // } // // Path: realm/src/main/java/hirez/realm/object/PlayerQuery.java // @Data // public class PlayerQuery implements ReturnedMessage { // private final long id; // private final String name; // private final int portalId; // @JsonProperty("ret_msg") // private final String returnedMessage; // private final long steamId; // }
import hirez.api.*; import hirez.api.object.*; import hirez.api.object.interfaces.Queue; import hirez.realm.object.PlayerQuery; import hirez.realm.object.*; import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.core.Single; import lombok.extern.slf4j.Slf4j; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.time.ZoneOffset; import java.util.Arrays; import java.util.Date; import java.util.TimeZone; import java.util.function.Consumer;
private RealmRoyale(Configuration configuration) { super(configuration); } public static RealmRoyale create(Consumer<ConfigurationBuilder> configuration) { return new RealmRoyale(new ConfigurationBuilder().applyFrom((cfg) -> { configuration.accept(cfg); if (cfg.getBaseEndpoint() == null) { cfg.setBaseEndpoint(DEFAULT_BASE); } }).build()); } /** * @deprecated This endpoint is not exist. Will be removed in the next release. */ @Deprecated public Flowable<Talent> getTalents(Language language) { return Flowable.error(new HiRezException("This endpoint has been removed!")); } /** * @deprecated This endpoint is not exist. Will be removed in the next release. */ @Deprecated public Flowable<Talent> getTalents() { return getTalents(getConfiguration().getLanguage()); }
// Path: api/src/main/java/hirez/api/object/interfaces/Queue.java // public interface Queue extends IDObject<Integer> { // String getName(); // // boolean isRanked(); // } // // Path: realm/src/main/java/hirez/realm/object/PlayerQuery.java // @Data // public class PlayerQuery implements ReturnedMessage { // private final long id; // private final String name; // private final int portalId; // @JsonProperty("ret_msg") // private final String returnedMessage; // private final long steamId; // } // Path: realm/src/main/java/hirez/realm/RealmRoyale.java import hirez.api.*; import hirez.api.object.*; import hirez.api.object.interfaces.Queue; import hirez.realm.object.PlayerQuery; import hirez.realm.object.*; import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.core.Single; import lombok.extern.slf4j.Slf4j; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.time.ZoneOffset; import java.util.Arrays; import java.util.Date; import java.util.TimeZone; import java.util.function.Consumer; private RealmRoyale(Configuration configuration) { super(configuration); } public static RealmRoyale create(Consumer<ConfigurationBuilder> configuration) { return new RealmRoyale(new ConfigurationBuilder().applyFrom((cfg) -> { configuration.accept(cfg); if (cfg.getBaseEndpoint() == null) { cfg.setBaseEndpoint(DEFAULT_BASE); } }).build()); } /** * @deprecated This endpoint is not exist. Will be removed in the next release. */ @Deprecated public Flowable<Talent> getTalents(Language language) { return Flowable.error(new HiRezException("This endpoint has been removed!")); } /** * @deprecated This endpoint is not exist. Will be removed in the next release. */ @Deprecated public Flowable<Talent> getTalents() { return getTalents(getConfiguration().getLanguage()); }
public Single<Leaderboard> getLeaderboard(Queue queue, Criteria criteria) {
stachu540/HiRezAPI
realm/src/main/java/hirez/realm/RealmRoyale.java
// Path: api/src/main/java/hirez/api/object/interfaces/Queue.java // public interface Queue extends IDObject<Integer> { // String getName(); // // boolean isRanked(); // } // // Path: realm/src/main/java/hirez/realm/object/PlayerQuery.java // @Data // public class PlayerQuery implements ReturnedMessage { // private final long id; // private final String name; // private final int portalId; // @JsonProperty("ret_msg") // private final String returnedMessage; // private final long steamId; // }
import hirez.api.*; import hirez.api.object.*; import hirez.api.object.interfaces.Queue; import hirez.realm.object.PlayerQuery; import hirez.realm.object.*; import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.core.Single; import lombok.extern.slf4j.Slf4j; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.time.ZoneOffset; import java.util.Arrays; import java.util.Date; import java.util.TimeZone; import java.util.function.Consumer;
return testAndCall(Player.class, "getplayer", Long.toString(userId), "hirez"); } public Single<Player> getPlayerBySteamId(long steamId) { return testAndCall(Player.class, "getplayer", Long.toString(steamId), "steam"); } public Flowable<PlayerIdPortal> getPlayerIdByName(String query) { return testAndCall(PlayerIdPortal.class, "getplayeridbyname", query) .flattenAsFlowable(Arrays::asList); } public Flowable<PlayerIdPortal> getPlayerIdByPortalUserId(Portal portal, long id) { return testAndCall(PlayerIdPortal[].class, "getplayeridbyportaluserid", portal.getId().toString(), Long.toString(id)) .flattenAsFlowable(Arrays::asList); } public Flowable<PlayerIdPortal> getPlayerIdsByGamerTag(Portal portal, String query) { return testAndCall(PlayerIdPortal[].class, "getplayeridsbygamertag", portal.getId().toString(), query) .flattenAsFlowable(Arrays::asList); } public Single<PlayerStats> getPlayerStats(long userId) { return testAndCall(PlayerStats.class, "getplayerstats", Long.toString(userId)); } public Single<PlayerStatus> getPlayerStatus(long userId) { return testAndCall(PlayerStatus.class, "getplayerstatus", Long.toString(userId)); }
// Path: api/src/main/java/hirez/api/object/interfaces/Queue.java // public interface Queue extends IDObject<Integer> { // String getName(); // // boolean isRanked(); // } // // Path: realm/src/main/java/hirez/realm/object/PlayerQuery.java // @Data // public class PlayerQuery implements ReturnedMessage { // private final long id; // private final String name; // private final int portalId; // @JsonProperty("ret_msg") // private final String returnedMessage; // private final long steamId; // } // Path: realm/src/main/java/hirez/realm/RealmRoyale.java import hirez.api.*; import hirez.api.object.*; import hirez.api.object.interfaces.Queue; import hirez.realm.object.PlayerQuery; import hirez.realm.object.*; import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.core.Single; import lombok.extern.slf4j.Slf4j; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.time.ZoneOffset; import java.util.Arrays; import java.util.Date; import java.util.TimeZone; import java.util.function.Consumer; return testAndCall(Player.class, "getplayer", Long.toString(userId), "hirez"); } public Single<Player> getPlayerBySteamId(long steamId) { return testAndCall(Player.class, "getplayer", Long.toString(steamId), "steam"); } public Flowable<PlayerIdPortal> getPlayerIdByName(String query) { return testAndCall(PlayerIdPortal.class, "getplayeridbyname", query) .flattenAsFlowable(Arrays::asList); } public Flowable<PlayerIdPortal> getPlayerIdByPortalUserId(Portal portal, long id) { return testAndCall(PlayerIdPortal[].class, "getplayeridbyportaluserid", portal.getId().toString(), Long.toString(id)) .flattenAsFlowable(Arrays::asList); } public Flowable<PlayerIdPortal> getPlayerIdsByGamerTag(Portal portal, String query) { return testAndCall(PlayerIdPortal[].class, "getplayeridsbygamertag", portal.getId().toString(), query) .flattenAsFlowable(Arrays::asList); } public Single<PlayerStats> getPlayerStats(long userId) { return testAndCall(PlayerStats.class, "getplayerstats", Long.toString(userId)); } public Single<PlayerStatus> getPlayerStatus(long userId) { return testAndCall(PlayerStatus.class, "getplayerstatus", Long.toString(userId)); }
public Flowable<PlayerQuery> searchPlayer(String query) {
stachu540/HiRezAPI
api/src/main/java/hirez/api/sessions/CachedSessionStorage.java
// Path: api/src/main/java/hirez/api/SessionStorage.java // public interface SessionStorage { // SessionStorage DEFAULT = CachedSessionStorage.create(); // // String get() throws NullPointerException; // // void get(Consumer<String> session); // // void set(CreateSession session); // // boolean isPresent(); // } // // Path: api/src/main/java/hirez/api/object/CreateSession.java // @Data // public class CreateSession implements ReturnedMessage { // @JsonProperty("ret_msg") // private String returnedMessage; // private String sessionId; // @DateTimeFormat // private Date timestamp; // // }
import hirez.api.SessionStorage; import hirez.api.object.CreateSession; import java.util.function.Consumer;
package hirez.api.sessions; public class CachedSessionStorage implements SessionStorage { private String session; public static SessionStorage create() { return new CachedSessionStorage(); } @Override public String get() throws NullPointerException { if (isPresent()) return session; else throw new NullPointerException("Please register session first!"); } @Override public void get(Consumer<String> session) { try { session.accept(get()); } catch (Throwable ignore) { } } @Override
// Path: api/src/main/java/hirez/api/SessionStorage.java // public interface SessionStorage { // SessionStorage DEFAULT = CachedSessionStorage.create(); // // String get() throws NullPointerException; // // void get(Consumer<String> session); // // void set(CreateSession session); // // boolean isPresent(); // } // // Path: api/src/main/java/hirez/api/object/CreateSession.java // @Data // public class CreateSession implements ReturnedMessage { // @JsonProperty("ret_msg") // private String returnedMessage; // private String sessionId; // @DateTimeFormat // private Date timestamp; // // } // Path: api/src/main/java/hirez/api/sessions/CachedSessionStorage.java import hirez.api.SessionStorage; import hirez.api.object.CreateSession; import java.util.function.Consumer; package hirez.api.sessions; public class CachedSessionStorage implements SessionStorage { private String session; public static SessionStorage create() { return new CachedSessionStorage(); } @Override public String get() throws NullPointerException { if (isPresent()) return session; else throw new NullPointerException("Please register session first!"); } @Override public void get(Consumer<String> session) { try { session.accept(get()); } catch (Throwable ignore) { } } @Override
public void set(CreateSession session) {
stachu540/HiRezAPI
paladins/src/main/java/hirez/paladins/object/MatchDetail.java
// Path: api/src/main/java/hirez/api/object/MergedAccount.java // @Data // public class MergedAccount { // @JsonProperty("merge_datetime") // @DateTimeFormat("MMM dd yyyy h:mma") // private final Date mergeDatetime; // @JsonProperty("playerId") // private final long playerId; // @JsonProperty("portalId") // private final int portalId; // } // // Path: api/src/main/java/hirez/api/object/interfaces/ReturnedMessage.java // public interface ReturnedMessage { // @JsonProperty("ret_msg") // String getReturnedMessage(); // }
import com.fasterxml.jackson.annotation.JsonProperty; import hirez.api.object.MergedAccount; import hirez.api.object.adapters.DateTimeFormat; import hirez.api.object.adapters.DurationTime; import hirez.api.object.adapters.TextToBoolean; import hirez.api.object.interfaces.ReturnedMessage; import lombok.Data; import lombok.Getter; import lombok.experimental.Accessors; import java.time.Duration; import java.time.temporal.ChronoUnit; import java.util.Date;
@JsonProperty("Kills_Player") private final int killsPlayer; @JsonProperty("Kills_Quadra") private final int killsQuadra; @JsonProperty("Kills_Siege_Juggernaut") private final int killsSiegeJuggernaut; @JsonProperty("Kills_Single") private final int killsSingle; @JsonProperty("Kills_Triple") private final int killsTriple; @JsonProperty("Kills_Wild_Juggernaut") private final int killsWildJuggernaut; @JsonProperty("League_Losses") private final int leagueLosses; @JsonProperty("League_Points") private final int leaguePoints; @JsonProperty("League_Tier") private final int leagueTier; @JsonProperty("League_Wins") private final int leagueWins; @JsonProperty("Map_Game") private final String mapGame; @JsonProperty("Mastery_Level") private final int masteryLevel; @JsonProperty("Match") private final long matchId; @DurationTime @JsonProperty("Match_Duration") private final Duration matchDuration; @JsonProperty("MergedPlayers")
// Path: api/src/main/java/hirez/api/object/MergedAccount.java // @Data // public class MergedAccount { // @JsonProperty("merge_datetime") // @DateTimeFormat("MMM dd yyyy h:mma") // private final Date mergeDatetime; // @JsonProperty("playerId") // private final long playerId; // @JsonProperty("portalId") // private final int portalId; // } // // Path: api/src/main/java/hirez/api/object/interfaces/ReturnedMessage.java // public interface ReturnedMessage { // @JsonProperty("ret_msg") // String getReturnedMessage(); // } // Path: paladins/src/main/java/hirez/paladins/object/MatchDetail.java import com.fasterxml.jackson.annotation.JsonProperty; import hirez.api.object.MergedAccount; import hirez.api.object.adapters.DateTimeFormat; import hirez.api.object.adapters.DurationTime; import hirez.api.object.adapters.TextToBoolean; import hirez.api.object.interfaces.ReturnedMessage; import lombok.Data; import lombok.Getter; import lombok.experimental.Accessors; import java.time.Duration; import java.time.temporal.ChronoUnit; import java.util.Date; @JsonProperty("Kills_Player") private final int killsPlayer; @JsonProperty("Kills_Quadra") private final int killsQuadra; @JsonProperty("Kills_Siege_Juggernaut") private final int killsSiegeJuggernaut; @JsonProperty("Kills_Single") private final int killsSingle; @JsonProperty("Kills_Triple") private final int killsTriple; @JsonProperty("Kills_Wild_Juggernaut") private final int killsWildJuggernaut; @JsonProperty("League_Losses") private final int leagueLosses; @JsonProperty("League_Points") private final int leaguePoints; @JsonProperty("League_Tier") private final int leagueTier; @JsonProperty("League_Wins") private final int leagueWins; @JsonProperty("Map_Game") private final String mapGame; @JsonProperty("Mastery_Level") private final int masteryLevel; @JsonProperty("Match") private final long matchId; @DurationTime @JsonProperty("Match_Duration") private final Duration matchDuration; @JsonProperty("MergedPlayers")
private final MergedAccount[] mergedPlayers;
stachu540/HiRezAPI
api/src/main/java/hirez/api/sessions/FileSessionStorage.java
// Path: api/src/main/java/hirez/api/SessionStorage.java // public interface SessionStorage { // SessionStorage DEFAULT = CachedSessionStorage.create(); // // String get() throws NullPointerException; // // void get(Consumer<String> session); // // void set(CreateSession session); // // boolean isPresent(); // } // // Path: api/src/main/java/hirez/api/object/CreateSession.java // @Data // public class CreateSession implements ReturnedMessage { // @JsonProperty("ret_msg") // private String returnedMessage; // private String sessionId; // @DateTimeFormat // private Date timestamp; // // }
import hirez.api.SessionStorage; import hirez.api.object.CreateSession; import lombok.RequiredArgsConstructor; import java.io.*; import java.util.function.Consumer;
package hirez.api.sessions; @RequiredArgsConstructor public class FileSessionStorage implements SessionStorage { private final File file; public static SessionStorage create() { return create(new File("hirez-session.txt")); } public static SessionStorage create(File file) { return new FileSessionStorage(file); } @Override public String get() throws NullPointerException { if (isPresent()) { try { return readFile(); } catch (IOException e) { throw new RuntimeException(e); } } else throw new NullPointerException("Please register session first!"); } @Override public void get(Consumer<String> session) { try { session.accept(get()); } catch (Throwable ignore) { } } @Override
// Path: api/src/main/java/hirez/api/SessionStorage.java // public interface SessionStorage { // SessionStorage DEFAULT = CachedSessionStorage.create(); // // String get() throws NullPointerException; // // void get(Consumer<String> session); // // void set(CreateSession session); // // boolean isPresent(); // } // // Path: api/src/main/java/hirez/api/object/CreateSession.java // @Data // public class CreateSession implements ReturnedMessage { // @JsonProperty("ret_msg") // private String returnedMessage; // private String sessionId; // @DateTimeFormat // private Date timestamp; // // } // Path: api/src/main/java/hirez/api/sessions/FileSessionStorage.java import hirez.api.SessionStorage; import hirez.api.object.CreateSession; import lombok.RequiredArgsConstructor; import java.io.*; import java.util.function.Consumer; package hirez.api.sessions; @RequiredArgsConstructor public class FileSessionStorage implements SessionStorage { private final File file; public static SessionStorage create() { return create(new File("hirez-session.txt")); } public static SessionStorage create(File file) { return new FileSessionStorage(file); } @Override public String get() throws NullPointerException { if (isPresent()) { try { return readFile(); } catch (IOException e) { throw new RuntimeException(e); } } else throw new NullPointerException("Please register session first!"); } @Override public void get(Consumer<String> session) { try { session.accept(get()); } catch (Throwable ignore) { } } @Override
public void set(CreateSession session) {
stachu540/HiRezAPI
smite/src/main/java/hirez/smite/object/Player.java
// Path: api/src/main/java/hirez/api/object/MergedAccount.java // @Data // public class MergedAccount { // @JsonProperty("merge_datetime") // @DateTimeFormat("MMM dd yyyy h:mma") // private final Date mergeDatetime; // @JsonProperty("playerId") // private final long playerId; // @JsonProperty("portalId") // private final int portalId; // } // // Path: api/src/main/java/hirez/api/object/interfaces/ReturnedMessage.java // public interface ReturnedMessage { // @JsonProperty("ret_msg") // String getReturnedMessage(); // }
import com.fasterxml.jackson.annotation.JsonProperty; import hirez.api.object.MergedAccount; import hirez.api.object.adapters.DateTimeFormat; import hirez.api.object.adapters.DurationTime; import hirez.api.object.interfaces.ReturnedMessage; import lombok.Data; import java.time.Duration; import java.time.temporal.ChronoUnit; import java.util.Date;
package hirez.smite.object; @Data public class Player implements ReturnedMessage { @JsonProperty("ActivePlayerId") private final long activePlayerId; @JsonProperty("Avatar_URL") private final String avatarURL; @DateTimeFormat("M/d/yyyy h:mm:ss a") @JsonProperty("Created_Datetime") private final Date createdDatetime; @DurationTime(ChronoUnit.HOURS) @JsonProperty("HoursPlayed") private final Duration hoursPlayed; @JsonProperty("Id") private final long id; @DateTimeFormat("M/d/yyyy h:mm:ss a") @JsonProperty("Last_Login_Datetime") private final Date lastLoginDatetime; @JsonProperty("Leaves") private final long leaves; @JsonProperty("Level") private final long level; @JsonProperty("Losses") private final long losses; @JsonProperty("MasteryLevel") private final long masteryLevel; @JsonProperty("MergedPlayers")
// Path: api/src/main/java/hirez/api/object/MergedAccount.java // @Data // public class MergedAccount { // @JsonProperty("merge_datetime") // @DateTimeFormat("MMM dd yyyy h:mma") // private final Date mergeDatetime; // @JsonProperty("playerId") // private final long playerId; // @JsonProperty("portalId") // private final int portalId; // } // // Path: api/src/main/java/hirez/api/object/interfaces/ReturnedMessage.java // public interface ReturnedMessage { // @JsonProperty("ret_msg") // String getReturnedMessage(); // } // Path: smite/src/main/java/hirez/smite/object/Player.java import com.fasterxml.jackson.annotation.JsonProperty; import hirez.api.object.MergedAccount; import hirez.api.object.adapters.DateTimeFormat; import hirez.api.object.adapters.DurationTime; import hirez.api.object.interfaces.ReturnedMessage; import lombok.Data; import java.time.Duration; import java.time.temporal.ChronoUnit; import java.util.Date; package hirez.smite.object; @Data public class Player implements ReturnedMessage { @JsonProperty("ActivePlayerId") private final long activePlayerId; @JsonProperty("Avatar_URL") private final String avatarURL; @DateTimeFormat("M/d/yyyy h:mm:ss a") @JsonProperty("Created_Datetime") private final Date createdDatetime; @DurationTime(ChronoUnit.HOURS) @JsonProperty("HoursPlayed") private final Duration hoursPlayed; @JsonProperty("Id") private final long id; @DateTimeFormat("M/d/yyyy h:mm:ss a") @JsonProperty("Last_Login_Datetime") private final Date lastLoginDatetime; @JsonProperty("Leaves") private final long leaves; @JsonProperty("Level") private final long level; @JsonProperty("Losses") private final long losses; @JsonProperty("MasteryLevel") private final long masteryLevel; @JsonProperty("MergedPlayers")
private final MergedAccount[] mergedPlayers;
stachu540/HiRezAPI
realm/src/main/java/hirez/realm/object/Talent.java
// Path: api/src/main/java/hirez/api/object/interfaces/ReturnedMessage.java // public interface ReturnedMessage { // @JsonProperty("ret_msg") // String getReturnedMessage(); // }
import com.fasterxml.jackson.annotation.JsonProperty; import hirez.api.object.interfaces.ReturnedMessage; import lombok.Data;
package hirez.realm.object; /** * @deprecated This endpoint is not exist */ @Data @Deprecated
// Path: api/src/main/java/hirez/api/object/interfaces/ReturnedMessage.java // public interface ReturnedMessage { // @JsonProperty("ret_msg") // String getReturnedMessage(); // } // Path: realm/src/main/java/hirez/realm/object/Talent.java import com.fasterxml.jackson.annotation.JsonProperty; import hirez.api.object.interfaces.ReturnedMessage; import lombok.Data; package hirez.realm.object; /** * @deprecated This endpoint is not exist */ @Data @Deprecated
public class Talent implements ReturnedMessage {
stachu540/HiRezAPI
api/src/main/java/hirez/api/Endpoint.java
// Path: api/src/main/java/hirez/api/object/interfaces/ReturnedMessage.java // public interface ReturnedMessage { // @JsonProperty("ret_msg") // String getReturnedMessage(); // }
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import hirez.api.object.*; import hirez.api.object.interfaces.ReturnedMessage; import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.core.Single; import lombok.Getter; import okhttp3.*; import okhttp3.logging.HttpLoggingInterceptor; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Arrays; import java.util.Objects;
final <T> Single<T> get(Class<T> type, String url) { return Single.<T>create(sink -> httpClient.newCall(new Request.Builder().get() .header("User-Agent", configuration.getUserAgent()) .url(url).build()).enqueue(new Callback() { @Override public void onFailure(@NotNull Call call, @NotNull IOException e) { sink.onError(e); } @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { sink.onSuccess(buildResponse(response, type)); } })) .doOnEvent((success, error) -> { if (Objects.nonNull(success)) { LOGGER.debug("[SUCCESS] " + url + " -> " + success); } if (Objects.nonNull(error)) { LOGGER.error("[ERROR] " + url, error); } }) .doOnSubscribe(d -> LOGGER.debug("[SUBSCRIBE] \"" + url + "\"")) .doOnDispose(() -> LOGGER.debug("[DISPOSE] \"" + url + "\"")) .doOnTerminate(() -> LOGGER.warn("[TERMINATE] \"" + url + "\"")); } protected final <T> Single<T> call(Class<T> type, String method, String... argv) { return get(type, configuration.createUrl(method, argv)).flatMap(r -> Single.create(sink -> {
// Path: api/src/main/java/hirez/api/object/interfaces/ReturnedMessage.java // public interface ReturnedMessage { // @JsonProperty("ret_msg") // String getReturnedMessage(); // } // Path: api/src/main/java/hirez/api/Endpoint.java import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import hirez.api.object.*; import hirez.api.object.interfaces.ReturnedMessage; import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.core.Single; import lombok.Getter; import okhttp3.*; import okhttp3.logging.HttpLoggingInterceptor; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Arrays; import java.util.Objects; final <T> Single<T> get(Class<T> type, String url) { return Single.<T>create(sink -> httpClient.newCall(new Request.Builder().get() .header("User-Agent", configuration.getUserAgent()) .url(url).build()).enqueue(new Callback() { @Override public void onFailure(@NotNull Call call, @NotNull IOException e) { sink.onError(e); } @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { sink.onSuccess(buildResponse(response, type)); } })) .doOnEvent((success, error) -> { if (Objects.nonNull(success)) { LOGGER.debug("[SUCCESS] " + url + " -> " + success); } if (Objects.nonNull(error)) { LOGGER.error("[ERROR] " + url, error); } }) .doOnSubscribe(d -> LOGGER.debug("[SUBSCRIBE] \"" + url + "\"")) .doOnDispose(() -> LOGGER.debug("[DISPOSE] \"" + url + "\"")) .doOnTerminate(() -> LOGGER.warn("[TERMINATE] \"" + url + "\"")); } protected final <T> Single<T> call(Class<T> type, String method, String... argv) { return get(type, configuration.createUrl(method, argv)).flatMap(r -> Single.create(sink -> {
ReturnedMessage rm = null;
stachu540/HiRezAPI
api/src/main/java/hirez/api/BaseEndpoint.java
// Path: api/src/main/java/hirez/api/object/Game.java // @Data // public class Game implements IDObject<String> { // private final String id; // private final String name; // } // // Path: api/src/main/java/hirez/api/object/Platform.java // @Data // public class Platform implements IDObject<String> { // private final String id; // private final String name; // }
import hirez.api.object.Game; import hirez.api.object.Platform;
package hirez.api; public interface BaseEndpoint { Game getGame();
// Path: api/src/main/java/hirez/api/object/Game.java // @Data // public class Game implements IDObject<String> { // private final String id; // private final String name; // } // // Path: api/src/main/java/hirez/api/object/Platform.java // @Data // public class Platform implements IDObject<String> { // private final String id; // private final String name; // } // Path: api/src/main/java/hirez/api/BaseEndpoint.java import hirez.api.object.Game; import hirez.api.object.Platform; package hirez.api; public interface BaseEndpoint { Game getGame();
Platform getPlatform();
stachu540/HiRezAPI
api/src/main/java/hirez/api/object/TestSession.java
// Path: api/src/main/java/hirez/api/HiRezUtils.java // public class HiRezUtils { // public static Date parse(String timestamp) { // timestamp = timestamp.replace("\\/", "/"); // SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a"); // sdf.setTimeZone(TimeZone.getTimeZone(ZoneOffset.UTC)); // try { // return sdf.parse(timestamp); // } catch (ParseException ignore) { // return null; // } // } // }
import hirez.api.HiRezUtils; import lombok.Data; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern;
package hirez.api.object; @Data public class TestSession { private final String rawMessage; private final boolean successful; private final Date timestamp; public TestSession(String raw) { this.rawMessage = raw.replace("\"", ""); Matcher matcher = Pattern.compile("^(.+): developer: ([0-9]{4}) time: (?<timestamp>.+) signature: (.+) session: (.+)$").matcher(raw.replace("\"", "")); if (matcher.find()) { successful = true;
// Path: api/src/main/java/hirez/api/HiRezUtils.java // public class HiRezUtils { // public static Date parse(String timestamp) { // timestamp = timestamp.replace("\\/", "/"); // SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a"); // sdf.setTimeZone(TimeZone.getTimeZone(ZoneOffset.UTC)); // try { // return sdf.parse(timestamp); // } catch (ParseException ignore) { // return null; // } // } // } // Path: api/src/main/java/hirez/api/object/TestSession.java import hirez.api.HiRezUtils; import lombok.Data; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; package hirez.api.object; @Data public class TestSession { private final String rawMessage; private final boolean successful; private final Date timestamp; public TestSession(String raw) { this.rawMessage = raw.replace("\"", ""); Matcher matcher = Pattern.compile("^(.+): developer: ([0-9]{4}) time: (?<timestamp>.+) signature: (.+) session: (.+)$").matcher(raw.replace("\"", "")); if (matcher.find()) { successful = true;
timestamp = HiRezUtils.parse(matcher.group("timestamp"));
stachu540/HiRezAPI
smite/src/main/java/hirez/smite/SmiteGame.java
// Path: api/src/main/java/hirez/api/object/interfaces/Queue.java // public interface Queue extends IDObject<Integer> { // String getName(); // // boolean isRanked(); // } // // Path: smite/src/main/java/hirez/smite/object/Rank.java // @Data // public class Rank implements ReturnedMessage { // @JsonProperty("Leaves") // private final int leaves; // @JsonProperty("Losses") // private final int losses; // @JsonProperty("Name") // private final String name; // @JsonProperty("Points") // private final int points; // @JsonProperty("PrevRank") // private final int prevRank; // @JsonProperty("Rank") // private final int rank; // @JsonProperty("Rank_Stat") // private final double rankStat; // @JsonProperty("Rank_Variance") // private final int rankVariance; // @JsonProperty("Season") // private final int season; // @JsonProperty("Tier") // private final int tier; // @JsonProperty("Trend") // private final int trend; // @JsonProperty("Wins") // private final int wins; // private final long playerId; // @JsonProperty("ret_msg") // private final String returnedMessage; // // }
import hirez.api.*; import hirez.api.object.*; import hirez.api.object.interfaces.Queue; import hirez.smite.object.*; import hirez.smite.object.Rank; import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.core.Single; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.function.Consumer; import java.util.stream.Collectors;
package hirez.smite; public class SmiteGame extends Endpoint { private SmiteGame(Configuration configuration) { super(configuration); } public static SmiteGame create(Consumer<ConfigurationBuilder> configuration) { return new SmiteGame(new ConfigurationBuilder().applyFrom((cfg) -> { configuration.accept(cfg); if (cfg.getBaseEndpoint() == null) { cfg.setBaseEndpoint(SmitePlatform.PC); } }).build()); } static boolean isRanked(int id) { return Arrays.asList(440, 450, 451, 502, 503, 504).contains(id); }
// Path: api/src/main/java/hirez/api/object/interfaces/Queue.java // public interface Queue extends IDObject<Integer> { // String getName(); // // boolean isRanked(); // } // // Path: smite/src/main/java/hirez/smite/object/Rank.java // @Data // public class Rank implements ReturnedMessage { // @JsonProperty("Leaves") // private final int leaves; // @JsonProperty("Losses") // private final int losses; // @JsonProperty("Name") // private final String name; // @JsonProperty("Points") // private final int points; // @JsonProperty("PrevRank") // private final int prevRank; // @JsonProperty("Rank") // private final int rank; // @JsonProperty("Rank_Stat") // private final double rankStat; // @JsonProperty("Rank_Variance") // private final int rankVariance; // @JsonProperty("Season") // private final int season; // @JsonProperty("Tier") // private final int tier; // @JsonProperty("Trend") // private final int trend; // @JsonProperty("Wins") // private final int wins; // private final long playerId; // @JsonProperty("ret_msg") // private final String returnedMessage; // // } // Path: smite/src/main/java/hirez/smite/SmiteGame.java import hirez.api.*; import hirez.api.object.*; import hirez.api.object.interfaces.Queue; import hirez.smite.object.*; import hirez.smite.object.Rank; import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.core.Single; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.function.Consumer; import java.util.stream.Collectors; package hirez.smite; public class SmiteGame extends Endpoint { private SmiteGame(Configuration configuration) { super(configuration); } public static SmiteGame create(Consumer<ConfigurationBuilder> configuration) { return new SmiteGame(new ConfigurationBuilder().applyFrom((cfg) -> { configuration.accept(cfg); if (cfg.getBaseEndpoint() == null) { cfg.setBaseEndpoint(SmitePlatform.PC); } }).build()); } static boolean isRanked(int id) { return Arrays.asList(440, 450, 451, 502, 503, 504).contains(id); }
public Flowable<GodLeaderboard> getGodLeaderboard(long godId, Queue queue) {
stachu540/HiRezAPI
smite/src/main/java/hirez/smite/SmiteGame.java
// Path: api/src/main/java/hirez/api/object/interfaces/Queue.java // public interface Queue extends IDObject<Integer> { // String getName(); // // boolean isRanked(); // } // // Path: smite/src/main/java/hirez/smite/object/Rank.java // @Data // public class Rank implements ReturnedMessage { // @JsonProperty("Leaves") // private final int leaves; // @JsonProperty("Losses") // private final int losses; // @JsonProperty("Name") // private final String name; // @JsonProperty("Points") // private final int points; // @JsonProperty("PrevRank") // private final int prevRank; // @JsonProperty("Rank") // private final int rank; // @JsonProperty("Rank_Stat") // private final double rankStat; // @JsonProperty("Rank_Variance") // private final int rankVariance; // @JsonProperty("Season") // private final int season; // @JsonProperty("Tier") // private final int tier; // @JsonProperty("Trend") // private final int trend; // @JsonProperty("Wins") // private final int wins; // private final long playerId; // @JsonProperty("ret_msg") // private final String returnedMessage; // // }
import hirez.api.*; import hirez.api.object.*; import hirez.api.object.interfaces.Queue; import hirez.smite.object.*; import hirez.smite.object.Rank; import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.core.Single; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.function.Consumer; import java.util.stream.Collectors;
.flattenAsFlowable(Arrays::asList); } public Flowable<God> getGods() { return getGods(getConfiguration().getLanguage()); } public Flowable<GodSkin> getGodSkins(long godId, Language language) { return testAndCall(GodSkin[].class, "getgodskins", Long.toString(godId), language.getId().toString()) .flattenAsFlowable(Arrays::asList); } public Flowable<GodSkin> getGodSkins(long godId) { return getGodSkins(godId, getConfiguration().getLanguage()); } public Flowable<Item> getItems(Language language) { return testAndCall(Item[].class, "getitems", language.getId().toString()) .flattenAsFlowable(Arrays::asList); } public Flowable<Item> getItems() { return getItems(getConfiguration().getLanguage()); } public Single<DemoDetail> getDemoDetails(long matchId) { return testAndCall(DemoDetail[].class, "getdemodetails", Long.toString(matchId)) .map(it -> it[0]); }
// Path: api/src/main/java/hirez/api/object/interfaces/Queue.java // public interface Queue extends IDObject<Integer> { // String getName(); // // boolean isRanked(); // } // // Path: smite/src/main/java/hirez/smite/object/Rank.java // @Data // public class Rank implements ReturnedMessage { // @JsonProperty("Leaves") // private final int leaves; // @JsonProperty("Losses") // private final int losses; // @JsonProperty("Name") // private final String name; // @JsonProperty("Points") // private final int points; // @JsonProperty("PrevRank") // private final int prevRank; // @JsonProperty("Rank") // private final int rank; // @JsonProperty("Rank_Stat") // private final double rankStat; // @JsonProperty("Rank_Variance") // private final int rankVariance; // @JsonProperty("Season") // private final int season; // @JsonProperty("Tier") // private final int tier; // @JsonProperty("Trend") // private final int trend; // @JsonProperty("Wins") // private final int wins; // private final long playerId; // @JsonProperty("ret_msg") // private final String returnedMessage; // // } // Path: smite/src/main/java/hirez/smite/SmiteGame.java import hirez.api.*; import hirez.api.object.*; import hirez.api.object.interfaces.Queue; import hirez.smite.object.*; import hirez.smite.object.Rank; import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.core.Single; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.function.Consumer; import java.util.stream.Collectors; .flattenAsFlowable(Arrays::asList); } public Flowable<God> getGods() { return getGods(getConfiguration().getLanguage()); } public Flowable<GodSkin> getGodSkins(long godId, Language language) { return testAndCall(GodSkin[].class, "getgodskins", Long.toString(godId), language.getId().toString()) .flattenAsFlowable(Arrays::asList); } public Flowable<GodSkin> getGodSkins(long godId) { return getGodSkins(godId, getConfiguration().getLanguage()); } public Flowable<Item> getItems(Language language) { return testAndCall(Item[].class, "getitems", language.getId().toString()) .flattenAsFlowable(Arrays::asList); } public Flowable<Item> getItems() { return getItems(getConfiguration().getLanguage()); } public Single<DemoDetail> getDemoDetails(long matchId) { return testAndCall(DemoDetail[].class, "getdemodetails", Long.toString(matchId)) .map(it -> it[0]); }
public Flowable<Rank> getLeagueLeaderboard(Queue queue, Division division, int round) {
stachu540/HiRezAPI
paladins/src/main/java/hirez/paladins/Paladins.java
// Path: api/src/main/java/hirez/api/object/interfaces/Queue.java // public interface Queue extends IDObject<Integer> { // String getName(); // // boolean isRanked(); // } // // Path: paladins/src/main/java/hirez/paladins/object/Rank.java // @Data // public class Rank implements ReturnedMessage { // @JsonProperty("Leaves") // private final int leaves; // @JsonProperty("Losses") // private final int losses; // @JsonProperty("Name") // private final String name; // @JsonProperty("Points") // private final int points; // @JsonProperty("PrevRank") // private final int prevRank; // @JsonProperty("Rank") // private final int rank; // @JsonProperty("Season") // private final int season; // @JsonProperty("Tier") // private final int tier; // @JsonProperty("Trend") // private final int trend; // @JsonProperty("Wins") // private final int wins; // private final long playerId; // @JsonProperty("ret_msg") // private final String returnedMessage; // }
import hirez.api.*; import hirez.api.object.*; import hirez.api.object.interfaces.Queue; import hirez.paladins.object.Rank; import hirez.paladins.object.*; import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.core.Maybe; import io.reactivex.rxjava3.core.Single; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.Optional; import java.util.function.Consumer; import java.util.stream.Collectors;
public Flowable<ChampionSkin> getChampionSkins(long championId, Language language) { return testAndCall(ChampionSkin[].class, "getchampionskins", Long.toString(championId), language.getId().toString()) .flattenAsFlowable(Arrays::asList); } public Flowable<ChampionSkin> getChampionSkins(long championId) { return getChampionSkins(championId, getConfiguration().getLanguage()); } public Flowable<Item> getItems(Language language) { return testAndCall(Item[].class, "getitems", language.getId().toString()) .flattenAsFlowable(Arrays::asList); } public Flowable<Item> getItems() { return getItems(getConfiguration().getLanguage()); } public Single<DemoDetail> getDemoDetails(long matchId) { return testAndCall(DemoDetail[].class, "getdemodetails", Long.toString(matchId)) .flatMap(it -> Single.create(sink -> { if (it.length > 0) { sink.onSuccess(it[0]); } else { sink.onError(new HiRezException(String.format("Demo of match %d is not exist", matchId))); } })); }
// Path: api/src/main/java/hirez/api/object/interfaces/Queue.java // public interface Queue extends IDObject<Integer> { // String getName(); // // boolean isRanked(); // } // // Path: paladins/src/main/java/hirez/paladins/object/Rank.java // @Data // public class Rank implements ReturnedMessage { // @JsonProperty("Leaves") // private final int leaves; // @JsonProperty("Losses") // private final int losses; // @JsonProperty("Name") // private final String name; // @JsonProperty("Points") // private final int points; // @JsonProperty("PrevRank") // private final int prevRank; // @JsonProperty("Rank") // private final int rank; // @JsonProperty("Season") // private final int season; // @JsonProperty("Tier") // private final int tier; // @JsonProperty("Trend") // private final int trend; // @JsonProperty("Wins") // private final int wins; // private final long playerId; // @JsonProperty("ret_msg") // private final String returnedMessage; // } // Path: paladins/src/main/java/hirez/paladins/Paladins.java import hirez.api.*; import hirez.api.object.*; import hirez.api.object.interfaces.Queue; import hirez.paladins.object.Rank; import hirez.paladins.object.*; import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.core.Maybe; import io.reactivex.rxjava3.core.Single; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.Optional; import java.util.function.Consumer; import java.util.stream.Collectors; public Flowable<ChampionSkin> getChampionSkins(long championId, Language language) { return testAndCall(ChampionSkin[].class, "getchampionskins", Long.toString(championId), language.getId().toString()) .flattenAsFlowable(Arrays::asList); } public Flowable<ChampionSkin> getChampionSkins(long championId) { return getChampionSkins(championId, getConfiguration().getLanguage()); } public Flowable<Item> getItems(Language language) { return testAndCall(Item[].class, "getitems", language.getId().toString()) .flattenAsFlowable(Arrays::asList); } public Flowable<Item> getItems() { return getItems(getConfiguration().getLanguage()); } public Single<DemoDetail> getDemoDetails(long matchId) { return testAndCall(DemoDetail[].class, "getdemodetails", Long.toString(matchId)) .flatMap(it -> Single.create(sink -> { if (it.length > 0) { sink.onSuccess(it[0]); } else { sink.onError(new HiRezException(String.format("Demo of match %d is not exist", matchId))); } })); }
public Flowable<Rank> getLeagueLeaderboard(Queue queue, Division division, int round) {
stachu540/HiRezAPI
paladins/src/main/java/hirez/paladins/Paladins.java
// Path: api/src/main/java/hirez/api/object/interfaces/Queue.java // public interface Queue extends IDObject<Integer> { // String getName(); // // boolean isRanked(); // } // // Path: paladins/src/main/java/hirez/paladins/object/Rank.java // @Data // public class Rank implements ReturnedMessage { // @JsonProperty("Leaves") // private final int leaves; // @JsonProperty("Losses") // private final int losses; // @JsonProperty("Name") // private final String name; // @JsonProperty("Points") // private final int points; // @JsonProperty("PrevRank") // private final int prevRank; // @JsonProperty("Rank") // private final int rank; // @JsonProperty("Season") // private final int season; // @JsonProperty("Tier") // private final int tier; // @JsonProperty("Trend") // private final int trend; // @JsonProperty("Wins") // private final int wins; // private final long playerId; // @JsonProperty("ret_msg") // private final String returnedMessage; // }
import hirez.api.*; import hirez.api.object.*; import hirez.api.object.interfaces.Queue; import hirez.paladins.object.Rank; import hirez.paladins.object.*; import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.core.Maybe; import io.reactivex.rxjava3.core.Single; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.Optional; import java.util.function.Consumer; import java.util.stream.Collectors;
public Flowable<ChampionSkin> getChampionSkins(long championId, Language language) { return testAndCall(ChampionSkin[].class, "getchampionskins", Long.toString(championId), language.getId().toString()) .flattenAsFlowable(Arrays::asList); } public Flowable<ChampionSkin> getChampionSkins(long championId) { return getChampionSkins(championId, getConfiguration().getLanguage()); } public Flowable<Item> getItems(Language language) { return testAndCall(Item[].class, "getitems", language.getId().toString()) .flattenAsFlowable(Arrays::asList); } public Flowable<Item> getItems() { return getItems(getConfiguration().getLanguage()); } public Single<DemoDetail> getDemoDetails(long matchId) { return testAndCall(DemoDetail[].class, "getdemodetails", Long.toString(matchId)) .flatMap(it -> Single.create(sink -> { if (it.length > 0) { sink.onSuccess(it[0]); } else { sink.onError(new HiRezException(String.format("Demo of match %d is not exist", matchId))); } })); }
// Path: api/src/main/java/hirez/api/object/interfaces/Queue.java // public interface Queue extends IDObject<Integer> { // String getName(); // // boolean isRanked(); // } // // Path: paladins/src/main/java/hirez/paladins/object/Rank.java // @Data // public class Rank implements ReturnedMessage { // @JsonProperty("Leaves") // private final int leaves; // @JsonProperty("Losses") // private final int losses; // @JsonProperty("Name") // private final String name; // @JsonProperty("Points") // private final int points; // @JsonProperty("PrevRank") // private final int prevRank; // @JsonProperty("Rank") // private final int rank; // @JsonProperty("Season") // private final int season; // @JsonProperty("Tier") // private final int tier; // @JsonProperty("Trend") // private final int trend; // @JsonProperty("Wins") // private final int wins; // private final long playerId; // @JsonProperty("ret_msg") // private final String returnedMessage; // } // Path: paladins/src/main/java/hirez/paladins/Paladins.java import hirez.api.*; import hirez.api.object.*; import hirez.api.object.interfaces.Queue; import hirez.paladins.object.Rank; import hirez.paladins.object.*; import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.core.Maybe; import io.reactivex.rxjava3.core.Single; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.Optional; import java.util.function.Consumer; import java.util.stream.Collectors; public Flowable<ChampionSkin> getChampionSkins(long championId, Language language) { return testAndCall(ChampionSkin[].class, "getchampionskins", Long.toString(championId), language.getId().toString()) .flattenAsFlowable(Arrays::asList); } public Flowable<ChampionSkin> getChampionSkins(long championId) { return getChampionSkins(championId, getConfiguration().getLanguage()); } public Flowable<Item> getItems(Language language) { return testAndCall(Item[].class, "getitems", language.getId().toString()) .flattenAsFlowable(Arrays::asList); } public Flowable<Item> getItems() { return getItems(getConfiguration().getLanguage()); } public Single<DemoDetail> getDemoDetails(long matchId) { return testAndCall(DemoDetail[].class, "getdemodetails", Long.toString(matchId)) .flatMap(it -> Single.create(sink -> { if (it.length > 0) { sink.onSuccess(it[0]); } else { sink.onError(new HiRezException(String.format("Demo of match %d is not exist", matchId))); } })); }
public Flowable<Rank> getLeagueLeaderboard(Queue queue, Division division, int round) {
stachu540/HiRezAPI
api/src/main/java/hirez/api/SessionStorage.java
// Path: api/src/main/java/hirez/api/object/CreateSession.java // @Data // public class CreateSession implements ReturnedMessage { // @JsonProperty("ret_msg") // private String returnedMessage; // private String sessionId; // @DateTimeFormat // private Date timestamp; // // } // // Path: api/src/main/java/hirez/api/sessions/CachedSessionStorage.java // public class CachedSessionStorage implements SessionStorage { // private String session; // // public static SessionStorage create() { // return new CachedSessionStorage(); // } // // @Override // public String get() throws NullPointerException { // if (isPresent()) // return session; // else // throw new NullPointerException("Please register session first!"); // } // // @Override // public void get(Consumer<String> session) { // try { // session.accept(get()); // } catch (Throwable ignore) { // } // } // // @Override // public void set(CreateSession session) { // if (session.getReturnedMessage().equals("Approved")) { // this.session = session.getSessionId(); // } else throw new IllegalStateException(session.getReturnedMessage()); // } // // @Override // public boolean isPresent() { // return session != null; // } // }
import hirez.api.object.CreateSession; import hirez.api.sessions.CachedSessionStorage; import java.util.function.Consumer;
package hirez.api; public interface SessionStorage { SessionStorage DEFAULT = CachedSessionStorage.create(); String get() throws NullPointerException; void get(Consumer<String> session);
// Path: api/src/main/java/hirez/api/object/CreateSession.java // @Data // public class CreateSession implements ReturnedMessage { // @JsonProperty("ret_msg") // private String returnedMessage; // private String sessionId; // @DateTimeFormat // private Date timestamp; // // } // // Path: api/src/main/java/hirez/api/sessions/CachedSessionStorage.java // public class CachedSessionStorage implements SessionStorage { // private String session; // // public static SessionStorage create() { // return new CachedSessionStorage(); // } // // @Override // public String get() throws NullPointerException { // if (isPresent()) // return session; // else // throw new NullPointerException("Please register session first!"); // } // // @Override // public void get(Consumer<String> session) { // try { // session.accept(get()); // } catch (Throwable ignore) { // } // } // // @Override // public void set(CreateSession session) { // if (session.getReturnedMessage().equals("Approved")) { // this.session = session.getSessionId(); // } else throw new IllegalStateException(session.getReturnedMessage()); // } // // @Override // public boolean isPresent() { // return session != null; // } // } // Path: api/src/main/java/hirez/api/SessionStorage.java import hirez.api.object.CreateSession; import hirez.api.sessions.CachedSessionStorage; import java.util.function.Consumer; package hirez.api; public interface SessionStorage { SessionStorage DEFAULT = CachedSessionStorage.create(); String get() throws NullPointerException; void get(Consumer<String> session);
void set(CreateSession session);
stachu540/HiRezAPI
paladins/src/main/java/hirez/paladins/object/Player.java
// Path: api/src/main/java/hirez/api/object/MergedAccount.java // @Data // public class MergedAccount { // @JsonProperty("merge_datetime") // @DateTimeFormat("MMM dd yyyy h:mma") // private final Date mergeDatetime; // @JsonProperty("playerId") // private final long playerId; // @JsonProperty("portalId") // private final int portalId; // } // // Path: api/src/main/java/hirez/api/object/interfaces/ReturnedMessage.java // public interface ReturnedMessage { // @JsonProperty("ret_msg") // String getReturnedMessage(); // }
import com.fasterxml.jackson.annotation.JsonProperty; import hirez.api.object.MergedAccount; import hirez.api.object.adapters.DateTimeFormat; import hirez.api.object.adapters.DurationTime; import hirez.api.object.interfaces.ReturnedMessage; import lombok.Data; import java.time.Duration; import java.time.temporal.ChronoUnit; import java.util.Date;
@Data public class Player implements ReturnedMessage { @JsonProperty("ActivePlayerId") private final long activePlayerId; @JsonProperty("AvatarId") private final long avatarId; @JsonProperty("AvatarURL") private final String avatarURL; @DateTimeFormat @JsonProperty("Created_Datetime") private final Date createdDatetime; @DurationTime(ChronoUnit.HOURS) @JsonProperty("HoursPlayed") private final Duration hoursPlayed; @JsonProperty("Id") private final long id; @DateTimeFormat @JsonProperty("Last_Login_Datetime") private final Date lastLoginDatetime; @JsonProperty("Leaves") private final int leaves; @JsonProperty("Level") private final int level; @JsonProperty("LoadingFrame") private final String loadingFrame; @JsonProperty("Losses") private final int losses; @JsonProperty("MasteryLevel") private final int masteryLevel; @JsonProperty("MergedPlayers")
// Path: api/src/main/java/hirez/api/object/MergedAccount.java // @Data // public class MergedAccount { // @JsonProperty("merge_datetime") // @DateTimeFormat("MMM dd yyyy h:mma") // private final Date mergeDatetime; // @JsonProperty("playerId") // private final long playerId; // @JsonProperty("portalId") // private final int portalId; // } // // Path: api/src/main/java/hirez/api/object/interfaces/ReturnedMessage.java // public interface ReturnedMessage { // @JsonProperty("ret_msg") // String getReturnedMessage(); // } // Path: paladins/src/main/java/hirez/paladins/object/Player.java import com.fasterxml.jackson.annotation.JsonProperty; import hirez.api.object.MergedAccount; import hirez.api.object.adapters.DateTimeFormat; import hirez.api.object.adapters.DurationTime; import hirez.api.object.interfaces.ReturnedMessage; import lombok.Data; import java.time.Duration; import java.time.temporal.ChronoUnit; import java.util.Date; @Data public class Player implements ReturnedMessage { @JsonProperty("ActivePlayerId") private final long activePlayerId; @JsonProperty("AvatarId") private final long avatarId; @JsonProperty("AvatarURL") private final String avatarURL; @DateTimeFormat @JsonProperty("Created_Datetime") private final Date createdDatetime; @DurationTime(ChronoUnit.HOURS) @JsonProperty("HoursPlayed") private final Duration hoursPlayed; @JsonProperty("Id") private final long id; @DateTimeFormat @JsonProperty("Last_Login_Datetime") private final Date lastLoginDatetime; @JsonProperty("Leaves") private final int leaves; @JsonProperty("Level") private final int level; @JsonProperty("LoadingFrame") private final String loadingFrame; @JsonProperty("Losses") private final int losses; @JsonProperty("MasteryLevel") private final int masteryLevel; @JsonProperty("MergedPlayers")
private final MergedAccount[] mergedPlayers;
stachu540/HiRezAPI
smite/src/main/java/hirez/smite/SmitePlatform.java
// Path: api/src/main/java/hirez/api/BaseEndpoint.java // public interface BaseEndpoint { // Game getGame(); // // Platform getPlatform(); // // String getBaseUrl(); // } // // Path: api/src/main/java/hirez/api/object/Game.java // @Data // public class Game implements IDObject<String> { // private final String id; // private final String name; // } // // Path: api/src/main/java/hirez/api/object/Platform.java // @Data // public class Platform implements IDObject<String> { // private final String id; // private final String name; // }
import hirez.api.BaseEndpoint; import hirez.api.object.Game; import hirez.api.object.Platform; import lombok.Getter;
package hirez.smite; @Getter public enum SmitePlatform implements BaseEndpoint { PC("http://api.smitegame.com/smiteapi.svc", "23d1x2hb4kyq"), XBOX("http://api.xbox.smitegame.com/smiteapi.svc", "7q3rm3krkkt6"), PS4("http://api.ps4.smitegame.com/smiteapi.svc", "glnkmmppldgp"); private final String baseUrl;
// Path: api/src/main/java/hirez/api/BaseEndpoint.java // public interface BaseEndpoint { // Game getGame(); // // Platform getPlatform(); // // String getBaseUrl(); // } // // Path: api/src/main/java/hirez/api/object/Game.java // @Data // public class Game implements IDObject<String> { // private final String id; // private final String name; // } // // Path: api/src/main/java/hirez/api/object/Platform.java // @Data // public class Platform implements IDObject<String> { // private final String id; // private final String name; // } // Path: smite/src/main/java/hirez/smite/SmitePlatform.java import hirez.api.BaseEndpoint; import hirez.api.object.Game; import hirez.api.object.Platform; import lombok.Getter; package hirez.smite; @Getter public enum SmitePlatform implements BaseEndpoint { PC("http://api.smitegame.com/smiteapi.svc", "23d1x2hb4kyq"), XBOX("http://api.xbox.smitegame.com/smiteapi.svc", "7q3rm3krkkt6"), PS4("http://api.ps4.smitegame.com/smiteapi.svc", "glnkmmppldgp"); private final String baseUrl;
private final Platform platform;
stachu540/HiRezAPI
smite/src/main/java/hirez/smite/SmitePlatform.java
// Path: api/src/main/java/hirez/api/BaseEndpoint.java // public interface BaseEndpoint { // Game getGame(); // // Platform getPlatform(); // // String getBaseUrl(); // } // // Path: api/src/main/java/hirez/api/object/Game.java // @Data // public class Game implements IDObject<String> { // private final String id; // private final String name; // } // // Path: api/src/main/java/hirez/api/object/Platform.java // @Data // public class Platform implements IDObject<String> { // private final String id; // private final String name; // }
import hirez.api.BaseEndpoint; import hirez.api.object.Game; import hirez.api.object.Platform; import lombok.Getter;
package hirez.smite; @Getter public enum SmitePlatform implements BaseEndpoint { PC("http://api.smitegame.com/smiteapi.svc", "23d1x2hb4kyq"), XBOX("http://api.xbox.smitegame.com/smiteapi.svc", "7q3rm3krkkt6"), PS4("http://api.ps4.smitegame.com/smiteapi.svc", "glnkmmppldgp"); private final String baseUrl; private final Platform platform;
// Path: api/src/main/java/hirez/api/BaseEndpoint.java // public interface BaseEndpoint { // Game getGame(); // // Platform getPlatform(); // // String getBaseUrl(); // } // // Path: api/src/main/java/hirez/api/object/Game.java // @Data // public class Game implements IDObject<String> { // private final String id; // private final String name; // } // // Path: api/src/main/java/hirez/api/object/Platform.java // @Data // public class Platform implements IDObject<String> { // private final String id; // private final String name; // } // Path: smite/src/main/java/hirez/smite/SmitePlatform.java import hirez.api.BaseEndpoint; import hirez.api.object.Game; import hirez.api.object.Platform; import lombok.Getter; package hirez.smite; @Getter public enum SmitePlatform implements BaseEndpoint { PC("http://api.smitegame.com/smiteapi.svc", "23d1x2hb4kyq"), XBOX("http://api.xbox.smitegame.com/smiteapi.svc", "7q3rm3krkkt6"), PS4("http://api.ps4.smitegame.com/smiteapi.svc", "glnkmmppldgp"); private final String baseUrl; private final Platform platform;
private final Game game = new Game("542zlqj9nwr6", "Smite");
stachu540/HiRezAPI
api/src/main/java/hirez/api/object/PatchInfo.java
// Path: api/src/main/java/hirez/api/object/interfaces/ReturnedMessage.java // public interface ReturnedMessage { // @JsonProperty("ret_msg") // String getReturnedMessage(); // }
import com.fasterxml.jackson.annotation.JsonAlias; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import hirez.api.object.interfaces.ReturnedMessage; import lombok.Data;
package hirez.api.object; @Data @JsonIgnoreProperties(ignoreUnknown = true)
// Path: api/src/main/java/hirez/api/object/interfaces/ReturnedMessage.java // public interface ReturnedMessage { // @JsonProperty("ret_msg") // String getReturnedMessage(); // } // Path: api/src/main/java/hirez/api/object/PatchInfo.java import com.fasterxml.jackson.annotation.JsonAlias; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import hirez.api.object.interfaces.ReturnedMessage; import lombok.Data; package hirez.api.object; @Data @JsonIgnoreProperties(ignoreUnknown = true)
public class PatchInfo implements ReturnedMessage {
AbigailBuccaneer/intellij-avro
src/main/java/claims/bold/intellij/avro/idl/structure/AvroIdlStructureViewFactory.java
// Path: src/main/java/claims/bold/intellij/avro/idl/psi/AvroIdlFile.java // public class AvroIdlFile extends PsiFileBase { // public AvroIdlFile(@NotNull FileViewProvider viewProvider) { // super(viewProvider, AvroIdlLanguage.INSTANCE); // } // // @NotNull // @Override // public FileType getFileType() { // return AvroIdlFileType.INSTANCE; // } // // @Override // public String toString() { // return "Avro™ IDL file"; // } // }
import claims.bold.intellij.avro.idl.psi.AvroIdlFile; import com.intellij.ide.structureView.StructureViewBuilder; import com.intellij.ide.structureView.StructureViewModel; import com.intellij.ide.structureView.TreeBasedStructureViewBuilder; import com.intellij.lang.PsiStructureViewFactory; import com.intellij.openapi.editor.Editor; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable;
package claims.bold.intellij.avro.idl.structure; public class AvroIdlStructureViewFactory implements PsiStructureViewFactory { @Nullable @Override public StructureViewBuilder getStructureViewBuilder(final PsiFile psiFile) { return new TreeBasedStructureViewBuilder() { @NotNull @Override public StructureViewModel createStructureViewModel(@Nullable Editor editor) {
// Path: src/main/java/claims/bold/intellij/avro/idl/psi/AvroIdlFile.java // public class AvroIdlFile extends PsiFileBase { // public AvroIdlFile(@NotNull FileViewProvider viewProvider) { // super(viewProvider, AvroIdlLanguage.INSTANCE); // } // // @NotNull // @Override // public FileType getFileType() { // return AvroIdlFileType.INSTANCE; // } // // @Override // public String toString() { // return "Avro™ IDL file"; // } // } // Path: src/main/java/claims/bold/intellij/avro/idl/structure/AvroIdlStructureViewFactory.java import claims.bold.intellij.avro.idl.psi.AvroIdlFile; import com.intellij.ide.structureView.StructureViewBuilder; import com.intellij.ide.structureView.StructureViewModel; import com.intellij.ide.structureView.TreeBasedStructureViewBuilder; import com.intellij.lang.PsiStructureViewFactory; import com.intellij.openapi.editor.Editor; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; package claims.bold.intellij.avro.idl.structure; public class AvroIdlStructureViewFactory implements PsiStructureViewFactory { @Nullable @Override public StructureViewBuilder getStructureViewBuilder(final PsiFile psiFile) { return new TreeBasedStructureViewBuilder() { @NotNull @Override public StructureViewModel createStructureViewModel(@Nullable Editor editor) {
return new AvroIdlStructureViewModel((AvroIdlFile)psiFile, editor);
AbigailBuccaneer/intellij-avro
src/main/java/claims/bold/intellij/avro/idl/colors/AvroIdlColorSettingsPage.java
// Path: src/main/java/claims/bold/intellij/avro/idl/AvroIdlIcons.java // public class AvroIdlIcons { // // TODO a language-specific file icon // public static final Icon FILE = AllIcons.FileTypes.Text; // }
import claims.bold.intellij.avro.idl.AvroIdlIcons; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.fileTypes.SyntaxHighlighter; import com.intellij.openapi.options.colors.AttributesDescriptor; import com.intellij.openapi.options.colors.ColorDescriptor; import com.intellij.openapi.options.colors.ColorSettingsPage; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.HashMap; import java.util.Map;
package claims.bold.intellij.avro.idl.colors; /** * Created by abigail on 06/10/15. */ public class AvroIdlColorSettingsPage implements ColorSettingsPage { @Nullable @Override public Icon getIcon() {
// Path: src/main/java/claims/bold/intellij/avro/idl/AvroIdlIcons.java // public class AvroIdlIcons { // // TODO a language-specific file icon // public static final Icon FILE = AllIcons.FileTypes.Text; // } // Path: src/main/java/claims/bold/intellij/avro/idl/colors/AvroIdlColorSettingsPage.java import claims.bold.intellij.avro.idl.AvroIdlIcons; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.fileTypes.SyntaxHighlighter; import com.intellij.openapi.options.colors.AttributesDescriptor; import com.intellij.openapi.options.colors.ColorDescriptor; import com.intellij.openapi.options.colors.ColorSettingsPage; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.HashMap; import java.util.Map; package claims.bold.intellij.avro.idl.colors; /** * Created by abigail on 06/10/15. */ public class AvroIdlColorSettingsPage implements ColorSettingsPage { @Nullable @Override public Icon getIcon() {
return AvroIdlIcons.FILE;
AbigailBuccaneer/intellij-avro
src/main/java/claims/bold/intellij/avro/idl/psi/AvroIdlFile.java
// Path: src/main/java/claims/bold/intellij/avro/idl/AvroIdlFileType.java // public class AvroIdlFileType extends LanguageFileType { // /** // * A shared instance of AvroIdlFileType. // */ // public static final AvroIdlFileType INSTANCE = new AvroIdlFileType(); // // protected AvroIdlFileType() { // super(AvroIdlLanguage.INSTANCE); // } // // @NotNull // @Override // public String getName() { // return "Avro™ IDL"; // } // // @NotNull // @Override // public String getDescription() { // return "Apache Avro™ IDL"; // } // // @NotNull // @Override // public String getDefaultExtension() { // return "avdl"; // } // // @Nullable // @Override // public Icon getIcon() { // return AvroIdlIcons.FILE; // } // } // // Path: src/main/java/claims/bold/intellij/avro/idl/AvroIdlLanguage.java // public class AvroIdlLanguage extends Language { // /** // * A shared instance of AvroIdlLanguage. // */ // @NotNull // public static final AvroIdlLanguage INSTANCE = new AvroIdlLanguage(); // // protected AvroIdlLanguage() { // super("AvroIDL", "text/vnd.apache.avro-idl"); // } // }
import claims.bold.intellij.avro.idl.AvroIdlFileType; import claims.bold.intellij.avro.idl.AvroIdlLanguage; import com.intellij.extapi.psi.PsiFileBase; import com.intellij.lang.Language; import com.intellij.openapi.fileTypes.FileType; import com.intellij.psi.FileViewProvider; import org.jetbrains.annotations.NotNull;
package claims.bold.intellij.avro.idl.psi; /** * Created by abigail on 06/10/15. */ public class AvroIdlFile extends PsiFileBase { public AvroIdlFile(@NotNull FileViewProvider viewProvider) {
// Path: src/main/java/claims/bold/intellij/avro/idl/AvroIdlFileType.java // public class AvroIdlFileType extends LanguageFileType { // /** // * A shared instance of AvroIdlFileType. // */ // public static final AvroIdlFileType INSTANCE = new AvroIdlFileType(); // // protected AvroIdlFileType() { // super(AvroIdlLanguage.INSTANCE); // } // // @NotNull // @Override // public String getName() { // return "Avro™ IDL"; // } // // @NotNull // @Override // public String getDescription() { // return "Apache Avro™ IDL"; // } // // @NotNull // @Override // public String getDefaultExtension() { // return "avdl"; // } // // @Nullable // @Override // public Icon getIcon() { // return AvroIdlIcons.FILE; // } // } // // Path: src/main/java/claims/bold/intellij/avro/idl/AvroIdlLanguage.java // public class AvroIdlLanguage extends Language { // /** // * A shared instance of AvroIdlLanguage. // */ // @NotNull // public static final AvroIdlLanguage INSTANCE = new AvroIdlLanguage(); // // protected AvroIdlLanguage() { // super("AvroIDL", "text/vnd.apache.avro-idl"); // } // } // Path: src/main/java/claims/bold/intellij/avro/idl/psi/AvroIdlFile.java import claims.bold.intellij.avro.idl.AvroIdlFileType; import claims.bold.intellij.avro.idl.AvroIdlLanguage; import com.intellij.extapi.psi.PsiFileBase; import com.intellij.lang.Language; import com.intellij.openapi.fileTypes.FileType; import com.intellij.psi.FileViewProvider; import org.jetbrains.annotations.NotNull; package claims.bold.intellij.avro.idl.psi; /** * Created by abigail on 06/10/15. */ public class AvroIdlFile extends PsiFileBase { public AvroIdlFile(@NotNull FileViewProvider viewProvider) {
super(viewProvider, AvroIdlLanguage.INSTANCE);
AbigailBuccaneer/intellij-avro
src/main/java/claims/bold/intellij/avro/idl/psi/AvroIdlFile.java
// Path: src/main/java/claims/bold/intellij/avro/idl/AvroIdlFileType.java // public class AvroIdlFileType extends LanguageFileType { // /** // * A shared instance of AvroIdlFileType. // */ // public static final AvroIdlFileType INSTANCE = new AvroIdlFileType(); // // protected AvroIdlFileType() { // super(AvroIdlLanguage.INSTANCE); // } // // @NotNull // @Override // public String getName() { // return "Avro™ IDL"; // } // // @NotNull // @Override // public String getDescription() { // return "Apache Avro™ IDL"; // } // // @NotNull // @Override // public String getDefaultExtension() { // return "avdl"; // } // // @Nullable // @Override // public Icon getIcon() { // return AvroIdlIcons.FILE; // } // } // // Path: src/main/java/claims/bold/intellij/avro/idl/AvroIdlLanguage.java // public class AvroIdlLanguage extends Language { // /** // * A shared instance of AvroIdlLanguage. // */ // @NotNull // public static final AvroIdlLanguage INSTANCE = new AvroIdlLanguage(); // // protected AvroIdlLanguage() { // super("AvroIDL", "text/vnd.apache.avro-idl"); // } // }
import claims.bold.intellij.avro.idl.AvroIdlFileType; import claims.bold.intellij.avro.idl.AvroIdlLanguage; import com.intellij.extapi.psi.PsiFileBase; import com.intellij.lang.Language; import com.intellij.openapi.fileTypes.FileType; import com.intellij.psi.FileViewProvider; import org.jetbrains.annotations.NotNull;
package claims.bold.intellij.avro.idl.psi; /** * Created by abigail on 06/10/15. */ public class AvroIdlFile extends PsiFileBase { public AvroIdlFile(@NotNull FileViewProvider viewProvider) { super(viewProvider, AvroIdlLanguage.INSTANCE); } @NotNull @Override public FileType getFileType() {
// Path: src/main/java/claims/bold/intellij/avro/idl/AvroIdlFileType.java // public class AvroIdlFileType extends LanguageFileType { // /** // * A shared instance of AvroIdlFileType. // */ // public static final AvroIdlFileType INSTANCE = new AvroIdlFileType(); // // protected AvroIdlFileType() { // super(AvroIdlLanguage.INSTANCE); // } // // @NotNull // @Override // public String getName() { // return "Avro™ IDL"; // } // // @NotNull // @Override // public String getDescription() { // return "Apache Avro™ IDL"; // } // // @NotNull // @Override // public String getDefaultExtension() { // return "avdl"; // } // // @Nullable // @Override // public Icon getIcon() { // return AvroIdlIcons.FILE; // } // } // // Path: src/main/java/claims/bold/intellij/avro/idl/AvroIdlLanguage.java // public class AvroIdlLanguage extends Language { // /** // * A shared instance of AvroIdlLanguage. // */ // @NotNull // public static final AvroIdlLanguage INSTANCE = new AvroIdlLanguage(); // // protected AvroIdlLanguage() { // super("AvroIDL", "text/vnd.apache.avro-idl"); // } // } // Path: src/main/java/claims/bold/intellij/avro/idl/psi/AvroIdlFile.java import claims.bold.intellij.avro.idl.AvroIdlFileType; import claims.bold.intellij.avro.idl.AvroIdlLanguage; import com.intellij.extapi.psi.PsiFileBase; import com.intellij.lang.Language; import com.intellij.openapi.fileTypes.FileType; import com.intellij.psi.FileViewProvider; import org.jetbrains.annotations.NotNull; package claims.bold.intellij.avro.idl.psi; /** * Created by abigail on 06/10/15. */ public class AvroIdlFile extends PsiFileBase { public AvroIdlFile(@NotNull FileViewProvider viewProvider) { super(viewProvider, AvroIdlLanguage.INSTANCE); } @NotNull @Override public FileType getFileType() {
return AvroIdlFileType.INSTANCE;
AbigailBuccaneer/intellij-avro
src/main/java/claims/bold/intellij/avro/idl/psi/AvroIdlTokenType.java
// Path: src/main/java/claims/bold/intellij/avro/idl/AvroIdlLanguage.java // public class AvroIdlLanguage extends Language { // /** // * A shared instance of AvroIdlLanguage. // */ // @NotNull // public static final AvroIdlLanguage INSTANCE = new AvroIdlLanguage(); // // protected AvroIdlLanguage() { // super("AvroIDL", "text/vnd.apache.avro-idl"); // } // }
import claims.bold.intellij.avro.idl.AvroIdlLanguage; import com.intellij.lang.Language; import com.intellij.psi.tree.IElementType;
package claims.bold.intellij.avro.idl.psi; /** * Created by abigail on 06/10/15. */ public class AvroIdlTokenType extends IElementType { public AvroIdlTokenType(String debugName) {
// Path: src/main/java/claims/bold/intellij/avro/idl/AvroIdlLanguage.java // public class AvroIdlLanguage extends Language { // /** // * A shared instance of AvroIdlLanguage. // */ // @NotNull // public static final AvroIdlLanguage INSTANCE = new AvroIdlLanguage(); // // protected AvroIdlLanguage() { // super("AvroIDL", "text/vnd.apache.avro-idl"); // } // } // Path: src/main/java/claims/bold/intellij/avro/idl/psi/AvroIdlTokenType.java import claims.bold.intellij.avro.idl.AvroIdlLanguage; import com.intellij.lang.Language; import com.intellij.psi.tree.IElementType; package claims.bold.intellij.avro.idl.psi; /** * Created by abigail on 06/10/15. */ public class AvroIdlTokenType extends IElementType { public AvroIdlTokenType(String debugName) {
super(debugName, AvroIdlLanguage.INSTANCE);
AbigailBuccaneer/intellij-avro
src/main/java/claims/bold/intellij/avro/idl/psi/AvroIdlElementType.java
// Path: src/main/java/claims/bold/intellij/avro/idl/AvroIdlLanguage.java // public class AvroIdlLanguage extends Language { // /** // * A shared instance of AvroIdlLanguage. // */ // @NotNull // public static final AvroIdlLanguage INSTANCE = new AvroIdlLanguage(); // // protected AvroIdlLanguage() { // super("AvroIDL", "text/vnd.apache.avro-idl"); // } // }
import claims.bold.intellij.avro.idl.AvroIdlLanguage; import com.intellij.lang.Language; import com.intellij.psi.tree.IElementType;
package claims.bold.intellij.avro.idl.psi; /** * Created by abigail on 06/10/15. */ public class AvroIdlElementType extends IElementType { public AvroIdlElementType(String debugName) {
// Path: src/main/java/claims/bold/intellij/avro/idl/AvroIdlLanguage.java // public class AvroIdlLanguage extends Language { // /** // * A shared instance of AvroIdlLanguage. // */ // @NotNull // public static final AvroIdlLanguage INSTANCE = new AvroIdlLanguage(); // // protected AvroIdlLanguage() { // super("AvroIDL", "text/vnd.apache.avro-idl"); // } // } // Path: src/main/java/claims/bold/intellij/avro/idl/psi/AvroIdlElementType.java import claims.bold.intellij.avro.idl.AvroIdlLanguage; import com.intellij.lang.Language; import com.intellij.psi.tree.IElementType; package claims.bold.intellij.avro.idl.psi; /** * Created by abigail on 06/10/15. */ public class AvroIdlElementType extends IElementType { public AvroIdlElementType(String debugName) {
super(debugName, AvroIdlLanguage.INSTANCE);
AbigailBuccaneer/intellij-avro
src/main/java/claims/bold/intellij/avro/idl/annotations/AnnotationAnnotator.java
// Path: src/main/java/claims/bold/intellij/avro/idl/colors/AvroIdlSyntaxColors.java // public interface AvroIdlSyntaxColors { // TextAttributesKey DOC_COMMENT = createTextAttributesKey("AVROIDL_DOC_COMMENT", DefaultLanguageHighlighterColors.DOC_COMMENT); // TextAttributesKey BLOCK_COMMENT = createTextAttributesKey("AVROIDL_BLOCK_COMMENT", DefaultLanguageHighlighterColors.BLOCK_COMMENT); // TextAttributesKey LINE_COMMENT = createTextAttributesKey("AVROIDL_LINE_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT); // TextAttributesKey BAD_CHAR = createTextAttributesKey("AVROIDL_BAD_CHAR", HighlighterColors.BAD_CHARACTER); // // TextAttributesKey STRING = createTextAttributesKey("AVROIDL_STRING", DefaultLanguageHighlighterColors.STRING); // TextAttributesKey NUMBER = createTextAttributesKey("AVROIDL_NUMBER", DefaultLanguageHighlighterColors.NUMBER); // // TextAttributesKey BRACES = createTextAttributesKey("AVROIDL_BRACES", DefaultLanguageHighlighterColors.BRACES); // TextAttributesKey PARENTHESES = createTextAttributesKey("AVROIDL_PARENTHESES", DefaultLanguageHighlighterColors.PARENTHESES); // TextAttributesKey BRACKETS = createTextAttributesKey("AVROIDL_BRACKETS", DefaultLanguageHighlighterColors.BRACKETS); // // TextAttributesKey SEMICOLON = createTextAttributesKey("AVROIDL_SEMICOLON", DefaultLanguageHighlighterColors.SEMICOLON); // TextAttributesKey COMMA = createTextAttributesKey("AVROIDL_COMMA", DefaultLanguageHighlighterColors.COMMA); // TextAttributesKey EQUALS = createTextAttributesKey("AVROIDL_EQUALS", DefaultLanguageHighlighterColors.OPERATION_SIGN); // // TextAttributesKey KEYWORD = createTextAttributesKey("AVROIDL_KEYWORD", DefaultLanguageHighlighterColors.KEYWORD); // TextAttributesKey TYPE = createTextAttributesKey("AVROIDL_TYPE", DefaultLanguageHighlighterColors.KEYWORD); // TextAttributesKey ANNOTATION = createTextAttributesKey("AVROIDL_ANNOTATION", CodeInsightColors.ANNOTATION_NAME_ATTRIBUTES); // // TextAttributesKey[] DOC_COMMENT_KEYS = new TextAttributesKey[] { DOC_COMMENT }; // TextAttributesKey[] BLOCK_COMMENT_KEYS = new TextAttributesKey[] { BLOCK_COMMENT }; // TextAttributesKey[] LINE_COMMENT_KEYS = new TextAttributesKey[] { LINE_COMMENT }; // TextAttributesKey[] BAD_CHAR_KEYS = new TextAttributesKey[] { BAD_CHAR }; // TextAttributesKey[] STRING_KEYS = new TextAttributesKey[] { STRING }; // TextAttributesKey[] NUMBER_KEYS = new TextAttributesKey[] { NUMBER }; // TextAttributesKey[] BRACES_KEYS = new TextAttributesKey[] { BRACES }; // TextAttributesKey[] PARENTHESES_KEYS = new TextAttributesKey[] { PARENTHESES }; // TextAttributesKey[] BRACKETS_KEYS = new TextAttributesKey[] { BRACKETS }; // TextAttributesKey[] SEMICOLON_KEYS = new TextAttributesKey[] { SEMICOLON }; // TextAttributesKey[] COMMA_KEYS = new TextAttributesKey[] { COMMA }; // TextAttributesKey[] EQUALS_KEYS = new TextAttributesKey[] { EQUALS }; // TextAttributesKey[] KEYWORD_KEYS = new TextAttributesKey[] { KEYWORD }; // TextAttributesKey[] TYPE_KEYS = new TextAttributesKey[] { TYPE }; // // AttributesDescriptor[] DESCRIPTORS = new AttributesDescriptor[] { // new AttributesDescriptor("Documentation comment", DOC_COMMENT), // new AttributesDescriptor("Block comment", BLOCK_COMMENT), // new AttributesDescriptor("Line comment", LINE_COMMENT), // new AttributesDescriptor("Bad character", BAD_CHAR), // new AttributesDescriptor("String", STRING), // new AttributesDescriptor("Number", NUMBER), // new AttributesDescriptor("Braces", BRACES), // new AttributesDescriptor("Parentheses", PARENTHESES), // new AttributesDescriptor("Brackets", BRACKETS), // new AttributesDescriptor("Semicolon", SEMICOLON), // new AttributesDescriptor("Comma", COMMA), // new AttributesDescriptor("Equals", EQUALS), // new AttributesDescriptor("Keywords", KEYWORD), // new AttributesDescriptor("Types", TYPE), // new AttributesDescriptor("Annotations", ANNOTATION) // }; // } // // Path: src/gen/java/claims/bold/intellij/avro/idl/psi/AvroIdlAnnotation.java // public interface AvroIdlAnnotation extends PsiElement { // // @Nullable // AvroIdlJsonValue getJsonValue(); // // @Nullable // PsiElement getIdentifier(); // // }
import claims.bold.intellij.avro.idl.colors.AvroIdlSyntaxColors; import claims.bold.intellij.avro.idl.psi.AvroIdlAnnotation; import com.intellij.lang.annotation.Annotation; import com.intellij.lang.annotation.AnnotationHolder; import com.intellij.lang.annotation.Annotator; import com.intellij.psi.PsiElement;
package claims.bold.intellij.avro.idl.annotations; /** * Created by abigail on 06/10/15. */ public class AnnotationAnnotator implements Annotator { @Override public void annotate(PsiElement element, AnnotationHolder holder) {
// Path: src/main/java/claims/bold/intellij/avro/idl/colors/AvroIdlSyntaxColors.java // public interface AvroIdlSyntaxColors { // TextAttributesKey DOC_COMMENT = createTextAttributesKey("AVROIDL_DOC_COMMENT", DefaultLanguageHighlighterColors.DOC_COMMENT); // TextAttributesKey BLOCK_COMMENT = createTextAttributesKey("AVROIDL_BLOCK_COMMENT", DefaultLanguageHighlighterColors.BLOCK_COMMENT); // TextAttributesKey LINE_COMMENT = createTextAttributesKey("AVROIDL_LINE_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT); // TextAttributesKey BAD_CHAR = createTextAttributesKey("AVROIDL_BAD_CHAR", HighlighterColors.BAD_CHARACTER); // // TextAttributesKey STRING = createTextAttributesKey("AVROIDL_STRING", DefaultLanguageHighlighterColors.STRING); // TextAttributesKey NUMBER = createTextAttributesKey("AVROIDL_NUMBER", DefaultLanguageHighlighterColors.NUMBER); // // TextAttributesKey BRACES = createTextAttributesKey("AVROIDL_BRACES", DefaultLanguageHighlighterColors.BRACES); // TextAttributesKey PARENTHESES = createTextAttributesKey("AVROIDL_PARENTHESES", DefaultLanguageHighlighterColors.PARENTHESES); // TextAttributesKey BRACKETS = createTextAttributesKey("AVROIDL_BRACKETS", DefaultLanguageHighlighterColors.BRACKETS); // // TextAttributesKey SEMICOLON = createTextAttributesKey("AVROIDL_SEMICOLON", DefaultLanguageHighlighterColors.SEMICOLON); // TextAttributesKey COMMA = createTextAttributesKey("AVROIDL_COMMA", DefaultLanguageHighlighterColors.COMMA); // TextAttributesKey EQUALS = createTextAttributesKey("AVROIDL_EQUALS", DefaultLanguageHighlighterColors.OPERATION_SIGN); // // TextAttributesKey KEYWORD = createTextAttributesKey("AVROIDL_KEYWORD", DefaultLanguageHighlighterColors.KEYWORD); // TextAttributesKey TYPE = createTextAttributesKey("AVROIDL_TYPE", DefaultLanguageHighlighterColors.KEYWORD); // TextAttributesKey ANNOTATION = createTextAttributesKey("AVROIDL_ANNOTATION", CodeInsightColors.ANNOTATION_NAME_ATTRIBUTES); // // TextAttributesKey[] DOC_COMMENT_KEYS = new TextAttributesKey[] { DOC_COMMENT }; // TextAttributesKey[] BLOCK_COMMENT_KEYS = new TextAttributesKey[] { BLOCK_COMMENT }; // TextAttributesKey[] LINE_COMMENT_KEYS = new TextAttributesKey[] { LINE_COMMENT }; // TextAttributesKey[] BAD_CHAR_KEYS = new TextAttributesKey[] { BAD_CHAR }; // TextAttributesKey[] STRING_KEYS = new TextAttributesKey[] { STRING }; // TextAttributesKey[] NUMBER_KEYS = new TextAttributesKey[] { NUMBER }; // TextAttributesKey[] BRACES_KEYS = new TextAttributesKey[] { BRACES }; // TextAttributesKey[] PARENTHESES_KEYS = new TextAttributesKey[] { PARENTHESES }; // TextAttributesKey[] BRACKETS_KEYS = new TextAttributesKey[] { BRACKETS }; // TextAttributesKey[] SEMICOLON_KEYS = new TextAttributesKey[] { SEMICOLON }; // TextAttributesKey[] COMMA_KEYS = new TextAttributesKey[] { COMMA }; // TextAttributesKey[] EQUALS_KEYS = new TextAttributesKey[] { EQUALS }; // TextAttributesKey[] KEYWORD_KEYS = new TextAttributesKey[] { KEYWORD }; // TextAttributesKey[] TYPE_KEYS = new TextAttributesKey[] { TYPE }; // // AttributesDescriptor[] DESCRIPTORS = new AttributesDescriptor[] { // new AttributesDescriptor("Documentation comment", DOC_COMMENT), // new AttributesDescriptor("Block comment", BLOCK_COMMENT), // new AttributesDescriptor("Line comment", LINE_COMMENT), // new AttributesDescriptor("Bad character", BAD_CHAR), // new AttributesDescriptor("String", STRING), // new AttributesDescriptor("Number", NUMBER), // new AttributesDescriptor("Braces", BRACES), // new AttributesDescriptor("Parentheses", PARENTHESES), // new AttributesDescriptor("Brackets", BRACKETS), // new AttributesDescriptor("Semicolon", SEMICOLON), // new AttributesDescriptor("Comma", COMMA), // new AttributesDescriptor("Equals", EQUALS), // new AttributesDescriptor("Keywords", KEYWORD), // new AttributesDescriptor("Types", TYPE), // new AttributesDescriptor("Annotations", ANNOTATION) // }; // } // // Path: src/gen/java/claims/bold/intellij/avro/idl/psi/AvroIdlAnnotation.java // public interface AvroIdlAnnotation extends PsiElement { // // @Nullable // AvroIdlJsonValue getJsonValue(); // // @Nullable // PsiElement getIdentifier(); // // } // Path: src/main/java/claims/bold/intellij/avro/idl/annotations/AnnotationAnnotator.java import claims.bold.intellij.avro.idl.colors.AvroIdlSyntaxColors; import claims.bold.intellij.avro.idl.psi.AvroIdlAnnotation; import com.intellij.lang.annotation.Annotation; import com.intellij.lang.annotation.AnnotationHolder; import com.intellij.lang.annotation.Annotator; import com.intellij.psi.PsiElement; package claims.bold.intellij.avro.idl.annotations; /** * Created by abigail on 06/10/15. */ public class AnnotationAnnotator implements Annotator { @Override public void annotate(PsiElement element, AnnotationHolder holder) {
if (!(element instanceof AvroIdlAnnotation)) return;
AbigailBuccaneer/intellij-avro
src/main/java/claims/bold/intellij/avro/idl/annotations/AnnotationAnnotator.java
// Path: src/main/java/claims/bold/intellij/avro/idl/colors/AvroIdlSyntaxColors.java // public interface AvroIdlSyntaxColors { // TextAttributesKey DOC_COMMENT = createTextAttributesKey("AVROIDL_DOC_COMMENT", DefaultLanguageHighlighterColors.DOC_COMMENT); // TextAttributesKey BLOCK_COMMENT = createTextAttributesKey("AVROIDL_BLOCK_COMMENT", DefaultLanguageHighlighterColors.BLOCK_COMMENT); // TextAttributesKey LINE_COMMENT = createTextAttributesKey("AVROIDL_LINE_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT); // TextAttributesKey BAD_CHAR = createTextAttributesKey("AVROIDL_BAD_CHAR", HighlighterColors.BAD_CHARACTER); // // TextAttributesKey STRING = createTextAttributesKey("AVROIDL_STRING", DefaultLanguageHighlighterColors.STRING); // TextAttributesKey NUMBER = createTextAttributesKey("AVROIDL_NUMBER", DefaultLanguageHighlighterColors.NUMBER); // // TextAttributesKey BRACES = createTextAttributesKey("AVROIDL_BRACES", DefaultLanguageHighlighterColors.BRACES); // TextAttributesKey PARENTHESES = createTextAttributesKey("AVROIDL_PARENTHESES", DefaultLanguageHighlighterColors.PARENTHESES); // TextAttributesKey BRACKETS = createTextAttributesKey("AVROIDL_BRACKETS", DefaultLanguageHighlighterColors.BRACKETS); // // TextAttributesKey SEMICOLON = createTextAttributesKey("AVROIDL_SEMICOLON", DefaultLanguageHighlighterColors.SEMICOLON); // TextAttributesKey COMMA = createTextAttributesKey("AVROIDL_COMMA", DefaultLanguageHighlighterColors.COMMA); // TextAttributesKey EQUALS = createTextAttributesKey("AVROIDL_EQUALS", DefaultLanguageHighlighterColors.OPERATION_SIGN); // // TextAttributesKey KEYWORD = createTextAttributesKey("AVROIDL_KEYWORD", DefaultLanguageHighlighterColors.KEYWORD); // TextAttributesKey TYPE = createTextAttributesKey("AVROIDL_TYPE", DefaultLanguageHighlighterColors.KEYWORD); // TextAttributesKey ANNOTATION = createTextAttributesKey("AVROIDL_ANNOTATION", CodeInsightColors.ANNOTATION_NAME_ATTRIBUTES); // // TextAttributesKey[] DOC_COMMENT_KEYS = new TextAttributesKey[] { DOC_COMMENT }; // TextAttributesKey[] BLOCK_COMMENT_KEYS = new TextAttributesKey[] { BLOCK_COMMENT }; // TextAttributesKey[] LINE_COMMENT_KEYS = new TextAttributesKey[] { LINE_COMMENT }; // TextAttributesKey[] BAD_CHAR_KEYS = new TextAttributesKey[] { BAD_CHAR }; // TextAttributesKey[] STRING_KEYS = new TextAttributesKey[] { STRING }; // TextAttributesKey[] NUMBER_KEYS = new TextAttributesKey[] { NUMBER }; // TextAttributesKey[] BRACES_KEYS = new TextAttributesKey[] { BRACES }; // TextAttributesKey[] PARENTHESES_KEYS = new TextAttributesKey[] { PARENTHESES }; // TextAttributesKey[] BRACKETS_KEYS = new TextAttributesKey[] { BRACKETS }; // TextAttributesKey[] SEMICOLON_KEYS = new TextAttributesKey[] { SEMICOLON }; // TextAttributesKey[] COMMA_KEYS = new TextAttributesKey[] { COMMA }; // TextAttributesKey[] EQUALS_KEYS = new TextAttributesKey[] { EQUALS }; // TextAttributesKey[] KEYWORD_KEYS = new TextAttributesKey[] { KEYWORD }; // TextAttributesKey[] TYPE_KEYS = new TextAttributesKey[] { TYPE }; // // AttributesDescriptor[] DESCRIPTORS = new AttributesDescriptor[] { // new AttributesDescriptor("Documentation comment", DOC_COMMENT), // new AttributesDescriptor("Block comment", BLOCK_COMMENT), // new AttributesDescriptor("Line comment", LINE_COMMENT), // new AttributesDescriptor("Bad character", BAD_CHAR), // new AttributesDescriptor("String", STRING), // new AttributesDescriptor("Number", NUMBER), // new AttributesDescriptor("Braces", BRACES), // new AttributesDescriptor("Parentheses", PARENTHESES), // new AttributesDescriptor("Brackets", BRACKETS), // new AttributesDescriptor("Semicolon", SEMICOLON), // new AttributesDescriptor("Comma", COMMA), // new AttributesDescriptor("Equals", EQUALS), // new AttributesDescriptor("Keywords", KEYWORD), // new AttributesDescriptor("Types", TYPE), // new AttributesDescriptor("Annotations", ANNOTATION) // }; // } // // Path: src/gen/java/claims/bold/intellij/avro/idl/psi/AvroIdlAnnotation.java // public interface AvroIdlAnnotation extends PsiElement { // // @Nullable // AvroIdlJsonValue getJsonValue(); // // @Nullable // PsiElement getIdentifier(); // // }
import claims.bold.intellij.avro.idl.colors.AvroIdlSyntaxColors; import claims.bold.intellij.avro.idl.psi.AvroIdlAnnotation; import com.intellij.lang.annotation.Annotation; import com.intellij.lang.annotation.AnnotationHolder; import com.intellij.lang.annotation.Annotator; import com.intellij.psi.PsiElement;
package claims.bold.intellij.avro.idl.annotations; /** * Created by abigail on 06/10/15. */ public class AnnotationAnnotator implements Annotator { @Override public void annotate(PsiElement element, AnnotationHolder holder) { if (!(element instanceof AvroIdlAnnotation)) return; Annotation annotation = holder.createInfoAnnotation(element, "");
// Path: src/main/java/claims/bold/intellij/avro/idl/colors/AvroIdlSyntaxColors.java // public interface AvroIdlSyntaxColors { // TextAttributesKey DOC_COMMENT = createTextAttributesKey("AVROIDL_DOC_COMMENT", DefaultLanguageHighlighterColors.DOC_COMMENT); // TextAttributesKey BLOCK_COMMENT = createTextAttributesKey("AVROIDL_BLOCK_COMMENT", DefaultLanguageHighlighterColors.BLOCK_COMMENT); // TextAttributesKey LINE_COMMENT = createTextAttributesKey("AVROIDL_LINE_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT); // TextAttributesKey BAD_CHAR = createTextAttributesKey("AVROIDL_BAD_CHAR", HighlighterColors.BAD_CHARACTER); // // TextAttributesKey STRING = createTextAttributesKey("AVROIDL_STRING", DefaultLanguageHighlighterColors.STRING); // TextAttributesKey NUMBER = createTextAttributesKey("AVROIDL_NUMBER", DefaultLanguageHighlighterColors.NUMBER); // // TextAttributesKey BRACES = createTextAttributesKey("AVROIDL_BRACES", DefaultLanguageHighlighterColors.BRACES); // TextAttributesKey PARENTHESES = createTextAttributesKey("AVROIDL_PARENTHESES", DefaultLanguageHighlighterColors.PARENTHESES); // TextAttributesKey BRACKETS = createTextAttributesKey("AVROIDL_BRACKETS", DefaultLanguageHighlighterColors.BRACKETS); // // TextAttributesKey SEMICOLON = createTextAttributesKey("AVROIDL_SEMICOLON", DefaultLanguageHighlighterColors.SEMICOLON); // TextAttributesKey COMMA = createTextAttributesKey("AVROIDL_COMMA", DefaultLanguageHighlighterColors.COMMA); // TextAttributesKey EQUALS = createTextAttributesKey("AVROIDL_EQUALS", DefaultLanguageHighlighterColors.OPERATION_SIGN); // // TextAttributesKey KEYWORD = createTextAttributesKey("AVROIDL_KEYWORD", DefaultLanguageHighlighterColors.KEYWORD); // TextAttributesKey TYPE = createTextAttributesKey("AVROIDL_TYPE", DefaultLanguageHighlighterColors.KEYWORD); // TextAttributesKey ANNOTATION = createTextAttributesKey("AVROIDL_ANNOTATION", CodeInsightColors.ANNOTATION_NAME_ATTRIBUTES); // // TextAttributesKey[] DOC_COMMENT_KEYS = new TextAttributesKey[] { DOC_COMMENT }; // TextAttributesKey[] BLOCK_COMMENT_KEYS = new TextAttributesKey[] { BLOCK_COMMENT }; // TextAttributesKey[] LINE_COMMENT_KEYS = new TextAttributesKey[] { LINE_COMMENT }; // TextAttributesKey[] BAD_CHAR_KEYS = new TextAttributesKey[] { BAD_CHAR }; // TextAttributesKey[] STRING_KEYS = new TextAttributesKey[] { STRING }; // TextAttributesKey[] NUMBER_KEYS = new TextAttributesKey[] { NUMBER }; // TextAttributesKey[] BRACES_KEYS = new TextAttributesKey[] { BRACES }; // TextAttributesKey[] PARENTHESES_KEYS = new TextAttributesKey[] { PARENTHESES }; // TextAttributesKey[] BRACKETS_KEYS = new TextAttributesKey[] { BRACKETS }; // TextAttributesKey[] SEMICOLON_KEYS = new TextAttributesKey[] { SEMICOLON }; // TextAttributesKey[] COMMA_KEYS = new TextAttributesKey[] { COMMA }; // TextAttributesKey[] EQUALS_KEYS = new TextAttributesKey[] { EQUALS }; // TextAttributesKey[] KEYWORD_KEYS = new TextAttributesKey[] { KEYWORD }; // TextAttributesKey[] TYPE_KEYS = new TextAttributesKey[] { TYPE }; // // AttributesDescriptor[] DESCRIPTORS = new AttributesDescriptor[] { // new AttributesDescriptor("Documentation comment", DOC_COMMENT), // new AttributesDescriptor("Block comment", BLOCK_COMMENT), // new AttributesDescriptor("Line comment", LINE_COMMENT), // new AttributesDescriptor("Bad character", BAD_CHAR), // new AttributesDescriptor("String", STRING), // new AttributesDescriptor("Number", NUMBER), // new AttributesDescriptor("Braces", BRACES), // new AttributesDescriptor("Parentheses", PARENTHESES), // new AttributesDescriptor("Brackets", BRACKETS), // new AttributesDescriptor("Semicolon", SEMICOLON), // new AttributesDescriptor("Comma", COMMA), // new AttributesDescriptor("Equals", EQUALS), // new AttributesDescriptor("Keywords", KEYWORD), // new AttributesDescriptor("Types", TYPE), // new AttributesDescriptor("Annotations", ANNOTATION) // }; // } // // Path: src/gen/java/claims/bold/intellij/avro/idl/psi/AvroIdlAnnotation.java // public interface AvroIdlAnnotation extends PsiElement { // // @Nullable // AvroIdlJsonValue getJsonValue(); // // @Nullable // PsiElement getIdentifier(); // // } // Path: src/main/java/claims/bold/intellij/avro/idl/annotations/AnnotationAnnotator.java import claims.bold.intellij.avro.idl.colors.AvroIdlSyntaxColors; import claims.bold.intellij.avro.idl.psi.AvroIdlAnnotation; import com.intellij.lang.annotation.Annotation; import com.intellij.lang.annotation.AnnotationHolder; import com.intellij.lang.annotation.Annotator; import com.intellij.psi.PsiElement; package claims.bold.intellij.avro.idl.annotations; /** * Created by abigail on 06/10/15. */ public class AnnotationAnnotator implements Annotator { @Override public void annotate(PsiElement element, AnnotationHolder holder) { if (!(element instanceof AvroIdlAnnotation)) return; Annotation annotation = holder.createInfoAnnotation(element, "");
annotation.setTextAttributes(AvroIdlSyntaxColors.ANNOTATION);
AbigailBuccaneer/intellij-avro
src/main/java/claims/bold/intellij/avro/idl/codestyle/AvroIdlCodeStyleSettingsProvider.java
// Path: src/main/java/claims/bold/intellij/avro/idl/AvroIdlLanguage.java // public class AvroIdlLanguage extends Language { // /** // * A shared instance of AvroIdlLanguage. // */ // @NotNull // public static final AvroIdlLanguage INSTANCE = new AvroIdlLanguage(); // // protected AvroIdlLanguage() { // super("AvroIDL", "text/vnd.apache.avro-idl"); // } // }
import claims.bold.intellij.avro.idl.AvroIdlLanguage; import com.intellij.application.options.CodeStyleAbstractConfigurable; import com.intellij.application.options.CodeStyleAbstractPanel; import com.intellij.application.options.TabbedLanguageCodeStylePanel; import com.intellij.openapi.options.Configurable; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CodeStyleSettingsProvider; import org.jetbrains.annotations.NotNull;
package claims.bold.intellij.avro.idl.codestyle; /** * Created by mwilber on 3/5/17. */ public class AvroIdlCodeStyleSettingsProvider extends CodeStyleSettingsProvider { @NotNull @Override public Configurable createSettingsPage(final CodeStyleSettings settings, final CodeStyleSettings originalSettings) {
// Path: src/main/java/claims/bold/intellij/avro/idl/AvroIdlLanguage.java // public class AvroIdlLanguage extends Language { // /** // * A shared instance of AvroIdlLanguage. // */ // @NotNull // public static final AvroIdlLanguage INSTANCE = new AvroIdlLanguage(); // // protected AvroIdlLanguage() { // super("AvroIDL", "text/vnd.apache.avro-idl"); // } // } // Path: src/main/java/claims/bold/intellij/avro/idl/codestyle/AvroIdlCodeStyleSettingsProvider.java import claims.bold.intellij.avro.idl.AvroIdlLanguage; import com.intellij.application.options.CodeStyleAbstractConfigurable; import com.intellij.application.options.CodeStyleAbstractPanel; import com.intellij.application.options.TabbedLanguageCodeStylePanel; import com.intellij.openapi.options.Configurable; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CodeStyleSettingsProvider; import org.jetbrains.annotations.NotNull; package claims.bold.intellij.avro.idl.codestyle; /** * Created by mwilber on 3/5/17. */ public class AvroIdlCodeStyleSettingsProvider extends CodeStyleSettingsProvider { @NotNull @Override public Configurable createSettingsPage(final CodeStyleSettings settings, final CodeStyleSettings originalSettings) {
return new CodeStyleAbstractConfigurable(settings, originalSettings, AvroIdlLanguage.INSTANCE.getDisplayName()) {
AbigailBuccaneer/intellij-avro
src/main/java/claims/bold/intellij/avro/idl/codestyle/AvroIdlLanguageCodeStyleSettingsProvider.java
// Path: src/main/java/claims/bold/intellij/avro/idl/AvroIdlLanguage.java // public class AvroIdlLanguage extends Language { // /** // * A shared instance of AvroIdlLanguage. // */ // @NotNull // public static final AvroIdlLanguage INSTANCE = new AvroIdlLanguage(); // // protected AvroIdlLanguage() { // super("AvroIDL", "text/vnd.apache.avro-idl"); // } // }
import claims.bold.intellij.avro.idl.AvroIdlLanguage; import com.intellij.application.options.IndentOptionsEditor; import com.intellij.lang.Language; import com.intellij.openapi.application.ApplicationBundle; import com.intellij.psi.codeStyle.CommonCodeStyleSettings; import com.intellij.psi.codeStyle.LanguageCodeStyleSettingsProvider; import org.jetbrains.annotations.NotNull; import javax.swing.*;
package claims.bold.intellij.avro.idl.codestyle; /** * Created by mwilber on 3/5/17. */ public class AvroIdlLanguageCodeStyleSettingsProvider extends LanguageCodeStyleSettingsProvider { @Override public CommonCodeStyleSettings getDefaultCommonSettings() {
// Path: src/main/java/claims/bold/intellij/avro/idl/AvroIdlLanguage.java // public class AvroIdlLanguage extends Language { // /** // * A shared instance of AvroIdlLanguage. // */ // @NotNull // public static final AvroIdlLanguage INSTANCE = new AvroIdlLanguage(); // // protected AvroIdlLanguage() { // super("AvroIDL", "text/vnd.apache.avro-idl"); // } // } // Path: src/main/java/claims/bold/intellij/avro/idl/codestyle/AvroIdlLanguageCodeStyleSettingsProvider.java import claims.bold.intellij.avro.idl.AvroIdlLanguage; import com.intellij.application.options.IndentOptionsEditor; import com.intellij.lang.Language; import com.intellij.openapi.application.ApplicationBundle; import com.intellij.psi.codeStyle.CommonCodeStyleSettings; import com.intellij.psi.codeStyle.LanguageCodeStyleSettingsProvider; import org.jetbrains.annotations.NotNull; import javax.swing.*; package claims.bold.intellij.avro.idl.codestyle; /** * Created by mwilber on 3/5/17. */ public class AvroIdlLanguageCodeStyleSettingsProvider extends LanguageCodeStyleSettingsProvider { @Override public CommonCodeStyleSettings getDefaultCommonSettings() {
CommonCodeStyleSettings defaultSettings = new CommonCodeStyleSettings(AvroIdlLanguage.INSTANCE);
actframework/act-aaa-plugin
testapps/morphia_model/src/main/java/test/endpoint/AuthenticatedServiceBaseV1.java
// Path: testapps/morphia_model/src/main/java/test/model/User.java // @Entity("user") // public class User extends MorphiaUserBase<User> implements UserLinked { // // public String firstName; // public String lastName; // // @Override // public boolean isLinkedTo(Principal user) { // return S.eq(email, user.getName()); // } // // @Stateless // public static class Dao extends MorphiaDao<User> { // // public User findByUsername(String username) { // return findOneBy("email", username); // } // // public boolean authenticate(String username, char[] password) { // User user = findByUsername(username); // if (null == user) { // return false; // } // return user.verifyPassword(password); // } // // } // }
import act.aaa.LoginUser; import test.model.User;
package test.endpoint; public class AuthenticatedServiceBaseV1 extends ServiceBaseV1 { @LoginUser
// Path: testapps/morphia_model/src/main/java/test/model/User.java // @Entity("user") // public class User extends MorphiaUserBase<User> implements UserLinked { // // public String firstName; // public String lastName; // // @Override // public boolean isLinkedTo(Principal user) { // return S.eq(email, user.getName()); // } // // @Stateless // public static class Dao extends MorphiaDao<User> { // // public User findByUsername(String username) { // return findOneBy("email", username); // } // // public boolean authenticate(String username, char[] password) { // User user = findByUsername(username); // if (null == user) { // return false; // } // return user.verifyPassword(password); // } // // } // } // Path: testapps/morphia_model/src/main/java/test/endpoint/AuthenticatedServiceBaseV1.java import act.aaa.LoginUser; import test.model.User; package test.endpoint; public class AuthenticatedServiceBaseV1 extends ServiceBaseV1 { @LoginUser
protected User me;
actframework/act-aaa-plugin
testapps/jpa_model_id/src/main/java/jpa_test/endpoint/AuthenticatedServiceBaseV1.java
// Path: testapps/jpa_model_id/src/main/java/jpa_test/model/User.java // @Entity(name = "user") // public class User extends UserBase implements UserLinked { // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long id; // // public String firstName; // public String lastName; // // @Override // public boolean isLinkedTo(Principal user) { // return S.eq(email, user.getName()); // } // // @Stateless // public static class Dao extends JPADao<Long, User> { // // public User findByUsername(String username) { // return findOneBy("email", username); // } // // public boolean authenticate(String username, char[] password) { // User user = findByUsername(username); // if (null == user) { // return false; // } // return user.verifyPassword(password); // } // // } // }
import act.aaa.LoginUser; import jpa_test.model.User;
package jpa_test.endpoint; public class AuthenticatedServiceBaseV1 extends ServiceBaseV1 { @LoginUser
// Path: testapps/jpa_model_id/src/main/java/jpa_test/model/User.java // @Entity(name = "user") // public class User extends UserBase implements UserLinked { // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long id; // // public String firstName; // public String lastName; // // @Override // public boolean isLinkedTo(Principal user) { // return S.eq(email, user.getName()); // } // // @Stateless // public static class Dao extends JPADao<Long, User> { // // public User findByUsername(String username) { // return findOneBy("email", username); // } // // public boolean authenticate(String username, char[] password) { // User user = findByUsername(username); // if (null == user) { // return false; // } // return user.verifyPassword(password); // } // // } // } // Path: testapps/jpa_model_id/src/main/java/jpa_test/endpoint/AuthenticatedServiceBaseV1.java import act.aaa.LoginUser; import jpa_test.model.User; package jpa_test.endpoint; public class AuthenticatedServiceBaseV1 extends ServiceBaseV1 { @LoginUser
protected User me;
actframework/act-aaa-plugin
src/main/java/act/aaa/AAAPlugin.java
// Path: src/main/java/act/aaa/util/LoginUserFinder.java // public class LoginUserFinder extends ValueLoader.Base { // // public static final String KEY_USER_KEY = "key"; // // private Dao dao; // private String querySpec; // private Class<?> userType; // private Class<?> userKeyType; // // @Override // public Object get() { // AAAContext aaaContext = AAA.context(); // if (null != aaaContext) { // Principal principal = aaaContext.getCurrentPrincipal(); // if (null != principal) { // if (userType.isInstance(principal)) { // return principal; // } // String querySpec = this.querySpec; // AAAPlugin plugin = Act.getInstance(AAAPlugin.class); // if (PROP_ID.equals(querySpec)) { // String s = principal.getProperty(PROP_ID); // E.unexpectedIf(S.isBlank(s), "Cannot determine id of principal"); // Object id = $.convert(s).to(dao.idType()); // String cacheKey = S.string(id); // Object cached = plugin.cachedUser(cacheKey); // if (null == cached) { // cached = dao.findById(id); // if (null != cached) { // plugin.cacheUser(cacheKey, cached); // } // } // return cached; // } // String name = principal.getName(); // int pos = name.indexOf(':'); // if (pos > 0) { // querySpec = name.substring(0, pos); // name = name.substring(pos + 1); // } // String cacheKey = S.concat(querySpec, "::", name); // Object cached = plugin.cachedUser(cacheKey); // if (null == cached) { // Object val = userKeyType == String.class ? name : $.convert(name).to(userKeyType); // cached = dao.findOneBy(querySpec, val); // if (null != cached) { // plugin.cacheUser(cacheKey, cached); // } // } // return cached; // } // } // return null; // } // // @Override // protected void initialized() { // App app = App.instance(); // // userType = spec.rawType(); // userKeyType = $.fieldOf(userType, AAAConfig.user.key.get()).getType(); // dao = app.dbServiceManager().dao(userType); // // querySpec = S.string(options.get(KEY_USER_KEY)); // if (S.blank(querySpec)) { // querySpec = AAAConfig.user.key.get(); // } // } // // public static String userKey(String userIdentifier) { // return S.concat(AAAConfig.user.key.get(), "::", userIdentifier); // } // }
import act.Act; import act.aaa.util.LoginUserFinder; import act.app.ActionContext; import act.app.ActionContext.PreFireSessionResolvedEvent; import act.app.App; import act.app.event.AppStop; import act.app.event.SysEventId; import act.event.*; import act.util.LogSupportedDestroyableBase; import org.osgl.$; import org.osgl.aaa.*; import org.osgl.aaa.impl.DumbAuditor; import org.osgl.cache.CacheService; import org.osgl.http.H; import org.osgl.util.E; import org.osgl.util.S; import osgl.version.Version; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap;
return "Permission"; } else if (Privilege.class.isAssignableFrom(clz)) { return "Privilege"; } else { return "Role"; } } private String cacheKey(Class<? extends AAAObject> clz, String name) { return cacheKey(typeName(clz), name); } private String cacheKey(AAAObject object) { return cacheKey(typeName(object), object.getName()); } private String cacheKey(String typeName, String name) { return S.concat(name, "-", typeName); } private void onLogin(String userIdentifier) { flushUserAndPrincipalCache(userIdentifier); } private void onLogout(String userIdentifier) { flushUserAndPrincipalCache(userIdentifier); } private void flushUserAndPrincipalCache(String userIdentifier) { evictUser(userIdentifier);
// Path: src/main/java/act/aaa/util/LoginUserFinder.java // public class LoginUserFinder extends ValueLoader.Base { // // public static final String KEY_USER_KEY = "key"; // // private Dao dao; // private String querySpec; // private Class<?> userType; // private Class<?> userKeyType; // // @Override // public Object get() { // AAAContext aaaContext = AAA.context(); // if (null != aaaContext) { // Principal principal = aaaContext.getCurrentPrincipal(); // if (null != principal) { // if (userType.isInstance(principal)) { // return principal; // } // String querySpec = this.querySpec; // AAAPlugin plugin = Act.getInstance(AAAPlugin.class); // if (PROP_ID.equals(querySpec)) { // String s = principal.getProperty(PROP_ID); // E.unexpectedIf(S.isBlank(s), "Cannot determine id of principal"); // Object id = $.convert(s).to(dao.idType()); // String cacheKey = S.string(id); // Object cached = plugin.cachedUser(cacheKey); // if (null == cached) { // cached = dao.findById(id); // if (null != cached) { // plugin.cacheUser(cacheKey, cached); // } // } // return cached; // } // String name = principal.getName(); // int pos = name.indexOf(':'); // if (pos > 0) { // querySpec = name.substring(0, pos); // name = name.substring(pos + 1); // } // String cacheKey = S.concat(querySpec, "::", name); // Object cached = plugin.cachedUser(cacheKey); // if (null == cached) { // Object val = userKeyType == String.class ? name : $.convert(name).to(userKeyType); // cached = dao.findOneBy(querySpec, val); // if (null != cached) { // plugin.cacheUser(cacheKey, cached); // } // } // return cached; // } // } // return null; // } // // @Override // protected void initialized() { // App app = App.instance(); // // userType = spec.rawType(); // userKeyType = $.fieldOf(userType, AAAConfig.user.key.get()).getType(); // dao = app.dbServiceManager().dao(userType); // // querySpec = S.string(options.get(KEY_USER_KEY)); // if (S.blank(querySpec)) { // querySpec = AAAConfig.user.key.get(); // } // } // // public static String userKey(String userIdentifier) { // return S.concat(AAAConfig.user.key.get(), "::", userIdentifier); // } // } // Path: src/main/java/act/aaa/AAAPlugin.java import act.Act; import act.aaa.util.LoginUserFinder; import act.app.ActionContext; import act.app.ActionContext.PreFireSessionResolvedEvent; import act.app.App; import act.app.event.AppStop; import act.app.event.SysEventId; import act.event.*; import act.util.LogSupportedDestroyableBase; import org.osgl.$; import org.osgl.aaa.*; import org.osgl.aaa.impl.DumbAuditor; import org.osgl.cache.CacheService; import org.osgl.http.H; import org.osgl.util.E; import org.osgl.util.S; import osgl.version.Version; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; return "Permission"; } else if (Privilege.class.isAssignableFrom(clz)) { return "Privilege"; } else { return "Role"; } } private String cacheKey(Class<? extends AAAObject> clz, String name) { return cacheKey(typeName(clz), name); } private String cacheKey(AAAObject object) { return cacheKey(typeName(object), object.getName()); } private String cacheKey(String typeName, String name) { return S.concat(name, "-", typeName); } private void onLogin(String userIdentifier) { flushUserAndPrincipalCache(userIdentifier); } private void onLogout(String userIdentifier) { flushUserAndPrincipalCache(userIdentifier); } private void flushUserAndPrincipalCache(String userIdentifier) { evictUser(userIdentifier);
evictUser(LoginUserFinder.userKey(userIdentifier));
actframework/act-aaa-plugin
testapps/morphia_model/src/main/java/test/endpoint/AuthenticateService.java
// Path: testapps/morphia_model/src/main/java/test/model/User.java // @Entity("user") // public class User extends MorphiaUserBase<User> implements UserLinked { // // public String firstName; // public String lastName; // // @Override // public boolean isLinkedTo(Principal user) { // return S.eq(email, user.getName()); // } // // @Stateless // public static class Dao extends MorphiaDao<User> { // // public User findByUsername(String username) { // return findOneBy("email", username); // } // // public boolean authenticate(String username, char[] password) { // User user = findByUsername(username); // if (null == user) { // return false; // } // return user.verifyPassword(password); // } // // } // }
import static org.osgl.http.H.Method.GET; import static org.osgl.http.H.Method.POST; import act.app.ActionContext; import org.osgl.mvc.annotation.Action; import org.osgl.mvc.annotation.PostAction; import test.model.User;
package test.endpoint; public class AuthenticateService extends PublicServiceBaseV1 { @PostAction("login")
// Path: testapps/morphia_model/src/main/java/test/model/User.java // @Entity("user") // public class User extends MorphiaUserBase<User> implements UserLinked { // // public String firstName; // public String lastName; // // @Override // public boolean isLinkedTo(Principal user) { // return S.eq(email, user.getName()); // } // // @Stateless // public static class Dao extends MorphiaDao<User> { // // public User findByUsername(String username) { // return findOneBy("email", username); // } // // public boolean authenticate(String username, char[] password) { // User user = findByUsername(username); // if (null == user) { // return false; // } // return user.verifyPassword(password); // } // // } // } // Path: testapps/morphia_model/src/main/java/test/endpoint/AuthenticateService.java import static org.osgl.http.H.Method.GET; import static org.osgl.http.H.Method.POST; import act.app.ActionContext; import org.osgl.mvc.annotation.Action; import org.osgl.mvc.annotation.PostAction; import test.model.User; package test.endpoint; public class AuthenticateService extends PublicServiceBaseV1 { @PostAction("login")
public void login(String username, char[] password, ActionContext ctx, User.Dao userDao) {
actframework/act-aaa-plugin
testapps/morphia_model/src/main/java/test/endpoint/MyService.java
// Path: testapps/morphia_model/src/main/java/test/model/Order.java // @Entity("order") // public class Order extends MorphiaAdaptiveRecord<Order> implements UserLinked, CustomerLinked { // // public String agent; // // public String customer; // // public String product; // // public int quantity; // // @Override // public boolean isLinkedTo(Principal user) { // String username = user.getName(); // return S.eq(username, agent); // } // // @Override // public boolean isLinkedToCustomer(Principal principal) { // String username = principal.getName(); // return S.eq(username, customer); // } // // @Stateless // public static class Dao extends MorphiaDao<Order> { // } // // } // // Path: testapps/morphia_model/src/main/java/test/model/User.java // @Entity("user") // public class User extends MorphiaUserBase<User> implements UserLinked { // // public String firstName; // public String lastName; // // @Override // public boolean isLinkedTo(Principal user) { // return S.eq(email, user.getName()); // } // // @Stateless // public static class Dao extends MorphiaDao<User> { // // public User findByUsername(String username) { // return findOneBy("email", username); // } // // public boolean authenticate(String username, char[] password) { // User user = findByUsername(username); // if (null == user) { // return false; // } // return user.verifyPassword(password); // } // // } // }
import act.controller.annotation.UrlContext; import act.db.DbBind; import org.osgl.aaa.AAA; import org.osgl.mvc.annotation.GetAction; import test.model.Order; import test.model.User;
package test.endpoint; @UrlContext("my") public class MyService extends AuthenticatedServiceBaseV1 { @GetAction
// Path: testapps/morphia_model/src/main/java/test/model/Order.java // @Entity("order") // public class Order extends MorphiaAdaptiveRecord<Order> implements UserLinked, CustomerLinked { // // public String agent; // // public String customer; // // public String product; // // public int quantity; // // @Override // public boolean isLinkedTo(Principal user) { // String username = user.getName(); // return S.eq(username, agent); // } // // @Override // public boolean isLinkedToCustomer(Principal principal) { // String username = principal.getName(); // return S.eq(username, customer); // } // // @Stateless // public static class Dao extends MorphiaDao<Order> { // } // // } // // Path: testapps/morphia_model/src/main/java/test/model/User.java // @Entity("user") // public class User extends MorphiaUserBase<User> implements UserLinked { // // public String firstName; // public String lastName; // // @Override // public boolean isLinkedTo(Principal user) { // return S.eq(email, user.getName()); // } // // @Stateless // public static class Dao extends MorphiaDao<User> { // // public User findByUsername(String username) { // return findOneBy("email", username); // } // // public boolean authenticate(String username, char[] password) { // User user = findByUsername(username); // if (null == user) { // return false; // } // return user.verifyPassword(password); // } // // } // } // Path: testapps/morphia_model/src/main/java/test/endpoint/MyService.java import act.controller.annotation.UrlContext; import act.db.DbBind; import org.osgl.aaa.AAA; import org.osgl.mvc.annotation.GetAction; import test.model.Order; import test.model.User; package test.endpoint; @UrlContext("my") public class MyService extends AuthenticatedServiceBaseV1 { @GetAction
public User myProfile() {
actframework/act-aaa-plugin
testapps/morphia_model/src/main/java/test/endpoint/MyService.java
// Path: testapps/morphia_model/src/main/java/test/model/Order.java // @Entity("order") // public class Order extends MorphiaAdaptiveRecord<Order> implements UserLinked, CustomerLinked { // // public String agent; // // public String customer; // // public String product; // // public int quantity; // // @Override // public boolean isLinkedTo(Principal user) { // String username = user.getName(); // return S.eq(username, agent); // } // // @Override // public boolean isLinkedToCustomer(Principal principal) { // String username = principal.getName(); // return S.eq(username, customer); // } // // @Stateless // public static class Dao extends MorphiaDao<Order> { // } // // } // // Path: testapps/morphia_model/src/main/java/test/model/User.java // @Entity("user") // public class User extends MorphiaUserBase<User> implements UserLinked { // // public String firstName; // public String lastName; // // @Override // public boolean isLinkedTo(Principal user) { // return S.eq(email, user.getName()); // } // // @Stateless // public static class Dao extends MorphiaDao<User> { // // public User findByUsername(String username) { // return findOneBy("email", username); // } // // public boolean authenticate(String username, char[] password) { // User user = findByUsername(username); // if (null == user) { // return false; // } // return user.verifyPassword(password); // } // // } // }
import act.controller.annotation.UrlContext; import act.db.DbBind; import org.osgl.aaa.AAA; import org.osgl.mvc.annotation.GetAction; import test.model.Order; import test.model.User;
package test.endpoint; @UrlContext("my") public class MyService extends AuthenticatedServiceBaseV1 { @GetAction public User myProfile() { AAA.requirePermission("view-my-profile"); return me; } @GetAction("orders/{order}")
// Path: testapps/morphia_model/src/main/java/test/model/Order.java // @Entity("order") // public class Order extends MorphiaAdaptiveRecord<Order> implements UserLinked, CustomerLinked { // // public String agent; // // public String customer; // // public String product; // // public int quantity; // // @Override // public boolean isLinkedTo(Principal user) { // String username = user.getName(); // return S.eq(username, agent); // } // // @Override // public boolean isLinkedToCustomer(Principal principal) { // String username = principal.getName(); // return S.eq(username, customer); // } // // @Stateless // public static class Dao extends MorphiaDao<Order> { // } // // } // // Path: testapps/morphia_model/src/main/java/test/model/User.java // @Entity("user") // public class User extends MorphiaUserBase<User> implements UserLinked { // // public String firstName; // public String lastName; // // @Override // public boolean isLinkedTo(Principal user) { // return S.eq(email, user.getName()); // } // // @Stateless // public static class Dao extends MorphiaDao<User> { // // public User findByUsername(String username) { // return findOneBy("email", username); // } // // public boolean authenticate(String username, char[] password) { // User user = findByUsername(username); // if (null == user) { // return false; // } // return user.verifyPassword(password); // } // // } // } // Path: testapps/morphia_model/src/main/java/test/endpoint/MyService.java import act.controller.annotation.UrlContext; import act.db.DbBind; import org.osgl.aaa.AAA; import org.osgl.mvc.annotation.GetAction; import test.model.Order; import test.model.User; package test.endpoint; @UrlContext("my") public class MyService extends AuthenticatedServiceBaseV1 { @GetAction public User myProfile() { AAA.requirePermission("view-my-profile"); return me; } @GetAction("orders/{order}")
public Order myOrder(@DbBind Order order) {
actframework/act-aaa-plugin
testapps/jpa_model_id/src/main/java/jpa_test/endpoint/UserService.java
// Path: testapps/jpa_model_id/src/main/java/jpa_test/model/User.java // @Entity(name = "user") // public class User extends UserBase implements UserLinked { // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long id; // // public String firstName; // public String lastName; // // @Override // public boolean isLinkedTo(Principal user) { // return S.eq(email, user.getName()); // } // // @Stateless // public static class Dao extends JPADao<Long, User> { // // public User findByUsername(String username) { // return findOneBy("email", username); // } // // public boolean authenticate(String username, char[] password) { // User user = findByUsername(username); // if (null == user) { // return false; // } // return user.verifyPassword(password); // } // // } // }
import act.controller.annotation.UrlContext; import act.db.sql.tx.Transactional; import org.osgl.aaa.AAA; import org.osgl.mvc.annotation.GetAction; import org.osgl.mvc.annotation.PostAction; import jpa_test.model.User; import javax.inject.Inject;
package jpa_test.endpoint; @UrlContext("users") public class UserService extends ServiceBaseV1 { @Inject
// Path: testapps/jpa_model_id/src/main/java/jpa_test/model/User.java // @Entity(name = "user") // public class User extends UserBase implements UserLinked { // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long id; // // public String firstName; // public String lastName; // // @Override // public boolean isLinkedTo(Principal user) { // return S.eq(email, user.getName()); // } // // @Stateless // public static class Dao extends JPADao<Long, User> { // // public User findByUsername(String username) { // return findOneBy("email", username); // } // // public boolean authenticate(String username, char[] password) { // User user = findByUsername(username); // if (null == user) { // return false; // } // return user.verifyPassword(password); // } // // } // } // Path: testapps/jpa_model_id/src/main/java/jpa_test/endpoint/UserService.java import act.controller.annotation.UrlContext; import act.db.sql.tx.Transactional; import org.osgl.aaa.AAA; import org.osgl.mvc.annotation.GetAction; import org.osgl.mvc.annotation.PostAction; import jpa_test.model.User; import javax.inject.Inject; package jpa_test.endpoint; @UrlContext("users") public class UserService extends ServiceBaseV1 { @Inject
private User.Dao userDao;
actframework/act-aaa-plugin
testapps/morphia_model/src/main/java/test/endpoint/OrderService.java
// Path: testapps/morphia_model/src/main/java/test/model/Order.java // @Entity("order") // public class Order extends MorphiaAdaptiveRecord<Order> implements UserLinked, CustomerLinked { // // public String agent; // // public String customer; // // public String product; // // public int quantity; // // @Override // public boolean isLinkedTo(Principal user) { // String username = user.getName(); // return S.eq(username, agent); // } // // @Override // public boolean isLinkedToCustomer(Principal principal) { // String username = principal.getName(); // return S.eq(username, customer); // } // // @Stateless // public static class Dao extends MorphiaDao<Order> { // } // // }
import act.controller.annotation.UrlContext; import act.db.DbBind; import org.osgl.aaa.AAA; import org.osgl.mvc.annotation.GetAction; import org.osgl.mvc.annotation.PostAction; import test.model.Order; import javax.inject.Inject;
package test.endpoint; @UrlContext("orders") public class OrderService extends AuthenticatedServiceBaseV1 { @Inject
// Path: testapps/morphia_model/src/main/java/test/model/Order.java // @Entity("order") // public class Order extends MorphiaAdaptiveRecord<Order> implements UserLinked, CustomerLinked { // // public String agent; // // public String customer; // // public String product; // // public int quantity; // // @Override // public boolean isLinkedTo(Principal user) { // String username = user.getName(); // return S.eq(username, agent); // } // // @Override // public boolean isLinkedToCustomer(Principal principal) { // String username = principal.getName(); // return S.eq(username, customer); // } // // @Stateless // public static class Dao extends MorphiaDao<Order> { // } // // } // Path: testapps/morphia_model/src/main/java/test/endpoint/OrderService.java import act.controller.annotation.UrlContext; import act.db.DbBind; import org.osgl.aaa.AAA; import org.osgl.mvc.annotation.GetAction; import org.osgl.mvc.annotation.PostAction; import test.model.Order; import javax.inject.Inject; package test.endpoint; @UrlContext("orders") public class OrderService extends AuthenticatedServiceBaseV1 { @Inject
private Order.Dao orderDao;
actframework/act-aaa-plugin
testapps/morphia_model/src/main/java/test/endpoint/CustomerLinked.java
// Path: src/main/java/act/aaa/DynamicPermissionCheckHelperBase.java // public abstract class DynamicPermissionCheckHelperBase<T> implements DynamicPermissionCheckHelper<T>{ // // private Class<T> targetType; // // public DynamicPermissionCheckHelperBase() { // List<Type> typeParams = Generics.typeParamImplementations(getClass(), DynamicPermissionCheckHelperBase.class); // targetType = (Class<T>) typeParams.get(0); // } // // public DynamicPermissionCheckHelperBase(Class<T> targetType) { // this.targetType = $.requireNotNull(targetType); // } // // public Class<T> getTargetClass() { // return targetType; // } // // /** // * // * @return // */ // @Override // public List<? extends Permission> permissions() { // List<String> names = permissionNames(); // if (names.isEmpty()) { // return C.list(); // } // AAAContext aaa = AAA.context(); // AAAPersistentService ps = aaa.getPersistentService(); // List<Permission> perms = C.newList(); // for (String name: names) { // Permission p = ps.findByName(name, Permission.class); // perms.add($.requireNotNull(p)); // } // return perms; // } // // /** // * Returns a list of permission name strings. By default // * this method will return an empty list. // * @return permission names in a string list // */ // protected List<String> permissionNames() { // return C.list(); // } // // }
import act.aaa.DynamicPermissionCheckHelperBase; import org.osgl.aaa.Principal; import org.osgl.util.C; import java.util.List;
package test.endpoint; public interface CustomerLinked { boolean isLinkedToCustomer(Principal principal);
// Path: src/main/java/act/aaa/DynamicPermissionCheckHelperBase.java // public abstract class DynamicPermissionCheckHelperBase<T> implements DynamicPermissionCheckHelper<T>{ // // private Class<T> targetType; // // public DynamicPermissionCheckHelperBase() { // List<Type> typeParams = Generics.typeParamImplementations(getClass(), DynamicPermissionCheckHelperBase.class); // targetType = (Class<T>) typeParams.get(0); // } // // public DynamicPermissionCheckHelperBase(Class<T> targetType) { // this.targetType = $.requireNotNull(targetType); // } // // public Class<T> getTargetClass() { // return targetType; // } // // /** // * // * @return // */ // @Override // public List<? extends Permission> permissions() { // List<String> names = permissionNames(); // if (names.isEmpty()) { // return C.list(); // } // AAAContext aaa = AAA.context(); // AAAPersistentService ps = aaa.getPersistentService(); // List<Permission> perms = C.newList(); // for (String name: names) { // Permission p = ps.findByName(name, Permission.class); // perms.add($.requireNotNull(p)); // } // return perms; // } // // /** // * Returns a list of permission name strings. By default // * this method will return an empty list. // * @return permission names in a string list // */ // protected List<String> permissionNames() { // return C.list(); // } // // } // Path: testapps/morphia_model/src/main/java/test/endpoint/CustomerLinked.java import act.aaa.DynamicPermissionCheckHelperBase; import org.osgl.aaa.Principal; import org.osgl.util.C; import java.util.List; package test.endpoint; public interface CustomerLinked { boolean isLinkedToCustomer(Principal principal);
class DynamicPermissionChecker extends DynamicPermissionCheckHelperBase<CustomerLinked> {
actframework/act-aaa-plugin
src/main/java/act/aaa/AAAServiceFinder.java
// Path: src/main/java/act/aaa/event/AAAInitialized.java // public class AAAInitialized extends ActEvent<AAAInitialized> { // } // // Path: src/main/java/act/aaa/util/AAAAdaptor.java // public class AAAAdaptor extends ActAAAService.Base { // // private boolean passwordTypeIsCharArray; // private Method passwordVerifier; // private Method roleProviderMethod; // private Method permissionProviderMethod; // private Method privilegeProviderMethod; // // public AAAAdaptor(Class userType, boolean passwordTypeIsCharArray, Method passwordVerifier, Method roleProviderMethod, Method permissionProviderMethod, Method privilegeProviderMethod) { // super(userType); // this.passwordTypeIsCharArray = passwordTypeIsCharArray; // this.passwordVerifier = passwordVerifier; // this.roleProviderMethod = roleProviderMethod; // this.permissionProviderMethod = permissionProviderMethod; // this.privilegeProviderMethod = privilegeProviderMethod; // } // // @Override // protected boolean verifyPassword(Object user, char[] password) { // if (passwordTypeIsCharArray) { // return $.invokeVirtual(user, passwordVerifier, password); // } else { // String passwordStr = new String(password); // return $.invokeVirtual(user, passwordVerifier, passwordStr); // } // } // // @Override // protected Set<String> rolesOf(Object user) { // if (null == roleProviderMethod) { // return C.Set(); // } // String roles = $.invokeVirtual(user, roleProviderMethod); // if (S.blank(roles)) { // return C.Set(); // } // return C.Set(S.fastSplit(roles, StringTokenSet.SEPARATOR)); // } // // @Override // protected Set<String> permissionsOf(Object user) { // if (null == permissionProviderMethod) { // return C.Set(); // } // String permissions = $.invokeVirtual(user, permissionProviderMethod); // if (S.blank(permissions)) { // return C.Set(); // } // return C.Set(S.fastSplit(permissions, StringTokenSet.SEPARATOR)); // } // // @Override // protected Integer privilegeOf(Object user) { // if (null == privilegeProviderMethod) { // return null; // } // Object o = $.invokeVirtual(user, privilegeProviderMethod); // if (null == o) { // return null; // } // if (o instanceof Integer) { // return (Integer) o; // } // Privilege p = AAALookup.privilege((String) o); // return null == p ? null : p.getLevel(); // } // // }
import org.osgl.aaa.*; import org.osgl.aaa.impl.DumbAuditor; import org.osgl.util.E; import javax.inject.Inject; import java.lang.reflect.Method; import java.util.EventObject; import act.Act; import act.aaa.event.AAAInitialized; import act.aaa.util.AAAAdaptor; import act.app.App; import act.app.event.SysEventId; import act.event.ActEventListenerBase; import act.job.OnAppStart; import act.util.LogSupport; import act.util.Stateless; import act.util.SubClassFinder;
package act.aaa; /*- * #%L * ACT AAA Plugin * %% * Copyright (C) 2015 - 2017 ActFramework * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ @SuppressWarnings("unused") @Stateless public class AAAServiceFinder<T> extends LogSupport { private App app; @Inject public AAAServiceFinder(App app) { this.app = app; } @SubClassFinder(callOn = SysEventId.PRE_START) public void foundActAAAService(Class<? extends ActAAAService> serviceType) {
// Path: src/main/java/act/aaa/event/AAAInitialized.java // public class AAAInitialized extends ActEvent<AAAInitialized> { // } // // Path: src/main/java/act/aaa/util/AAAAdaptor.java // public class AAAAdaptor extends ActAAAService.Base { // // private boolean passwordTypeIsCharArray; // private Method passwordVerifier; // private Method roleProviderMethod; // private Method permissionProviderMethod; // private Method privilegeProviderMethod; // // public AAAAdaptor(Class userType, boolean passwordTypeIsCharArray, Method passwordVerifier, Method roleProviderMethod, Method permissionProviderMethod, Method privilegeProviderMethod) { // super(userType); // this.passwordTypeIsCharArray = passwordTypeIsCharArray; // this.passwordVerifier = passwordVerifier; // this.roleProviderMethod = roleProviderMethod; // this.permissionProviderMethod = permissionProviderMethod; // this.privilegeProviderMethod = privilegeProviderMethod; // } // // @Override // protected boolean verifyPassword(Object user, char[] password) { // if (passwordTypeIsCharArray) { // return $.invokeVirtual(user, passwordVerifier, password); // } else { // String passwordStr = new String(password); // return $.invokeVirtual(user, passwordVerifier, passwordStr); // } // } // // @Override // protected Set<String> rolesOf(Object user) { // if (null == roleProviderMethod) { // return C.Set(); // } // String roles = $.invokeVirtual(user, roleProviderMethod); // if (S.blank(roles)) { // return C.Set(); // } // return C.Set(S.fastSplit(roles, StringTokenSet.SEPARATOR)); // } // // @Override // protected Set<String> permissionsOf(Object user) { // if (null == permissionProviderMethod) { // return C.Set(); // } // String permissions = $.invokeVirtual(user, permissionProviderMethod); // if (S.blank(permissions)) { // return C.Set(); // } // return C.Set(S.fastSplit(permissions, StringTokenSet.SEPARATOR)); // } // // @Override // protected Integer privilegeOf(Object user) { // if (null == privilegeProviderMethod) { // return null; // } // Object o = $.invokeVirtual(user, privilegeProviderMethod); // if (null == o) { // return null; // } // if (o instanceof Integer) { // return (Integer) o; // } // Privilege p = AAALookup.privilege((String) o); // return null == p ? null : p.getLevel(); // } // // } // Path: src/main/java/act/aaa/AAAServiceFinder.java import org.osgl.aaa.*; import org.osgl.aaa.impl.DumbAuditor; import org.osgl.util.E; import javax.inject.Inject; import java.lang.reflect.Method; import java.util.EventObject; import act.Act; import act.aaa.event.AAAInitialized; import act.aaa.util.AAAAdaptor; import act.app.App; import act.app.event.SysEventId; import act.event.ActEventListenerBase; import act.job.OnAppStart; import act.util.LogSupport; import act.util.Stateless; import act.util.SubClassFinder; package act.aaa; /*- * #%L * ACT AAA Plugin * %% * Copyright (C) 2015 - 2017 ActFramework * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ @SuppressWarnings("unused") @Stateless public class AAAServiceFinder<T> extends LogSupport { private App app; @Inject public AAAServiceFinder(App app) { this.app = app; } @SubClassFinder(callOn = SysEventId.PRE_START) public void foundActAAAService(Class<? extends ActAAAService> serviceType) {
if (AAAAdaptor.class == serviceType) {
actframework/act-aaa-plugin
src/main/java/act/aaa/AAAServiceFinder.java
// Path: src/main/java/act/aaa/event/AAAInitialized.java // public class AAAInitialized extends ActEvent<AAAInitialized> { // } // // Path: src/main/java/act/aaa/util/AAAAdaptor.java // public class AAAAdaptor extends ActAAAService.Base { // // private boolean passwordTypeIsCharArray; // private Method passwordVerifier; // private Method roleProviderMethod; // private Method permissionProviderMethod; // private Method privilegeProviderMethod; // // public AAAAdaptor(Class userType, boolean passwordTypeIsCharArray, Method passwordVerifier, Method roleProviderMethod, Method permissionProviderMethod, Method privilegeProviderMethod) { // super(userType); // this.passwordTypeIsCharArray = passwordTypeIsCharArray; // this.passwordVerifier = passwordVerifier; // this.roleProviderMethod = roleProviderMethod; // this.permissionProviderMethod = permissionProviderMethod; // this.privilegeProviderMethod = privilegeProviderMethod; // } // // @Override // protected boolean verifyPassword(Object user, char[] password) { // if (passwordTypeIsCharArray) { // return $.invokeVirtual(user, passwordVerifier, password); // } else { // String passwordStr = new String(password); // return $.invokeVirtual(user, passwordVerifier, passwordStr); // } // } // // @Override // protected Set<String> rolesOf(Object user) { // if (null == roleProviderMethod) { // return C.Set(); // } // String roles = $.invokeVirtual(user, roleProviderMethod); // if (S.blank(roles)) { // return C.Set(); // } // return C.Set(S.fastSplit(roles, StringTokenSet.SEPARATOR)); // } // // @Override // protected Set<String> permissionsOf(Object user) { // if (null == permissionProviderMethod) { // return C.Set(); // } // String permissions = $.invokeVirtual(user, permissionProviderMethod); // if (S.blank(permissions)) { // return C.Set(); // } // return C.Set(S.fastSplit(permissions, StringTokenSet.SEPARATOR)); // } // // @Override // protected Integer privilegeOf(Object user) { // if (null == privilegeProviderMethod) { // return null; // } // Object o = $.invokeVirtual(user, privilegeProviderMethod); // if (null == o) { // return null; // } // if (o instanceof Integer) { // return (Integer) o; // } // Privilege p = AAALookup.privilege((String) o); // return null == p ? null : p.getLevel(); // } // // }
import org.osgl.aaa.*; import org.osgl.aaa.impl.DumbAuditor; import org.osgl.util.E; import javax.inject.Inject; import java.lang.reflect.Method; import java.util.EventObject; import act.Act; import act.aaa.event.AAAInitialized; import act.aaa.util.AAAAdaptor; import act.app.App; import act.app.event.SysEventId; import act.event.ActEventListenerBase; import act.job.OnAppStart; import act.util.LogSupport; import act.util.Stateless; import act.util.SubClassFinder;
plugin().buildService(app, service); } @SubClassFinder(callOn = SysEventId.PRE_START) public void foundAuditorService(Class<Auditor> auditorClass) { if (DumbAuditor.class.equals(auditorClass) || DefaultAuditor.class.getName().equals(auditorClass.getName())) { return; } Auditor auditor = app.getInstance(auditorClass); plugin().buildService(app, auditor); } @SubClassFinder(callOn = SysEventId.PRE_START) public void foundAuthenticationService(Class<AuthenticationService> serviceType) { if (ActAAAService.class.isAssignableFrom(serviceType)) { return; } AuthenticationService service = app.getInstance(serviceType); plugin().buildService(app, service); } @SubClassFinder(callOn = SysEventId.PRE_START) public void foundAuthorizationService(Class<AuthorizationService> serviceType) { AuthorizationService service = app.getInstance(serviceType); plugin().buildService(app, service); } @SubClassFinder(callOn = SysEventId.PRE_START) public void foundDynamicPermissionCheckHelper(final Class<DynamicPermissionCheckHelperBase> target) { final DynamicPermissionCheckHelperBase helper = app.getInstance(target);
// Path: src/main/java/act/aaa/event/AAAInitialized.java // public class AAAInitialized extends ActEvent<AAAInitialized> { // } // // Path: src/main/java/act/aaa/util/AAAAdaptor.java // public class AAAAdaptor extends ActAAAService.Base { // // private boolean passwordTypeIsCharArray; // private Method passwordVerifier; // private Method roleProviderMethod; // private Method permissionProviderMethod; // private Method privilegeProviderMethod; // // public AAAAdaptor(Class userType, boolean passwordTypeIsCharArray, Method passwordVerifier, Method roleProviderMethod, Method permissionProviderMethod, Method privilegeProviderMethod) { // super(userType); // this.passwordTypeIsCharArray = passwordTypeIsCharArray; // this.passwordVerifier = passwordVerifier; // this.roleProviderMethod = roleProviderMethod; // this.permissionProviderMethod = permissionProviderMethod; // this.privilegeProviderMethod = privilegeProviderMethod; // } // // @Override // protected boolean verifyPassword(Object user, char[] password) { // if (passwordTypeIsCharArray) { // return $.invokeVirtual(user, passwordVerifier, password); // } else { // String passwordStr = new String(password); // return $.invokeVirtual(user, passwordVerifier, passwordStr); // } // } // // @Override // protected Set<String> rolesOf(Object user) { // if (null == roleProviderMethod) { // return C.Set(); // } // String roles = $.invokeVirtual(user, roleProviderMethod); // if (S.blank(roles)) { // return C.Set(); // } // return C.Set(S.fastSplit(roles, StringTokenSet.SEPARATOR)); // } // // @Override // protected Set<String> permissionsOf(Object user) { // if (null == permissionProviderMethod) { // return C.Set(); // } // String permissions = $.invokeVirtual(user, permissionProviderMethod); // if (S.blank(permissions)) { // return C.Set(); // } // return C.Set(S.fastSplit(permissions, StringTokenSet.SEPARATOR)); // } // // @Override // protected Integer privilegeOf(Object user) { // if (null == privilegeProviderMethod) { // return null; // } // Object o = $.invokeVirtual(user, privilegeProviderMethod); // if (null == o) { // return null; // } // if (o instanceof Integer) { // return (Integer) o; // } // Privilege p = AAALookup.privilege((String) o); // return null == p ? null : p.getLevel(); // } // // } // Path: src/main/java/act/aaa/AAAServiceFinder.java import org.osgl.aaa.*; import org.osgl.aaa.impl.DumbAuditor; import org.osgl.util.E; import javax.inject.Inject; import java.lang.reflect.Method; import java.util.EventObject; import act.Act; import act.aaa.event.AAAInitialized; import act.aaa.util.AAAAdaptor; import act.app.App; import act.app.event.SysEventId; import act.event.ActEventListenerBase; import act.job.OnAppStart; import act.util.LogSupport; import act.util.Stateless; import act.util.SubClassFinder; plugin().buildService(app, service); } @SubClassFinder(callOn = SysEventId.PRE_START) public void foundAuditorService(Class<Auditor> auditorClass) { if (DumbAuditor.class.equals(auditorClass) || DefaultAuditor.class.getName().equals(auditorClass.getName())) { return; } Auditor auditor = app.getInstance(auditorClass); plugin().buildService(app, auditor); } @SubClassFinder(callOn = SysEventId.PRE_START) public void foundAuthenticationService(Class<AuthenticationService> serviceType) { if (ActAAAService.class.isAssignableFrom(serviceType)) { return; } AuthenticationService service = app.getInstance(serviceType); plugin().buildService(app, service); } @SubClassFinder(callOn = SysEventId.PRE_START) public void foundAuthorizationService(Class<AuthorizationService> serviceType) { AuthorizationService service = app.getInstance(serviceType); plugin().buildService(app, service); } @SubClassFinder(callOn = SysEventId.PRE_START) public void foundDynamicPermissionCheckHelper(final Class<DynamicPermissionCheckHelperBase> target) { final DynamicPermissionCheckHelperBase helper = app.getInstance(target);
app.eventBus().bind(AAAInitialized.class, new ActEventListenerBase() {
actframework/act-aaa-plugin
testapps/jpa_model_id/src/main/java/jpa_test/endpoint/MyService.java
// Path: testapps/jpa_model_id/src/main/java/jpa_test/model/Order.java // @Entity(name = "orders") // public class Order implements SimpleBean, UserLinked, CustomerLinked { // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long id; // // @ManyToOne(optional = false) // @JoinColumn(name = "agent_id") // public User agent; // // @ManyToOne(optional = false) // @JoinColumn(name = "cust_id", nullable = false) // public User customer; // // public String product; // // public int quantity; // // @Override // public boolean isLinkedTo(Principal user) { // String agentName = null == agent ? null : agent.email; // String username = user.getName(); // return S.eq(username, agentName); // } // // @Override // public boolean isLinkedToCustomer(Principal principal) { // String customerName = null == customer ? null : customer.email; // String username = principal.getName(); // return S.eq(username, customerName); // } // // @Stateless // public static class Dao extends JPADao<Long, Order> { // } // // } // // Path: testapps/jpa_model_id/src/main/java/jpa_test/model/User.java // @Entity(name = "user") // public class User extends UserBase implements UserLinked { // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long id; // // public String firstName; // public String lastName; // // @Override // public boolean isLinkedTo(Principal user) { // return S.eq(email, user.getName()); // } // // @Stateless // public static class Dao extends JPADao<Long, User> { // // public User findByUsername(String username) { // return findOneBy("email", username); // } // // public boolean authenticate(String username, char[] password) { // User user = findByUsername(username); // if (null == user) { // return false; // } // return user.verifyPassword(password); // } // // } // }
import act.controller.annotation.UrlContext; import act.db.DbBind; import org.osgl.aaa.AAA; import org.osgl.mvc.annotation.GetAction; import jpa_test.model.Order; import jpa_test.model.User;
package jpa_test.endpoint; @UrlContext("my") public class MyService extends AuthenticatedServiceBaseV1 { @GetAction
// Path: testapps/jpa_model_id/src/main/java/jpa_test/model/Order.java // @Entity(name = "orders") // public class Order implements SimpleBean, UserLinked, CustomerLinked { // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long id; // // @ManyToOne(optional = false) // @JoinColumn(name = "agent_id") // public User agent; // // @ManyToOne(optional = false) // @JoinColumn(name = "cust_id", nullable = false) // public User customer; // // public String product; // // public int quantity; // // @Override // public boolean isLinkedTo(Principal user) { // String agentName = null == agent ? null : agent.email; // String username = user.getName(); // return S.eq(username, agentName); // } // // @Override // public boolean isLinkedToCustomer(Principal principal) { // String customerName = null == customer ? null : customer.email; // String username = principal.getName(); // return S.eq(username, customerName); // } // // @Stateless // public static class Dao extends JPADao<Long, Order> { // } // // } // // Path: testapps/jpa_model_id/src/main/java/jpa_test/model/User.java // @Entity(name = "user") // public class User extends UserBase implements UserLinked { // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long id; // // public String firstName; // public String lastName; // // @Override // public boolean isLinkedTo(Principal user) { // return S.eq(email, user.getName()); // } // // @Stateless // public static class Dao extends JPADao<Long, User> { // // public User findByUsername(String username) { // return findOneBy("email", username); // } // // public boolean authenticate(String username, char[] password) { // User user = findByUsername(username); // if (null == user) { // return false; // } // return user.verifyPassword(password); // } // // } // } // Path: testapps/jpa_model_id/src/main/java/jpa_test/endpoint/MyService.java import act.controller.annotation.UrlContext; import act.db.DbBind; import org.osgl.aaa.AAA; import org.osgl.mvc.annotation.GetAction; import jpa_test.model.Order; import jpa_test.model.User; package jpa_test.endpoint; @UrlContext("my") public class MyService extends AuthenticatedServiceBaseV1 { @GetAction
public User myProfile() {
actframework/act-aaa-plugin
testapps/jpa_model_id/src/main/java/jpa_test/endpoint/MyService.java
// Path: testapps/jpa_model_id/src/main/java/jpa_test/model/Order.java // @Entity(name = "orders") // public class Order implements SimpleBean, UserLinked, CustomerLinked { // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long id; // // @ManyToOne(optional = false) // @JoinColumn(name = "agent_id") // public User agent; // // @ManyToOne(optional = false) // @JoinColumn(name = "cust_id", nullable = false) // public User customer; // // public String product; // // public int quantity; // // @Override // public boolean isLinkedTo(Principal user) { // String agentName = null == agent ? null : agent.email; // String username = user.getName(); // return S.eq(username, agentName); // } // // @Override // public boolean isLinkedToCustomer(Principal principal) { // String customerName = null == customer ? null : customer.email; // String username = principal.getName(); // return S.eq(username, customerName); // } // // @Stateless // public static class Dao extends JPADao<Long, Order> { // } // // } // // Path: testapps/jpa_model_id/src/main/java/jpa_test/model/User.java // @Entity(name = "user") // public class User extends UserBase implements UserLinked { // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long id; // // public String firstName; // public String lastName; // // @Override // public boolean isLinkedTo(Principal user) { // return S.eq(email, user.getName()); // } // // @Stateless // public static class Dao extends JPADao<Long, User> { // // public User findByUsername(String username) { // return findOneBy("email", username); // } // // public boolean authenticate(String username, char[] password) { // User user = findByUsername(username); // if (null == user) { // return false; // } // return user.verifyPassword(password); // } // // } // }
import act.controller.annotation.UrlContext; import act.db.DbBind; import org.osgl.aaa.AAA; import org.osgl.mvc.annotation.GetAction; import jpa_test.model.Order; import jpa_test.model.User;
package jpa_test.endpoint; @UrlContext("my") public class MyService extends AuthenticatedServiceBaseV1 { @GetAction public User myProfile() { AAA.requirePermission(me, "view-my-profile"); return me; } @GetAction("orders/{order}")
// Path: testapps/jpa_model_id/src/main/java/jpa_test/model/Order.java // @Entity(name = "orders") // public class Order implements SimpleBean, UserLinked, CustomerLinked { // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long id; // // @ManyToOne(optional = false) // @JoinColumn(name = "agent_id") // public User agent; // // @ManyToOne(optional = false) // @JoinColumn(name = "cust_id", nullable = false) // public User customer; // // public String product; // // public int quantity; // // @Override // public boolean isLinkedTo(Principal user) { // String agentName = null == agent ? null : agent.email; // String username = user.getName(); // return S.eq(username, agentName); // } // // @Override // public boolean isLinkedToCustomer(Principal principal) { // String customerName = null == customer ? null : customer.email; // String username = principal.getName(); // return S.eq(username, customerName); // } // // @Stateless // public static class Dao extends JPADao<Long, Order> { // } // // } // // Path: testapps/jpa_model_id/src/main/java/jpa_test/model/User.java // @Entity(name = "user") // public class User extends UserBase implements UserLinked { // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long id; // // public String firstName; // public String lastName; // // @Override // public boolean isLinkedTo(Principal user) { // return S.eq(email, user.getName()); // } // // @Stateless // public static class Dao extends JPADao<Long, User> { // // public User findByUsername(String username) { // return findOneBy("email", username); // } // // public boolean authenticate(String username, char[] password) { // User user = findByUsername(username); // if (null == user) { // return false; // } // return user.verifyPassword(password); // } // // } // } // Path: testapps/jpa_model_id/src/main/java/jpa_test/endpoint/MyService.java import act.controller.annotation.UrlContext; import act.db.DbBind; import org.osgl.aaa.AAA; import org.osgl.mvc.annotation.GetAction; import jpa_test.model.Order; import jpa_test.model.User; package jpa_test.endpoint; @UrlContext("my") public class MyService extends AuthenticatedServiceBaseV1 { @GetAction public User myProfile() { AAA.requirePermission(me, "view-my-profile"); return me; } @GetAction("orders/{order}")
public Order myOrder(@DbBind Order order) {
actframework/act-aaa-plugin
src/main/java/act/aaa/ActAAAService.java
// Path: src/main/java/act/aaa/model/UserBase.java // public static final String PROP_ID = "id";
import act.Act; import act.app.event.SysEventId; import act.db.Dao; import act.util.LogSupport; import org.osgl.$; import org.osgl.Lang; import org.osgl.aaa.*; import org.osgl.aaa.impl.SimplePrincipal; import org.osgl.cache.CacheService; import org.osgl.util.C; import org.osgl.util.E; import org.osgl.util.Generics; import org.osgl.util.S; import javax.inject.Inject; import javax.inject.Provider; import javax.persistence.Id; import java.lang.reflect.Field; import java.lang.reflect.Type; import java.util.List; import java.util.Set; import static act.aaa.model.UserBase.PROP_ID;
* Get the {@link Principal} from the user entity. * * This method relies on the implementation of * - {@link #privilegeOf(Object)} * - {@link #rolesOf(Object)} * - {@link #permissionsOf(Object)} * * App developer can also overwrite this method though * not recommended to do that * * @param user the user entity instance * @return the principal corresponding to the user entity */ private Principal buildPrincipalFrom(USER_TYPE user) { if (user instanceof Principal) { return (Principal) user; } SimplePrincipal.Builder pb = new SimplePrincipal.Builder(username(user)); AAAPersistentService store = persistentServiceProvider.get(); Integer I = privilegeOf(user); if (null != I) { pb.grantPrivilege(store.findPrivilege(I)); } for (String role: rolesOf(user)) { pb.grantRole(store.findByName(role, Role.class)); } for (String perm: permissionsOf(user)) { pb.grantPermission(store.findByName(perm, Permission.class)); } Principal principal = pb.toPrincipal();
// Path: src/main/java/act/aaa/model/UserBase.java // public static final String PROP_ID = "id"; // Path: src/main/java/act/aaa/ActAAAService.java import act.Act; import act.app.event.SysEventId; import act.db.Dao; import act.util.LogSupport; import org.osgl.$; import org.osgl.Lang; import org.osgl.aaa.*; import org.osgl.aaa.impl.SimplePrincipal; import org.osgl.cache.CacheService; import org.osgl.util.C; import org.osgl.util.E; import org.osgl.util.Generics; import org.osgl.util.S; import javax.inject.Inject; import javax.inject.Provider; import javax.persistence.Id; import java.lang.reflect.Field; import java.lang.reflect.Type; import java.util.List; import java.util.Set; import static act.aaa.model.UserBase.PROP_ID; * Get the {@link Principal} from the user entity. * * This method relies on the implementation of * - {@link #privilegeOf(Object)} * - {@link #rolesOf(Object)} * - {@link #permissionsOf(Object)} * * App developer can also overwrite this method though * not recommended to do that * * @param user the user entity instance * @return the principal corresponding to the user entity */ private Principal buildPrincipalFrom(USER_TYPE user) { if (user instanceof Principal) { return (Principal) user; } SimplePrincipal.Builder pb = new SimplePrincipal.Builder(username(user)); AAAPersistentService store = persistentServiceProvider.get(); Integer I = privilegeOf(user); if (null != I) { pb.grantPrivilege(store.findPrivilege(I)); } for (String role: rolesOf(user)) { pb.grantRole(store.findByName(role, Role.class)); } for (String perm: permissionsOf(user)) { pb.grantPermission(store.findByName(perm, Permission.class)); } Principal principal = pb.toPrincipal();
if (PROP_ID.equals(AAAConfig.user.key.get())) {
actframework/act-aaa-plugin
src/main/java/act/aaa/util/AAACliOverHttpAuthority.java
// Path: src/main/java/act/aaa/AAAConfig.java // @AutoConfig("aaa") // public class AAAConfig extends AppServicePlugin { // // public static final Const<String> PRINCIPAL_MODEL = $.constant(); // public static final Const<String> AUDIT_MODEL = $.constant(); // public static final Const<Boolean> AUDIT = $.constant(true); // public static final Const<String> PASSWORD_VERIFIER = $.constant(); // public static final Const<String> ROLE_PROVIDER = $.constant(); // public static final Const<String> PERMISSION_PROVIDER = $.constant(); // public static final Const<String> PRIVILEGE_PROVIDER = $.constant(); // // public static final class ddl { // /** // * `aaa.ddl.create` // * // * Disable/enable create DDL for roles/permissions/privileges // * // * Default value: `true` // */ // public static boolean create = true; // // /** // * `aaa.ddl.update` // * // * Disable/enable update DDL for roles/permissions/privileges // * // * Default value: `true` when app running in {@link act.Act.Mode#DEV dev mode} or `false` otherwise // */ // public static Boolean update = Act.isDev(); // // /** // * `aaa.ddl.delete` // * // * Disable/enable delete DDL for roles/permissions/privileges // * // * Default value: `false` // */ // public static boolean delete = false; // // public static final class principal { // /** // * `aaa.ddl.principal.create` // * // * Disable/enable create DDL for principal // * // * Default value: `false` // */ // public static boolean create = false; // // /** // * `aaa.ddl.principal.update` // * // * Disable/enable update DDL for principal // * // * Default value: `false` // */ // public static Boolean update = false; // // /** // * `aaa.ddl.principal.delete` // * // * Disable/enable delete DDL for principal // * // * Default value: `false` // */ // public static boolean delete = false; // } // } // // /** // * `aaa.loginUrl` // * // * Specify the login URL // */ // public static String loginUrl = null; // // public static final class user { // // public static final String DEF_USER_KEY = "email"; // // /** // * `aaa.user.key`. // * // * Configure the key to search the user by user identifier which // * is stored in session storage by {@link act.app.ActionContext#login(Object)} // * API call. // * // * Default value: `email` // */ // public static final Const<String> key = $.constant(DEF_USER_KEY); // // /** // * `aaa.user.username`. // * // * Configure the key to fetch username to construct the // * {@link org.osgl.aaa.Principal} represented by // * a user. // * // * Default value: `email` // */ // public static final Const<String> username = $.constant(DEF_USER_KEY); // } // // public static final class cliOverHttp { // /** // * `aaa.cliOverHttp.authorization` // * // * When set to `true` CliOverHttp request will be authorized // * // * Default value: `true` // */ // public static final Const<Boolean> authorization = $.constant(true); // // /** // * `aaa.cliOverHttp.privilege` // * // * Configure the required privilege when `aaa.cliOverHttp.authorization` is enabled // * // * Default value: {@link AAA#SUPER_USER} // */ // public static final Const<Integer> privilege = $.constant(AAA.SUPER_USER); // } // // @Override // protected void applyTo(App app) { // loadPluginAutoConfig(AAAConfig.class, app); // loadPluginAutoConfig(AAAService.class, app); // ensureDDL(); // ensureLoginUrl(app); // } // // private void ensureDDL() { // if (null == ddl.update) { // ddl.update = Act.isDev(); // } // } // // private void ensureLoginUrl(final App app) { // app.jobManager().beforeAppStart(new Runnable() { // @Override // public void run() { // if (S.notBlank(loginUrl)) { // return; // } // loginUrl = app.config().loginUrl(); // } // }); // } // }
import act.Act; import act.aaa.AAAConfig; import act.app.event.SysEventId; import act.cli.CliOverHttpAuthority; import org.osgl.aaa.AAA;
package act.aaa.util; /*- * #%L * ACT AAA Plugin * %% * Copyright (C) 2015 - 2017 ActFramework * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ /** * AAA default implementation of {@link CliOverHttpAuthority}. */ public class AAACliOverHttpAuthority implements CliOverHttpAuthority { private boolean enabled; private int privilege; public AAACliOverHttpAuthority() { Act.jobManager().on(SysEventId.START, new Runnable() { @Override public void run() { delayedInit(); } }); } @Override public void authorize() { if (enabled) { AAA.requirePrivilege(privilege); } } private void delayedInit() {
// Path: src/main/java/act/aaa/AAAConfig.java // @AutoConfig("aaa") // public class AAAConfig extends AppServicePlugin { // // public static final Const<String> PRINCIPAL_MODEL = $.constant(); // public static final Const<String> AUDIT_MODEL = $.constant(); // public static final Const<Boolean> AUDIT = $.constant(true); // public static final Const<String> PASSWORD_VERIFIER = $.constant(); // public static final Const<String> ROLE_PROVIDER = $.constant(); // public static final Const<String> PERMISSION_PROVIDER = $.constant(); // public static final Const<String> PRIVILEGE_PROVIDER = $.constant(); // // public static final class ddl { // /** // * `aaa.ddl.create` // * // * Disable/enable create DDL for roles/permissions/privileges // * // * Default value: `true` // */ // public static boolean create = true; // // /** // * `aaa.ddl.update` // * // * Disable/enable update DDL for roles/permissions/privileges // * // * Default value: `true` when app running in {@link act.Act.Mode#DEV dev mode} or `false` otherwise // */ // public static Boolean update = Act.isDev(); // // /** // * `aaa.ddl.delete` // * // * Disable/enable delete DDL for roles/permissions/privileges // * // * Default value: `false` // */ // public static boolean delete = false; // // public static final class principal { // /** // * `aaa.ddl.principal.create` // * // * Disable/enable create DDL for principal // * // * Default value: `false` // */ // public static boolean create = false; // // /** // * `aaa.ddl.principal.update` // * // * Disable/enable update DDL for principal // * // * Default value: `false` // */ // public static Boolean update = false; // // /** // * `aaa.ddl.principal.delete` // * // * Disable/enable delete DDL for principal // * // * Default value: `false` // */ // public static boolean delete = false; // } // } // // /** // * `aaa.loginUrl` // * // * Specify the login URL // */ // public static String loginUrl = null; // // public static final class user { // // public static final String DEF_USER_KEY = "email"; // // /** // * `aaa.user.key`. // * // * Configure the key to search the user by user identifier which // * is stored in session storage by {@link act.app.ActionContext#login(Object)} // * API call. // * // * Default value: `email` // */ // public static final Const<String> key = $.constant(DEF_USER_KEY); // // /** // * `aaa.user.username`. // * // * Configure the key to fetch username to construct the // * {@link org.osgl.aaa.Principal} represented by // * a user. // * // * Default value: `email` // */ // public static final Const<String> username = $.constant(DEF_USER_KEY); // } // // public static final class cliOverHttp { // /** // * `aaa.cliOverHttp.authorization` // * // * When set to `true` CliOverHttp request will be authorized // * // * Default value: `true` // */ // public static final Const<Boolean> authorization = $.constant(true); // // /** // * `aaa.cliOverHttp.privilege` // * // * Configure the required privilege when `aaa.cliOverHttp.authorization` is enabled // * // * Default value: {@link AAA#SUPER_USER} // */ // public static final Const<Integer> privilege = $.constant(AAA.SUPER_USER); // } // // @Override // protected void applyTo(App app) { // loadPluginAutoConfig(AAAConfig.class, app); // loadPluginAutoConfig(AAAService.class, app); // ensureDDL(); // ensureLoginUrl(app); // } // // private void ensureDDL() { // if (null == ddl.update) { // ddl.update = Act.isDev(); // } // } // // private void ensureLoginUrl(final App app) { // app.jobManager().beforeAppStart(new Runnable() { // @Override // public void run() { // if (S.notBlank(loginUrl)) { // return; // } // loginUrl = app.config().loginUrl(); // } // }); // } // } // Path: src/main/java/act/aaa/util/AAACliOverHttpAuthority.java import act.Act; import act.aaa.AAAConfig; import act.app.event.SysEventId; import act.cli.CliOverHttpAuthority; import org.osgl.aaa.AAA; package act.aaa.util; /*- * #%L * ACT AAA Plugin * %% * Copyright (C) 2015 - 2017 ActFramework * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ /** * AAA default implementation of {@link CliOverHttpAuthority}. */ public class AAACliOverHttpAuthority implements CliOverHttpAuthority { private boolean enabled; private int privilege; public AAACliOverHttpAuthority() { Act.jobManager().on(SysEventId.START, new Runnable() { @Override public void run() { delayedInit(); } }); } @Override public void authorize() { if (enabled) { AAA.requirePrivilege(privilege); } } private void delayedInit() {
enabled = AAAConfig.cliOverHttp.authorization.get();
actframework/act-aaa-plugin
testapps/jpa_model_id/src/main/java/jpa_test/endpoint/CustomerLinked.java
// Path: src/main/java/act/aaa/DynamicPermissionCheckHelperBase.java // public abstract class DynamicPermissionCheckHelperBase<T> implements DynamicPermissionCheckHelper<T>{ // // private Class<T> targetType; // // public DynamicPermissionCheckHelperBase() { // List<Type> typeParams = Generics.typeParamImplementations(getClass(), DynamicPermissionCheckHelperBase.class); // targetType = (Class<T>) typeParams.get(0); // } // // public DynamicPermissionCheckHelperBase(Class<T> targetType) { // this.targetType = $.requireNotNull(targetType); // } // // public Class<T> getTargetClass() { // return targetType; // } // // /** // * // * @return // */ // @Override // public List<? extends Permission> permissions() { // List<String> names = permissionNames(); // if (names.isEmpty()) { // return C.list(); // } // AAAContext aaa = AAA.context(); // AAAPersistentService ps = aaa.getPersistentService(); // List<Permission> perms = C.newList(); // for (String name: names) { // Permission p = ps.findByName(name, Permission.class); // perms.add($.requireNotNull(p)); // } // return perms; // } // // /** // * Returns a list of permission name strings. By default // * this method will return an empty list. // * @return permission names in a string list // */ // protected List<String> permissionNames() { // return C.list(); // } // // }
import act.aaa.DynamicPermissionCheckHelperBase; import org.osgl.aaa.Principal; import org.osgl.util.C; import java.util.List;
package jpa_test.endpoint; public interface CustomerLinked { boolean isLinkedToCustomer(Principal principal);
// Path: src/main/java/act/aaa/DynamicPermissionCheckHelperBase.java // public abstract class DynamicPermissionCheckHelperBase<T> implements DynamicPermissionCheckHelper<T>{ // // private Class<T> targetType; // // public DynamicPermissionCheckHelperBase() { // List<Type> typeParams = Generics.typeParamImplementations(getClass(), DynamicPermissionCheckHelperBase.class); // targetType = (Class<T>) typeParams.get(0); // } // // public DynamicPermissionCheckHelperBase(Class<T> targetType) { // this.targetType = $.requireNotNull(targetType); // } // // public Class<T> getTargetClass() { // return targetType; // } // // /** // * // * @return // */ // @Override // public List<? extends Permission> permissions() { // List<String> names = permissionNames(); // if (names.isEmpty()) { // return C.list(); // } // AAAContext aaa = AAA.context(); // AAAPersistentService ps = aaa.getPersistentService(); // List<Permission> perms = C.newList(); // for (String name: names) { // Permission p = ps.findByName(name, Permission.class); // perms.add($.requireNotNull(p)); // } // return perms; // } // // /** // * Returns a list of permission name strings. By default // * this method will return an empty list. // * @return permission names in a string list // */ // protected List<String> permissionNames() { // return C.list(); // } // // } // Path: testapps/jpa_model_id/src/main/java/jpa_test/endpoint/CustomerLinked.java import act.aaa.DynamicPermissionCheckHelperBase; import org.osgl.aaa.Principal; import org.osgl.util.C; import java.util.List; package jpa_test.endpoint; public interface CustomerLinked { boolean isLinkedToCustomer(Principal principal);
class DynamicPermissionChecker extends DynamicPermissionCheckHelperBase<CustomerLinked> {
actframework/act-aaa-plugin
testapps/jpa_model_id/src/main/java/jpa_test/endpoint/AuthenticateService.java
// Path: testapps/jpa_model_id/src/main/java/jpa_test/model/User.java // @Entity(name = "user") // public class User extends UserBase implements UserLinked { // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long id; // // public String firstName; // public String lastName; // // @Override // public boolean isLinkedTo(Principal user) { // return S.eq(email, user.getName()); // } // // @Stateless // public static class Dao extends JPADao<Long, User> { // // public User findByUsername(String username) { // return findOneBy("email", username); // } // // public boolean authenticate(String username, char[] password) { // User user = findByUsername(username); // if (null == user) { // return false; // } // return user.verifyPassword(password); // } // // } // }
import static org.osgl.http.H.Method.GET; import static org.osgl.http.H.Method.POST; import act.app.ActionContext; import org.osgl.mvc.annotation.Action; import org.osgl.mvc.annotation.PostAction; import jpa_test.model.User;
package jpa_test.endpoint; public class AuthenticateService extends PublicServiceBaseV1 { @PostAction("login")
// Path: testapps/jpa_model_id/src/main/java/jpa_test/model/User.java // @Entity(name = "user") // public class User extends UserBase implements UserLinked { // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long id; // // public String firstName; // public String lastName; // // @Override // public boolean isLinkedTo(Principal user) { // return S.eq(email, user.getName()); // } // // @Stateless // public static class Dao extends JPADao<Long, User> { // // public User findByUsername(String username) { // return findOneBy("email", username); // } // // public boolean authenticate(String username, char[] password) { // User user = findByUsername(username); // if (null == user) { // return false; // } // return user.verifyPassword(password); // } // // } // } // Path: testapps/jpa_model_id/src/main/java/jpa_test/endpoint/AuthenticateService.java import static org.osgl.http.H.Method.GET; import static org.osgl.http.H.Method.POST; import act.app.ActionContext; import org.osgl.mvc.annotation.Action; import org.osgl.mvc.annotation.PostAction; import jpa_test.model.User; package jpa_test.endpoint; public class AuthenticateService extends PublicServiceBaseV1 { @PostAction("login")
public void login(String username, char[] password, ActionContext ctx, User.Dao userDao) {
actframework/act-aaa-plugin
src/main/java/act/aaa/AAAMetaInfo.java
// Path: src/main/java/act/aaa/model/AuditBase.java // @MappedSuperclass // public abstract class AuditBase implements SimpleBean { // // public String message; // public String target; // public String principal; // public String privilege; // public boolean success; // public String permission; // // public AuditBase() {} // // public AuditBase(Object aTarget, Principal aPrincipal, String aPermission, String aPrivilege, boolean theSuccess, String aMessage) { // this.message = aMessage; // this.target = targetStr(aTarget); // this.principal = aPrincipal.getName(); // this.permission = aPermission; // this.privilege = aPrivilege; // this.success = theSuccess; // } // // private String targetStr(Object target) { // if (target instanceof Auditor.Target) { // return ((Auditor.Target) target).auditTag(); // } else if (target instanceof Model) { // return S.concat(target.getClass().getSimpleName(), "[", S.string(((Model) target)._id()), "]"); // } else { // return S.string(target); // } // } // // }
import org.osgl.util.S; import javax.inject.Inject; import javax.inject.Singleton; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashSet; import java.util.Set; import act.aaa.model.AuditBase; import act.app.App; import act.app.event.SysEventId; import act.conf.AppConfig; import act.job.OnSysEvent; import act.util.AnnotatedClassFinder; import act.util.SubClassFinder; import org.osgl.aaa.Principal; import org.osgl.exception.ConfigurationException; import org.osgl.util.E;
package act.aaa; /*- * #%L * ACT AAA Plugin * %% * Copyright (C) 2015 - 2018 ActFramework * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ @Singleton public class AAAMetaInfo { Class<?> principalEntityType; Method passwordVerifier; Method roleProvider; Method permissionProvider; Method privilegeProvider; Set<Class> userTypes = new HashSet<>(); Set<Class> auditTypes = new HashSet<>(); @Inject private AppConfig config; @Inject private App app; @AnnotatedClassFinder(PrincipalEntity.class) public void foundUserType(Class type) { if (config.possibleControllerClass(type.getName())) { userTypes.add(type); } } @SubClassFinder public void foundUserType2(Class<Principal> type) { String typeName = type.getName(); if (config.possibleControllerClass(typeName) && !typeName.startsWith("act.")) { userTypes.add(type); } } @SubClassFinder
// Path: src/main/java/act/aaa/model/AuditBase.java // @MappedSuperclass // public abstract class AuditBase implements SimpleBean { // // public String message; // public String target; // public String principal; // public String privilege; // public boolean success; // public String permission; // // public AuditBase() {} // // public AuditBase(Object aTarget, Principal aPrincipal, String aPermission, String aPrivilege, boolean theSuccess, String aMessage) { // this.message = aMessage; // this.target = targetStr(aTarget); // this.principal = aPrincipal.getName(); // this.permission = aPermission; // this.privilege = aPrivilege; // this.success = theSuccess; // } // // private String targetStr(Object target) { // if (target instanceof Auditor.Target) { // return ((Auditor.Target) target).auditTag(); // } else if (target instanceof Model) { // return S.concat(target.getClass().getSimpleName(), "[", S.string(((Model) target)._id()), "]"); // } else { // return S.string(target); // } // } // // } // Path: src/main/java/act/aaa/AAAMetaInfo.java import org.osgl.util.S; import javax.inject.Inject; import javax.inject.Singleton; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashSet; import java.util.Set; import act.aaa.model.AuditBase; import act.app.App; import act.app.event.SysEventId; import act.conf.AppConfig; import act.job.OnSysEvent; import act.util.AnnotatedClassFinder; import act.util.SubClassFinder; import org.osgl.aaa.Principal; import org.osgl.exception.ConfigurationException; import org.osgl.util.E; package act.aaa; /*- * #%L * ACT AAA Plugin * %% * Copyright (C) 2015 - 2018 ActFramework * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ @Singleton public class AAAMetaInfo { Class<?> principalEntityType; Method passwordVerifier; Method roleProvider; Method permissionProvider; Method privilegeProvider; Set<Class> userTypes = new HashSet<>(); Set<Class> auditTypes = new HashSet<>(); @Inject private AppConfig config; @Inject private App app; @AnnotatedClassFinder(PrincipalEntity.class) public void foundUserType(Class type) { if (config.possibleControllerClass(type.getName())) { userTypes.add(type); } } @SubClassFinder public void foundUserType2(Class<Principal> type) { String typeName = type.getName(); if (config.possibleControllerClass(typeName) && !typeName.startsWith("act.")) { userTypes.add(type); } } @SubClassFinder
public void foundAuditType(Class<AuditBase> type) {
actframework/act-aaa-plugin
src/main/java/act/aaa/model/UserLinked.java
// Path: src/main/java/act/aaa/DynamicPermissionCheckHelperBase.java // public abstract class DynamicPermissionCheckHelperBase<T> implements DynamicPermissionCheckHelper<T>{ // // private Class<T> targetType; // // public DynamicPermissionCheckHelperBase() { // List<Type> typeParams = Generics.typeParamImplementations(getClass(), DynamicPermissionCheckHelperBase.class); // targetType = (Class<T>) typeParams.get(0); // } // // public DynamicPermissionCheckHelperBase(Class<T> targetType) { // this.targetType = $.requireNotNull(targetType); // } // // public Class<T> getTargetClass() { // return targetType; // } // // /** // * // * @return // */ // @Override // public List<? extends Permission> permissions() { // List<String> names = permissionNames(); // if (names.isEmpty()) { // return C.list(); // } // AAAContext aaa = AAA.context(); // AAAPersistentService ps = aaa.getPersistentService(); // List<Permission> perms = C.newList(); // for (String name: names) { // Permission p = ps.findByName(name, Permission.class); // perms.add($.requireNotNull(p)); // } // return perms; // } // // /** // * Returns a list of permission name strings. By default // * this method will return an empty list. // * @return permission names in a string list // */ // protected List<String> permissionNames() { // return C.list(); // } // // }
import act.aaa.DynamicPermissionCheckHelperBase; import org.osgl.aaa.Principal;
package act.aaa.model; /*- * #%L * ACT AAA Plugin * %% * Copyright (C) 2015 - 2018 ActFramework * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ public interface UserLinked { boolean isLinkedTo(Principal user);
// Path: src/main/java/act/aaa/DynamicPermissionCheckHelperBase.java // public abstract class DynamicPermissionCheckHelperBase<T> implements DynamicPermissionCheckHelper<T>{ // // private Class<T> targetType; // // public DynamicPermissionCheckHelperBase() { // List<Type> typeParams = Generics.typeParamImplementations(getClass(), DynamicPermissionCheckHelperBase.class); // targetType = (Class<T>) typeParams.get(0); // } // // public DynamicPermissionCheckHelperBase(Class<T> targetType) { // this.targetType = $.requireNotNull(targetType); // } // // public Class<T> getTargetClass() { // return targetType; // } // // /** // * // * @return // */ // @Override // public List<? extends Permission> permissions() { // List<String> names = permissionNames(); // if (names.isEmpty()) { // return C.list(); // } // AAAContext aaa = AAA.context(); // AAAPersistentService ps = aaa.getPersistentService(); // List<Permission> perms = C.newList(); // for (String name: names) { // Permission p = ps.findByName(name, Permission.class); // perms.add($.requireNotNull(p)); // } // return perms; // } // // /** // * Returns a list of permission name strings. By default // * this method will return an empty list. // * @return permission names in a string list // */ // protected List<String> permissionNames() { // return C.list(); // } // // } // Path: src/main/java/act/aaa/model/UserLinked.java import act.aaa.DynamicPermissionCheckHelperBase; import org.osgl.aaa.Principal; package act.aaa.model; /*- * #%L * ACT AAA Plugin * %% * Copyright (C) 2015 - 2018 ActFramework * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ public interface UserLinked { boolean isLinkedTo(Principal user);
class DynamicPermissionChecker extends DynamicPermissionCheckHelperBase<UserLinked> {
actframework/act-aaa-plugin
testapps/jpa_model_id/src/main/java/jpa_test/endpoint/OrderService.java
// Path: testapps/jpa_model_id/src/main/java/jpa_test/model/Order.java // @Entity(name = "orders") // public class Order implements SimpleBean, UserLinked, CustomerLinked { // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long id; // // @ManyToOne(optional = false) // @JoinColumn(name = "agent_id") // public User agent; // // @ManyToOne(optional = false) // @JoinColumn(name = "cust_id", nullable = false) // public User customer; // // public String product; // // public int quantity; // // @Override // public boolean isLinkedTo(Principal user) { // String agentName = null == agent ? null : agent.email; // String username = user.getName(); // return S.eq(username, agentName); // } // // @Override // public boolean isLinkedToCustomer(Principal principal) { // String customerName = null == customer ? null : customer.email; // String username = principal.getName(); // return S.eq(username, customerName); // } // // @Stateless // public static class Dao extends JPADao<Long, Order> { // } // // }
import act.controller.annotation.UrlContext; import act.db.DbBind; import act.db.sql.tx.Transactional; import org.osgl.$; import org.osgl.aaa.AAA; import org.osgl.mvc.annotation.GetAction; import org.osgl.mvc.annotation.PostAction; import org.osgl.mvc.annotation.PutAction; import jpa_test.model.Order; import java.util.Map; import javax.inject.Inject;
package jpa_test.endpoint; @UrlContext("orders") public class OrderService extends AuthenticatedServiceBaseV1 { @Inject
// Path: testapps/jpa_model_id/src/main/java/jpa_test/model/Order.java // @Entity(name = "orders") // public class Order implements SimpleBean, UserLinked, CustomerLinked { // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long id; // // @ManyToOne(optional = false) // @JoinColumn(name = "agent_id") // public User agent; // // @ManyToOne(optional = false) // @JoinColumn(name = "cust_id", nullable = false) // public User customer; // // public String product; // // public int quantity; // // @Override // public boolean isLinkedTo(Principal user) { // String agentName = null == agent ? null : agent.email; // String username = user.getName(); // return S.eq(username, agentName); // } // // @Override // public boolean isLinkedToCustomer(Principal principal) { // String customerName = null == customer ? null : customer.email; // String username = principal.getName(); // return S.eq(username, customerName); // } // // @Stateless // public static class Dao extends JPADao<Long, Order> { // } // // } // Path: testapps/jpa_model_id/src/main/java/jpa_test/endpoint/OrderService.java import act.controller.annotation.UrlContext; import act.db.DbBind; import act.db.sql.tx.Transactional; import org.osgl.$; import org.osgl.aaa.AAA; import org.osgl.mvc.annotation.GetAction; import org.osgl.mvc.annotation.PostAction; import org.osgl.mvc.annotation.PutAction; import jpa_test.model.Order; import java.util.Map; import javax.inject.Inject; package jpa_test.endpoint; @UrlContext("orders") public class OrderService extends AuthenticatedServiceBaseV1 { @Inject
private Order.Dao orderDao;
actframework/act-aaa-plugin
testapps/jpa_model/src/main/java/test/endpoint/OrderService.java
// Path: testapps/morphia_model/src/main/java/test/model/Order.java // @Entity("order") // public class Order extends MorphiaAdaptiveRecord<Order> implements UserLinked, CustomerLinked { // // public String agent; // // public String customer; // // public String product; // // public int quantity; // // @Override // public boolean isLinkedTo(Principal user) { // String username = user.getName(); // return S.eq(username, agent); // } // // @Override // public boolean isLinkedToCustomer(Principal principal) { // String username = principal.getName(); // return S.eq(username, customer); // } // // @Stateless // public static class Dao extends MorphiaDao<Order> { // } // // }
import act.controller.annotation.UrlContext; import act.db.DbBind; import act.db.sql.tx.Transactional; import org.osgl.$; import org.osgl.aaa.AAA; import org.osgl.mvc.annotation.GetAction; import org.osgl.mvc.annotation.PostAction; import org.osgl.mvc.annotation.PutAction; import test.model.Order; import java.util.Map; import javax.inject.Inject;
package test.endpoint; @UrlContext("orders") public class OrderService extends AuthenticatedServiceBaseV1 { @Inject
// Path: testapps/morphia_model/src/main/java/test/model/Order.java // @Entity("order") // public class Order extends MorphiaAdaptiveRecord<Order> implements UserLinked, CustomerLinked { // // public String agent; // // public String customer; // // public String product; // // public int quantity; // // @Override // public boolean isLinkedTo(Principal user) { // String username = user.getName(); // return S.eq(username, agent); // } // // @Override // public boolean isLinkedToCustomer(Principal principal) { // String username = principal.getName(); // return S.eq(username, customer); // } // // @Stateless // public static class Dao extends MorphiaDao<Order> { // } // // } // Path: testapps/jpa_model/src/main/java/test/endpoint/OrderService.java import act.controller.annotation.UrlContext; import act.db.DbBind; import act.db.sql.tx.Transactional; import org.osgl.$; import org.osgl.aaa.AAA; import org.osgl.mvc.annotation.GetAction; import org.osgl.mvc.annotation.PostAction; import org.osgl.mvc.annotation.PutAction; import test.model.Order; import java.util.Map; import javax.inject.Inject; package test.endpoint; @UrlContext("orders") public class OrderService extends AuthenticatedServiceBaseV1 { @Inject
private Order.Dao orderDao;
actframework/act-aaa-plugin
testapps/jpa_model/src/main/java/test/endpoint/UserService.java
// Path: testapps/morphia_model/src/main/java/test/model/User.java // @Entity("user") // public class User extends MorphiaUserBase<User> implements UserLinked { // // public String firstName; // public String lastName; // // @Override // public boolean isLinkedTo(Principal user) { // return S.eq(email, user.getName()); // } // // @Stateless // public static class Dao extends MorphiaDao<User> { // // public User findByUsername(String username) { // return findOneBy("email", username); // } // // public boolean authenticate(String username, char[] password) { // User user = findByUsername(username); // if (null == user) { // return false; // } // return user.verifyPassword(password); // } // // } // }
import act.controller.annotation.UrlContext; import act.db.sql.tx.Transactional; import org.osgl.aaa.AAA; import org.osgl.mvc.annotation.GetAction; import org.osgl.mvc.annotation.PostAction; import test.model.User; import javax.inject.Inject;
package test.endpoint; @UrlContext("users") public class UserService extends ServiceBaseV1 { @Inject
// Path: testapps/morphia_model/src/main/java/test/model/User.java // @Entity("user") // public class User extends MorphiaUserBase<User> implements UserLinked { // // public String firstName; // public String lastName; // // @Override // public boolean isLinkedTo(Principal user) { // return S.eq(email, user.getName()); // } // // @Stateless // public static class Dao extends MorphiaDao<User> { // // public User findByUsername(String username) { // return findOneBy("email", username); // } // // public boolean authenticate(String username, char[] password) { // User user = findByUsername(username); // if (null == user) { // return false; // } // return user.verifyPassword(password); // } // // } // } // Path: testapps/jpa_model/src/main/java/test/endpoint/UserService.java import act.controller.annotation.UrlContext; import act.db.sql.tx.Transactional; import org.osgl.aaa.AAA; import org.osgl.mvc.annotation.GetAction; import org.osgl.mvc.annotation.PostAction; import test.model.User; import javax.inject.Inject; package test.endpoint; @UrlContext("users") public class UserService extends ServiceBaseV1 { @Inject
private User.Dao userDao;
actframework/act-aaa-plugin
testapps/morphia_model/src/main/java/test/endpoint/UserService.java
// Path: testapps/morphia_model/src/main/java/test/model/User.java // @Entity("user") // public class User extends MorphiaUserBase<User> implements UserLinked { // // public String firstName; // public String lastName; // // @Override // public boolean isLinkedTo(Principal user) { // return S.eq(email, user.getName()); // } // // @Stateless // public static class Dao extends MorphiaDao<User> { // // public User findByUsername(String username) { // return findOneBy("email", username); // } // // public boolean authenticate(String username, char[] password) { // User user = findByUsername(username); // if (null == user) { // return false; // } // return user.verifyPassword(password); // } // // } // }
import act.controller.annotation.UrlContext; import org.osgl.aaa.AAA; import org.osgl.mvc.annotation.GetAction; import org.osgl.mvc.annotation.PostAction; import test.model.User; import javax.inject.Inject;
package test.endpoint; @UrlContext("users") public class UserService extends ServiceBaseV1 { @Inject
// Path: testapps/morphia_model/src/main/java/test/model/User.java // @Entity("user") // public class User extends MorphiaUserBase<User> implements UserLinked { // // public String firstName; // public String lastName; // // @Override // public boolean isLinkedTo(Principal user) { // return S.eq(email, user.getName()); // } // // @Stateless // public static class Dao extends MorphiaDao<User> { // // public User findByUsername(String username) { // return findOneBy("email", username); // } // // public boolean authenticate(String username, char[] password) { // User user = findByUsername(username); // if (null == user) { // return false; // } // return user.verifyPassword(password); // } // // } // } // Path: testapps/morphia_model/src/main/java/test/endpoint/UserService.java import act.controller.annotation.UrlContext; import org.osgl.aaa.AAA; import org.osgl.mvc.annotation.GetAction; import org.osgl.mvc.annotation.PostAction; import test.model.User; import javax.inject.Inject; package test.endpoint; @UrlContext("users") public class UserService extends ServiceBaseV1 { @Inject
private User.Dao userDao;
x7hub/Calendar_lunar
src/edu/bupt/calendar/GoogleCalendarUriIntentFilter.java
// Path: src/com/android/calendarcommon/DateException.java // public class DateException extends Exception // { // public DateException(String message) // { // super(message); // } // } // // Path: src/com/android/calendarcommon/Duration.java // public class Duration // { // public int sign; // 1 or -1 // public int weeks; // public int days; // public int hours; // public int minutes; // public int seconds; // // public Duration() // { // sign = 1; // } // // /** // * Parse according to RFC2445 ss4.3.6. (It's actually a little loose with // * its parsing, for better or for worse) // */ // public void parse(String str) throws DateException // { // sign = 1; // weeks = 0; // days = 0; // hours = 0; // minutes = 0; // seconds = 0; // // int len = str.length(); // int index = 0; // char c; // // if (len < 1) { // return ; // } // // c = str.charAt(0); // if (c == '-') { // sign = -1; // index++; // } // else if (c == '+') { // index++; // } // // if (len < index) { // return ; // } // // c = str.charAt(index); // if (c != 'P') { // throw new DateException ( // "Duration.parse(str='" + str + "') expected 'P' at index=" // + index); // } // index++; // c = str.charAt(index); // if (c == 'T') { // index++; // } // // int n = 0; // for (; index < len; index++) { // c = str.charAt(index); // if (c >= '0' && c <= '9') { // n *= 10; // n += ((int)(c-'0')); // } // else if (c == 'W') { // weeks = n; // n = 0; // } // else if (c == 'H') { // hours = n; // n = 0; // } // else if (c == 'M') { // minutes = n; // n = 0; // } // else if (c == 'S') { // seconds = n; // n = 0; // } // else if (c == 'D') { // days = n; // n = 0; // } // else if (c == 'T') { // } // else { // throw new DateException ( // "Duration.parse(str='" + str + "') unexpected char '" // + c + "' at index=" + index); // } // } // } // // /** // * Add this to the calendar provided, in place, in the calendar. // */ // public void addTo(Calendar cal) // { // cal.add(Calendar.DAY_OF_MONTH, sign*weeks*7); // cal.add(Calendar.DAY_OF_MONTH, sign*days); // cal.add(Calendar.HOUR, sign*hours); // cal.add(Calendar.MINUTE, sign*minutes); // cal.add(Calendar.SECOND, sign*seconds); // } // // public long addTo(long dt) { // return dt + getMillis(); // } // // public long getMillis() { // long factor = 1000 * sign; // return factor * ((7*24*60*60*weeks) // + (24*60*60*days) // + (60*60*hours) // + (60*minutes) // + seconds); // } // }
import static android.provider.CalendarContract.Attendees.ATTENDEE_STATUS; import static android.provider.CalendarContract.Attendees.ATTENDEE_STATUS_ACCEPTED; import static android.provider.CalendarContract.Attendees.ATTENDEE_STATUS_DECLINED; import static android.provider.CalendarContract.Attendees.ATTENDEE_STATUS_NONE; import static android.provider.CalendarContract.Attendees.ATTENDEE_STATUS_TENTATIVE; import static android.provider.CalendarContract.EXTRA_EVENT_BEGIN_TIME; import static android.provider.CalendarContract.EXTRA_EVENT_END_TIME; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.ContentUris; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.CalendarContract.Calendars; import android.provider.CalendarContract.Events; import android.text.TextUtils; import android.util.Base64; import android.util.Log; import com.android.calendarcommon.DateException; import com.android.calendarcommon.Duration;
if (debug) Log.d(TAG, "selection: " + selection); Cursor eventCursor = getContentResolver().query(Events.CONTENT_URI, EVENT_PROJECTION, selection, null, Calendars.CALENDAR_ACCESS_LEVEL + " desc"); if (debug) Log.d(TAG, "Found: " + eventCursor.getCount()); if (eventCursor != null && eventCursor.getCount() > 0) { if (eventCursor.getCount() > 1) { Log.i(TAG, "NOTE: found " + eventCursor.getCount() + " matches on event with id='" + eidParts[0] + "'"); // Don't print eidPart[1] as it contains the user's PII } // Get info from Cursor while (eventCursor.moveToNext()) { int eventId = eventCursor.getInt(EVENT_INDEX_ID); long startMillis = eventCursor.getLong(EVENT_INDEX_START); long endMillis = eventCursor.getLong(EVENT_INDEX_END); if (debug) Log.d(TAG, "_id: " + eventCursor.getLong(EVENT_INDEX_ID)); if (debug) Log.d(TAG, "startMillis: " + startMillis); if (debug) Log.d(TAG, "endMillis: " + endMillis); if (endMillis == 0) { String duration = eventCursor.getString(EVENT_INDEX_DURATION); if (debug) Log.d(TAG, "duration: " + duration); if (TextUtils.isEmpty(duration)) { continue; } try {
// Path: src/com/android/calendarcommon/DateException.java // public class DateException extends Exception // { // public DateException(String message) // { // super(message); // } // } // // Path: src/com/android/calendarcommon/Duration.java // public class Duration // { // public int sign; // 1 or -1 // public int weeks; // public int days; // public int hours; // public int minutes; // public int seconds; // // public Duration() // { // sign = 1; // } // // /** // * Parse according to RFC2445 ss4.3.6. (It's actually a little loose with // * its parsing, for better or for worse) // */ // public void parse(String str) throws DateException // { // sign = 1; // weeks = 0; // days = 0; // hours = 0; // minutes = 0; // seconds = 0; // // int len = str.length(); // int index = 0; // char c; // // if (len < 1) { // return ; // } // // c = str.charAt(0); // if (c == '-') { // sign = -1; // index++; // } // else if (c == '+') { // index++; // } // // if (len < index) { // return ; // } // // c = str.charAt(index); // if (c != 'P') { // throw new DateException ( // "Duration.parse(str='" + str + "') expected 'P' at index=" // + index); // } // index++; // c = str.charAt(index); // if (c == 'T') { // index++; // } // // int n = 0; // for (; index < len; index++) { // c = str.charAt(index); // if (c >= '0' && c <= '9') { // n *= 10; // n += ((int)(c-'0')); // } // else if (c == 'W') { // weeks = n; // n = 0; // } // else if (c == 'H') { // hours = n; // n = 0; // } // else if (c == 'M') { // minutes = n; // n = 0; // } // else if (c == 'S') { // seconds = n; // n = 0; // } // else if (c == 'D') { // days = n; // n = 0; // } // else if (c == 'T') { // } // else { // throw new DateException ( // "Duration.parse(str='" + str + "') unexpected char '" // + c + "' at index=" + index); // } // } // } // // /** // * Add this to the calendar provided, in place, in the calendar. // */ // public void addTo(Calendar cal) // { // cal.add(Calendar.DAY_OF_MONTH, sign*weeks*7); // cal.add(Calendar.DAY_OF_MONTH, sign*days); // cal.add(Calendar.HOUR, sign*hours); // cal.add(Calendar.MINUTE, sign*minutes); // cal.add(Calendar.SECOND, sign*seconds); // } // // public long addTo(long dt) { // return dt + getMillis(); // } // // public long getMillis() { // long factor = 1000 * sign; // return factor * ((7*24*60*60*weeks) // + (24*60*60*days) // + (60*60*hours) // + (60*minutes) // + seconds); // } // } // Path: src/edu/bupt/calendar/GoogleCalendarUriIntentFilter.java import static android.provider.CalendarContract.Attendees.ATTENDEE_STATUS; import static android.provider.CalendarContract.Attendees.ATTENDEE_STATUS_ACCEPTED; import static android.provider.CalendarContract.Attendees.ATTENDEE_STATUS_DECLINED; import static android.provider.CalendarContract.Attendees.ATTENDEE_STATUS_NONE; import static android.provider.CalendarContract.Attendees.ATTENDEE_STATUS_TENTATIVE; import static android.provider.CalendarContract.EXTRA_EVENT_BEGIN_TIME; import static android.provider.CalendarContract.EXTRA_EVENT_END_TIME; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.ContentUris; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.CalendarContract.Calendars; import android.provider.CalendarContract.Events; import android.text.TextUtils; import android.util.Base64; import android.util.Log; import com.android.calendarcommon.DateException; import com.android.calendarcommon.Duration; if (debug) Log.d(TAG, "selection: " + selection); Cursor eventCursor = getContentResolver().query(Events.CONTENT_URI, EVENT_PROJECTION, selection, null, Calendars.CALENDAR_ACCESS_LEVEL + " desc"); if (debug) Log.d(TAG, "Found: " + eventCursor.getCount()); if (eventCursor != null && eventCursor.getCount() > 0) { if (eventCursor.getCount() > 1) { Log.i(TAG, "NOTE: found " + eventCursor.getCount() + " matches on event with id='" + eidParts[0] + "'"); // Don't print eidPart[1] as it contains the user's PII } // Get info from Cursor while (eventCursor.moveToNext()) { int eventId = eventCursor.getInt(EVENT_INDEX_ID); long startMillis = eventCursor.getLong(EVENT_INDEX_START); long endMillis = eventCursor.getLong(EVENT_INDEX_END); if (debug) Log.d(TAG, "_id: " + eventCursor.getLong(EVENT_INDEX_ID)); if (debug) Log.d(TAG, "startMillis: " + startMillis); if (debug) Log.d(TAG, "endMillis: " + endMillis); if (endMillis == 0) { String duration = eventCursor.getString(EVENT_INDEX_DURATION); if (debug) Log.d(TAG, "duration: " + duration); if (TextUtils.isEmpty(duration)) { continue; } try {
Duration d = new Duration();
x7hub/Calendar_lunar
src/edu/bupt/calendar/GoogleCalendarUriIntentFilter.java
// Path: src/com/android/calendarcommon/DateException.java // public class DateException extends Exception // { // public DateException(String message) // { // super(message); // } // } // // Path: src/com/android/calendarcommon/Duration.java // public class Duration // { // public int sign; // 1 or -1 // public int weeks; // public int days; // public int hours; // public int minutes; // public int seconds; // // public Duration() // { // sign = 1; // } // // /** // * Parse according to RFC2445 ss4.3.6. (It's actually a little loose with // * its parsing, for better or for worse) // */ // public void parse(String str) throws DateException // { // sign = 1; // weeks = 0; // days = 0; // hours = 0; // minutes = 0; // seconds = 0; // // int len = str.length(); // int index = 0; // char c; // // if (len < 1) { // return ; // } // // c = str.charAt(0); // if (c == '-') { // sign = -1; // index++; // } // else if (c == '+') { // index++; // } // // if (len < index) { // return ; // } // // c = str.charAt(index); // if (c != 'P') { // throw new DateException ( // "Duration.parse(str='" + str + "') expected 'P' at index=" // + index); // } // index++; // c = str.charAt(index); // if (c == 'T') { // index++; // } // // int n = 0; // for (; index < len; index++) { // c = str.charAt(index); // if (c >= '0' && c <= '9') { // n *= 10; // n += ((int)(c-'0')); // } // else if (c == 'W') { // weeks = n; // n = 0; // } // else if (c == 'H') { // hours = n; // n = 0; // } // else if (c == 'M') { // minutes = n; // n = 0; // } // else if (c == 'S') { // seconds = n; // n = 0; // } // else if (c == 'D') { // days = n; // n = 0; // } // else if (c == 'T') { // } // else { // throw new DateException ( // "Duration.parse(str='" + str + "') unexpected char '" // + c + "' at index=" + index); // } // } // } // // /** // * Add this to the calendar provided, in place, in the calendar. // */ // public void addTo(Calendar cal) // { // cal.add(Calendar.DAY_OF_MONTH, sign*weeks*7); // cal.add(Calendar.DAY_OF_MONTH, sign*days); // cal.add(Calendar.HOUR, sign*hours); // cal.add(Calendar.MINUTE, sign*minutes); // cal.add(Calendar.SECOND, sign*seconds); // } // // public long addTo(long dt) { // return dt + getMillis(); // } // // public long getMillis() { // long factor = 1000 * sign; // return factor * ((7*24*60*60*weeks) // + (24*60*60*days) // + (60*60*hours) // + (60*minutes) // + seconds); // } // }
import static android.provider.CalendarContract.Attendees.ATTENDEE_STATUS; import static android.provider.CalendarContract.Attendees.ATTENDEE_STATUS_ACCEPTED; import static android.provider.CalendarContract.Attendees.ATTENDEE_STATUS_DECLINED; import static android.provider.CalendarContract.Attendees.ATTENDEE_STATUS_NONE; import static android.provider.CalendarContract.Attendees.ATTENDEE_STATUS_TENTATIVE; import static android.provider.CalendarContract.EXTRA_EVENT_BEGIN_TIME; import static android.provider.CalendarContract.EXTRA_EVENT_END_TIME; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.ContentUris; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.CalendarContract.Calendars; import android.provider.CalendarContract.Events; import android.text.TextUtils; import android.util.Base64; import android.util.Log; import com.android.calendarcommon.DateException; import com.android.calendarcommon.Duration;
Log.i(TAG, "NOTE: found " + eventCursor.getCount() + " matches on event with id='" + eidParts[0] + "'"); // Don't print eidPart[1] as it contains the user's PII } // Get info from Cursor while (eventCursor.moveToNext()) { int eventId = eventCursor.getInt(EVENT_INDEX_ID); long startMillis = eventCursor.getLong(EVENT_INDEX_START); long endMillis = eventCursor.getLong(EVENT_INDEX_END); if (debug) Log.d(TAG, "_id: " + eventCursor.getLong(EVENT_INDEX_ID)); if (debug) Log.d(TAG, "startMillis: " + startMillis); if (debug) Log.d(TAG, "endMillis: " + endMillis); if (endMillis == 0) { String duration = eventCursor.getString(EVENT_INDEX_DURATION); if (debug) Log.d(TAG, "duration: " + duration); if (TextUtils.isEmpty(duration)) { continue; } try { Duration d = new Duration(); d.parse(duration); endMillis = startMillis + d.getMillis(); if (debug) Log.d(TAG, "startMillis! " + startMillis); if (debug) Log.d(TAG, "endMillis! " + endMillis); if (endMillis < startMillis) { continue; }
// Path: src/com/android/calendarcommon/DateException.java // public class DateException extends Exception // { // public DateException(String message) // { // super(message); // } // } // // Path: src/com/android/calendarcommon/Duration.java // public class Duration // { // public int sign; // 1 or -1 // public int weeks; // public int days; // public int hours; // public int minutes; // public int seconds; // // public Duration() // { // sign = 1; // } // // /** // * Parse according to RFC2445 ss4.3.6. (It's actually a little loose with // * its parsing, for better or for worse) // */ // public void parse(String str) throws DateException // { // sign = 1; // weeks = 0; // days = 0; // hours = 0; // minutes = 0; // seconds = 0; // // int len = str.length(); // int index = 0; // char c; // // if (len < 1) { // return ; // } // // c = str.charAt(0); // if (c == '-') { // sign = -1; // index++; // } // else if (c == '+') { // index++; // } // // if (len < index) { // return ; // } // // c = str.charAt(index); // if (c != 'P') { // throw new DateException ( // "Duration.parse(str='" + str + "') expected 'P' at index=" // + index); // } // index++; // c = str.charAt(index); // if (c == 'T') { // index++; // } // // int n = 0; // for (; index < len; index++) { // c = str.charAt(index); // if (c >= '0' && c <= '9') { // n *= 10; // n += ((int)(c-'0')); // } // else if (c == 'W') { // weeks = n; // n = 0; // } // else if (c == 'H') { // hours = n; // n = 0; // } // else if (c == 'M') { // minutes = n; // n = 0; // } // else if (c == 'S') { // seconds = n; // n = 0; // } // else if (c == 'D') { // days = n; // n = 0; // } // else if (c == 'T') { // } // else { // throw new DateException ( // "Duration.parse(str='" + str + "') unexpected char '" // + c + "' at index=" + index); // } // } // } // // /** // * Add this to the calendar provided, in place, in the calendar. // */ // public void addTo(Calendar cal) // { // cal.add(Calendar.DAY_OF_MONTH, sign*weeks*7); // cal.add(Calendar.DAY_OF_MONTH, sign*days); // cal.add(Calendar.HOUR, sign*hours); // cal.add(Calendar.MINUTE, sign*minutes); // cal.add(Calendar.SECOND, sign*seconds); // } // // public long addTo(long dt) { // return dt + getMillis(); // } // // public long getMillis() { // long factor = 1000 * sign; // return factor * ((7*24*60*60*weeks) // + (24*60*60*days) // + (60*60*hours) // + (60*minutes) // + seconds); // } // } // Path: src/edu/bupt/calendar/GoogleCalendarUriIntentFilter.java import static android.provider.CalendarContract.Attendees.ATTENDEE_STATUS; import static android.provider.CalendarContract.Attendees.ATTENDEE_STATUS_ACCEPTED; import static android.provider.CalendarContract.Attendees.ATTENDEE_STATUS_DECLINED; import static android.provider.CalendarContract.Attendees.ATTENDEE_STATUS_NONE; import static android.provider.CalendarContract.Attendees.ATTENDEE_STATUS_TENTATIVE; import static android.provider.CalendarContract.EXTRA_EVENT_BEGIN_TIME; import static android.provider.CalendarContract.EXTRA_EVENT_END_TIME; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.ContentUris; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.CalendarContract.Calendars; import android.provider.CalendarContract.Events; import android.text.TextUtils; import android.util.Base64; import android.util.Log; import com.android.calendarcommon.DateException; import com.android.calendarcommon.Duration; Log.i(TAG, "NOTE: found " + eventCursor.getCount() + " matches on event with id='" + eidParts[0] + "'"); // Don't print eidPart[1] as it contains the user's PII } // Get info from Cursor while (eventCursor.moveToNext()) { int eventId = eventCursor.getInt(EVENT_INDEX_ID); long startMillis = eventCursor.getLong(EVENT_INDEX_START); long endMillis = eventCursor.getLong(EVENT_INDEX_END); if (debug) Log.d(TAG, "_id: " + eventCursor.getLong(EVENT_INDEX_ID)); if (debug) Log.d(TAG, "startMillis: " + startMillis); if (debug) Log.d(TAG, "endMillis: " + endMillis); if (endMillis == 0) { String duration = eventCursor.getString(EVENT_INDEX_DURATION); if (debug) Log.d(TAG, "duration: " + duration); if (TextUtils.isEmpty(duration)) { continue; } try { Duration d = new Duration(); d.parse(duration); endMillis = startMillis + d.getMillis(); if (debug) Log.d(TAG, "startMillis! " + startMillis); if (debug) Log.d(TAG, "endMillis! " + endMillis); if (endMillis < startMillis) { continue; }
} catch (DateException e) {
x7hub/Calendar_lunar
src/edu/bupt/calendar/alerts/NotificationMgr.java
// Path: src/edu/bupt/calendar/alerts/AlertService.java // public static class NotificationWrapper { // Notification mNotification; // long mEventId; // long mBegin; // long mEnd; // ArrayList<NotificationWrapper> mNw; // // public NotificationWrapper(Notification n, int notificationId, long eventId, // long startMillis, long endMillis, boolean doPopup) { // mNotification = n; // mEventId = eventId; // mBegin = startMillis; // mEnd = endMillis; // // // popup? // // notification id? // } // // public NotificationWrapper(Notification n) { // mNotification = n; // } // // public void add(NotificationWrapper nw) { // if (mNw == null) { // mNw = new ArrayList<NotificationWrapper>(); // } // mNw.add(nw); // } // }
import edu.bupt.calendar.alerts.AlertService.NotificationWrapper;
package edu.bupt.calendar.alerts; public interface NotificationMgr { public void cancel(int id); public void cancel(String tag, int id); public void cancelAll();
// Path: src/edu/bupt/calendar/alerts/AlertService.java // public static class NotificationWrapper { // Notification mNotification; // long mEventId; // long mBegin; // long mEnd; // ArrayList<NotificationWrapper> mNw; // // public NotificationWrapper(Notification n, int notificationId, long eventId, // long startMillis, long endMillis, boolean doPopup) { // mNotification = n; // mEventId = eventId; // mBegin = startMillis; // mEnd = endMillis; // // // popup? // // notification id? // } // // public NotificationWrapper(Notification n) { // mNotification = n; // } // // public void add(NotificationWrapper nw) { // if (mNw == null) { // mNw = new ArrayList<NotificationWrapper>(); // } // mNw.add(nw); // } // } // Path: src/edu/bupt/calendar/alerts/NotificationMgr.java import edu.bupt.calendar.alerts.AlertService.NotificationWrapper; package edu.bupt.calendar.alerts; public interface NotificationMgr { public void cancel(int id); public void cancel(String tag, int id); public void cancelAll();
public void notify(int id, NotificationWrapper notification);
x7hub/Calendar_lunar
src/edu/bupt/calendar/AsyncQueryServiceHelper.java
// Path: src/edu/bupt/calendar/AsyncQueryService.java // public static class Operation { // static final int EVENT_ARG_QUERY = 1; // static final int EVENT_ARG_INSERT = 2; // static final int EVENT_ARG_UPDATE = 3; // static final int EVENT_ARG_DELETE = 4; // static final int EVENT_ARG_BATCH = 5; // // /** // * unique identify for cancellation purpose // */ // public int token; // // /** // * One of the EVENT_ARG_ constants in the class describing the operation // */ // public int op; // // /** // * {@link SystemClock.elapsedRealtime()} based // */ // public long scheduledExecutionTime; // // protected static char opToChar(int op) { // switch (op) { // case Operation.EVENT_ARG_QUERY: // return 'Q'; // case Operation.EVENT_ARG_INSERT: // return 'I'; // case Operation.EVENT_ARG_UPDATE: // return 'U'; // case Operation.EVENT_ARG_DELETE: // return 'D'; // case Operation.EVENT_ARG_BATCH: // return 'B'; // default: // return '?'; // } // } // // @Override // public String toString() { // StringBuilder builder = new StringBuilder(); // builder.append("Operation [op="); // builder.append(op); // builder.append(", token="); // builder.append(token); // builder.append(", scheduledExecutionTime="); // builder.append(scheduledExecutionTime); // builder.append("]"); // return builder.toString(); // } // }
import edu.bupt.calendar.AsyncQueryService.Operation; import android.app.IntentService; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.OperationApplicationException; import android.database.Cursor; import android.net.Uri; import android.os.Handler; import android.os.Message; import android.os.RemoteException; import android.os.SystemClock; import android.util.Log; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.PriorityQueue; import java.util.concurrent.Delayed; import java.util.concurrent.TimeUnit;
// @VisibleForTesting void calculateScheduledTime() { mScheduledTimeMillis = SystemClock.elapsedRealtime() + delayMillis; } // @Override // Uncomment with Java6 public long getDelay(TimeUnit unit) { return unit.convert(mScheduledTimeMillis - SystemClock.elapsedRealtime(), TimeUnit.MILLISECONDS); } // @Override // Uncomment with Java6 public int compareTo(Delayed another) { OperationInfo anotherArgs = (OperationInfo) another; if (this.mScheduledTimeMillis == anotherArgs.mScheduledTimeMillis) { return 0; } else if (this.mScheduledTimeMillis < anotherArgs.mScheduledTimeMillis) { return -1; } else { return 1; } } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("OperationInfo [\n\t token= "); builder.append(token); builder.append(",\n\t op= ");
// Path: src/edu/bupt/calendar/AsyncQueryService.java // public static class Operation { // static final int EVENT_ARG_QUERY = 1; // static final int EVENT_ARG_INSERT = 2; // static final int EVENT_ARG_UPDATE = 3; // static final int EVENT_ARG_DELETE = 4; // static final int EVENT_ARG_BATCH = 5; // // /** // * unique identify for cancellation purpose // */ // public int token; // // /** // * One of the EVENT_ARG_ constants in the class describing the operation // */ // public int op; // // /** // * {@link SystemClock.elapsedRealtime()} based // */ // public long scheduledExecutionTime; // // protected static char opToChar(int op) { // switch (op) { // case Operation.EVENT_ARG_QUERY: // return 'Q'; // case Operation.EVENT_ARG_INSERT: // return 'I'; // case Operation.EVENT_ARG_UPDATE: // return 'U'; // case Operation.EVENT_ARG_DELETE: // return 'D'; // case Operation.EVENT_ARG_BATCH: // return 'B'; // default: // return '?'; // } // } // // @Override // public String toString() { // StringBuilder builder = new StringBuilder(); // builder.append("Operation [op="); // builder.append(op); // builder.append(", token="); // builder.append(token); // builder.append(", scheduledExecutionTime="); // builder.append(scheduledExecutionTime); // builder.append("]"); // return builder.toString(); // } // } // Path: src/edu/bupt/calendar/AsyncQueryServiceHelper.java import edu.bupt.calendar.AsyncQueryService.Operation; import android.app.IntentService; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.OperationApplicationException; import android.database.Cursor; import android.net.Uri; import android.os.Handler; import android.os.Message; import android.os.RemoteException; import android.os.SystemClock; import android.util.Log; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.PriorityQueue; import java.util.concurrent.Delayed; import java.util.concurrent.TimeUnit; // @VisibleForTesting void calculateScheduledTime() { mScheduledTimeMillis = SystemClock.elapsedRealtime() + delayMillis; } // @Override // Uncomment with Java6 public long getDelay(TimeUnit unit) { return unit.convert(mScheduledTimeMillis - SystemClock.elapsedRealtime(), TimeUnit.MILLISECONDS); } // @Override // Uncomment with Java6 public int compareTo(Delayed another) { OperationInfo anotherArgs = (OperationInfo) another; if (this.mScheduledTimeMillis == anotherArgs.mScheduledTimeMillis) { return 0; } else if (this.mScheduledTimeMillis < anotherArgs.mScheduledTimeMillis) { return -1; } else { return 1; } } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("OperationInfo [\n\t token= "); builder.append(token); builder.append(",\n\t op= ");
builder.append(Operation.opToChar(op));
x7hub/Calendar_lunar
src/edu/bupt/calendar/ContactsAsyncHelper.java
// Path: src/edu/bupt/calendar/event/EditEventHelper.java // public static class AttendeeItem { // public boolean mRemoved; // public Attendee mAttendee; // public Drawable mBadge; // public int mUpdateCounts; // public View mView; // public Uri mContactLookupUri; // // public AttendeeItem(Attendee attendee, Drawable badge) { // mAttendee = attendee; // mBadge = badge; // } // }
import java.io.InputStream; import edu.bupt.calendar.event.EditEventHelper.AttendeeItem; import android.content.Context; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; import android.provider.ContactsContract.Contacts; import android.util.Log; import android.view.View; import android.widget.ImageView;
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.bupt.calendar; /** * Helper class for async access of images. */ public class ContactsAsyncHelper extends Handler { private static final boolean DBG = false; private static final String LOG_TAG = "ContactsAsyncHelper"; private static ContactsAsyncHelper mInstance = null; /** * Interface for a WorkerHandler result return. */ public interface OnImageLoadCompleteListener { /** * Called when the image load is complete. * * @param imagePresent true if an image was found */ public void onImageLoadComplete(int token, Object cookie, ImageView iView, boolean imagePresent); } // constants private static final int EVENT_LOAD_IMAGE = 1; private static final int EVENT_LOAD_DRAWABLE = 2; private static final int DEFAULT_TOKEN = -1; // static objects private static Handler sThreadHandler; private static final class WorkerArgs { public Context context; public ImageView view; public Uri uri; public int defaultResource; public Object result;
// Path: src/edu/bupt/calendar/event/EditEventHelper.java // public static class AttendeeItem { // public boolean mRemoved; // public Attendee mAttendee; // public Drawable mBadge; // public int mUpdateCounts; // public View mView; // public Uri mContactLookupUri; // // public AttendeeItem(Attendee attendee, Drawable badge) { // mAttendee = attendee; // mBadge = badge; // } // } // Path: src/edu/bupt/calendar/ContactsAsyncHelper.java import java.io.InputStream; import edu.bupt.calendar.event.EditEventHelper.AttendeeItem; import android.content.Context; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; import android.provider.ContactsContract.Contacts; import android.util.Log; import android.view.View; import android.widget.ImageView; /* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.bupt.calendar; /** * Helper class for async access of images. */ public class ContactsAsyncHelper extends Handler { private static final boolean DBG = false; private static final String LOG_TAG = "ContactsAsyncHelper"; private static ContactsAsyncHelper mInstance = null; /** * Interface for a WorkerHandler result return. */ public interface OnImageLoadCompleteListener { /** * Called when the image load is complete. * * @param imagePresent true if an image was found */ public void onImageLoadComplete(int token, Object cookie, ImageView iView, boolean imagePresent); } // constants private static final int EVENT_LOAD_IMAGE = 1; private static final int EVENT_LOAD_DRAWABLE = 2; private static final int DEFAULT_TOKEN = -1; // static objects private static Handler sThreadHandler; private static final class WorkerArgs { public Context context; public ImageView view; public Uri uri; public int defaultResource; public Object result;
public AttendeeItem item;
x7hub/Calendar_lunar
src/edu/bupt/calendar/DayView.java
// Path: src/edu/bupt/calendar/CalendarController.java // public interface EventType { // final long CREATE_EVENT = 1L; // // // Simple view of an event // final long VIEW_EVENT = 1L << 1; // // // Full detail view in read only mode // final long VIEW_EVENT_DETAILS = 1L << 2; // // // full detail view in edit mode // final long EDIT_EVENT = 1L << 3; // // final long DELETE_EVENT = 1L << 4; // // final long GO_TO = 1L << 5; // // final long LAUNCH_SETTINGS = 1L << 6; // // final long EVENTS_CHANGED = 1L << 7; // // final long SEARCH = 1L << 8; // // // User has pressed the home key // final long USER_HOME = 1L << 9; // // // date range has changed, update the title // final long UPDATE_TITLE = 1L << 10; // // // select which calendars to display // final long LAUNCH_SELECT_VISIBLE_CALENDARS = 1L << 11; // } // // Path: src/edu/bupt/calendar/CalendarController.java // public interface ViewType { // final int DETAIL = -1; // final int CURRENT = 0; // final int AGENDA = 1; // final int DAY = 2; // final int WEEK = 3; // final int MONTH = 4; // final int EDIT = 5; // }
import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.app.AlertDialog; import android.app.Service; import android.content.ContentResolver; import android.content.ContentUris; import android.content.Context; import android.content.DialogInterface; import android.content.res.Resources; import android.content.res.TypedArray; import android.database.Cursor; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.Paint.Style; import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Handler; import android.provider.CalendarContract.Attendees; import android.provider.CalendarContract.Calendars; import android.provider.CalendarContract.Events; import android.text.Layout.Alignment; import android.text.SpannableStringBuilder; import android.text.StaticLayout; import android.text.TextPaint; import android.text.TextUtils; import android.text.format.DateFormat; import android.text.format.DateUtils; import android.text.format.Time; import android.text.style.StyleSpan; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.GestureDetector; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.WindowManager; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityManager; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.Animation; import android.view.animation.Interpolator; import android.view.animation.TranslateAnimation; import android.widget.EdgeEffect; import android.widget.ImageView; import android.widget.OverScroller; import android.widget.PopupWindow; import android.widget.TextView; import android.widget.ViewSwitcher; import edu.bupt.calendar.CalendarController.EventType; import edu.bupt.calendar.CalendarController.ViewType; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Formatter; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern;
protected static StringBuilder mStringBuilder = new StringBuilder(50); // TODO recreate formatter when locale changes protected static Formatter mFormatter = new Formatter(mStringBuilder, Locale.getDefault()); private final Runnable mTZUpdater = new Runnable() { @Override public void run() { String tz = Utils.getTimeZone(mContext, this); mBaseDate.timezone = tz; mBaseDate.normalize(true); mCurrentTime.switchTimezone(tz); invalidate(); } }; // Sets the "clicked" color from the clicked event private final Runnable mSetClick = new Runnable() { @Override public void run() { mClickedEvent = mSavedClickedEvent; mSavedClickedEvent = null; DayView.this.invalidate(); } }; // Clears the "clicked" color from the clicked event and launch the event private final Runnable mClearClick = new Runnable() { @Override public void run() { if (mClickedEvent != null) {
// Path: src/edu/bupt/calendar/CalendarController.java // public interface EventType { // final long CREATE_EVENT = 1L; // // // Simple view of an event // final long VIEW_EVENT = 1L << 1; // // // Full detail view in read only mode // final long VIEW_EVENT_DETAILS = 1L << 2; // // // full detail view in edit mode // final long EDIT_EVENT = 1L << 3; // // final long DELETE_EVENT = 1L << 4; // // final long GO_TO = 1L << 5; // // final long LAUNCH_SETTINGS = 1L << 6; // // final long EVENTS_CHANGED = 1L << 7; // // final long SEARCH = 1L << 8; // // // User has pressed the home key // final long USER_HOME = 1L << 9; // // // date range has changed, update the title // final long UPDATE_TITLE = 1L << 10; // // // select which calendars to display // final long LAUNCH_SELECT_VISIBLE_CALENDARS = 1L << 11; // } // // Path: src/edu/bupt/calendar/CalendarController.java // public interface ViewType { // final int DETAIL = -1; // final int CURRENT = 0; // final int AGENDA = 1; // final int DAY = 2; // final int WEEK = 3; // final int MONTH = 4; // final int EDIT = 5; // } // Path: src/edu/bupt/calendar/DayView.java import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.app.AlertDialog; import android.app.Service; import android.content.ContentResolver; import android.content.ContentUris; import android.content.Context; import android.content.DialogInterface; import android.content.res.Resources; import android.content.res.TypedArray; import android.database.Cursor; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.Paint.Style; import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Handler; import android.provider.CalendarContract.Attendees; import android.provider.CalendarContract.Calendars; import android.provider.CalendarContract.Events; import android.text.Layout.Alignment; import android.text.SpannableStringBuilder; import android.text.StaticLayout; import android.text.TextPaint; import android.text.TextUtils; import android.text.format.DateFormat; import android.text.format.DateUtils; import android.text.format.Time; import android.text.style.StyleSpan; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.GestureDetector; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.WindowManager; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityManager; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.Animation; import android.view.animation.Interpolator; import android.view.animation.TranslateAnimation; import android.widget.EdgeEffect; import android.widget.ImageView; import android.widget.OverScroller; import android.widget.PopupWindow; import android.widget.TextView; import android.widget.ViewSwitcher; import edu.bupt.calendar.CalendarController.EventType; import edu.bupt.calendar.CalendarController.ViewType; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Formatter; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; protected static StringBuilder mStringBuilder = new StringBuilder(50); // TODO recreate formatter when locale changes protected static Formatter mFormatter = new Formatter(mStringBuilder, Locale.getDefault()); private final Runnable mTZUpdater = new Runnable() { @Override public void run() { String tz = Utils.getTimeZone(mContext, this); mBaseDate.timezone = tz; mBaseDate.normalize(true); mCurrentTime.switchTimezone(tz); invalidate(); } }; // Sets the "clicked" color from the clicked event private final Runnable mSetClick = new Runnable() { @Override public void run() { mClickedEvent = mSavedClickedEvent; mSavedClickedEvent = null; DayView.this.invalidate(); } }; // Clears the "clicked" color from the clicked event and launch the event private final Runnable mClearClick = new Runnable() { @Override public void run() { if (mClickedEvent != null) {
mController.sendEventRelatedEvent(this, EventType.VIEW_EVENT, mClickedEvent.id,
x7hub/Calendar_lunar
src/edu/bupt/calendar/DayView.java
// Path: src/edu/bupt/calendar/CalendarController.java // public interface EventType { // final long CREATE_EVENT = 1L; // // // Simple view of an event // final long VIEW_EVENT = 1L << 1; // // // Full detail view in read only mode // final long VIEW_EVENT_DETAILS = 1L << 2; // // // full detail view in edit mode // final long EDIT_EVENT = 1L << 3; // // final long DELETE_EVENT = 1L << 4; // // final long GO_TO = 1L << 5; // // final long LAUNCH_SETTINGS = 1L << 6; // // final long EVENTS_CHANGED = 1L << 7; // // final long SEARCH = 1L << 8; // // // User has pressed the home key // final long USER_HOME = 1L << 9; // // // date range has changed, update the title // final long UPDATE_TITLE = 1L << 10; // // // select which calendars to display // final long LAUNCH_SELECT_VISIBLE_CALENDARS = 1L << 11; // } // // Path: src/edu/bupt/calendar/CalendarController.java // public interface ViewType { // final int DETAIL = -1; // final int CURRENT = 0; // final int AGENDA = 1; // final int DAY = 2; // final int WEEK = 3; // final int MONTH = 4; // final int EDIT = 5; // }
import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.app.AlertDialog; import android.app.Service; import android.content.ContentResolver; import android.content.ContentUris; import android.content.Context; import android.content.DialogInterface; import android.content.res.Resources; import android.content.res.TypedArray; import android.database.Cursor; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.Paint.Style; import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Handler; import android.provider.CalendarContract.Attendees; import android.provider.CalendarContract.Calendars; import android.provider.CalendarContract.Events; import android.text.Layout.Alignment; import android.text.SpannableStringBuilder; import android.text.StaticLayout; import android.text.TextPaint; import android.text.TextUtils; import android.text.format.DateFormat; import android.text.format.DateUtils; import android.text.format.Time; import android.text.style.StyleSpan; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.GestureDetector; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.WindowManager; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityManager; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.Animation; import android.view.animation.Interpolator; import android.view.animation.TranslateAnimation; import android.widget.EdgeEffect; import android.widget.ImageView; import android.widget.OverScroller; import android.widget.PopupWindow; import android.widget.TextView; import android.widget.ViewSwitcher; import edu.bupt.calendar.CalendarController.EventType; import edu.bupt.calendar.CalendarController.ViewType; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Formatter; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern;
time.setJulianDay(mSelectionDay); time.hour = mSelectionHour; // We ignore the "isDst" field because we want normalize() to figure // out the correct DST value and not adjust the selected time based // on the current setting of DST. time.normalize(true /* ignore isDst */); return time; } public void updateTitle() { Time start = new Time(mBaseDate); start.normalize(true); Time end = new Time(start); end.monthDay += mNumDays - 1; // Move it forward one minute so the formatter doesn't lose a day end.minute += 1; end.normalize(true); long formatFlags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR; if (mNumDays != 1) { // Don't show day of the month if for multi-day view formatFlags |= DateUtils.FORMAT_NO_MONTH_DAY; // Abbreviate the month if showing multiple months if (start.month != end.month) { formatFlags |= DateUtils.FORMAT_ABBREV_MONTH; } }
// Path: src/edu/bupt/calendar/CalendarController.java // public interface EventType { // final long CREATE_EVENT = 1L; // // // Simple view of an event // final long VIEW_EVENT = 1L << 1; // // // Full detail view in read only mode // final long VIEW_EVENT_DETAILS = 1L << 2; // // // full detail view in edit mode // final long EDIT_EVENT = 1L << 3; // // final long DELETE_EVENT = 1L << 4; // // final long GO_TO = 1L << 5; // // final long LAUNCH_SETTINGS = 1L << 6; // // final long EVENTS_CHANGED = 1L << 7; // // final long SEARCH = 1L << 8; // // // User has pressed the home key // final long USER_HOME = 1L << 9; // // // date range has changed, update the title // final long UPDATE_TITLE = 1L << 10; // // // select which calendars to display // final long LAUNCH_SELECT_VISIBLE_CALENDARS = 1L << 11; // } // // Path: src/edu/bupt/calendar/CalendarController.java // public interface ViewType { // final int DETAIL = -1; // final int CURRENT = 0; // final int AGENDA = 1; // final int DAY = 2; // final int WEEK = 3; // final int MONTH = 4; // final int EDIT = 5; // } // Path: src/edu/bupt/calendar/DayView.java import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.app.AlertDialog; import android.app.Service; import android.content.ContentResolver; import android.content.ContentUris; import android.content.Context; import android.content.DialogInterface; import android.content.res.Resources; import android.content.res.TypedArray; import android.database.Cursor; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.Paint.Style; import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Handler; import android.provider.CalendarContract.Attendees; import android.provider.CalendarContract.Calendars; import android.provider.CalendarContract.Events; import android.text.Layout.Alignment; import android.text.SpannableStringBuilder; import android.text.StaticLayout; import android.text.TextPaint; import android.text.TextUtils; import android.text.format.DateFormat; import android.text.format.DateUtils; import android.text.format.Time; import android.text.style.StyleSpan; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.GestureDetector; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.WindowManager; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityManager; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.Animation; import android.view.animation.Interpolator; import android.view.animation.TranslateAnimation; import android.widget.EdgeEffect; import android.widget.ImageView; import android.widget.OverScroller; import android.widget.PopupWindow; import android.widget.TextView; import android.widget.ViewSwitcher; import edu.bupt.calendar.CalendarController.EventType; import edu.bupt.calendar.CalendarController.ViewType; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Formatter; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; time.setJulianDay(mSelectionDay); time.hour = mSelectionHour; // We ignore the "isDst" field because we want normalize() to figure // out the correct DST value and not adjust the selected time based // on the current setting of DST. time.normalize(true /* ignore isDst */); return time; } public void updateTitle() { Time start = new Time(mBaseDate); start.normalize(true); Time end = new Time(start); end.monthDay += mNumDays - 1; // Move it forward one minute so the formatter doesn't lose a day end.minute += 1; end.normalize(true); long formatFlags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR; if (mNumDays != 1) { // Don't show day of the month if for multi-day view formatFlags |= DateUtils.FORMAT_NO_MONTH_DAY; // Abbreviate the month if showing multiple months if (start.month != end.month) { formatFlags |= DateUtils.FORMAT_ABBREV_MONTH; } }
mController.sendEvent(this, EventType.UPDATE_TITLE, start, end, null, -1, ViewType.CURRENT,
x7hub/Calendar_lunar
src/edu/bupt/calendar/AsyncQueryService.java
// Path: src/edu/bupt/calendar/AsyncQueryServiceHelper.java // protected static class OperationInfo implements Delayed{ // public int token; // Used for cancel // public int op; // public ContentResolver resolver; // public Uri uri; // public String authority; // public Handler handler; // public String[] projection; // public String selection; // public String[] selectionArgs; // public String orderBy; // public Object result; // public Object cookie; // public ContentValues values; // public ArrayList<ContentProviderOperation> cpo; // // /** // * delayMillis is relative time e.g. 10,000 milliseconds // */ // public long delayMillis; // // /** // * scheduleTimeMillis is the time scheduled for this to be processed. // * e.g. SystemClock.elapsedRealtime() + 10,000 milliseconds Based on // * {@link android.os.SystemClock#elapsedRealtime } // */ // private long mScheduledTimeMillis = 0; // // // @VisibleForTesting // void calculateScheduledTime() { // mScheduledTimeMillis = SystemClock.elapsedRealtime() + delayMillis; // } // // // @Override // Uncomment with Java6 // public long getDelay(TimeUnit unit) { // return unit.convert(mScheduledTimeMillis - SystemClock.elapsedRealtime(), // TimeUnit.MILLISECONDS); // } // // // @Override // Uncomment with Java6 // public int compareTo(Delayed another) { // OperationInfo anotherArgs = (OperationInfo) another; // if (this.mScheduledTimeMillis == anotherArgs.mScheduledTimeMillis) { // return 0; // } else if (this.mScheduledTimeMillis < anotherArgs.mScheduledTimeMillis) { // return -1; // } else { // return 1; // } // } // // @Override // public String toString() { // StringBuilder builder = new StringBuilder(); // builder.append("OperationInfo [\n\t token= "); // builder.append(token); // builder.append(",\n\t op= "); // builder.append(Operation.opToChar(op)); // builder.append(",\n\t uri= "); // builder.append(uri); // builder.append(",\n\t authority= "); // builder.append(authority); // builder.append(",\n\t delayMillis= "); // builder.append(delayMillis); // builder.append(",\n\t mScheduledTimeMillis= "); // builder.append(mScheduledTimeMillis); // builder.append(",\n\t resolver= "); // builder.append(resolver); // builder.append(",\n\t handler= "); // builder.append(handler); // builder.append(",\n\t projection= "); // builder.append(Arrays.toString(projection)); // builder.append(",\n\t selection= "); // builder.append(selection); // builder.append(",\n\t selectionArgs= "); // builder.append(Arrays.toString(selectionArgs)); // builder.append(",\n\t orderBy= "); // builder.append(orderBy); // builder.append(",\n\t result= "); // builder.append(result); // builder.append(",\n\t cookie= "); // builder.append(cookie); // builder.append(",\n\t values= "); // builder.append(values); // builder.append(",\n\t cpo= "); // builder.append(cpo); // builder.append("\n]"); // return builder.toString(); // } // // /** // * Compares an user-visible operation to this private OperationInfo // * object // * // * @param o operation to be compared // * @return true if logically equivalent // */ // public boolean equivalent(Operation o) { // return o.token == this.token && o.op == this.op; // } // }
import java.util.concurrent.atomic.AtomicInteger; import edu.bupt.calendar.AsyncQueryServiceHelper.OperationInfo; import android.content.ContentProviderOperation; import android.content.ContentProviderResult; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.Handler; import android.os.Message; import android.util.Log; import java.util.ArrayList;
*/ public final int cancelOperation(int token) { return AsyncQueryServiceHelper.cancelOperation(token); } /** * This method begins an asynchronous query. When the query is done * {@link #onQueryComplete} is called. * * @param token A token passed into {@link #onQueryComplete} to identify the * query. * @param cookie An object that gets passed into {@link #onQueryComplete} * @param uri The URI, using the content:// scheme, for the content to * retrieve. * @param projection A list of which columns to return. Passing null will * return all columns, which is discouraged to prevent reading * data from storage that isn't going to be used. * @param selection A filter declaring which rows to return, formatted as an * SQL WHERE clause (excluding the WHERE itself). Passing null * will return all rows for the given URI. * @param selectionArgs You may include ?s in selection, which will be * replaced by the values from selectionArgs, in the order that * they appear in the selection. The values will be bound as * Strings. * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause * (excluding the ORDER BY itself). Passing null will use the * default sort order, which may be unordered. */ public void startQuery(int token, Object cookie, Uri uri, String[] projection, String selection, String[] selectionArgs, String orderBy) {
// Path: src/edu/bupt/calendar/AsyncQueryServiceHelper.java // protected static class OperationInfo implements Delayed{ // public int token; // Used for cancel // public int op; // public ContentResolver resolver; // public Uri uri; // public String authority; // public Handler handler; // public String[] projection; // public String selection; // public String[] selectionArgs; // public String orderBy; // public Object result; // public Object cookie; // public ContentValues values; // public ArrayList<ContentProviderOperation> cpo; // // /** // * delayMillis is relative time e.g. 10,000 milliseconds // */ // public long delayMillis; // // /** // * scheduleTimeMillis is the time scheduled for this to be processed. // * e.g. SystemClock.elapsedRealtime() + 10,000 milliseconds Based on // * {@link android.os.SystemClock#elapsedRealtime } // */ // private long mScheduledTimeMillis = 0; // // // @VisibleForTesting // void calculateScheduledTime() { // mScheduledTimeMillis = SystemClock.elapsedRealtime() + delayMillis; // } // // // @Override // Uncomment with Java6 // public long getDelay(TimeUnit unit) { // return unit.convert(mScheduledTimeMillis - SystemClock.elapsedRealtime(), // TimeUnit.MILLISECONDS); // } // // // @Override // Uncomment with Java6 // public int compareTo(Delayed another) { // OperationInfo anotherArgs = (OperationInfo) another; // if (this.mScheduledTimeMillis == anotherArgs.mScheduledTimeMillis) { // return 0; // } else if (this.mScheduledTimeMillis < anotherArgs.mScheduledTimeMillis) { // return -1; // } else { // return 1; // } // } // // @Override // public String toString() { // StringBuilder builder = new StringBuilder(); // builder.append("OperationInfo [\n\t token= "); // builder.append(token); // builder.append(",\n\t op= "); // builder.append(Operation.opToChar(op)); // builder.append(",\n\t uri= "); // builder.append(uri); // builder.append(",\n\t authority= "); // builder.append(authority); // builder.append(",\n\t delayMillis= "); // builder.append(delayMillis); // builder.append(",\n\t mScheduledTimeMillis= "); // builder.append(mScheduledTimeMillis); // builder.append(",\n\t resolver= "); // builder.append(resolver); // builder.append(",\n\t handler= "); // builder.append(handler); // builder.append(",\n\t projection= "); // builder.append(Arrays.toString(projection)); // builder.append(",\n\t selection= "); // builder.append(selection); // builder.append(",\n\t selectionArgs= "); // builder.append(Arrays.toString(selectionArgs)); // builder.append(",\n\t orderBy= "); // builder.append(orderBy); // builder.append(",\n\t result= "); // builder.append(result); // builder.append(",\n\t cookie= "); // builder.append(cookie); // builder.append(",\n\t values= "); // builder.append(values); // builder.append(",\n\t cpo= "); // builder.append(cpo); // builder.append("\n]"); // return builder.toString(); // } // // /** // * Compares an user-visible operation to this private OperationInfo // * object // * // * @param o operation to be compared // * @return true if logically equivalent // */ // public boolean equivalent(Operation o) { // return o.token == this.token && o.op == this.op; // } // } // Path: src/edu/bupt/calendar/AsyncQueryService.java import java.util.concurrent.atomic.AtomicInteger; import edu.bupt.calendar.AsyncQueryServiceHelper.OperationInfo; import android.content.ContentProviderOperation; import android.content.ContentProviderResult; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.Handler; import android.os.Message; import android.util.Log; import java.util.ArrayList; */ public final int cancelOperation(int token) { return AsyncQueryServiceHelper.cancelOperation(token); } /** * This method begins an asynchronous query. When the query is done * {@link #onQueryComplete} is called. * * @param token A token passed into {@link #onQueryComplete} to identify the * query. * @param cookie An object that gets passed into {@link #onQueryComplete} * @param uri The URI, using the content:// scheme, for the content to * retrieve. * @param projection A list of which columns to return. Passing null will * return all columns, which is discouraged to prevent reading * data from storage that isn't going to be used. * @param selection A filter declaring which rows to return, formatted as an * SQL WHERE clause (excluding the WHERE itself). Passing null * will return all rows for the given URI. * @param selectionArgs You may include ?s in selection, which will be * replaced by the values from selectionArgs, in the order that * they appear in the selection. The values will be bound as * Strings. * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause * (excluding the ORDER BY itself). Passing null will use the * default sort order, which may be unordered. */ public void startQuery(int token, Object cookie, Uri uri, String[] projection, String selection, String[] selectionArgs, String orderBy) {
OperationInfo info = new OperationInfo();
x7hub/Calendar_lunar
src/edu/bupt/calendar/event/EventViewUtils.java
// Path: src/edu/bupt/calendar/CalendarEventModel.java // public static class ReminderEntry implements Comparable<ReminderEntry>, Serializable { // private final int mMinutes; // private final int mMethod; // // /** // * Returns a new ReminderEntry, with the specified minutes and method. // * // * @param minutes Number of minutes before the start of the event that the alert will fire. // * @param method Type of alert ({@link Reminders#METHOD_ALERT}, etc). // */ // public static ReminderEntry valueOf(int minutes, int method) { // // TODO: cache common instances // return new ReminderEntry(minutes, method); // } // // /** // * Returns a ReminderEntry, with the specified number of minutes and a default alert method. // * // * @param minutes Number of minutes before the start of the event that the alert will fire. // */ // public static ReminderEntry valueOf(int minutes) { // return valueOf(minutes, Reminders.METHOD_DEFAULT); // } // // /** // * Constructs a new ReminderEntry. // * // * @param minutes Number of minutes before the start of the event that the alert will fire. // * @param method Type of alert ({@link Reminders#METHOD_ALERT}, etc). // */ // private ReminderEntry(int minutes, int method) { // // TODO: error-check args // mMinutes = minutes; // mMethod = method; // } // // @Override // public int hashCode() { // return mMinutes * 10 + mMethod; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (!(obj instanceof ReminderEntry)) { // return false; // } // // ReminderEntry re = (ReminderEntry) obj; // // if (re.mMinutes != mMinutes) { // return false; // } // // // Treat ALERT and DEFAULT as equivalent. This is useful during the "has anything // // "changed" test, so that if DEFAULT is present, but we don't change anything, // // the internal conversion of DEFAULT to ALERT doesn't force a database update. // return re.mMethod == mMethod || // (re.mMethod == Reminders.METHOD_DEFAULT && mMethod == Reminders.METHOD_ALERT) || // (re.mMethod == Reminders.METHOD_ALERT && mMethod == Reminders.METHOD_DEFAULT); // } // // @Override // public String toString() { // return "ReminderEntry min=" + mMinutes + " meth=" + mMethod; // } // // /** // * Comparison function for a sort ordered primarily descending by minutes, // * secondarily ascending by method type. // */ // public int compareTo(ReminderEntry re) { // if (re.mMinutes != mMinutes) { // return re.mMinutes - mMinutes; // } // if (re.mMethod != mMethod) { // return mMethod - re.mMethod; // } // return 0; // } // // /** Returns the minutes. */ // public int getMinutes() { // return mMinutes; // } // // /** Returns the alert method. */ // public int getMethod() { // return mMethod; // } // }
import java.util.ArrayList; import edu.bupt.calendar.CalendarEventModel.ReminderEntry; import edu.bupt.calendar.R; import android.app.Activity; import android.content.Context; import android.content.res.Resources; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.Spinner;
/** * Finds the index of the given method in the "methods" list. If the method isn't present * (perhaps because we don't think it's allowed for this calendar), we return zero (the * first item in the list). * <p> * With the current definitions, this effectively converts DEFAULT and unsupported method * types to ALERT. * * @param values the list of minutes corresponding to the spinner choices * @param method the method to search for in the values list * @return the index of the method in the "values" list */ public static int findMethodInReminderList(ArrayList<Integer> values, int method) { int index = values.indexOf(method); if (index == -1) { // If not allowed, or undefined, just use the first entry in the list. //Log.d(TAG, "Cannot find method (" + method + ") in allowed list"); index = 0; } return index; } /** * Extracts reminder minutes info from UI elements. * * @param reminderItems UI elements (layouts with spinners) that hold array indices. * @param reminderMinuteValues Maps array index to time in minutes. * @param reminderMethodValues Maps array index to alert method constant. * @return Array with reminder data. */
// Path: src/edu/bupt/calendar/CalendarEventModel.java // public static class ReminderEntry implements Comparable<ReminderEntry>, Serializable { // private final int mMinutes; // private final int mMethod; // // /** // * Returns a new ReminderEntry, with the specified minutes and method. // * // * @param minutes Number of minutes before the start of the event that the alert will fire. // * @param method Type of alert ({@link Reminders#METHOD_ALERT}, etc). // */ // public static ReminderEntry valueOf(int minutes, int method) { // // TODO: cache common instances // return new ReminderEntry(minutes, method); // } // // /** // * Returns a ReminderEntry, with the specified number of minutes and a default alert method. // * // * @param minutes Number of minutes before the start of the event that the alert will fire. // */ // public static ReminderEntry valueOf(int minutes) { // return valueOf(minutes, Reminders.METHOD_DEFAULT); // } // // /** // * Constructs a new ReminderEntry. // * // * @param minutes Number of minutes before the start of the event that the alert will fire. // * @param method Type of alert ({@link Reminders#METHOD_ALERT}, etc). // */ // private ReminderEntry(int minutes, int method) { // // TODO: error-check args // mMinutes = minutes; // mMethod = method; // } // // @Override // public int hashCode() { // return mMinutes * 10 + mMethod; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (!(obj instanceof ReminderEntry)) { // return false; // } // // ReminderEntry re = (ReminderEntry) obj; // // if (re.mMinutes != mMinutes) { // return false; // } // // // Treat ALERT and DEFAULT as equivalent. This is useful during the "has anything // // "changed" test, so that if DEFAULT is present, but we don't change anything, // // the internal conversion of DEFAULT to ALERT doesn't force a database update. // return re.mMethod == mMethod || // (re.mMethod == Reminders.METHOD_DEFAULT && mMethod == Reminders.METHOD_ALERT) || // (re.mMethod == Reminders.METHOD_ALERT && mMethod == Reminders.METHOD_DEFAULT); // } // // @Override // public String toString() { // return "ReminderEntry min=" + mMinutes + " meth=" + mMethod; // } // // /** // * Comparison function for a sort ordered primarily descending by minutes, // * secondarily ascending by method type. // */ // public int compareTo(ReminderEntry re) { // if (re.mMinutes != mMinutes) { // return re.mMinutes - mMinutes; // } // if (re.mMethod != mMethod) { // return mMethod - re.mMethod; // } // return 0; // } // // /** Returns the minutes. */ // public int getMinutes() { // return mMinutes; // } // // /** Returns the alert method. */ // public int getMethod() { // return mMethod; // } // } // Path: src/edu/bupt/calendar/event/EventViewUtils.java import java.util.ArrayList; import edu.bupt.calendar.CalendarEventModel.ReminderEntry; import edu.bupt.calendar.R; import android.app.Activity; import android.content.Context; import android.content.res.Resources; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.Spinner; /** * Finds the index of the given method in the "methods" list. If the method isn't present * (perhaps because we don't think it's allowed for this calendar), we return zero (the * first item in the list). * <p> * With the current definitions, this effectively converts DEFAULT and unsupported method * types to ALERT. * * @param values the list of minutes corresponding to the spinner choices * @param method the method to search for in the values list * @return the index of the method in the "values" list */ public static int findMethodInReminderList(ArrayList<Integer> values, int method) { int index = values.indexOf(method); if (index == -1) { // If not allowed, or undefined, just use the first entry in the list. //Log.d(TAG, "Cannot find method (" + method + ") in allowed list"); index = 0; } return index; } /** * Extracts reminder minutes info from UI elements. * * @param reminderItems UI elements (layouts with spinners) that hold array indices. * @param reminderMinuteValues Maps array index to time in minutes. * @param reminderMethodValues Maps array index to alert method constant. * @return Array with reminder data. */
public static ArrayList<ReminderEntry> reminderItemsToReminders(
FlyingPumba/SoundBox
src/com/arcusapp/soundbox/activity/SongsListActivity.java
// Path: src/com/arcusapp/soundbox/SoundBoxApplication.java // public class SoundBoxApplication extends Application { // private static Context appContext; // // public static final String ACTION_MAIN_ACTIVITY = "com.arcusapp.soundbox.action.MAIN_ACTIVITY"; // public static final String ACTION_FOLDERS_ACTIVITY = "com.arcusapp.soundbox.action.FOLDERS_ACTIVITY"; // public static final String ACTION_SONGSLIST_ACTIVITY = "com.arcusapp.soundbox.action.SONGSLIST_ACTIVITY"; // public static final String ACTION_ABOUT_ACTIVITY = "com.arcusapp.soundbox.action.ABOUT_ACTIVITY"; // public static final String ACTION_MEDIA_PLAYER_SERVICE = "com.arcusapp.soundbox.action.MEDIA_PLAYER_SERVICE"; // // private static List<File> sdCards; // // private static int mForegroundActivities = 0; // // @Override // public void onCreate() { // super.onCreate(); // // appContext = getApplicationContext(); // searchForSDCards(); // } // // public static Context getContext() { // return appContext; // } // // public static void notifyForegroundStateChanged(boolean inForeground) { // int old = mForegroundActivities; // if (inForeground) { // mForegroundActivities++; // } else { // mForegroundActivities--; // } // // if (old == 0 || mForegroundActivities == 0) { // Intent intent = new Intent(); // intent.setAction(MediaPlayerService.CHANGE_FOREGROUND_STATE); // intent.putExtra(MediaPlayerService.NOW_IN_FOREGROUND, mForegroundActivities == 0); // appContext.startService(intent); // } // // } // // public static List<File> getSDCards() { // return sdCards; // } // // public static List<File> getDefaultUserDirectoriesOptions() { // List<File> defaultUserOptions = new ArrayList<File>(); // // if(Build.VERSION.SDK_INT > Build.VERSION_CODES.ECLAIR_MR1) { // File musicDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC); // defaultUserOptions.add(musicDirectory); // } // defaultUserOptions.addAll(sdCards); // return defaultUserOptions; // } // // private void searchForSDCards() { // sdCards = new ArrayList<File>(); // File primarysdCard = Environment.getExternalStorageDirectory(); // String[] sdCardDirectories = DirectoryHelper.getStorageDirectories(); // String[] othersdCardDirectories = DirectoryHelper.getOtherStorageDirectories(); // // sdCards.add(primarysdCard); // for (String s : sdCardDirectories) { // File directory = new File(s); // if (!sdCards.contains(directory)) { // sdCards.add(directory); // } // } // for (String s : othersdCardDirectories) { // File directory = new File(s); // if (!sdCards.contains(directory)) { // sdCards.add(directory); // } // } // } // }
import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.Menu; import com.arcusapp.soundbox.R; import com.arcusapp.soundbox.SoundBoxApplication;
/* * SoundBox - Android Music Player * Copyright (C) 2013 Iván Arcuschin Moreno * * This file is part of SoundBox. * * SoundBox is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * SoundBox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SoundBox. If not, see <http://www.gnu.org/licenses/>. */ package com.arcusapp.soundbox.activity; public class SongsListActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_songslist); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. //getMenuInflater().inflate(R.menu.songs_list, menu); return true; } @Override protected void onStart() { super.onStart();
// Path: src/com/arcusapp/soundbox/SoundBoxApplication.java // public class SoundBoxApplication extends Application { // private static Context appContext; // // public static final String ACTION_MAIN_ACTIVITY = "com.arcusapp.soundbox.action.MAIN_ACTIVITY"; // public static final String ACTION_FOLDERS_ACTIVITY = "com.arcusapp.soundbox.action.FOLDERS_ACTIVITY"; // public static final String ACTION_SONGSLIST_ACTIVITY = "com.arcusapp.soundbox.action.SONGSLIST_ACTIVITY"; // public static final String ACTION_ABOUT_ACTIVITY = "com.arcusapp.soundbox.action.ABOUT_ACTIVITY"; // public static final String ACTION_MEDIA_PLAYER_SERVICE = "com.arcusapp.soundbox.action.MEDIA_PLAYER_SERVICE"; // // private static List<File> sdCards; // // private static int mForegroundActivities = 0; // // @Override // public void onCreate() { // super.onCreate(); // // appContext = getApplicationContext(); // searchForSDCards(); // } // // public static Context getContext() { // return appContext; // } // // public static void notifyForegroundStateChanged(boolean inForeground) { // int old = mForegroundActivities; // if (inForeground) { // mForegroundActivities++; // } else { // mForegroundActivities--; // } // // if (old == 0 || mForegroundActivities == 0) { // Intent intent = new Intent(); // intent.setAction(MediaPlayerService.CHANGE_FOREGROUND_STATE); // intent.putExtra(MediaPlayerService.NOW_IN_FOREGROUND, mForegroundActivities == 0); // appContext.startService(intent); // } // // } // // public static List<File> getSDCards() { // return sdCards; // } // // public static List<File> getDefaultUserDirectoriesOptions() { // List<File> defaultUserOptions = new ArrayList<File>(); // // if(Build.VERSION.SDK_INT > Build.VERSION_CODES.ECLAIR_MR1) { // File musicDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC); // defaultUserOptions.add(musicDirectory); // } // defaultUserOptions.addAll(sdCards); // return defaultUserOptions; // } // // private void searchForSDCards() { // sdCards = new ArrayList<File>(); // File primarysdCard = Environment.getExternalStorageDirectory(); // String[] sdCardDirectories = DirectoryHelper.getStorageDirectories(); // String[] othersdCardDirectories = DirectoryHelper.getOtherStorageDirectories(); // // sdCards.add(primarysdCard); // for (String s : sdCardDirectories) { // File directory = new File(s); // if (!sdCards.contains(directory)) { // sdCards.add(directory); // } // } // for (String s : othersdCardDirectories) { // File directory = new File(s); // if (!sdCards.contains(directory)) { // sdCards.add(directory); // } // } // } // } // Path: src/com/arcusapp/soundbox/activity/SongsListActivity.java import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.Menu; import com.arcusapp.soundbox.R; import com.arcusapp.soundbox.SoundBoxApplication; /* * SoundBox - Android Music Player * Copyright (C) 2013 Iván Arcuschin Moreno * * This file is part of SoundBox. * * SoundBox is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * SoundBox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SoundBox. If not, see <http://www.gnu.org/licenses/>. */ package com.arcusapp.soundbox.activity; public class SongsListActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_songslist); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. //getMenuInflater().inflate(R.menu.songs_list, menu); return true; } @Override protected void onStart() { super.onStart();
SoundBoxApplication.notifyForegroundStateChanged(true);
FlyingPumba/SoundBox
src/com/arcusapp/soundbox/data/SoundBoxPreferences.java
// Path: src/com/arcusapp/soundbox/SoundBoxApplication.java // public class SoundBoxApplication extends Application { // private static Context appContext; // // public static final String ACTION_MAIN_ACTIVITY = "com.arcusapp.soundbox.action.MAIN_ACTIVITY"; // public static final String ACTION_FOLDERS_ACTIVITY = "com.arcusapp.soundbox.action.FOLDERS_ACTIVITY"; // public static final String ACTION_SONGSLIST_ACTIVITY = "com.arcusapp.soundbox.action.SONGSLIST_ACTIVITY"; // public static final String ACTION_ABOUT_ACTIVITY = "com.arcusapp.soundbox.action.ABOUT_ACTIVITY"; // public static final String ACTION_MEDIA_PLAYER_SERVICE = "com.arcusapp.soundbox.action.MEDIA_PLAYER_SERVICE"; // // private static List<File> sdCards; // // private static int mForegroundActivities = 0; // // @Override // public void onCreate() { // super.onCreate(); // // appContext = getApplicationContext(); // searchForSDCards(); // } // // public static Context getContext() { // return appContext; // } // // public static void notifyForegroundStateChanged(boolean inForeground) { // int old = mForegroundActivities; // if (inForeground) { // mForegroundActivities++; // } else { // mForegroundActivities--; // } // // if (old == 0 || mForegroundActivities == 0) { // Intent intent = new Intent(); // intent.setAction(MediaPlayerService.CHANGE_FOREGROUND_STATE); // intent.putExtra(MediaPlayerService.NOW_IN_FOREGROUND, mForegroundActivities == 0); // appContext.startService(intent); // } // // } // // public static List<File> getSDCards() { // return sdCards; // } // // public static List<File> getDefaultUserDirectoriesOptions() { // List<File> defaultUserOptions = new ArrayList<File>(); // // if(Build.VERSION.SDK_INT > Build.VERSION_CODES.ECLAIR_MR1) { // File musicDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC); // defaultUserOptions.add(musicDirectory); // } // defaultUserOptions.addAll(sdCards); // return defaultUserOptions; // } // // private void searchForSDCards() { // sdCards = new ArrayList<File>(); // File primarysdCard = Environment.getExternalStorageDirectory(); // String[] sdCardDirectories = DirectoryHelper.getStorageDirectories(); // String[] othersdCardDirectories = DirectoryHelper.getOtherStorageDirectories(); // // sdCards.add(primarysdCard); // for (String s : sdCardDirectories) { // File directory = new File(s); // if (!sdCards.contains(directory)) { // sdCards.add(directory); // } // } // for (String s : othersdCardDirectories) { // File directory = new File(s); // if (!sdCards.contains(directory)) { // sdCards.add(directory); // } // } // } // } // // Path: src/com/arcusapp/soundbox/model/BundleExtra.java // public class BundleExtra { // public final static String CURRENT_ID = "currentid"; // public final static String SONGS_ID_LIST = "songsidlist"; // // public class DefaultValues { // public final static String DEFAULT_ID = "-1"; // } // // public static String getBundleString(Bundle b, String key, String def) { // String value = b.getString(key); // if(value == null) { // value = def; // } // return value; // } // }
import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.arcusapp.soundbox.SoundBoxApplication; import com.arcusapp.soundbox.model.BundleExtra; import org.json.JSONArray; import java.util.ArrayList; import java.util.List;
/* * SoundBox - Android Music Player * Copyright (C) 2013 Iván Arcuschin Moreno * * This file is part of SoundBox. * * SoundBox is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * SoundBox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SoundBox. If not, see <http://www.gnu.org/licenses/>. */ package com.arcusapp.soundbox.data; public class SoundBoxPreferences { private final static String LAST_SONGS = "lastsongs"; private final static String LAST_PLAYED_SONG = "lastplayedsong"; public static class LastSongs { public static List<String> getLastSongs() {
// Path: src/com/arcusapp/soundbox/SoundBoxApplication.java // public class SoundBoxApplication extends Application { // private static Context appContext; // // public static final String ACTION_MAIN_ACTIVITY = "com.arcusapp.soundbox.action.MAIN_ACTIVITY"; // public static final String ACTION_FOLDERS_ACTIVITY = "com.arcusapp.soundbox.action.FOLDERS_ACTIVITY"; // public static final String ACTION_SONGSLIST_ACTIVITY = "com.arcusapp.soundbox.action.SONGSLIST_ACTIVITY"; // public static final String ACTION_ABOUT_ACTIVITY = "com.arcusapp.soundbox.action.ABOUT_ACTIVITY"; // public static final String ACTION_MEDIA_PLAYER_SERVICE = "com.arcusapp.soundbox.action.MEDIA_PLAYER_SERVICE"; // // private static List<File> sdCards; // // private static int mForegroundActivities = 0; // // @Override // public void onCreate() { // super.onCreate(); // // appContext = getApplicationContext(); // searchForSDCards(); // } // // public static Context getContext() { // return appContext; // } // // public static void notifyForegroundStateChanged(boolean inForeground) { // int old = mForegroundActivities; // if (inForeground) { // mForegroundActivities++; // } else { // mForegroundActivities--; // } // // if (old == 0 || mForegroundActivities == 0) { // Intent intent = new Intent(); // intent.setAction(MediaPlayerService.CHANGE_FOREGROUND_STATE); // intent.putExtra(MediaPlayerService.NOW_IN_FOREGROUND, mForegroundActivities == 0); // appContext.startService(intent); // } // // } // // public static List<File> getSDCards() { // return sdCards; // } // // public static List<File> getDefaultUserDirectoriesOptions() { // List<File> defaultUserOptions = new ArrayList<File>(); // // if(Build.VERSION.SDK_INT > Build.VERSION_CODES.ECLAIR_MR1) { // File musicDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC); // defaultUserOptions.add(musicDirectory); // } // defaultUserOptions.addAll(sdCards); // return defaultUserOptions; // } // // private void searchForSDCards() { // sdCards = new ArrayList<File>(); // File primarysdCard = Environment.getExternalStorageDirectory(); // String[] sdCardDirectories = DirectoryHelper.getStorageDirectories(); // String[] othersdCardDirectories = DirectoryHelper.getOtherStorageDirectories(); // // sdCards.add(primarysdCard); // for (String s : sdCardDirectories) { // File directory = new File(s); // if (!sdCards.contains(directory)) { // sdCards.add(directory); // } // } // for (String s : othersdCardDirectories) { // File directory = new File(s); // if (!sdCards.contains(directory)) { // sdCards.add(directory); // } // } // } // } // // Path: src/com/arcusapp/soundbox/model/BundleExtra.java // public class BundleExtra { // public final static String CURRENT_ID = "currentid"; // public final static String SONGS_ID_LIST = "songsidlist"; // // public class DefaultValues { // public final static String DEFAULT_ID = "-1"; // } // // public static String getBundleString(Bundle b, String key, String def) { // String value = b.getString(key); // if(value == null) { // value = def; // } // return value; // } // } // Path: src/com/arcusapp/soundbox/data/SoundBoxPreferences.java import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.arcusapp.soundbox.SoundBoxApplication; import com.arcusapp.soundbox.model.BundleExtra; import org.json.JSONArray; import java.util.ArrayList; import java.util.List; /* * SoundBox - Android Music Player * Copyright (C) 2013 Iván Arcuschin Moreno * * This file is part of SoundBox. * * SoundBox is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * SoundBox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SoundBox. If not, see <http://www.gnu.org/licenses/>. */ package com.arcusapp.soundbox.data; public class SoundBoxPreferences { private final static String LAST_SONGS = "lastsongs"; private final static String LAST_PLAYED_SONG = "lastplayedsong"; public static class LastSongs { public static List<String> getLastSongs() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(SoundBoxApplication.getContext());
FlyingPumba/SoundBox
src/com/arcusapp/soundbox/data/SoundBoxPreferences.java
// Path: src/com/arcusapp/soundbox/SoundBoxApplication.java // public class SoundBoxApplication extends Application { // private static Context appContext; // // public static final String ACTION_MAIN_ACTIVITY = "com.arcusapp.soundbox.action.MAIN_ACTIVITY"; // public static final String ACTION_FOLDERS_ACTIVITY = "com.arcusapp.soundbox.action.FOLDERS_ACTIVITY"; // public static final String ACTION_SONGSLIST_ACTIVITY = "com.arcusapp.soundbox.action.SONGSLIST_ACTIVITY"; // public static final String ACTION_ABOUT_ACTIVITY = "com.arcusapp.soundbox.action.ABOUT_ACTIVITY"; // public static final String ACTION_MEDIA_PLAYER_SERVICE = "com.arcusapp.soundbox.action.MEDIA_PLAYER_SERVICE"; // // private static List<File> sdCards; // // private static int mForegroundActivities = 0; // // @Override // public void onCreate() { // super.onCreate(); // // appContext = getApplicationContext(); // searchForSDCards(); // } // // public static Context getContext() { // return appContext; // } // // public static void notifyForegroundStateChanged(boolean inForeground) { // int old = mForegroundActivities; // if (inForeground) { // mForegroundActivities++; // } else { // mForegroundActivities--; // } // // if (old == 0 || mForegroundActivities == 0) { // Intent intent = new Intent(); // intent.setAction(MediaPlayerService.CHANGE_FOREGROUND_STATE); // intent.putExtra(MediaPlayerService.NOW_IN_FOREGROUND, mForegroundActivities == 0); // appContext.startService(intent); // } // // } // // public static List<File> getSDCards() { // return sdCards; // } // // public static List<File> getDefaultUserDirectoriesOptions() { // List<File> defaultUserOptions = new ArrayList<File>(); // // if(Build.VERSION.SDK_INT > Build.VERSION_CODES.ECLAIR_MR1) { // File musicDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC); // defaultUserOptions.add(musicDirectory); // } // defaultUserOptions.addAll(sdCards); // return defaultUserOptions; // } // // private void searchForSDCards() { // sdCards = new ArrayList<File>(); // File primarysdCard = Environment.getExternalStorageDirectory(); // String[] sdCardDirectories = DirectoryHelper.getStorageDirectories(); // String[] othersdCardDirectories = DirectoryHelper.getOtherStorageDirectories(); // // sdCards.add(primarysdCard); // for (String s : sdCardDirectories) { // File directory = new File(s); // if (!sdCards.contains(directory)) { // sdCards.add(directory); // } // } // for (String s : othersdCardDirectories) { // File directory = new File(s); // if (!sdCards.contains(directory)) { // sdCards.add(directory); // } // } // } // } // // Path: src/com/arcusapp/soundbox/model/BundleExtra.java // public class BundleExtra { // public final static String CURRENT_ID = "currentid"; // public final static String SONGS_ID_LIST = "songsidlist"; // // public class DefaultValues { // public final static String DEFAULT_ID = "-1"; // } // // public static String getBundleString(Bundle b, String key, String def) { // String value = b.getString(key); // if(value == null) { // value = def; // } // return value; // } // }
import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.arcusapp.soundbox.SoundBoxApplication; import com.arcusapp.soundbox.model.BundleExtra; import org.json.JSONArray; import java.util.ArrayList; import java.util.List;
/* * SoundBox - Android Music Player * Copyright (C) 2013 Iván Arcuschin Moreno * * This file is part of SoundBox. * * SoundBox is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * SoundBox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SoundBox. If not, see <http://www.gnu.org/licenses/>. */ package com.arcusapp.soundbox.data; public class SoundBoxPreferences { private final static String LAST_SONGS = "lastsongs"; private final static String LAST_PLAYED_SONG = "lastplayedsong"; public static class LastSongs { public static List<String> getLastSongs() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(SoundBoxApplication.getContext()); List<String> songs = new ArrayList<String>(); try { JSONArray jsonArray = new JSONArray(preferences.getString(LAST_SONGS, null)); for (int i = 0; i <= jsonArray.length(); i++) { songs.add(jsonArray.getString(i)); } } catch (Exception e) { } return songs; } public static void setLastSongs(List<String> songsID) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(SoundBoxApplication.getContext()); SharedPreferences.Editor editor = preferences.edit(); String serializedString = new JSONArray(songsID).toString(); editor.putString(LAST_SONGS, serializedString); editor.commit(); } } public static class LastPlayedSong { public static String getLastPlayedSong() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(SoundBoxApplication.getContext());
// Path: src/com/arcusapp/soundbox/SoundBoxApplication.java // public class SoundBoxApplication extends Application { // private static Context appContext; // // public static final String ACTION_MAIN_ACTIVITY = "com.arcusapp.soundbox.action.MAIN_ACTIVITY"; // public static final String ACTION_FOLDERS_ACTIVITY = "com.arcusapp.soundbox.action.FOLDERS_ACTIVITY"; // public static final String ACTION_SONGSLIST_ACTIVITY = "com.arcusapp.soundbox.action.SONGSLIST_ACTIVITY"; // public static final String ACTION_ABOUT_ACTIVITY = "com.arcusapp.soundbox.action.ABOUT_ACTIVITY"; // public static final String ACTION_MEDIA_PLAYER_SERVICE = "com.arcusapp.soundbox.action.MEDIA_PLAYER_SERVICE"; // // private static List<File> sdCards; // // private static int mForegroundActivities = 0; // // @Override // public void onCreate() { // super.onCreate(); // // appContext = getApplicationContext(); // searchForSDCards(); // } // // public static Context getContext() { // return appContext; // } // // public static void notifyForegroundStateChanged(boolean inForeground) { // int old = mForegroundActivities; // if (inForeground) { // mForegroundActivities++; // } else { // mForegroundActivities--; // } // // if (old == 0 || mForegroundActivities == 0) { // Intent intent = new Intent(); // intent.setAction(MediaPlayerService.CHANGE_FOREGROUND_STATE); // intent.putExtra(MediaPlayerService.NOW_IN_FOREGROUND, mForegroundActivities == 0); // appContext.startService(intent); // } // // } // // public static List<File> getSDCards() { // return sdCards; // } // // public static List<File> getDefaultUserDirectoriesOptions() { // List<File> defaultUserOptions = new ArrayList<File>(); // // if(Build.VERSION.SDK_INT > Build.VERSION_CODES.ECLAIR_MR1) { // File musicDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC); // defaultUserOptions.add(musicDirectory); // } // defaultUserOptions.addAll(sdCards); // return defaultUserOptions; // } // // private void searchForSDCards() { // sdCards = new ArrayList<File>(); // File primarysdCard = Environment.getExternalStorageDirectory(); // String[] sdCardDirectories = DirectoryHelper.getStorageDirectories(); // String[] othersdCardDirectories = DirectoryHelper.getOtherStorageDirectories(); // // sdCards.add(primarysdCard); // for (String s : sdCardDirectories) { // File directory = new File(s); // if (!sdCards.contains(directory)) { // sdCards.add(directory); // } // } // for (String s : othersdCardDirectories) { // File directory = new File(s); // if (!sdCards.contains(directory)) { // sdCards.add(directory); // } // } // } // } // // Path: src/com/arcusapp/soundbox/model/BundleExtra.java // public class BundleExtra { // public final static String CURRENT_ID = "currentid"; // public final static String SONGS_ID_LIST = "songsidlist"; // // public class DefaultValues { // public final static String DEFAULT_ID = "-1"; // } // // public static String getBundleString(Bundle b, String key, String def) { // String value = b.getString(key); // if(value == null) { // value = def; // } // return value; // } // } // Path: src/com/arcusapp/soundbox/data/SoundBoxPreferences.java import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.arcusapp.soundbox.SoundBoxApplication; import com.arcusapp.soundbox.model.BundleExtra; import org.json.JSONArray; import java.util.ArrayList; import java.util.List; /* * SoundBox - Android Music Player * Copyright (C) 2013 Iván Arcuschin Moreno * * This file is part of SoundBox. * * SoundBox is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * SoundBox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SoundBox. If not, see <http://www.gnu.org/licenses/>. */ package com.arcusapp.soundbox.data; public class SoundBoxPreferences { private final static String LAST_SONGS = "lastsongs"; private final static String LAST_PLAYED_SONG = "lastplayedsong"; public static class LastSongs { public static List<String> getLastSongs() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(SoundBoxApplication.getContext()); List<String> songs = new ArrayList<String>(); try { JSONArray jsonArray = new JSONArray(preferences.getString(LAST_SONGS, null)); for (int i = 0; i <= jsonArray.length(); i++) { songs.add(jsonArray.getString(i)); } } catch (Exception e) { } return songs; } public static void setLastSongs(List<String> songsID) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(SoundBoxApplication.getContext()); SharedPreferences.Editor editor = preferences.edit(); String serializedString = new JSONArray(songsID).toString(); editor.putString(LAST_SONGS, serializedString); editor.commit(); } } public static class LastPlayedSong { public static String getLastPlayedSong() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(SoundBoxApplication.getContext());
return preferences.getString(LAST_PLAYED_SONG, BundleExtra.DefaultValues.DEFAULT_ID);
FlyingPumba/SoundBox
src/com/arcusapp/soundbox/activity/AboutActivity.java
// Path: src/com/arcusapp/soundbox/SoundBoxApplication.java // public class SoundBoxApplication extends Application { // private static Context appContext; // // public static final String ACTION_MAIN_ACTIVITY = "com.arcusapp.soundbox.action.MAIN_ACTIVITY"; // public static final String ACTION_FOLDERS_ACTIVITY = "com.arcusapp.soundbox.action.FOLDERS_ACTIVITY"; // public static final String ACTION_SONGSLIST_ACTIVITY = "com.arcusapp.soundbox.action.SONGSLIST_ACTIVITY"; // public static final String ACTION_ABOUT_ACTIVITY = "com.arcusapp.soundbox.action.ABOUT_ACTIVITY"; // public static final String ACTION_MEDIA_PLAYER_SERVICE = "com.arcusapp.soundbox.action.MEDIA_PLAYER_SERVICE"; // // private static List<File> sdCards; // // private static int mForegroundActivities = 0; // // @Override // public void onCreate() { // super.onCreate(); // // appContext = getApplicationContext(); // searchForSDCards(); // } // // public static Context getContext() { // return appContext; // } // // public static void notifyForegroundStateChanged(boolean inForeground) { // int old = mForegroundActivities; // if (inForeground) { // mForegroundActivities++; // } else { // mForegroundActivities--; // } // // if (old == 0 || mForegroundActivities == 0) { // Intent intent = new Intent(); // intent.setAction(MediaPlayerService.CHANGE_FOREGROUND_STATE); // intent.putExtra(MediaPlayerService.NOW_IN_FOREGROUND, mForegroundActivities == 0); // appContext.startService(intent); // } // // } // // public static List<File> getSDCards() { // return sdCards; // } // // public static List<File> getDefaultUserDirectoriesOptions() { // List<File> defaultUserOptions = new ArrayList<File>(); // // if(Build.VERSION.SDK_INT > Build.VERSION_CODES.ECLAIR_MR1) { // File musicDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC); // defaultUserOptions.add(musicDirectory); // } // defaultUserOptions.addAll(sdCards); // return defaultUserOptions; // } // // private void searchForSDCards() { // sdCards = new ArrayList<File>(); // File primarysdCard = Environment.getExternalStorageDirectory(); // String[] sdCardDirectories = DirectoryHelper.getStorageDirectories(); // String[] othersdCardDirectories = DirectoryHelper.getOtherStorageDirectories(); // // sdCards.add(primarysdCard); // for (String s : sdCardDirectories) { // File directory = new File(s); // if (!sdCards.contains(directory)) { // sdCards.add(directory); // } // } // for (String s : othersdCardDirectories) { // File directory = new File(s); // if (!sdCards.contains(directory)) { // sdCards.add(directory); // } // } // } // }
import com.arcusapp.soundbox.R; import com.arcusapp.soundbox.SoundBoxApplication; import android.app.AlertDialog; import android.content.Intent; import android.content.pm.PackageInfo; import android.net.Uri; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity; import android.webkit.WebView; import android.widget.Toast;
/* * SoundBox - Android Music Player * Copyright (C) 2013 Iván Arcuschin Moreno * * This file is part of SoundBox. * * SoundBox is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * SoundBox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SoundBox. If not, see <http://www.gnu.org/licenses/>. */ package com.arcusapp.soundbox.activity; public class AboutActivity extends PreferenceActivity { @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Add the preferences addPreferencesFromResource(R.xml.about); showOpenSourceLicenses(); seeOnGitHub(); try{ final PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0); findPreference("version").setSummary(packageInfo.versionName + " " +packageInfo.versionCode); } catch (Exception ex) { Toast.makeText(this, getString(R.string.ErrorFetchingVersion), Toast.LENGTH_LONG); findPreference("version").setSummary("?"); } } @Override protected void onStart() { super.onStart();
// Path: src/com/arcusapp/soundbox/SoundBoxApplication.java // public class SoundBoxApplication extends Application { // private static Context appContext; // // public static final String ACTION_MAIN_ACTIVITY = "com.arcusapp.soundbox.action.MAIN_ACTIVITY"; // public static final String ACTION_FOLDERS_ACTIVITY = "com.arcusapp.soundbox.action.FOLDERS_ACTIVITY"; // public static final String ACTION_SONGSLIST_ACTIVITY = "com.arcusapp.soundbox.action.SONGSLIST_ACTIVITY"; // public static final String ACTION_ABOUT_ACTIVITY = "com.arcusapp.soundbox.action.ABOUT_ACTIVITY"; // public static final String ACTION_MEDIA_PLAYER_SERVICE = "com.arcusapp.soundbox.action.MEDIA_PLAYER_SERVICE"; // // private static List<File> sdCards; // // private static int mForegroundActivities = 0; // // @Override // public void onCreate() { // super.onCreate(); // // appContext = getApplicationContext(); // searchForSDCards(); // } // // public static Context getContext() { // return appContext; // } // // public static void notifyForegroundStateChanged(boolean inForeground) { // int old = mForegroundActivities; // if (inForeground) { // mForegroundActivities++; // } else { // mForegroundActivities--; // } // // if (old == 0 || mForegroundActivities == 0) { // Intent intent = new Intent(); // intent.setAction(MediaPlayerService.CHANGE_FOREGROUND_STATE); // intent.putExtra(MediaPlayerService.NOW_IN_FOREGROUND, mForegroundActivities == 0); // appContext.startService(intent); // } // // } // // public static List<File> getSDCards() { // return sdCards; // } // // public static List<File> getDefaultUserDirectoriesOptions() { // List<File> defaultUserOptions = new ArrayList<File>(); // // if(Build.VERSION.SDK_INT > Build.VERSION_CODES.ECLAIR_MR1) { // File musicDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC); // defaultUserOptions.add(musicDirectory); // } // defaultUserOptions.addAll(sdCards); // return defaultUserOptions; // } // // private void searchForSDCards() { // sdCards = new ArrayList<File>(); // File primarysdCard = Environment.getExternalStorageDirectory(); // String[] sdCardDirectories = DirectoryHelper.getStorageDirectories(); // String[] othersdCardDirectories = DirectoryHelper.getOtherStorageDirectories(); // // sdCards.add(primarysdCard); // for (String s : sdCardDirectories) { // File directory = new File(s); // if (!sdCards.contains(directory)) { // sdCards.add(directory); // } // } // for (String s : othersdCardDirectories) { // File directory = new File(s); // if (!sdCards.contains(directory)) { // sdCards.add(directory); // } // } // } // } // Path: src/com/arcusapp/soundbox/activity/AboutActivity.java import com.arcusapp.soundbox.R; import com.arcusapp.soundbox.SoundBoxApplication; import android.app.AlertDialog; import android.content.Intent; import android.content.pm.PackageInfo; import android.net.Uri; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity; import android.webkit.WebView; import android.widget.Toast; /* * SoundBox - Android Music Player * Copyright (C) 2013 Iván Arcuschin Moreno * * This file is part of SoundBox. * * SoundBox is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * SoundBox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SoundBox. If not, see <http://www.gnu.org/licenses/>. */ package com.arcusapp.soundbox.activity; public class AboutActivity extends PreferenceActivity { @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Add the preferences addPreferencesFromResource(R.xml.about); showOpenSourceLicenses(); seeOnGitHub(); try{ final PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0); findPreference("version").setSummary(packageInfo.versionName + " " +packageInfo.versionCode); } catch (Exception ex) { Toast.makeText(this, getString(R.string.ErrorFetchingVersion), Toast.LENGTH_LONG); findPreference("version").setSummary("?"); } } @Override protected void onStart() { super.onStart();
SoundBoxApplication.notifyForegroundStateChanged(true);
Sage-Bionetworks/BridgePF
test/org/sagebionetworks/bridge/play/controllers/ActivityEventControllerTest.java
// Path: test/org/sagebionetworks/bridge/TestConstants.java // public class TestConstants { // // public static final String ENCRYPTED_HEALTH_CODE = "TFMkaVFKPD48WissX0bgcD3esBMEshxb3MVgKxHnkXLSEPN4FQMKc01tDbBAVcXx94kMX6ckXVYUZ8wx4iICl08uE+oQr9gorE1hlgAyLAM="; // // public static final String TEST_STUDY_IDENTIFIER = "api"; // public static final StudyIdentifier TEST_STUDY = new StudyIdentifierImpl(TEST_STUDY_IDENTIFIER); // public static final CriteriaContext TEST_CONTEXT = new CriteriaContext.Builder() // .withUserId("user-id").withStudyIdentifier(TestConstants.TEST_STUDY).build(); // // public static final String EMAIL = "email@email.com"; // public static final String PASSWORD = "password"; // // /** // * During tests, must sometimes pause because the underlying query uses a DynamoDB global // * secondary index, and this does not currently support consistent reads. // */ // public static final int GSI_WAIT_DURATION = 2000; // // public static final ConsentStatus REQUIRED_SIGNED_CURRENT = new ConsentStatus.Builder().withName("Name1") // .withGuid(SubpopulationGuid.create("foo1")).withRequired(true).withConsented(true) // .withSignedMostRecentConsent(true).build(); // public static final ConsentStatus REQUIRED_UNSIGNED = new ConsentStatus.Builder().withName("Name1") // .withGuid(SubpopulationGuid.create("foo5")).withRequired(true).withConsented(false) // .withSignedMostRecentConsent(false).build(); // // public static final Map<SubpopulationGuid, ConsentStatus> UNCONSENTED_STATUS_MAP = new ImmutableMap.Builder<SubpopulationGuid, ConsentStatus>() // .put(SubpopulationGuid.create(REQUIRED_UNSIGNED.getSubpopulationGuid()), REQUIRED_UNSIGNED).build(); // // public static final Set<String> USER_DATA_GROUPS = ImmutableSet.of("group1","group2"); // // public static final Set<String> USER_SUBSTUDY_IDS = ImmutableSet.of("substudyA","substudyB"); // // public static final List<String> LANGUAGES = ImmutableList.of("en","fr"); // // public static final Phone PHONE = new Phone("9712486796", "US"); // // public static final AndroidAppLink ANDROID_APP_LINK = new AndroidAppLink("namespace", "package_name", // Lists.newArrayList("sha256_cert_fingerprints")); // public static final AndroidAppLink ANDROID_APP_LINK_2 = new AndroidAppLink("namespace2", "package_name2", // Lists.newArrayList("sha256_cert_fingerprints2")); // public static final AndroidAppLink ANDROID_APP_LINK_3 = new AndroidAppLink("namespace3", "package_name3", // Lists.newArrayList("sha256_cert_fingerprints3")); // public static final AndroidAppLink ANDROID_APP_LINK_4 = new AndroidAppLink("namespace4", "package_name4", // Lists.newArrayList("sha256_cert_fingerprints4")); // public static final AppleAppLink APPLE_APP_LINK = new AppleAppLink("studyId", // Lists.newArrayList("/appId/", "/appId/*")); // public static final AppleAppLink APPLE_APP_LINK_2 = new AppleAppLink("studyId2", // Lists.newArrayList("/appId2/", "/appId2/*")); // public static final AppleAppLink APPLE_APP_LINK_3 = new AppleAppLink("studyId3", // Lists.newArrayList("/appId3/", "/appId3/*")); // public static final AppleAppLink APPLE_APP_LINK_4 = new AppleAppLink("studyId4", // Lists.newArrayList("/appId4/", "/appId4/*")); // // }
import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.same; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.joda.time.DateTime; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import play.mvc.Result; import org.sagebionetworks.bridge.TestConstants; import org.sagebionetworks.bridge.TestUtils; import org.sagebionetworks.bridge.models.accounts.UserSession; import org.sagebionetworks.bridge.models.studies.Study; import org.sagebionetworks.bridge.services.ActivityEventService; import org.sagebionetworks.bridge.services.StudyService;
package org.sagebionetworks.bridge.play.controllers; public class ActivityEventControllerTest { private static final Study DUMMY_STUDY = Study.create(); private static final String HEALTH_CODE = "my-health-code"; private static final String EVENT_KEY = "my-event"; private static final String EVENT_TIMESTAMP_STRING = "2018-04-04T16:43:11.357-0700"; private static final DateTime EVENT_TIMESTAMP = DateTime.parse(EVENT_TIMESTAMP_STRING); private ActivityEventController controller; private ActivityEventService mockActivityEventService; @Before public void setup() { // Mock services mockActivityEventService = mock(ActivityEventService.class); StudyService mockStudyService = mock(StudyService.class);
// Path: test/org/sagebionetworks/bridge/TestConstants.java // public class TestConstants { // // public static final String ENCRYPTED_HEALTH_CODE = "TFMkaVFKPD48WissX0bgcD3esBMEshxb3MVgKxHnkXLSEPN4FQMKc01tDbBAVcXx94kMX6ckXVYUZ8wx4iICl08uE+oQr9gorE1hlgAyLAM="; // // public static final String TEST_STUDY_IDENTIFIER = "api"; // public static final StudyIdentifier TEST_STUDY = new StudyIdentifierImpl(TEST_STUDY_IDENTIFIER); // public static final CriteriaContext TEST_CONTEXT = new CriteriaContext.Builder() // .withUserId("user-id").withStudyIdentifier(TestConstants.TEST_STUDY).build(); // // public static final String EMAIL = "email@email.com"; // public static final String PASSWORD = "password"; // // /** // * During tests, must sometimes pause because the underlying query uses a DynamoDB global // * secondary index, and this does not currently support consistent reads. // */ // public static final int GSI_WAIT_DURATION = 2000; // // public static final ConsentStatus REQUIRED_SIGNED_CURRENT = new ConsentStatus.Builder().withName("Name1") // .withGuid(SubpopulationGuid.create("foo1")).withRequired(true).withConsented(true) // .withSignedMostRecentConsent(true).build(); // public static final ConsentStatus REQUIRED_UNSIGNED = new ConsentStatus.Builder().withName("Name1") // .withGuid(SubpopulationGuid.create("foo5")).withRequired(true).withConsented(false) // .withSignedMostRecentConsent(false).build(); // // public static final Map<SubpopulationGuid, ConsentStatus> UNCONSENTED_STATUS_MAP = new ImmutableMap.Builder<SubpopulationGuid, ConsentStatus>() // .put(SubpopulationGuid.create(REQUIRED_UNSIGNED.getSubpopulationGuid()), REQUIRED_UNSIGNED).build(); // // public static final Set<String> USER_DATA_GROUPS = ImmutableSet.of("group1","group2"); // // public static final Set<String> USER_SUBSTUDY_IDS = ImmutableSet.of("substudyA","substudyB"); // // public static final List<String> LANGUAGES = ImmutableList.of("en","fr"); // // public static final Phone PHONE = new Phone("9712486796", "US"); // // public static final AndroidAppLink ANDROID_APP_LINK = new AndroidAppLink("namespace", "package_name", // Lists.newArrayList("sha256_cert_fingerprints")); // public static final AndroidAppLink ANDROID_APP_LINK_2 = new AndroidAppLink("namespace2", "package_name2", // Lists.newArrayList("sha256_cert_fingerprints2")); // public static final AndroidAppLink ANDROID_APP_LINK_3 = new AndroidAppLink("namespace3", "package_name3", // Lists.newArrayList("sha256_cert_fingerprints3")); // public static final AndroidAppLink ANDROID_APP_LINK_4 = new AndroidAppLink("namespace4", "package_name4", // Lists.newArrayList("sha256_cert_fingerprints4")); // public static final AppleAppLink APPLE_APP_LINK = new AppleAppLink("studyId", // Lists.newArrayList("/appId/", "/appId/*")); // public static final AppleAppLink APPLE_APP_LINK_2 = new AppleAppLink("studyId2", // Lists.newArrayList("/appId2/", "/appId2/*")); // public static final AppleAppLink APPLE_APP_LINK_3 = new AppleAppLink("studyId3", // Lists.newArrayList("/appId3/", "/appId3/*")); // public static final AppleAppLink APPLE_APP_LINK_4 = new AppleAppLink("studyId4", // Lists.newArrayList("/appId4/", "/appId4/*")); // // } // Path: test/org/sagebionetworks/bridge/play/controllers/ActivityEventControllerTest.java import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.same; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.joda.time.DateTime; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import play.mvc.Result; import org.sagebionetworks.bridge.TestConstants; import org.sagebionetworks.bridge.TestUtils; import org.sagebionetworks.bridge.models.accounts.UserSession; import org.sagebionetworks.bridge.models.studies.Study; import org.sagebionetworks.bridge.services.ActivityEventService; import org.sagebionetworks.bridge.services.StudyService; package org.sagebionetworks.bridge.play.controllers; public class ActivityEventControllerTest { private static final Study DUMMY_STUDY = Study.create(); private static final String HEALTH_CODE = "my-health-code"; private static final String EVENT_KEY = "my-event"; private static final String EVENT_TIMESTAMP_STRING = "2018-04-04T16:43:11.357-0700"; private static final DateTime EVENT_TIMESTAMP = DateTime.parse(EVENT_TIMESTAMP_STRING); private ActivityEventController controller; private ActivityEventService mockActivityEventService; @Before public void setup() { // Mock services mockActivityEventService = mock(ActivityEventService.class); StudyService mockStudyService = mock(StudyService.class);
when(mockStudyService.getStudy(TestConstants.TEST_STUDY)).thenReturn(DUMMY_STUDY);
Sage-Bionetworks/BridgePF
test/org/sagebionetworks/bridge/play/controllers/SchedulePlanControllerMockTest.java
// Path: test/org/sagebionetworks/bridge/TestConstants.java // public class TestConstants { // // public static final String ENCRYPTED_HEALTH_CODE = "TFMkaVFKPD48WissX0bgcD3esBMEshxb3MVgKxHnkXLSEPN4FQMKc01tDbBAVcXx94kMX6ckXVYUZ8wx4iICl08uE+oQr9gorE1hlgAyLAM="; // // public static final String TEST_STUDY_IDENTIFIER = "api"; // public static final StudyIdentifier TEST_STUDY = new StudyIdentifierImpl(TEST_STUDY_IDENTIFIER); // public static final CriteriaContext TEST_CONTEXT = new CriteriaContext.Builder() // .withUserId("user-id").withStudyIdentifier(TestConstants.TEST_STUDY).build(); // // public static final String EMAIL = "email@email.com"; // public static final String PASSWORD = "password"; // // /** // * During tests, must sometimes pause because the underlying query uses a DynamoDB global // * secondary index, and this does not currently support consistent reads. // */ // public static final int GSI_WAIT_DURATION = 2000; // // public static final ConsentStatus REQUIRED_SIGNED_CURRENT = new ConsentStatus.Builder().withName("Name1") // .withGuid(SubpopulationGuid.create("foo1")).withRequired(true).withConsented(true) // .withSignedMostRecentConsent(true).build(); // public static final ConsentStatus REQUIRED_UNSIGNED = new ConsentStatus.Builder().withName("Name1") // .withGuid(SubpopulationGuid.create("foo5")).withRequired(true).withConsented(false) // .withSignedMostRecentConsent(false).build(); // // public static final Map<SubpopulationGuid, ConsentStatus> UNCONSENTED_STATUS_MAP = new ImmutableMap.Builder<SubpopulationGuid, ConsentStatus>() // .put(SubpopulationGuid.create(REQUIRED_UNSIGNED.getSubpopulationGuid()), REQUIRED_UNSIGNED).build(); // // public static final Set<String> USER_DATA_GROUPS = ImmutableSet.of("group1","group2"); // // public static final Set<String> USER_SUBSTUDY_IDS = ImmutableSet.of("substudyA","substudyB"); // // public static final List<String> LANGUAGES = ImmutableList.of("en","fr"); // // public static final Phone PHONE = new Phone("9712486796", "US"); // // public static final AndroidAppLink ANDROID_APP_LINK = new AndroidAppLink("namespace", "package_name", // Lists.newArrayList("sha256_cert_fingerprints")); // public static final AndroidAppLink ANDROID_APP_LINK_2 = new AndroidAppLink("namespace2", "package_name2", // Lists.newArrayList("sha256_cert_fingerprints2")); // public static final AndroidAppLink ANDROID_APP_LINK_3 = new AndroidAppLink("namespace3", "package_name3", // Lists.newArrayList("sha256_cert_fingerprints3")); // public static final AndroidAppLink ANDROID_APP_LINK_4 = new AndroidAppLink("namespace4", "package_name4", // Lists.newArrayList("sha256_cert_fingerprints4")); // public static final AppleAppLink APPLE_APP_LINK = new AppleAppLink("studyId", // Lists.newArrayList("/appId/", "/appId/*")); // public static final AppleAppLink APPLE_APP_LINK_2 = new AppleAppLink("studyId2", // Lists.newArrayList("/appId2/", "/appId2/*")); // public static final AppleAppLink APPLE_APP_LINK_3 = new AppleAppLink("studyId3", // Lists.newArrayList("/appId3/", "/appId3/*")); // public static final AppleAppLink APPLE_APP_LINK_4 = new AppleAppLink("studyId4", // Lists.newArrayList("/appId4/", "/appId4/*")); // // }
import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.List; import static org.mockito.Mockito.spy; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.sagebionetworks.bridge.Roles; import org.sagebionetworks.bridge.TestConstants; import org.sagebionetworks.bridge.TestUtils; import org.sagebionetworks.bridge.dynamodb.DynamoSchedulePlan; import org.sagebionetworks.bridge.dynamodb.DynamoStudy; import org.sagebionetworks.bridge.json.BridgeObjectMapper; import org.sagebionetworks.bridge.models.ClientInfo; import org.sagebionetworks.bridge.models.ResourceList; import org.sagebionetworks.bridge.models.accounts.UserSession; import org.sagebionetworks.bridge.models.schedules.ABTestScheduleStrategy; import org.sagebionetworks.bridge.models.schedules.Activity; import org.sagebionetworks.bridge.models.schedules.Schedule; import org.sagebionetworks.bridge.models.schedules.SchedulePlan; import org.sagebionetworks.bridge.models.studies.Study; import org.sagebionetworks.bridge.services.SchedulePlanService; import org.sagebionetworks.bridge.services.StudyService; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.collect.Lists; import play.mvc.Result; import play.test.Helpers;
package org.sagebionetworks.bridge.play.controllers; @RunWith(MockitoJUnitRunner.class) public class SchedulePlanControllerMockTest { private SchedulePlanController controller; @Mock private StudyService mockStudyService; @Mock private SchedulePlanService mockSchedulePlanService; @Mock private UserSession mockUserSession; @Captor private ArgumentCaptor<SchedulePlan> schedulePlanCaptor; private Study study; @Before public void before() { controller = spy(new SchedulePlanController()); study = new DynamoStudy();
// Path: test/org/sagebionetworks/bridge/TestConstants.java // public class TestConstants { // // public static final String ENCRYPTED_HEALTH_CODE = "TFMkaVFKPD48WissX0bgcD3esBMEshxb3MVgKxHnkXLSEPN4FQMKc01tDbBAVcXx94kMX6ckXVYUZ8wx4iICl08uE+oQr9gorE1hlgAyLAM="; // // public static final String TEST_STUDY_IDENTIFIER = "api"; // public static final StudyIdentifier TEST_STUDY = new StudyIdentifierImpl(TEST_STUDY_IDENTIFIER); // public static final CriteriaContext TEST_CONTEXT = new CriteriaContext.Builder() // .withUserId("user-id").withStudyIdentifier(TestConstants.TEST_STUDY).build(); // // public static final String EMAIL = "email@email.com"; // public static final String PASSWORD = "password"; // // /** // * During tests, must sometimes pause because the underlying query uses a DynamoDB global // * secondary index, and this does not currently support consistent reads. // */ // public static final int GSI_WAIT_DURATION = 2000; // // public static final ConsentStatus REQUIRED_SIGNED_CURRENT = new ConsentStatus.Builder().withName("Name1") // .withGuid(SubpopulationGuid.create("foo1")).withRequired(true).withConsented(true) // .withSignedMostRecentConsent(true).build(); // public static final ConsentStatus REQUIRED_UNSIGNED = new ConsentStatus.Builder().withName("Name1") // .withGuid(SubpopulationGuid.create("foo5")).withRequired(true).withConsented(false) // .withSignedMostRecentConsent(false).build(); // // public static final Map<SubpopulationGuid, ConsentStatus> UNCONSENTED_STATUS_MAP = new ImmutableMap.Builder<SubpopulationGuid, ConsentStatus>() // .put(SubpopulationGuid.create(REQUIRED_UNSIGNED.getSubpopulationGuid()), REQUIRED_UNSIGNED).build(); // // public static final Set<String> USER_DATA_GROUPS = ImmutableSet.of("group1","group2"); // // public static final Set<String> USER_SUBSTUDY_IDS = ImmutableSet.of("substudyA","substudyB"); // // public static final List<String> LANGUAGES = ImmutableList.of("en","fr"); // // public static final Phone PHONE = new Phone("9712486796", "US"); // // public static final AndroidAppLink ANDROID_APP_LINK = new AndroidAppLink("namespace", "package_name", // Lists.newArrayList("sha256_cert_fingerprints")); // public static final AndroidAppLink ANDROID_APP_LINK_2 = new AndroidAppLink("namespace2", "package_name2", // Lists.newArrayList("sha256_cert_fingerprints2")); // public static final AndroidAppLink ANDROID_APP_LINK_3 = new AndroidAppLink("namespace3", "package_name3", // Lists.newArrayList("sha256_cert_fingerprints3")); // public static final AndroidAppLink ANDROID_APP_LINK_4 = new AndroidAppLink("namespace4", "package_name4", // Lists.newArrayList("sha256_cert_fingerprints4")); // public static final AppleAppLink APPLE_APP_LINK = new AppleAppLink("studyId", // Lists.newArrayList("/appId/", "/appId/*")); // public static final AppleAppLink APPLE_APP_LINK_2 = new AppleAppLink("studyId2", // Lists.newArrayList("/appId2/", "/appId2/*")); // public static final AppleAppLink APPLE_APP_LINK_3 = new AppleAppLink("studyId3", // Lists.newArrayList("/appId3/", "/appId3/*")); // public static final AppleAppLink APPLE_APP_LINK_4 = new AppleAppLink("studyId4", // Lists.newArrayList("/appId4/", "/appId4/*")); // // } // Path: test/org/sagebionetworks/bridge/play/controllers/SchedulePlanControllerMockTest.java import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.List; import static org.mockito.Mockito.spy; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.sagebionetworks.bridge.Roles; import org.sagebionetworks.bridge.TestConstants; import org.sagebionetworks.bridge.TestUtils; import org.sagebionetworks.bridge.dynamodb.DynamoSchedulePlan; import org.sagebionetworks.bridge.dynamodb.DynamoStudy; import org.sagebionetworks.bridge.json.BridgeObjectMapper; import org.sagebionetworks.bridge.models.ClientInfo; import org.sagebionetworks.bridge.models.ResourceList; import org.sagebionetworks.bridge.models.accounts.UserSession; import org.sagebionetworks.bridge.models.schedules.ABTestScheduleStrategy; import org.sagebionetworks.bridge.models.schedules.Activity; import org.sagebionetworks.bridge.models.schedules.Schedule; import org.sagebionetworks.bridge.models.schedules.SchedulePlan; import org.sagebionetworks.bridge.models.studies.Study; import org.sagebionetworks.bridge.services.SchedulePlanService; import org.sagebionetworks.bridge.services.StudyService; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.collect.Lists; import play.mvc.Result; import play.test.Helpers; package org.sagebionetworks.bridge.play.controllers; @RunWith(MockitoJUnitRunner.class) public class SchedulePlanControllerMockTest { private SchedulePlanController controller; @Mock private StudyService mockStudyService; @Mock private SchedulePlanService mockSchedulePlanService; @Mock private UserSession mockUserSession; @Captor private ArgumentCaptor<SchedulePlan> schedulePlanCaptor; private Study study; @Before public void before() { controller = spy(new SchedulePlanController()); study = new DynamoStudy();
study.setIdentifier(TestConstants.TEST_STUDY_IDENTIFIER);
Sage-Bionetworks/BridgePF
test/org/sagebionetworks/bridge/services/SurveyServiceTest.java
// Path: test/org/sagebionetworks/bridge/TestConstants.java // public static final int GSI_WAIT_DURATION = 2000; // // Path: test/org/sagebionetworks/bridge/TestConstants.java // public static final StudyIdentifier TEST_STUDY = new StudyIdentifierImpl(TEST_STUDY_IDENTIFIER);
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 static org.junit.Assert.fail; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyBoolean; import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sagebionetworks.bridge.TestConstants.GSI_WAIT_DURATION; import static org.sagebionetworks.bridge.TestConstants.TEST_STUDY; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.annotation.Resource; import com.google.common.collect.ImmutableList; import com.google.common.collect.Sets; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.sagebionetworks.bridge.TestUtils; import org.sagebionetworks.bridge.dynamodb.DynamoSurveyInfoScreen; import org.sagebionetworks.bridge.exceptions.BridgeServiceException; import org.sagebionetworks.bridge.exceptions.ConcurrentModificationException; import org.sagebionetworks.bridge.exceptions.EntityNotFoundException; import org.sagebionetworks.bridge.exceptions.InvalidEntityException; import org.sagebionetworks.bridge.exceptions.PublishedSurveyException; import org.sagebionetworks.bridge.json.BridgeObjectMapper; import org.sagebionetworks.bridge.models.GuidCreatedOnVersionHolder; import org.sagebionetworks.bridge.models.GuidCreatedOnVersionHolderImpl; import org.sagebionetworks.bridge.models.studies.StudyIdentifier; import org.sagebionetworks.bridge.models.studies.StudyIdentifierImpl; import org.sagebionetworks.bridge.models.surveys.DataType; import org.sagebionetworks.bridge.models.surveys.Image; import org.sagebionetworks.bridge.models.surveys.MultiValueConstraints; import org.sagebionetworks.bridge.models.surveys.Survey; import org.sagebionetworks.bridge.models.surveys.SurveyElement; import org.sagebionetworks.bridge.models.surveys.SurveyQuestion; import org.sagebionetworks.bridge.models.surveys.TestSurvey; import org.sagebionetworks.bridge.models.surveys.UIHint;
package org.sagebionetworks.bridge.services; @ContextConfiguration("classpath:test-context.xml") @RunWith(SpringJUnit4ClassRunner.class) public class SurveyServiceTest { private static final Logger logger = LoggerFactory.getLogger(SurveyServiceTest.class); @Resource UploadSchemaService schemaService; @Resource SurveyService surveyService; private SharedModuleMetadataService mockSharedModuleMetadataService; private String surveyId; private TestSurvey testSurvey; private Set<GuidCreatedOnVersionHolderImpl> surveysToDelete; @Before public void before() { mockSharedModuleMetadataService = mock(SharedModuleMetadataService.class); when(mockSharedModuleMetadataService.queryAllMetadata(anyBoolean(), anyBoolean(), anyString(), any(), any(), anyBoolean())).thenReturn(ImmutableList.of()); surveyId = TestUtils.randomName(SurveyServiceTest.class); testSurvey = new TestSurvey(SurveyServiceTest.class, true); testSurvey.setIdentifier(surveyId); surveysToDelete = new HashSet<>(); surveyService.setSharedModuleMetadataService(mockSharedModuleMetadataService); schemaService.setSharedModuleMetadataService(mockSharedModuleMetadataService); } @After public void after() { // clean up surveys for (GuidCreatedOnVersionHolder oneSurvey : surveysToDelete) { try {
// Path: test/org/sagebionetworks/bridge/TestConstants.java // public static final int GSI_WAIT_DURATION = 2000; // // Path: test/org/sagebionetworks/bridge/TestConstants.java // public static final StudyIdentifier TEST_STUDY = new StudyIdentifierImpl(TEST_STUDY_IDENTIFIER); // Path: test/org/sagebionetworks/bridge/services/SurveyServiceTest.java 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 static org.junit.Assert.fail; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyBoolean; import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sagebionetworks.bridge.TestConstants.GSI_WAIT_DURATION; import static org.sagebionetworks.bridge.TestConstants.TEST_STUDY; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.annotation.Resource; import com.google.common.collect.ImmutableList; import com.google.common.collect.Sets; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.sagebionetworks.bridge.TestUtils; import org.sagebionetworks.bridge.dynamodb.DynamoSurveyInfoScreen; import org.sagebionetworks.bridge.exceptions.BridgeServiceException; import org.sagebionetworks.bridge.exceptions.ConcurrentModificationException; import org.sagebionetworks.bridge.exceptions.EntityNotFoundException; import org.sagebionetworks.bridge.exceptions.InvalidEntityException; import org.sagebionetworks.bridge.exceptions.PublishedSurveyException; import org.sagebionetworks.bridge.json.BridgeObjectMapper; import org.sagebionetworks.bridge.models.GuidCreatedOnVersionHolder; import org.sagebionetworks.bridge.models.GuidCreatedOnVersionHolderImpl; import org.sagebionetworks.bridge.models.studies.StudyIdentifier; import org.sagebionetworks.bridge.models.studies.StudyIdentifierImpl; import org.sagebionetworks.bridge.models.surveys.DataType; import org.sagebionetworks.bridge.models.surveys.Image; import org.sagebionetworks.bridge.models.surveys.MultiValueConstraints; import org.sagebionetworks.bridge.models.surveys.Survey; import org.sagebionetworks.bridge.models.surveys.SurveyElement; import org.sagebionetworks.bridge.models.surveys.SurveyQuestion; import org.sagebionetworks.bridge.models.surveys.TestSurvey; import org.sagebionetworks.bridge.models.surveys.UIHint; package org.sagebionetworks.bridge.services; @ContextConfiguration("classpath:test-context.xml") @RunWith(SpringJUnit4ClassRunner.class) public class SurveyServiceTest { private static final Logger logger = LoggerFactory.getLogger(SurveyServiceTest.class); @Resource UploadSchemaService schemaService; @Resource SurveyService surveyService; private SharedModuleMetadataService mockSharedModuleMetadataService; private String surveyId; private TestSurvey testSurvey; private Set<GuidCreatedOnVersionHolderImpl> surveysToDelete; @Before public void before() { mockSharedModuleMetadataService = mock(SharedModuleMetadataService.class); when(mockSharedModuleMetadataService.queryAllMetadata(anyBoolean(), anyBoolean(), anyString(), any(), any(), anyBoolean())).thenReturn(ImmutableList.of()); surveyId = TestUtils.randomName(SurveyServiceTest.class); testSurvey = new TestSurvey(SurveyServiceTest.class, true); testSurvey.setIdentifier(surveyId); surveysToDelete = new HashSet<>(); surveyService.setSharedModuleMetadataService(mockSharedModuleMetadataService); schemaService.setSharedModuleMetadataService(mockSharedModuleMetadataService); } @After public void after() { // clean up surveys for (GuidCreatedOnVersionHolder oneSurvey : surveysToDelete) { try {
surveyService.deleteSurveyPermanently(TEST_STUDY, oneSurvey);
Sage-Bionetworks/BridgePF
test/org/sagebionetworks/bridge/services/SurveyServiceTest.java
// Path: test/org/sagebionetworks/bridge/TestConstants.java // public static final int GSI_WAIT_DURATION = 2000; // // Path: test/org/sagebionetworks/bridge/TestConstants.java // public static final StudyIdentifier TEST_STUDY = new StudyIdentifierImpl(TEST_STUDY_IDENTIFIER);
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 static org.junit.Assert.fail; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyBoolean; import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sagebionetworks.bridge.TestConstants.GSI_WAIT_DURATION; import static org.sagebionetworks.bridge.TestConstants.TEST_STUDY; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.annotation.Resource; import com.google.common.collect.ImmutableList; import com.google.common.collect.Sets; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.sagebionetworks.bridge.TestUtils; import org.sagebionetworks.bridge.dynamodb.DynamoSurveyInfoScreen; import org.sagebionetworks.bridge.exceptions.BridgeServiceException; import org.sagebionetworks.bridge.exceptions.ConcurrentModificationException; import org.sagebionetworks.bridge.exceptions.EntityNotFoundException; import org.sagebionetworks.bridge.exceptions.InvalidEntityException; import org.sagebionetworks.bridge.exceptions.PublishedSurveyException; import org.sagebionetworks.bridge.json.BridgeObjectMapper; import org.sagebionetworks.bridge.models.GuidCreatedOnVersionHolder; import org.sagebionetworks.bridge.models.GuidCreatedOnVersionHolderImpl; import org.sagebionetworks.bridge.models.studies.StudyIdentifier; import org.sagebionetworks.bridge.models.studies.StudyIdentifierImpl; import org.sagebionetworks.bridge.models.surveys.DataType; import org.sagebionetworks.bridge.models.surveys.Image; import org.sagebionetworks.bridge.models.surveys.MultiValueConstraints; import org.sagebionetworks.bridge.models.surveys.Survey; import org.sagebionetworks.bridge.models.surveys.SurveyElement; import org.sagebionetworks.bridge.models.surveys.SurveyQuestion; import org.sagebionetworks.bridge.models.surveys.TestSurvey; import org.sagebionetworks.bridge.models.surveys.UIHint;
laterSurvey = surveyService.publishSurvey(TEST_STUDY, laterSurvey, false); Survey pubSurvey = surveyService.getSurveyMostRecentlyPublishedVersion(TEST_STUDY, survey.getGuid(), true); assertEquals("Later testSurvey is the published testSurvey", laterSurvey.getCreatedOn(), pubSurvey.getCreatedOn()); } // GET SURVEYS @Test public void failToGetSurveysByBadStudyKey() { StudyIdentifier studyIdentifier = new StudyIdentifierImpl("foo"); List<Survey> surveys = surveyService.getAllSurveysMostRecentVersion(studyIdentifier, false); assertEquals("No surveys", 0, surveys.size()); } @Test public void canGetAllSurveys() throws Exception { Set<GuidCreatedOnVersionHolderImpl> mostRecentVersionSurveys = new HashSet<>(); mostRecentVersionSurveys.add(new GuidCreatedOnVersionHolderImpl(surveyService.createSurvey(new TestSurvey(SurveyServiceTest.class, true)))); mostRecentVersionSurveys.add(new GuidCreatedOnVersionHolderImpl(surveyService.createSurvey(new TestSurvey(SurveyServiceTest.class, true)))); mostRecentVersionSurveys.add(new GuidCreatedOnVersionHolderImpl(surveyService.createSurvey(new TestSurvey(SurveyServiceTest.class, true)))); mostRecentVersionSurveys.add(new GuidCreatedOnVersionHolderImpl(surveyService.createSurvey(new TestSurvey(SurveyServiceTest.class, true)))); Survey survey = surveyService.createSurvey(new TestSurvey(SurveyServiceTest.class, true)); surveysToDelete.add(new GuidCreatedOnVersionHolderImpl(survey)); Survey nextVersion = surveyService.versionSurvey(TEST_STUDY, survey); mostRecentVersionSurveys.add(new GuidCreatedOnVersionHolderImpl(nextVersion)); surveysToDelete.addAll(mostRecentVersionSurveys);
// Path: test/org/sagebionetworks/bridge/TestConstants.java // public static final int GSI_WAIT_DURATION = 2000; // // Path: test/org/sagebionetworks/bridge/TestConstants.java // public static final StudyIdentifier TEST_STUDY = new StudyIdentifierImpl(TEST_STUDY_IDENTIFIER); // Path: test/org/sagebionetworks/bridge/services/SurveyServiceTest.java 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 static org.junit.Assert.fail; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyBoolean; import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sagebionetworks.bridge.TestConstants.GSI_WAIT_DURATION; import static org.sagebionetworks.bridge.TestConstants.TEST_STUDY; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.annotation.Resource; import com.google.common.collect.ImmutableList; import com.google.common.collect.Sets; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.sagebionetworks.bridge.TestUtils; import org.sagebionetworks.bridge.dynamodb.DynamoSurveyInfoScreen; import org.sagebionetworks.bridge.exceptions.BridgeServiceException; import org.sagebionetworks.bridge.exceptions.ConcurrentModificationException; import org.sagebionetworks.bridge.exceptions.EntityNotFoundException; import org.sagebionetworks.bridge.exceptions.InvalidEntityException; import org.sagebionetworks.bridge.exceptions.PublishedSurveyException; import org.sagebionetworks.bridge.json.BridgeObjectMapper; import org.sagebionetworks.bridge.models.GuidCreatedOnVersionHolder; import org.sagebionetworks.bridge.models.GuidCreatedOnVersionHolderImpl; import org.sagebionetworks.bridge.models.studies.StudyIdentifier; import org.sagebionetworks.bridge.models.studies.StudyIdentifierImpl; import org.sagebionetworks.bridge.models.surveys.DataType; import org.sagebionetworks.bridge.models.surveys.Image; import org.sagebionetworks.bridge.models.surveys.MultiValueConstraints; import org.sagebionetworks.bridge.models.surveys.Survey; import org.sagebionetworks.bridge.models.surveys.SurveyElement; import org.sagebionetworks.bridge.models.surveys.SurveyQuestion; import org.sagebionetworks.bridge.models.surveys.TestSurvey; import org.sagebionetworks.bridge.models.surveys.UIHint; laterSurvey = surveyService.publishSurvey(TEST_STUDY, laterSurvey, false); Survey pubSurvey = surveyService.getSurveyMostRecentlyPublishedVersion(TEST_STUDY, survey.getGuid(), true); assertEquals("Later testSurvey is the published testSurvey", laterSurvey.getCreatedOn(), pubSurvey.getCreatedOn()); } // GET SURVEYS @Test public void failToGetSurveysByBadStudyKey() { StudyIdentifier studyIdentifier = new StudyIdentifierImpl("foo"); List<Survey> surveys = surveyService.getAllSurveysMostRecentVersion(studyIdentifier, false); assertEquals("No surveys", 0, surveys.size()); } @Test public void canGetAllSurveys() throws Exception { Set<GuidCreatedOnVersionHolderImpl> mostRecentVersionSurveys = new HashSet<>(); mostRecentVersionSurveys.add(new GuidCreatedOnVersionHolderImpl(surveyService.createSurvey(new TestSurvey(SurveyServiceTest.class, true)))); mostRecentVersionSurveys.add(new GuidCreatedOnVersionHolderImpl(surveyService.createSurvey(new TestSurvey(SurveyServiceTest.class, true)))); mostRecentVersionSurveys.add(new GuidCreatedOnVersionHolderImpl(surveyService.createSurvey(new TestSurvey(SurveyServiceTest.class, true)))); mostRecentVersionSurveys.add(new GuidCreatedOnVersionHolderImpl(surveyService.createSurvey(new TestSurvey(SurveyServiceTest.class, true)))); Survey survey = surveyService.createSurvey(new TestSurvey(SurveyServiceTest.class, true)); surveysToDelete.add(new GuidCreatedOnVersionHolderImpl(survey)); Survey nextVersion = surveyService.versionSurvey(TEST_STUDY, survey); mostRecentVersionSurveys.add(new GuidCreatedOnVersionHolderImpl(nextVersion)); surveysToDelete.addAll(mostRecentVersionSurveys);
Thread.sleep(GSI_WAIT_DURATION);
Sage-Bionetworks/BridgePF
test/org/sagebionetworks/bridge/play/controllers/SubstudyControllerTest.java
// Path: test/org/sagebionetworks/bridge/TestConstants.java // public class TestConstants { // // public static final String ENCRYPTED_HEALTH_CODE = "TFMkaVFKPD48WissX0bgcD3esBMEshxb3MVgKxHnkXLSEPN4FQMKc01tDbBAVcXx94kMX6ckXVYUZ8wx4iICl08uE+oQr9gorE1hlgAyLAM="; // // public static final String TEST_STUDY_IDENTIFIER = "api"; // public static final StudyIdentifier TEST_STUDY = new StudyIdentifierImpl(TEST_STUDY_IDENTIFIER); // public static final CriteriaContext TEST_CONTEXT = new CriteriaContext.Builder() // .withUserId("user-id").withStudyIdentifier(TestConstants.TEST_STUDY).build(); // // public static final String EMAIL = "email@email.com"; // public static final String PASSWORD = "password"; // // /** // * During tests, must sometimes pause because the underlying query uses a DynamoDB global // * secondary index, and this does not currently support consistent reads. // */ // public static final int GSI_WAIT_DURATION = 2000; // // public static final ConsentStatus REQUIRED_SIGNED_CURRENT = new ConsentStatus.Builder().withName("Name1") // .withGuid(SubpopulationGuid.create("foo1")).withRequired(true).withConsented(true) // .withSignedMostRecentConsent(true).build(); // public static final ConsentStatus REQUIRED_UNSIGNED = new ConsentStatus.Builder().withName("Name1") // .withGuid(SubpopulationGuid.create("foo5")).withRequired(true).withConsented(false) // .withSignedMostRecentConsent(false).build(); // // public static final Map<SubpopulationGuid, ConsentStatus> UNCONSENTED_STATUS_MAP = new ImmutableMap.Builder<SubpopulationGuid, ConsentStatus>() // .put(SubpopulationGuid.create(REQUIRED_UNSIGNED.getSubpopulationGuid()), REQUIRED_UNSIGNED).build(); // // public static final Set<String> USER_DATA_GROUPS = ImmutableSet.of("group1","group2"); // // public static final Set<String> USER_SUBSTUDY_IDS = ImmutableSet.of("substudyA","substudyB"); // // public static final List<String> LANGUAGES = ImmutableList.of("en","fr"); // // public static final Phone PHONE = new Phone("9712486796", "US"); // // public static final AndroidAppLink ANDROID_APP_LINK = new AndroidAppLink("namespace", "package_name", // Lists.newArrayList("sha256_cert_fingerprints")); // public static final AndroidAppLink ANDROID_APP_LINK_2 = new AndroidAppLink("namespace2", "package_name2", // Lists.newArrayList("sha256_cert_fingerprints2")); // public static final AndroidAppLink ANDROID_APP_LINK_3 = new AndroidAppLink("namespace3", "package_name3", // Lists.newArrayList("sha256_cert_fingerprints3")); // public static final AndroidAppLink ANDROID_APP_LINK_4 = new AndroidAppLink("namespace4", "package_name4", // Lists.newArrayList("sha256_cert_fingerprints4")); // public static final AppleAppLink APPLE_APP_LINK = new AppleAppLink("studyId", // Lists.newArrayList("/appId/", "/appId/*")); // public static final AppleAppLink APPLE_APP_LINK_2 = new AppleAppLink("studyId2", // Lists.newArrayList("/appId2/", "/appId2/*")); // public static final AppleAppLink APPLE_APP_LINK_3 = new AppleAppLink("studyId3", // Lists.newArrayList("/appId3/", "/appId3/*")); // public static final AppleAppLink APPLE_APP_LINK_4 = new AppleAppLink("studyId4", // Lists.newArrayList("/appId4/", "/appId4/*")); // // }
import java.util.List; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; import org.sagebionetworks.bridge.Roles; import org.sagebionetworks.bridge.TestConstants; import org.sagebionetworks.bridge.TestUtils; import org.sagebionetworks.bridge.models.ResourceList; import org.sagebionetworks.bridge.models.VersionHolder; import org.sagebionetworks.bridge.models.accounts.StudyParticipant; import org.sagebionetworks.bridge.models.accounts.UserSession; import org.sagebionetworks.bridge.models.substudies.Substudy; import org.sagebionetworks.bridge.services.SubstudyService; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import play.mvc.Result;
package org.sagebionetworks.bridge.play.controllers; @RunWith(MockitoJUnitRunner.class) public class SubstudyControllerTest { private static final String INCLUDE_DELETED_PARAM = "includeDeleted"; private static final List<Substudy> SUBSTUDIES = ImmutableList.of(Substudy.create(), Substudy.create()); private static final TypeReference<ResourceList<Substudy>> SUBSTUDY_TYPEREF = new TypeReference<ResourceList<Substudy>>() {}; private static final VersionHolder VERSION_HOLDER = new VersionHolder(1L); @Mock private SubstudyService service; @Captor private ArgumentCaptor<Substudy> substudyCaptor; @Spy private SubstudyController controller; private UserSession session; @Before public void before() { session = new UserSession(); session.setParticipant(new StudyParticipant.Builder().withRoles(ImmutableSet.of(Roles.ADMIN)).build());
// Path: test/org/sagebionetworks/bridge/TestConstants.java // public class TestConstants { // // public static final String ENCRYPTED_HEALTH_CODE = "TFMkaVFKPD48WissX0bgcD3esBMEshxb3MVgKxHnkXLSEPN4FQMKc01tDbBAVcXx94kMX6ckXVYUZ8wx4iICl08uE+oQr9gorE1hlgAyLAM="; // // public static final String TEST_STUDY_IDENTIFIER = "api"; // public static final StudyIdentifier TEST_STUDY = new StudyIdentifierImpl(TEST_STUDY_IDENTIFIER); // public static final CriteriaContext TEST_CONTEXT = new CriteriaContext.Builder() // .withUserId("user-id").withStudyIdentifier(TestConstants.TEST_STUDY).build(); // // public static final String EMAIL = "email@email.com"; // public static final String PASSWORD = "password"; // // /** // * During tests, must sometimes pause because the underlying query uses a DynamoDB global // * secondary index, and this does not currently support consistent reads. // */ // public static final int GSI_WAIT_DURATION = 2000; // // public static final ConsentStatus REQUIRED_SIGNED_CURRENT = new ConsentStatus.Builder().withName("Name1") // .withGuid(SubpopulationGuid.create("foo1")).withRequired(true).withConsented(true) // .withSignedMostRecentConsent(true).build(); // public static final ConsentStatus REQUIRED_UNSIGNED = new ConsentStatus.Builder().withName("Name1") // .withGuid(SubpopulationGuid.create("foo5")).withRequired(true).withConsented(false) // .withSignedMostRecentConsent(false).build(); // // public static final Map<SubpopulationGuid, ConsentStatus> UNCONSENTED_STATUS_MAP = new ImmutableMap.Builder<SubpopulationGuid, ConsentStatus>() // .put(SubpopulationGuid.create(REQUIRED_UNSIGNED.getSubpopulationGuid()), REQUIRED_UNSIGNED).build(); // // public static final Set<String> USER_DATA_GROUPS = ImmutableSet.of("group1","group2"); // // public static final Set<String> USER_SUBSTUDY_IDS = ImmutableSet.of("substudyA","substudyB"); // // public static final List<String> LANGUAGES = ImmutableList.of("en","fr"); // // public static final Phone PHONE = new Phone("9712486796", "US"); // // public static final AndroidAppLink ANDROID_APP_LINK = new AndroidAppLink("namespace", "package_name", // Lists.newArrayList("sha256_cert_fingerprints")); // public static final AndroidAppLink ANDROID_APP_LINK_2 = new AndroidAppLink("namespace2", "package_name2", // Lists.newArrayList("sha256_cert_fingerprints2")); // public static final AndroidAppLink ANDROID_APP_LINK_3 = new AndroidAppLink("namespace3", "package_name3", // Lists.newArrayList("sha256_cert_fingerprints3")); // public static final AndroidAppLink ANDROID_APP_LINK_4 = new AndroidAppLink("namespace4", "package_name4", // Lists.newArrayList("sha256_cert_fingerprints4")); // public static final AppleAppLink APPLE_APP_LINK = new AppleAppLink("studyId", // Lists.newArrayList("/appId/", "/appId/*")); // public static final AppleAppLink APPLE_APP_LINK_2 = new AppleAppLink("studyId2", // Lists.newArrayList("/appId2/", "/appId2/*")); // public static final AppleAppLink APPLE_APP_LINK_3 = new AppleAppLink("studyId3", // Lists.newArrayList("/appId3/", "/appId3/*")); // public static final AppleAppLink APPLE_APP_LINK_4 = new AppleAppLink("studyId4", // Lists.newArrayList("/appId4/", "/appId4/*")); // // } // Path: test/org/sagebionetworks/bridge/play/controllers/SubstudyControllerTest.java import java.util.List; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; import org.sagebionetworks.bridge.Roles; import org.sagebionetworks.bridge.TestConstants; import org.sagebionetworks.bridge.TestUtils; import org.sagebionetworks.bridge.models.ResourceList; import org.sagebionetworks.bridge.models.VersionHolder; import org.sagebionetworks.bridge.models.accounts.StudyParticipant; import org.sagebionetworks.bridge.models.accounts.UserSession; import org.sagebionetworks.bridge.models.substudies.Substudy; import org.sagebionetworks.bridge.services.SubstudyService; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import play.mvc.Result; package org.sagebionetworks.bridge.play.controllers; @RunWith(MockitoJUnitRunner.class) public class SubstudyControllerTest { private static final String INCLUDE_DELETED_PARAM = "includeDeleted"; private static final List<Substudy> SUBSTUDIES = ImmutableList.of(Substudy.create(), Substudy.create()); private static final TypeReference<ResourceList<Substudy>> SUBSTUDY_TYPEREF = new TypeReference<ResourceList<Substudy>>() {}; private static final VersionHolder VERSION_HOLDER = new VersionHolder(1L); @Mock private SubstudyService service; @Captor private ArgumentCaptor<Substudy> substudyCaptor; @Spy private SubstudyController controller; private UserSession session; @Before public void before() { session = new UserSession(); session.setParticipant(new StudyParticipant.Builder().withRoles(ImmutableSet.of(Roles.ADMIN)).build());
session.setStudyIdentifier(TestConstants.TEST_STUDY);
Sage-Bionetworks/BridgePF
test/org/sagebionetworks/bridge/play/controllers/NotificationTopicControllerTest.java
// Path: test/org/sagebionetworks/bridge/TestConstants.java // public static final StudyIdentifier TEST_STUDY = new StudyIdentifierImpl(TEST_STUDY_IDENTIFIER);
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.mockito.Mockito.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.sagebionetworks.bridge.Roles.ADMIN; import static org.sagebionetworks.bridge.Roles.DEVELOPER; import static org.sagebionetworks.bridge.TestConstants.TEST_STUDY; import static org.sagebionetworks.bridge.TestUtils.getNotificationTopic; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; import org.sagebionetworks.bridge.TestUtils; import org.sagebionetworks.bridge.config.BridgeConfig; import org.sagebionetworks.bridge.config.Environment; import org.sagebionetworks.bridge.exceptions.NotAuthenticatedException; import org.sagebionetworks.bridge.json.BridgeObjectMapper; import org.sagebionetworks.bridge.models.ResourceList; import org.sagebionetworks.bridge.models.accounts.UserSession; import org.sagebionetworks.bridge.models.notifications.NotificationMessage; import org.sagebionetworks.bridge.models.notifications.NotificationTopic; import org.sagebionetworks.bridge.models.notifications.SubscriptionRequest; import org.sagebionetworks.bridge.services.NotificationTopicService; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.collect.Lists; import play.mvc.Result; import play.test.Helpers;
package org.sagebionetworks.bridge.play.controllers; @RunWith(MockitoJUnitRunner.class) public class NotificationTopicControllerTest { private static final String GUID = "DEF-GHI"; @Spy private NotificationTopicController controller; @Mock private NotificationTopicService mockTopicService; @Mock private BridgeConfig mockBridgeConfig; @Mock private UserSession mockUserSession; @Captor private ArgumentCaptor<NotificationTopic> topicCaptor; @Captor private ArgumentCaptor<NotificationMessage> messageCaptor; @Captor private ArgumentCaptor<SubscriptionRequest> subRequestCaptor; @Before public void before() throws Exception { this.controller.setNotificationTopicService(mockTopicService); controller.setBridgeConfig(mockBridgeConfig); doReturn(Environment.UAT).when(mockBridgeConfig).getEnvironment();
// Path: test/org/sagebionetworks/bridge/TestConstants.java // public static final StudyIdentifier TEST_STUDY = new StudyIdentifierImpl(TEST_STUDY_IDENTIFIER); // Path: test/org/sagebionetworks/bridge/play/controllers/NotificationTopicControllerTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.mockito.Mockito.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.sagebionetworks.bridge.Roles.ADMIN; import static org.sagebionetworks.bridge.Roles.DEVELOPER; import static org.sagebionetworks.bridge.TestConstants.TEST_STUDY; import static org.sagebionetworks.bridge.TestUtils.getNotificationTopic; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; import org.sagebionetworks.bridge.TestUtils; import org.sagebionetworks.bridge.config.BridgeConfig; import org.sagebionetworks.bridge.config.Environment; import org.sagebionetworks.bridge.exceptions.NotAuthenticatedException; import org.sagebionetworks.bridge.json.BridgeObjectMapper; import org.sagebionetworks.bridge.models.ResourceList; import org.sagebionetworks.bridge.models.accounts.UserSession; import org.sagebionetworks.bridge.models.notifications.NotificationMessage; import org.sagebionetworks.bridge.models.notifications.NotificationTopic; import org.sagebionetworks.bridge.models.notifications.SubscriptionRequest; import org.sagebionetworks.bridge.services.NotificationTopicService; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.collect.Lists; import play.mvc.Result; import play.test.Helpers; package org.sagebionetworks.bridge.play.controllers; @RunWith(MockitoJUnitRunner.class) public class NotificationTopicControllerTest { private static final String GUID = "DEF-GHI"; @Spy private NotificationTopicController controller; @Mock private NotificationTopicService mockTopicService; @Mock private BridgeConfig mockBridgeConfig; @Mock private UserSession mockUserSession; @Captor private ArgumentCaptor<NotificationTopic> topicCaptor; @Captor private ArgumentCaptor<NotificationMessage> messageCaptor; @Captor private ArgumentCaptor<SubscriptionRequest> subRequestCaptor; @Before public void before() throws Exception { this.controller.setNotificationTopicService(mockTopicService); controller.setBridgeConfig(mockBridgeConfig); doReturn(Environment.UAT).when(mockBridgeConfig).getEnvironment();
doReturn(TEST_STUDY).when(mockUserSession).getStudyIdentifier();
Sage-Bionetworks/BridgePF
test/org/sagebionetworks/bridge/play/controllers/EmailControllerTest.java
// Path: test/org/sagebionetworks/bridge/TestConstants.java // public class TestConstants { // // public static final String ENCRYPTED_HEALTH_CODE = "TFMkaVFKPD48WissX0bgcD3esBMEshxb3MVgKxHnkXLSEPN4FQMKc01tDbBAVcXx94kMX6ckXVYUZ8wx4iICl08uE+oQr9gorE1hlgAyLAM="; // // public static final String TEST_STUDY_IDENTIFIER = "api"; // public static final StudyIdentifier TEST_STUDY = new StudyIdentifierImpl(TEST_STUDY_IDENTIFIER); // public static final CriteriaContext TEST_CONTEXT = new CriteriaContext.Builder() // .withUserId("user-id").withStudyIdentifier(TestConstants.TEST_STUDY).build(); // // public static final String EMAIL = "email@email.com"; // public static final String PASSWORD = "password"; // // /** // * During tests, must sometimes pause because the underlying query uses a DynamoDB global // * secondary index, and this does not currently support consistent reads. // */ // public static final int GSI_WAIT_DURATION = 2000; // // public static final ConsentStatus REQUIRED_SIGNED_CURRENT = new ConsentStatus.Builder().withName("Name1") // .withGuid(SubpopulationGuid.create("foo1")).withRequired(true).withConsented(true) // .withSignedMostRecentConsent(true).build(); // public static final ConsentStatus REQUIRED_UNSIGNED = new ConsentStatus.Builder().withName("Name1") // .withGuid(SubpopulationGuid.create("foo5")).withRequired(true).withConsented(false) // .withSignedMostRecentConsent(false).build(); // // public static final Map<SubpopulationGuid, ConsentStatus> UNCONSENTED_STATUS_MAP = new ImmutableMap.Builder<SubpopulationGuid, ConsentStatus>() // .put(SubpopulationGuid.create(REQUIRED_UNSIGNED.getSubpopulationGuid()), REQUIRED_UNSIGNED).build(); // // public static final Set<String> USER_DATA_GROUPS = ImmutableSet.of("group1","group2"); // // public static final Set<String> USER_SUBSTUDY_IDS = ImmutableSet.of("substudyA","substudyB"); // // public static final List<String> LANGUAGES = ImmutableList.of("en","fr"); // // public static final Phone PHONE = new Phone("9712486796", "US"); // // public static final AndroidAppLink ANDROID_APP_LINK = new AndroidAppLink("namespace", "package_name", // Lists.newArrayList("sha256_cert_fingerprints")); // public static final AndroidAppLink ANDROID_APP_LINK_2 = new AndroidAppLink("namespace2", "package_name2", // Lists.newArrayList("sha256_cert_fingerprints2")); // public static final AndroidAppLink ANDROID_APP_LINK_3 = new AndroidAppLink("namespace3", "package_name3", // Lists.newArrayList("sha256_cert_fingerprints3")); // public static final AndroidAppLink ANDROID_APP_LINK_4 = new AndroidAppLink("namespace4", "package_name4", // Lists.newArrayList("sha256_cert_fingerprints4")); // public static final AppleAppLink APPLE_APP_LINK = new AppleAppLink("studyId", // Lists.newArrayList("/appId/", "/appId/*")); // public static final AppleAppLink APPLE_APP_LINK_2 = new AppleAppLink("studyId2", // Lists.newArrayList("/appId2/", "/appId2/*")); // public static final AppleAppLink APPLE_APP_LINK_3 = new AppleAppLink("studyId3", // Lists.newArrayList("/appId3/", "/appId3/*")); // public static final AppleAppLink APPLE_APP_LINK_4 = new AppleAppLink("studyId4", // Lists.newArrayList("/appId4/", "/appId4/*")); // // }
import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.mockito.Mockito.verify; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; import org.sagebionetworks.bridge.TestConstants; import org.sagebionetworks.bridge.TestUtils; import org.sagebionetworks.bridge.config.BridgeConfig; import org.sagebionetworks.bridge.dao.AccountDao; import org.sagebionetworks.bridge.play.controllers.EmailController; import org.sagebionetworks.bridge.services.StudyService; import play.mvc.Http; import play.mvc.Result; import play.test.Helpers; import java.util.Map; import org.sagebionetworks.bridge.models.accounts.Account; import org.sagebionetworks.bridge.models.accounts.AccountId; import org.sagebionetworks.bridge.models.studies.Study; import com.google.common.collect.Maps;
package org.sagebionetworks.bridge.play.controllers; @RunWith(MockitoJUnitRunner.class) public class EmailControllerTest { private static final String EMAIL = "email"; private static final String DATA_BRACKET_EMAIL = "data[email]"; private static final String HEALTH_CODE = "healthCode"; private static final String UNSUBSCRIBE_TOKEN = "unsubscribeToken"; private static final String TOKEN = "token"; private static final String STUDY2 = "study";
// Path: test/org/sagebionetworks/bridge/TestConstants.java // public class TestConstants { // // public static final String ENCRYPTED_HEALTH_CODE = "TFMkaVFKPD48WissX0bgcD3esBMEshxb3MVgKxHnkXLSEPN4FQMKc01tDbBAVcXx94kMX6ckXVYUZ8wx4iICl08uE+oQr9gorE1hlgAyLAM="; // // public static final String TEST_STUDY_IDENTIFIER = "api"; // public static final StudyIdentifier TEST_STUDY = new StudyIdentifierImpl(TEST_STUDY_IDENTIFIER); // public static final CriteriaContext TEST_CONTEXT = new CriteriaContext.Builder() // .withUserId("user-id").withStudyIdentifier(TestConstants.TEST_STUDY).build(); // // public static final String EMAIL = "email@email.com"; // public static final String PASSWORD = "password"; // // /** // * During tests, must sometimes pause because the underlying query uses a DynamoDB global // * secondary index, and this does not currently support consistent reads. // */ // public static final int GSI_WAIT_DURATION = 2000; // // public static final ConsentStatus REQUIRED_SIGNED_CURRENT = new ConsentStatus.Builder().withName("Name1") // .withGuid(SubpopulationGuid.create("foo1")).withRequired(true).withConsented(true) // .withSignedMostRecentConsent(true).build(); // public static final ConsentStatus REQUIRED_UNSIGNED = new ConsentStatus.Builder().withName("Name1") // .withGuid(SubpopulationGuid.create("foo5")).withRequired(true).withConsented(false) // .withSignedMostRecentConsent(false).build(); // // public static final Map<SubpopulationGuid, ConsentStatus> UNCONSENTED_STATUS_MAP = new ImmutableMap.Builder<SubpopulationGuid, ConsentStatus>() // .put(SubpopulationGuid.create(REQUIRED_UNSIGNED.getSubpopulationGuid()), REQUIRED_UNSIGNED).build(); // // public static final Set<String> USER_DATA_GROUPS = ImmutableSet.of("group1","group2"); // // public static final Set<String> USER_SUBSTUDY_IDS = ImmutableSet.of("substudyA","substudyB"); // // public static final List<String> LANGUAGES = ImmutableList.of("en","fr"); // // public static final Phone PHONE = new Phone("9712486796", "US"); // // public static final AndroidAppLink ANDROID_APP_LINK = new AndroidAppLink("namespace", "package_name", // Lists.newArrayList("sha256_cert_fingerprints")); // public static final AndroidAppLink ANDROID_APP_LINK_2 = new AndroidAppLink("namespace2", "package_name2", // Lists.newArrayList("sha256_cert_fingerprints2")); // public static final AndroidAppLink ANDROID_APP_LINK_3 = new AndroidAppLink("namespace3", "package_name3", // Lists.newArrayList("sha256_cert_fingerprints3")); // public static final AndroidAppLink ANDROID_APP_LINK_4 = new AndroidAppLink("namespace4", "package_name4", // Lists.newArrayList("sha256_cert_fingerprints4")); // public static final AppleAppLink APPLE_APP_LINK = new AppleAppLink("studyId", // Lists.newArrayList("/appId/", "/appId/*")); // public static final AppleAppLink APPLE_APP_LINK_2 = new AppleAppLink("studyId2", // Lists.newArrayList("/appId2/", "/appId2/*")); // public static final AppleAppLink APPLE_APP_LINK_3 = new AppleAppLink("studyId3", // Lists.newArrayList("/appId3/", "/appId3/*")); // public static final AppleAppLink APPLE_APP_LINK_4 = new AppleAppLink("studyId4", // Lists.newArrayList("/appId4/", "/appId4/*")); // // } // Path: test/org/sagebionetworks/bridge/play/controllers/EmailControllerTest.java import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.mockito.Mockito.verify; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; import org.sagebionetworks.bridge.TestConstants; import org.sagebionetworks.bridge.TestUtils; import org.sagebionetworks.bridge.config.BridgeConfig; import org.sagebionetworks.bridge.dao.AccountDao; import org.sagebionetworks.bridge.play.controllers.EmailController; import org.sagebionetworks.bridge.services.StudyService; import play.mvc.Http; import play.mvc.Result; import play.test.Helpers; import java.util.Map; import org.sagebionetworks.bridge.models.accounts.Account; import org.sagebionetworks.bridge.models.accounts.AccountId; import org.sagebionetworks.bridge.models.studies.Study; import com.google.common.collect.Maps; package org.sagebionetworks.bridge.play.controllers; @RunWith(MockitoJUnitRunner.class) public class EmailControllerTest { private static final String EMAIL = "email"; private static final String DATA_BRACKET_EMAIL = "data[email]"; private static final String HEALTH_CODE = "healthCode"; private static final String UNSUBSCRIBE_TOKEN = "unsubscribeToken"; private static final String TOKEN = "token"; private static final String STUDY2 = "study";
private static final String API = TestConstants.TEST_STUDY_IDENTIFIER;
Sage-Bionetworks/BridgePF
test/org/sagebionetworks/bridge/TestUserAdminHelper.java
// Path: test/org/sagebionetworks/bridge/TestConstants.java // public static final String TEST_STUDY_IDENTIFIER = "api";
import static com.google.common.base.Preconditions.checkNotNull; import static org.sagebionetworks.bridge.TestConstants.TEST_STUDY_IDENTIFIER; import java.util.HashSet; import java.util.List; import java.util.Set; import org.sagebionetworks.bridge.models.CriteriaContext; import org.sagebionetworks.bridge.models.accounts.AccountId; import org.sagebionetworks.bridge.models.accounts.SignIn; import org.sagebionetworks.bridge.models.accounts.StudyParticipant; import org.sagebionetworks.bridge.models.accounts.UserSession; import org.sagebionetworks.bridge.models.studies.Study; import org.sagebionetworks.bridge.models.studies.StudyIdentifier; import org.sagebionetworks.bridge.models.subpopulations.SubpopulationGuid; import org.sagebionetworks.bridge.services.AuthenticationService; import org.sagebionetworks.bridge.services.StudyService; import org.sagebionetworks.bridge.services.UserAdminService; import com.google.common.collect.Sets; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;
return this; } public Builder withRoles(Set<Roles> roles) { this.roles = Sets.newHashSet(roles); return this; } public Builder withRoles(Roles... roles) { this.roles = Sets.newHashSet(roles); return this; } public Builder withDataGroups(Set<String> dataGroups) { this.dataGroups = dataGroups; return this; } public Builder withLanguages(List<String> languages) { this.languages = languages; return this; } public Builder withEmail(String email) { this.email = email; return this; } public Builder withPassword(String password) { this.password = password; return this; } public TestUser build() { // There are tests where we partially create a user with the builder, then change just // some fields before creating another test user with multiple build() calls. Anything we // default in thie build method needs to be updated with each call to build().
// Path: test/org/sagebionetworks/bridge/TestConstants.java // public static final String TEST_STUDY_IDENTIFIER = "api"; // Path: test/org/sagebionetworks/bridge/TestUserAdminHelper.java import static com.google.common.base.Preconditions.checkNotNull; import static org.sagebionetworks.bridge.TestConstants.TEST_STUDY_IDENTIFIER; import java.util.HashSet; import java.util.List; import java.util.Set; import org.sagebionetworks.bridge.models.CriteriaContext; import org.sagebionetworks.bridge.models.accounts.AccountId; import org.sagebionetworks.bridge.models.accounts.SignIn; import org.sagebionetworks.bridge.models.accounts.StudyParticipant; import org.sagebionetworks.bridge.models.accounts.UserSession; import org.sagebionetworks.bridge.models.studies.Study; import org.sagebionetworks.bridge.models.studies.StudyIdentifier; import org.sagebionetworks.bridge.models.subpopulations.SubpopulationGuid; import org.sagebionetworks.bridge.services.AuthenticationService; import org.sagebionetworks.bridge.services.StudyService; import org.sagebionetworks.bridge.services.UserAdminService; import com.google.common.collect.Sets; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; return this; } public Builder withRoles(Set<Roles> roles) { this.roles = Sets.newHashSet(roles); return this; } public Builder withRoles(Roles... roles) { this.roles = Sets.newHashSet(roles); return this; } public Builder withDataGroups(Set<String> dataGroups) { this.dataGroups = dataGroups; return this; } public Builder withLanguages(List<String> languages) { this.languages = languages; return this; } public Builder withEmail(String email) { this.email = email; return this; } public Builder withPassword(String password) { this.password = password; return this; } public TestUser build() { // There are tests where we partially create a user with the builder, then change just // some fields before creating another test user with multiple build() calls. Anything we // default in thie build method needs to be updated with each call to build().
Study finalStudy = (study == null) ? studyService.getStudy(TEST_STUDY_IDENTIFIER) : study;
Sage-Bionetworks/BridgePF
test/org/sagebionetworks/bridge/dynamodb/DynamoFPHSExternalIdentifierDaoTest.java
// Path: test/org/sagebionetworks/bridge/TestConstants.java // public class TestConstants { // // public static final String ENCRYPTED_HEALTH_CODE = "TFMkaVFKPD48WissX0bgcD3esBMEshxb3MVgKxHnkXLSEPN4FQMKc01tDbBAVcXx94kMX6ckXVYUZ8wx4iICl08uE+oQr9gorE1hlgAyLAM="; // // public static final String TEST_STUDY_IDENTIFIER = "api"; // public static final StudyIdentifier TEST_STUDY = new StudyIdentifierImpl(TEST_STUDY_IDENTIFIER); // public static final CriteriaContext TEST_CONTEXT = new CriteriaContext.Builder() // .withUserId("user-id").withStudyIdentifier(TestConstants.TEST_STUDY).build(); // // public static final String EMAIL = "email@email.com"; // public static final String PASSWORD = "password"; // // /** // * During tests, must sometimes pause because the underlying query uses a DynamoDB global // * secondary index, and this does not currently support consistent reads. // */ // public static final int GSI_WAIT_DURATION = 2000; // // public static final ConsentStatus REQUIRED_SIGNED_CURRENT = new ConsentStatus.Builder().withName("Name1") // .withGuid(SubpopulationGuid.create("foo1")).withRequired(true).withConsented(true) // .withSignedMostRecentConsent(true).build(); // public static final ConsentStatus REQUIRED_UNSIGNED = new ConsentStatus.Builder().withName("Name1") // .withGuid(SubpopulationGuid.create("foo5")).withRequired(true).withConsented(false) // .withSignedMostRecentConsent(false).build(); // // public static final Map<SubpopulationGuid, ConsentStatus> UNCONSENTED_STATUS_MAP = new ImmutableMap.Builder<SubpopulationGuid, ConsentStatus>() // .put(SubpopulationGuid.create(REQUIRED_UNSIGNED.getSubpopulationGuid()), REQUIRED_UNSIGNED).build(); // // public static final Set<String> USER_DATA_GROUPS = ImmutableSet.of("group1","group2"); // // public static final Set<String> USER_SUBSTUDY_IDS = ImmutableSet.of("substudyA","substudyB"); // // public static final List<String> LANGUAGES = ImmutableList.of("en","fr"); // // public static final Phone PHONE = new Phone("9712486796", "US"); // // public static final AndroidAppLink ANDROID_APP_LINK = new AndroidAppLink("namespace", "package_name", // Lists.newArrayList("sha256_cert_fingerprints")); // public static final AndroidAppLink ANDROID_APP_LINK_2 = new AndroidAppLink("namespace2", "package_name2", // Lists.newArrayList("sha256_cert_fingerprints2")); // public static final AndroidAppLink ANDROID_APP_LINK_3 = new AndroidAppLink("namespace3", "package_name3", // Lists.newArrayList("sha256_cert_fingerprints3")); // public static final AndroidAppLink ANDROID_APP_LINK_4 = new AndroidAppLink("namespace4", "package_name4", // Lists.newArrayList("sha256_cert_fingerprints4")); // public static final AppleAppLink APPLE_APP_LINK = new AppleAppLink("studyId", // Lists.newArrayList("/appId/", "/appId/*")); // public static final AppleAppLink APPLE_APP_LINK_2 = new AppleAppLink("studyId2", // Lists.newArrayList("/appId2/", "/appId2/*")); // public static final AppleAppLink APPLE_APP_LINK_3 = new AppleAppLink("studyId3", // Lists.newArrayList("/appId3/", "/appId3/*")); // public static final AppleAppLink APPLE_APP_LINK_4 = new AppleAppLink("studyId4", // Lists.newArrayList("/appId4/", "/appId4/*")); // // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.sagebionetworks.bridge.TestConstants; import org.sagebionetworks.bridge.TestUtils; import org.sagebionetworks.bridge.exceptions.BadRequestException; import org.sagebionetworks.bridge.exceptions.EntityAlreadyExistsException; import org.sagebionetworks.bridge.exceptions.EntityNotFoundException; import org.sagebionetworks.bridge.models.accounts.ExternalIdentifier; import org.sagebionetworks.bridge.models.accounts.FPHSExternalIdentifier; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.google.common.collect.Lists;
package org.sagebionetworks.bridge.dynamodb; @ContextConfiguration("classpath:test-context.xml") @RunWith(SpringJUnit4ClassRunner.class) public class DynamoFPHSExternalIdentifierDaoTest { @Resource private DynamoFPHSExternalIdentifierDao dao; private List<String> idsToDelete; @Before public void before() { idsToDelete = Lists.newArrayList(); } @After public void after() { idsToDelete.forEach(dao::deleteExternalId); } private String getId() { return TestUtils.randomName(DynamoFPHSExternalIdentifierDaoTest.class); } @Test(expected=EntityNotFoundException.class) public void verifyExternalIdDoesNotExist() throws Exception {
// Path: test/org/sagebionetworks/bridge/TestConstants.java // public class TestConstants { // // public static final String ENCRYPTED_HEALTH_CODE = "TFMkaVFKPD48WissX0bgcD3esBMEshxb3MVgKxHnkXLSEPN4FQMKc01tDbBAVcXx94kMX6ckXVYUZ8wx4iICl08uE+oQr9gorE1hlgAyLAM="; // // public static final String TEST_STUDY_IDENTIFIER = "api"; // public static final StudyIdentifier TEST_STUDY = new StudyIdentifierImpl(TEST_STUDY_IDENTIFIER); // public static final CriteriaContext TEST_CONTEXT = new CriteriaContext.Builder() // .withUserId("user-id").withStudyIdentifier(TestConstants.TEST_STUDY).build(); // // public static final String EMAIL = "email@email.com"; // public static final String PASSWORD = "password"; // // /** // * During tests, must sometimes pause because the underlying query uses a DynamoDB global // * secondary index, and this does not currently support consistent reads. // */ // public static final int GSI_WAIT_DURATION = 2000; // // public static final ConsentStatus REQUIRED_SIGNED_CURRENT = new ConsentStatus.Builder().withName("Name1") // .withGuid(SubpopulationGuid.create("foo1")).withRequired(true).withConsented(true) // .withSignedMostRecentConsent(true).build(); // public static final ConsentStatus REQUIRED_UNSIGNED = new ConsentStatus.Builder().withName("Name1") // .withGuid(SubpopulationGuid.create("foo5")).withRequired(true).withConsented(false) // .withSignedMostRecentConsent(false).build(); // // public static final Map<SubpopulationGuid, ConsentStatus> UNCONSENTED_STATUS_MAP = new ImmutableMap.Builder<SubpopulationGuid, ConsentStatus>() // .put(SubpopulationGuid.create(REQUIRED_UNSIGNED.getSubpopulationGuid()), REQUIRED_UNSIGNED).build(); // // public static final Set<String> USER_DATA_GROUPS = ImmutableSet.of("group1","group2"); // // public static final Set<String> USER_SUBSTUDY_IDS = ImmutableSet.of("substudyA","substudyB"); // // public static final List<String> LANGUAGES = ImmutableList.of("en","fr"); // // public static final Phone PHONE = new Phone("9712486796", "US"); // // public static final AndroidAppLink ANDROID_APP_LINK = new AndroidAppLink("namespace", "package_name", // Lists.newArrayList("sha256_cert_fingerprints")); // public static final AndroidAppLink ANDROID_APP_LINK_2 = new AndroidAppLink("namespace2", "package_name2", // Lists.newArrayList("sha256_cert_fingerprints2")); // public static final AndroidAppLink ANDROID_APP_LINK_3 = new AndroidAppLink("namespace3", "package_name3", // Lists.newArrayList("sha256_cert_fingerprints3")); // public static final AndroidAppLink ANDROID_APP_LINK_4 = new AndroidAppLink("namespace4", "package_name4", // Lists.newArrayList("sha256_cert_fingerprints4")); // public static final AppleAppLink APPLE_APP_LINK = new AppleAppLink("studyId", // Lists.newArrayList("/appId/", "/appId/*")); // public static final AppleAppLink APPLE_APP_LINK_2 = new AppleAppLink("studyId2", // Lists.newArrayList("/appId2/", "/appId2/*")); // public static final AppleAppLink APPLE_APP_LINK_3 = new AppleAppLink("studyId3", // Lists.newArrayList("/appId3/", "/appId3/*")); // public static final AppleAppLink APPLE_APP_LINK_4 = new AppleAppLink("studyId4", // Lists.newArrayList("/appId4/", "/appId4/*")); // // } // Path: test/org/sagebionetworks/bridge/dynamodb/DynamoFPHSExternalIdentifierDaoTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.sagebionetworks.bridge.TestConstants; import org.sagebionetworks.bridge.TestUtils; import org.sagebionetworks.bridge.exceptions.BadRequestException; import org.sagebionetworks.bridge.exceptions.EntityAlreadyExistsException; import org.sagebionetworks.bridge.exceptions.EntityNotFoundException; import org.sagebionetworks.bridge.models.accounts.ExternalIdentifier; import org.sagebionetworks.bridge.models.accounts.FPHSExternalIdentifier; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.google.common.collect.Lists; package org.sagebionetworks.bridge.dynamodb; @ContextConfiguration("classpath:test-context.xml") @RunWith(SpringJUnit4ClassRunner.class) public class DynamoFPHSExternalIdentifierDaoTest { @Resource private DynamoFPHSExternalIdentifierDao dao; private List<String> idsToDelete; @Before public void before() { idsToDelete = Lists.newArrayList(); } @After public void after() { idsToDelete.forEach(dao::deleteExternalId); } private String getId() { return TestUtils.randomName(DynamoFPHSExternalIdentifierDaoTest.class); } @Test(expected=EntityNotFoundException.class) public void verifyExternalIdDoesNotExist() throws Exception {
ExternalIdentifier externalId = ExternalIdentifier.create(TestConstants.TEST_STUDY, getId());
Sage-Bionetworks/BridgePF
test/org/sagebionetworks/bridge/play/controllers/CompoundActivityDefinitionControllerTest.java
// Path: test/org/sagebionetworks/bridge/TestConstants.java // public class TestConstants { // // public static final String ENCRYPTED_HEALTH_CODE = "TFMkaVFKPD48WissX0bgcD3esBMEshxb3MVgKxHnkXLSEPN4FQMKc01tDbBAVcXx94kMX6ckXVYUZ8wx4iICl08uE+oQr9gorE1hlgAyLAM="; // // public static final String TEST_STUDY_IDENTIFIER = "api"; // public static final StudyIdentifier TEST_STUDY = new StudyIdentifierImpl(TEST_STUDY_IDENTIFIER); // public static final CriteriaContext TEST_CONTEXT = new CriteriaContext.Builder() // .withUserId("user-id").withStudyIdentifier(TestConstants.TEST_STUDY).build(); // // public static final String EMAIL = "email@email.com"; // public static final String PASSWORD = "password"; // // /** // * During tests, must sometimes pause because the underlying query uses a DynamoDB global // * secondary index, and this does not currently support consistent reads. // */ // public static final int GSI_WAIT_DURATION = 2000; // // public static final ConsentStatus REQUIRED_SIGNED_CURRENT = new ConsentStatus.Builder().withName("Name1") // .withGuid(SubpopulationGuid.create("foo1")).withRequired(true).withConsented(true) // .withSignedMostRecentConsent(true).build(); // public static final ConsentStatus REQUIRED_UNSIGNED = new ConsentStatus.Builder().withName("Name1") // .withGuid(SubpopulationGuid.create("foo5")).withRequired(true).withConsented(false) // .withSignedMostRecentConsent(false).build(); // // public static final Map<SubpopulationGuid, ConsentStatus> UNCONSENTED_STATUS_MAP = new ImmutableMap.Builder<SubpopulationGuid, ConsentStatus>() // .put(SubpopulationGuid.create(REQUIRED_UNSIGNED.getSubpopulationGuid()), REQUIRED_UNSIGNED).build(); // // public static final Set<String> USER_DATA_GROUPS = ImmutableSet.of("group1","group2"); // // public static final Set<String> USER_SUBSTUDY_IDS = ImmutableSet.of("substudyA","substudyB"); // // public static final List<String> LANGUAGES = ImmutableList.of("en","fr"); // // public static final Phone PHONE = new Phone("9712486796", "US"); // // public static final AndroidAppLink ANDROID_APP_LINK = new AndroidAppLink("namespace", "package_name", // Lists.newArrayList("sha256_cert_fingerprints")); // public static final AndroidAppLink ANDROID_APP_LINK_2 = new AndroidAppLink("namespace2", "package_name2", // Lists.newArrayList("sha256_cert_fingerprints2")); // public static final AndroidAppLink ANDROID_APP_LINK_3 = new AndroidAppLink("namespace3", "package_name3", // Lists.newArrayList("sha256_cert_fingerprints3")); // public static final AndroidAppLink ANDROID_APP_LINK_4 = new AndroidAppLink("namespace4", "package_name4", // Lists.newArrayList("sha256_cert_fingerprints4")); // public static final AppleAppLink APPLE_APP_LINK = new AppleAppLink("studyId", // Lists.newArrayList("/appId/", "/appId/*")); // public static final AppleAppLink APPLE_APP_LINK_2 = new AppleAppLink("studyId2", // Lists.newArrayList("/appId2/", "/appId2/*")); // public static final AppleAppLink APPLE_APP_LINK_3 = new AppleAppLink("studyId3", // Lists.newArrayList("/appId3/", "/appId3/*")); // public static final AppleAppLink APPLE_APP_LINK_4 = new AppleAppLink("studyId4", // Lists.newArrayList("/appId4/", "/appId4/*")); // // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.mockito.Mockito.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; import java.util.List; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.collect.ImmutableList; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import play.mvc.Result; import play.test.Helpers; import org.sagebionetworks.bridge.Roles; import org.sagebionetworks.bridge.TestConstants; import org.sagebionetworks.bridge.TestUtils; import org.sagebionetworks.bridge.json.BridgeObjectMapper; import org.sagebionetworks.bridge.models.ResourceList; import org.sagebionetworks.bridge.models.accounts.UserSession; import org.sagebionetworks.bridge.models.schedules.CompoundActivityDefinition; import org.sagebionetworks.bridge.services.CompoundActivityDefinitionService; import org.sagebionetworks.bridge.services.StudyService;
package org.sagebionetworks.bridge.play.controllers; public class CompoundActivityDefinitionControllerTest { private static final String TASK_ID = "test-task"; private CompoundActivityDefinitionController controller; private CompoundActivityDefinitionService defService; private StudyService studyService; @Before public void setup() { // mock session UserSession mockSession = new UserSession();
// Path: test/org/sagebionetworks/bridge/TestConstants.java // public class TestConstants { // // public static final String ENCRYPTED_HEALTH_CODE = "TFMkaVFKPD48WissX0bgcD3esBMEshxb3MVgKxHnkXLSEPN4FQMKc01tDbBAVcXx94kMX6ckXVYUZ8wx4iICl08uE+oQr9gorE1hlgAyLAM="; // // public static final String TEST_STUDY_IDENTIFIER = "api"; // public static final StudyIdentifier TEST_STUDY = new StudyIdentifierImpl(TEST_STUDY_IDENTIFIER); // public static final CriteriaContext TEST_CONTEXT = new CriteriaContext.Builder() // .withUserId("user-id").withStudyIdentifier(TestConstants.TEST_STUDY).build(); // // public static final String EMAIL = "email@email.com"; // public static final String PASSWORD = "password"; // // /** // * During tests, must sometimes pause because the underlying query uses a DynamoDB global // * secondary index, and this does not currently support consistent reads. // */ // public static final int GSI_WAIT_DURATION = 2000; // // public static final ConsentStatus REQUIRED_SIGNED_CURRENT = new ConsentStatus.Builder().withName("Name1") // .withGuid(SubpopulationGuid.create("foo1")).withRequired(true).withConsented(true) // .withSignedMostRecentConsent(true).build(); // public static final ConsentStatus REQUIRED_UNSIGNED = new ConsentStatus.Builder().withName("Name1") // .withGuid(SubpopulationGuid.create("foo5")).withRequired(true).withConsented(false) // .withSignedMostRecentConsent(false).build(); // // public static final Map<SubpopulationGuid, ConsentStatus> UNCONSENTED_STATUS_MAP = new ImmutableMap.Builder<SubpopulationGuid, ConsentStatus>() // .put(SubpopulationGuid.create(REQUIRED_UNSIGNED.getSubpopulationGuid()), REQUIRED_UNSIGNED).build(); // // public static final Set<String> USER_DATA_GROUPS = ImmutableSet.of("group1","group2"); // // public static final Set<String> USER_SUBSTUDY_IDS = ImmutableSet.of("substudyA","substudyB"); // // public static final List<String> LANGUAGES = ImmutableList.of("en","fr"); // // public static final Phone PHONE = new Phone("9712486796", "US"); // // public static final AndroidAppLink ANDROID_APP_LINK = new AndroidAppLink("namespace", "package_name", // Lists.newArrayList("sha256_cert_fingerprints")); // public static final AndroidAppLink ANDROID_APP_LINK_2 = new AndroidAppLink("namespace2", "package_name2", // Lists.newArrayList("sha256_cert_fingerprints2")); // public static final AndroidAppLink ANDROID_APP_LINK_3 = new AndroidAppLink("namespace3", "package_name3", // Lists.newArrayList("sha256_cert_fingerprints3")); // public static final AndroidAppLink ANDROID_APP_LINK_4 = new AndroidAppLink("namespace4", "package_name4", // Lists.newArrayList("sha256_cert_fingerprints4")); // public static final AppleAppLink APPLE_APP_LINK = new AppleAppLink("studyId", // Lists.newArrayList("/appId/", "/appId/*")); // public static final AppleAppLink APPLE_APP_LINK_2 = new AppleAppLink("studyId2", // Lists.newArrayList("/appId2/", "/appId2/*")); // public static final AppleAppLink APPLE_APP_LINK_3 = new AppleAppLink("studyId3", // Lists.newArrayList("/appId3/", "/appId3/*")); // public static final AppleAppLink APPLE_APP_LINK_4 = new AppleAppLink("studyId4", // Lists.newArrayList("/appId4/", "/appId4/*")); // // } // Path: test/org/sagebionetworks/bridge/play/controllers/CompoundActivityDefinitionControllerTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.mockito.Mockito.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; import java.util.List; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.collect.ImmutableList; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import play.mvc.Result; import play.test.Helpers; import org.sagebionetworks.bridge.Roles; import org.sagebionetworks.bridge.TestConstants; import org.sagebionetworks.bridge.TestUtils; import org.sagebionetworks.bridge.json.BridgeObjectMapper; import org.sagebionetworks.bridge.models.ResourceList; import org.sagebionetworks.bridge.models.accounts.UserSession; import org.sagebionetworks.bridge.models.schedules.CompoundActivityDefinition; import org.sagebionetworks.bridge.services.CompoundActivityDefinitionService; import org.sagebionetworks.bridge.services.StudyService; package org.sagebionetworks.bridge.play.controllers; public class CompoundActivityDefinitionControllerTest { private static final String TASK_ID = "test-task"; private CompoundActivityDefinitionController controller; private CompoundActivityDefinitionService defService; private StudyService studyService; @Before public void setup() { // mock session UserSession mockSession = new UserSession();
mockSession.setStudyIdentifier(TestConstants.TEST_STUDY);
xiprox/WaniKani-for-Android
WaniKani/src/tr/xip/wanikani/client/error/RetrofitErrorHandler.java
// Path: WaniKani/src/tr/xip/wanikani/app/App.java // public class App extends Application { // // private static App instance; // // private final Billing billing = new Billing(this, new Billing.DefaultConfiguration() { // @Override // public String getPublicKey() { // return "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsKCnkO5/8UsJ0fnXpYi2dxYIkOknG/2KhrGp/k2LGvwx07T4lLIEdSlo6bE785b2vFfG9wMY2tNmwmbBjjVlixVDTMFydbMGRoE2Nd9dQ4Fq+oVlC7SvuAamLJ6atKOAPd2g4Xr74PyURU8lmXnA7MldMYcoBU3wvdHzW5os8r+inkyY14IRyHSoslm/LgWt9YtXtF3XSzgmKRS/uAJXC83SxODgy4KNSizmdqXwZqasRUOQH0nT/yiY5H3n+cMb3aWu68tUuOwQ2GBcGkT2pYzD+qDZ3ADMbz57wR5+9hvI3XG82C2jnsgYXcozcGJA3jbHJCkBL7oFR54vSy3YdQIDAQAB"; // } // }); // // @SuppressLint("StaticFieldLeak") // private static Context context; // // public App() { // instance = this; // } // // @Override // public void onCreate() { // context = getApplicationContext(); // DatabaseManager.init(getApplicationContext()); // PrefManager.init(getApplicationContext()); // super.onCreate(); // } // // public static App get() { // return instance; // } // // public Billing getBilling() { // return billing; // } // // public static Context getContext() { // return context; // } // } // // Path: WaniKani/src/tr/xip/wanikani/content/receiver/BroadcastIntents.java // public class BroadcastIntents { // // public static String SYNC() { // return "action.SYNC"; // } // // public static String RETROFIT_ERROR_CONNECTION() { // return "error.retrofit.CONNECTION"; // } // // public static String RETROFIT_ERROR_UNKNOWN() { // return "error.retrofit.UNKNOWN"; // } // // public static String NOTIFICATION() { // return "NOTIFICATION"; // } // // }
import android.content.Intent; import android.support.v4.content.LocalBroadcastManager; import java.lang.reflect.Field; import tr.xip.wanikani.app.App; import tr.xip.wanikani.content.receiver.BroadcastIntents;
package tr.xip.wanikani.client.error; public class RetrofitErrorHandler { public static void handleError(Throwable throwable) { if (throwable != null) { try { // Ghhhhh! Field f = Throwable.class.getDeclaredField("cause"); f.setAccessible(true); String message = f.get(throwable).toString(); if (message.contains("GaiException") || message.contains("UnknownHostException")) {
// Path: WaniKani/src/tr/xip/wanikani/app/App.java // public class App extends Application { // // private static App instance; // // private final Billing billing = new Billing(this, new Billing.DefaultConfiguration() { // @Override // public String getPublicKey() { // return "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsKCnkO5/8UsJ0fnXpYi2dxYIkOknG/2KhrGp/k2LGvwx07T4lLIEdSlo6bE785b2vFfG9wMY2tNmwmbBjjVlixVDTMFydbMGRoE2Nd9dQ4Fq+oVlC7SvuAamLJ6atKOAPd2g4Xr74PyURU8lmXnA7MldMYcoBU3wvdHzW5os8r+inkyY14IRyHSoslm/LgWt9YtXtF3XSzgmKRS/uAJXC83SxODgy4KNSizmdqXwZqasRUOQH0nT/yiY5H3n+cMb3aWu68tUuOwQ2GBcGkT2pYzD+qDZ3ADMbz57wR5+9hvI3XG82C2jnsgYXcozcGJA3jbHJCkBL7oFR54vSy3YdQIDAQAB"; // } // }); // // @SuppressLint("StaticFieldLeak") // private static Context context; // // public App() { // instance = this; // } // // @Override // public void onCreate() { // context = getApplicationContext(); // DatabaseManager.init(getApplicationContext()); // PrefManager.init(getApplicationContext()); // super.onCreate(); // } // // public static App get() { // return instance; // } // // public Billing getBilling() { // return billing; // } // // public static Context getContext() { // return context; // } // } // // Path: WaniKani/src/tr/xip/wanikani/content/receiver/BroadcastIntents.java // public class BroadcastIntents { // // public static String SYNC() { // return "action.SYNC"; // } // // public static String RETROFIT_ERROR_CONNECTION() { // return "error.retrofit.CONNECTION"; // } // // public static String RETROFIT_ERROR_UNKNOWN() { // return "error.retrofit.UNKNOWN"; // } // // public static String NOTIFICATION() { // return "NOTIFICATION"; // } // // } // Path: WaniKani/src/tr/xip/wanikani/client/error/RetrofitErrorHandler.java import android.content.Intent; import android.support.v4.content.LocalBroadcastManager; import java.lang.reflect.Field; import tr.xip.wanikani.app.App; import tr.xip.wanikani.content.receiver.BroadcastIntents; package tr.xip.wanikani.client.error; public class RetrofitErrorHandler { public static void handleError(Throwable throwable) { if (throwable != null) { try { // Ghhhhh! Field f = Throwable.class.getDeclaredField("cause"); f.setAccessible(true); String message = f.get(throwable).toString(); if (message.contains("GaiException") || message.contains("UnknownHostException")) {
Intent intent = new Intent(BroadcastIntents.RETROFIT_ERROR_CONNECTION());
xiprox/WaniKani-for-Android
WaniKani/src/tr/xip/wanikani/client/error/RetrofitErrorHandler.java
// Path: WaniKani/src/tr/xip/wanikani/app/App.java // public class App extends Application { // // private static App instance; // // private final Billing billing = new Billing(this, new Billing.DefaultConfiguration() { // @Override // public String getPublicKey() { // return "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsKCnkO5/8UsJ0fnXpYi2dxYIkOknG/2KhrGp/k2LGvwx07T4lLIEdSlo6bE785b2vFfG9wMY2tNmwmbBjjVlixVDTMFydbMGRoE2Nd9dQ4Fq+oVlC7SvuAamLJ6atKOAPd2g4Xr74PyURU8lmXnA7MldMYcoBU3wvdHzW5os8r+inkyY14IRyHSoslm/LgWt9YtXtF3XSzgmKRS/uAJXC83SxODgy4KNSizmdqXwZqasRUOQH0nT/yiY5H3n+cMb3aWu68tUuOwQ2GBcGkT2pYzD+qDZ3ADMbz57wR5+9hvI3XG82C2jnsgYXcozcGJA3jbHJCkBL7oFR54vSy3YdQIDAQAB"; // } // }); // // @SuppressLint("StaticFieldLeak") // private static Context context; // // public App() { // instance = this; // } // // @Override // public void onCreate() { // context = getApplicationContext(); // DatabaseManager.init(getApplicationContext()); // PrefManager.init(getApplicationContext()); // super.onCreate(); // } // // public static App get() { // return instance; // } // // public Billing getBilling() { // return billing; // } // // public static Context getContext() { // return context; // } // } // // Path: WaniKani/src/tr/xip/wanikani/content/receiver/BroadcastIntents.java // public class BroadcastIntents { // // public static String SYNC() { // return "action.SYNC"; // } // // public static String RETROFIT_ERROR_CONNECTION() { // return "error.retrofit.CONNECTION"; // } // // public static String RETROFIT_ERROR_UNKNOWN() { // return "error.retrofit.UNKNOWN"; // } // // public static String NOTIFICATION() { // return "NOTIFICATION"; // } // // }
import android.content.Intent; import android.support.v4.content.LocalBroadcastManager; import java.lang.reflect.Field; import tr.xip.wanikani.app.App; import tr.xip.wanikani.content.receiver.BroadcastIntents;
package tr.xip.wanikani.client.error; public class RetrofitErrorHandler { public static void handleError(Throwable throwable) { if (throwable != null) { try { // Ghhhhh! Field f = Throwable.class.getDeclaredField("cause"); f.setAccessible(true); String message = f.get(throwable).toString(); if (message.contains("GaiException") || message.contains("UnknownHostException")) { Intent intent = new Intent(BroadcastIntents.RETROFIT_ERROR_CONNECTION());
// Path: WaniKani/src/tr/xip/wanikani/app/App.java // public class App extends Application { // // private static App instance; // // private final Billing billing = new Billing(this, new Billing.DefaultConfiguration() { // @Override // public String getPublicKey() { // return "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsKCnkO5/8UsJ0fnXpYi2dxYIkOknG/2KhrGp/k2LGvwx07T4lLIEdSlo6bE785b2vFfG9wMY2tNmwmbBjjVlixVDTMFydbMGRoE2Nd9dQ4Fq+oVlC7SvuAamLJ6atKOAPd2g4Xr74PyURU8lmXnA7MldMYcoBU3wvdHzW5os8r+inkyY14IRyHSoslm/LgWt9YtXtF3XSzgmKRS/uAJXC83SxODgy4KNSizmdqXwZqasRUOQH0nT/yiY5H3n+cMb3aWu68tUuOwQ2GBcGkT2pYzD+qDZ3ADMbz57wR5+9hvI3XG82C2jnsgYXcozcGJA3jbHJCkBL7oFR54vSy3YdQIDAQAB"; // } // }); // // @SuppressLint("StaticFieldLeak") // private static Context context; // // public App() { // instance = this; // } // // @Override // public void onCreate() { // context = getApplicationContext(); // DatabaseManager.init(getApplicationContext()); // PrefManager.init(getApplicationContext()); // super.onCreate(); // } // // public static App get() { // return instance; // } // // public Billing getBilling() { // return billing; // } // // public static Context getContext() { // return context; // } // } // // Path: WaniKani/src/tr/xip/wanikani/content/receiver/BroadcastIntents.java // public class BroadcastIntents { // // public static String SYNC() { // return "action.SYNC"; // } // // public static String RETROFIT_ERROR_CONNECTION() { // return "error.retrofit.CONNECTION"; // } // // public static String RETROFIT_ERROR_UNKNOWN() { // return "error.retrofit.UNKNOWN"; // } // // public static String NOTIFICATION() { // return "NOTIFICATION"; // } // // } // Path: WaniKani/src/tr/xip/wanikani/client/error/RetrofitErrorHandler.java import android.content.Intent; import android.support.v4.content.LocalBroadcastManager; import java.lang.reflect.Field; import tr.xip.wanikani.app.App; import tr.xip.wanikani.content.receiver.BroadcastIntents; package tr.xip.wanikani.client.error; public class RetrofitErrorHandler { public static void handleError(Throwable throwable) { if (throwable != null) { try { // Ghhhhh! Field f = Throwable.class.getDeclaredField("cause"); f.setAccessible(true); String message = f.get(throwable).toString(); if (message.contains("GaiException") || message.contains("UnknownHostException")) { Intent intent = new Intent(BroadcastIntents.RETROFIT_ERROR_CONNECTION());
LocalBroadcastManager.getInstance(App.getContext()).sendBroadcast(intent);
xiprox/WaniKani-for-Android
WaniKani/src/tr/xip/wanikani/app/fragment/card/NotificationsCard.java
// Path: WaniKani/src/tr/xip/wanikani/app/activity/NotificationDetailsActivity.java // public class NotificationDetailsActivity extends AppCompatActivity { // public static final String ARG_NOTIFICATION = "notification"; // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_notification_details); // // Bundle bundle = getIntent().getExtras(); // if (bundle != null && bundle.getSerializable(ARG_NOTIFICATION) != null) { // load((Notification) bundle.getSerializable(ARG_NOTIFICATION)); // } else { // finish(); // } // } // // private void load(final Notification item) { // ImageView image = (ImageView) findViewById(R.id.notification_image); // TextView title = (TextView) findViewById(R.id.notification_title); // TextView shortText = (TextView) findViewById(R.id.notification_short_text); // TextView text = (TextView) findViewById(R.id.notification_text); // Button action = (Button) findViewById(R.id.notification_action); // // text.setMovementMethod(new LinkMovementMethod()); // // if (item.getImage() != null) { // Picasso.with(this).load(item.getImage()).into(image); // } else { // image.setVisibility(View.GONE); // } // // if (item.getTitle() != null) { // title.setText(item.getTitle()); // } else { // title.setVisibility(View.GONE); // } // // if (item.getShortText() != null) { // shortText.setText(item.getShortText()); // } else { // shortText.setVisibility(View.GONE); // } // // if (item.getText() != null) { // text.setText(Html.fromHtml(item.getText())); // } else { // text.setVisibility(View.GONE); // } // // if (item.getActionUrl() != null && item.getActionText() != null) { // action.setText(item.getActionText()); // action.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(item.getActionUrl())); // startActivity(intent); // } // }); // } else { // action.setVisibility(View.GONE); // } // // /* Mark notification as read */ // item.setRead(true); // DatabaseManager.saveNotification(item); // } // } // // Path: WaniKani/src/tr/xip/wanikani/models/Notification.java // public class Notification implements Serializable { // public static final String DATA_NOTIFICATION_ID = "notification_id"; // public static final String DATA_NOTIFICATION_TITLE = "notification_title"; // public static final String DATA_NOTIFICATION_SHORT_TEXT = "notification_short_text"; // public static final String DATA_NOTIFICATION_TEXT = "notification_text"; // public static final String DATA_NOTIFICATION_IMAGE = "notification_image"; // public static final String DATA_NOTIFICATION_ACTION_URL = "notification_action_url"; // public static final String DATA_NOTIFICATION_ACTION_TEXT = "notification_action_text"; // // private int id; // private String title; // private String shortText; // private String text; // private String image; // private String actionUrl; // private String actionText; // private boolean read; // // public Notification(int id, String title, String shortText, String text, String image, String actionUrl, String actionText, boolean read) { // this.id = id; // this.title = title; // this.shortText = shortText; // this.text = text; // this.image = image; // this.actionUrl = actionUrl; // this.actionText = actionText; // this.read = read; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getShortText() { // return shortText; // } // // public void setShortText(String shortText) { // this.shortText = shortText; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // // public String getActionUrl() { // return actionUrl; // } // // public void setActionUrl(String actionUrl) { // this.actionUrl = actionUrl; // } // // public String getActionText() { // return actionText; // } // // public void setActionText(String actionText) { // this.actionText = actionText; // } // // public boolean isRead() { // return read; // } // // public void setRead(boolean read) { // this.read = read; // } // }
import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import java.util.List; import tr.xip.wanikani.R; import tr.xip.wanikani.app.activity.NotificationDetailsActivity; import tr.xip.wanikani.models.Notification;
package tr.xip.wanikani.app.fragment.card; public class NotificationsCard extends Fragment { public static final String ARG_NOTIFICATIONS = "notifications"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.card_notifications, container, false); Bundle bundle = getArguments(); //noinspection unchecked
// Path: WaniKani/src/tr/xip/wanikani/app/activity/NotificationDetailsActivity.java // public class NotificationDetailsActivity extends AppCompatActivity { // public static final String ARG_NOTIFICATION = "notification"; // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_notification_details); // // Bundle bundle = getIntent().getExtras(); // if (bundle != null && bundle.getSerializable(ARG_NOTIFICATION) != null) { // load((Notification) bundle.getSerializable(ARG_NOTIFICATION)); // } else { // finish(); // } // } // // private void load(final Notification item) { // ImageView image = (ImageView) findViewById(R.id.notification_image); // TextView title = (TextView) findViewById(R.id.notification_title); // TextView shortText = (TextView) findViewById(R.id.notification_short_text); // TextView text = (TextView) findViewById(R.id.notification_text); // Button action = (Button) findViewById(R.id.notification_action); // // text.setMovementMethod(new LinkMovementMethod()); // // if (item.getImage() != null) { // Picasso.with(this).load(item.getImage()).into(image); // } else { // image.setVisibility(View.GONE); // } // // if (item.getTitle() != null) { // title.setText(item.getTitle()); // } else { // title.setVisibility(View.GONE); // } // // if (item.getShortText() != null) { // shortText.setText(item.getShortText()); // } else { // shortText.setVisibility(View.GONE); // } // // if (item.getText() != null) { // text.setText(Html.fromHtml(item.getText())); // } else { // text.setVisibility(View.GONE); // } // // if (item.getActionUrl() != null && item.getActionText() != null) { // action.setText(item.getActionText()); // action.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(item.getActionUrl())); // startActivity(intent); // } // }); // } else { // action.setVisibility(View.GONE); // } // // /* Mark notification as read */ // item.setRead(true); // DatabaseManager.saveNotification(item); // } // } // // Path: WaniKani/src/tr/xip/wanikani/models/Notification.java // public class Notification implements Serializable { // public static final String DATA_NOTIFICATION_ID = "notification_id"; // public static final String DATA_NOTIFICATION_TITLE = "notification_title"; // public static final String DATA_NOTIFICATION_SHORT_TEXT = "notification_short_text"; // public static final String DATA_NOTIFICATION_TEXT = "notification_text"; // public static final String DATA_NOTIFICATION_IMAGE = "notification_image"; // public static final String DATA_NOTIFICATION_ACTION_URL = "notification_action_url"; // public static final String DATA_NOTIFICATION_ACTION_TEXT = "notification_action_text"; // // private int id; // private String title; // private String shortText; // private String text; // private String image; // private String actionUrl; // private String actionText; // private boolean read; // // public Notification(int id, String title, String shortText, String text, String image, String actionUrl, String actionText, boolean read) { // this.id = id; // this.title = title; // this.shortText = shortText; // this.text = text; // this.image = image; // this.actionUrl = actionUrl; // this.actionText = actionText; // this.read = read; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getShortText() { // return shortText; // } // // public void setShortText(String shortText) { // this.shortText = shortText; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // // public String getActionUrl() { // return actionUrl; // } // // public void setActionUrl(String actionUrl) { // this.actionUrl = actionUrl; // } // // public String getActionText() { // return actionText; // } // // public void setActionText(String actionText) { // this.actionText = actionText; // } // // public boolean isRead() { // return read; // } // // public void setRead(boolean read) { // this.read = read; // } // } // Path: WaniKani/src/tr/xip/wanikani/app/fragment/card/NotificationsCard.java import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import java.util.List; import tr.xip.wanikani.R; import tr.xip.wanikani.app.activity.NotificationDetailsActivity; import tr.xip.wanikani.models.Notification; package tr.xip.wanikani.app.fragment.card; public class NotificationsCard extends Fragment { public static final String ARG_NOTIFICATIONS = "notifications"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.card_notifications, container, false); Bundle bundle = getArguments(); //noinspection unchecked
List<Notification> notifications = (List<Notification>) bundle.getSerializable(ARG_NOTIFICATIONS);
xiprox/WaniKani-for-Android
WaniKani/src/tr/xip/wanikani/database/SQL.java
// Path: WaniKani/src/tr/xip/wanikani/database/table/NotificationsTable.java // public class NotificationsTable implements BaseColumns { // public static final String TABLE_NAME = "notifications"; // public static final String COLUMN_NAME_ID = "_id"; // public static final String COLUMN_NAME_TITLE = "title"; // public static final String COLUMN_NAME_SHORT_TEXT = "short_text"; // public static final String COLUMN_NAME_TEXT = "text"; // public static final String COLUMN_NAME_IMAGE = "image"; // public static final String COLUMN_NAME_ACTION_URL = "action_url"; // public static final String COLUMN_NAME_ACTION_TEXT = "action_text"; // public static final String COLUMN_NAME_READ = "read"; // public static final String COLUMN_NAME_NULLABLE = "nullable"; // // public static final String[] COLUMNS = { // COLUMN_NAME_ID, // COLUMN_NAME_TITLE, // COLUMN_NAME_SHORT_TEXT, // COLUMN_NAME_TEXT, // COLUMN_NAME_IMAGE, // COLUMN_NAME_ACTION_URL, // COLUMN_NAME_ACTION_TEXT, // COLUMN_NAME_READ, // COLUMN_NAME_NULLABLE // }; // }
import tr.xip.wanikani.database.table.CriticalItemsTable; import tr.xip.wanikani.database.table.ItemsTable; import tr.xip.wanikani.database.table.LevelProgressionTable; import tr.xip.wanikani.database.table.NotificationsTable; import tr.xip.wanikani.database.table.RecentUnlocksTable; import tr.xip.wanikani.database.table.SRSDistributionTable; import tr.xip.wanikani.database.table.StudyQueueTable; import tr.xip.wanikani.database.table.UsersTable;
+ SRSDistributionTable.COLUMN_NAME_ENLIGHTENED_KANJI + INTEGER_TYPE + COMMA_SEP + SRSDistributionTable.COLUMN_NAME_ENLIGHTENED_VOCABULARY + INTEGER_TYPE + COMMA_SEP + SRSDistributionTable.COLUMN_NAME_BURNED_RADICALS + INTEGER_TYPE + COMMA_SEP + SRSDistributionTable.COLUMN_NAME_BURNED_KANJI + INTEGER_TYPE + COMMA_SEP + SRSDistributionTable.COLUMN_NAME_BURNED_VOCABULARY + INTEGER_TYPE + COMMA_SEP + SRSDistributionTable.COLUMN_NAME_NULLABLE + TEXT_TYPE + ")"; public static final String DELETE_TABLE_SRS = "DROP TABLE IF EXISTS " + SRSDistributionTable.TABLE_NAME; public static final String CREATE_TABLE_USERS = "CREATE TABLE " + UsersTable.TABLE_NAME + " (" + UsersTable.COLUMN_NAME_ID + INTEGER_PRIMARY_KEY_AUTOINCREMENT + COMMA_SEP + UsersTable.COLUMN_NAME_USERNAME + TEXT_TYPE + COMMA_SEP + UsersTable.COLUMN_NAME_GRAVATAR + TEXT_TYPE + COMMA_SEP + UsersTable.COLUMN_NAME_LEVEL + INTEGER_TYPE + COMMA_SEP + UsersTable.COLUMN_NAME_TITLE + TEXT_TYPE + COMMA_SEP + UsersTable.COLUMN_NAME_ABOUT + TEXT_TYPE + COMMA_SEP + UsersTable.COLUMN_NAME_WEBSITE + TEXT_TYPE + COMMA_SEP + UsersTable.COLUMN_NAME_TWITTER + TEXT_TYPE + COMMA_SEP + UsersTable.COLUMN_NAME_TOPICS_COUNT + INTEGER_TYPE + COMMA_SEP + UsersTable.COLUMN_NAME_POSTS_COUNT + INTEGER_TYPE + COMMA_SEP + UsersTable.COLUMN_NAME_CREATION_DATE + INTEGER_TYPE + COMMA_SEP + UsersTable.COLUMN_NAME_VACATION_DATE + INTEGER_TYPE + COMMA_SEP + UsersTable.COLUMN_NAME_NULLABLE + TEXT_TYPE + ")"; public static final String DELETE_TABLE_USERS = "DROP TABLE IF EXISTS " + UsersTable.TABLE_NAME; public static final String CREATE_TABLE_NOTIFICATIONS = "CREATE TABLE "
// Path: WaniKani/src/tr/xip/wanikani/database/table/NotificationsTable.java // public class NotificationsTable implements BaseColumns { // public static final String TABLE_NAME = "notifications"; // public static final String COLUMN_NAME_ID = "_id"; // public static final String COLUMN_NAME_TITLE = "title"; // public static final String COLUMN_NAME_SHORT_TEXT = "short_text"; // public static final String COLUMN_NAME_TEXT = "text"; // public static final String COLUMN_NAME_IMAGE = "image"; // public static final String COLUMN_NAME_ACTION_URL = "action_url"; // public static final String COLUMN_NAME_ACTION_TEXT = "action_text"; // public static final String COLUMN_NAME_READ = "read"; // public static final String COLUMN_NAME_NULLABLE = "nullable"; // // public static final String[] COLUMNS = { // COLUMN_NAME_ID, // COLUMN_NAME_TITLE, // COLUMN_NAME_SHORT_TEXT, // COLUMN_NAME_TEXT, // COLUMN_NAME_IMAGE, // COLUMN_NAME_ACTION_URL, // COLUMN_NAME_ACTION_TEXT, // COLUMN_NAME_READ, // COLUMN_NAME_NULLABLE // }; // } // Path: WaniKani/src/tr/xip/wanikani/database/SQL.java import tr.xip.wanikani.database.table.CriticalItemsTable; import tr.xip.wanikani.database.table.ItemsTable; import tr.xip.wanikani.database.table.LevelProgressionTable; import tr.xip.wanikani.database.table.NotificationsTable; import tr.xip.wanikani.database.table.RecentUnlocksTable; import tr.xip.wanikani.database.table.SRSDistributionTable; import tr.xip.wanikani.database.table.StudyQueueTable; import tr.xip.wanikani.database.table.UsersTable; + SRSDistributionTable.COLUMN_NAME_ENLIGHTENED_KANJI + INTEGER_TYPE + COMMA_SEP + SRSDistributionTable.COLUMN_NAME_ENLIGHTENED_VOCABULARY + INTEGER_TYPE + COMMA_SEP + SRSDistributionTable.COLUMN_NAME_BURNED_RADICALS + INTEGER_TYPE + COMMA_SEP + SRSDistributionTable.COLUMN_NAME_BURNED_KANJI + INTEGER_TYPE + COMMA_SEP + SRSDistributionTable.COLUMN_NAME_BURNED_VOCABULARY + INTEGER_TYPE + COMMA_SEP + SRSDistributionTable.COLUMN_NAME_NULLABLE + TEXT_TYPE + ")"; public static final String DELETE_TABLE_SRS = "DROP TABLE IF EXISTS " + SRSDistributionTable.TABLE_NAME; public static final String CREATE_TABLE_USERS = "CREATE TABLE " + UsersTable.TABLE_NAME + " (" + UsersTable.COLUMN_NAME_ID + INTEGER_PRIMARY_KEY_AUTOINCREMENT + COMMA_SEP + UsersTable.COLUMN_NAME_USERNAME + TEXT_TYPE + COMMA_SEP + UsersTable.COLUMN_NAME_GRAVATAR + TEXT_TYPE + COMMA_SEP + UsersTable.COLUMN_NAME_LEVEL + INTEGER_TYPE + COMMA_SEP + UsersTable.COLUMN_NAME_TITLE + TEXT_TYPE + COMMA_SEP + UsersTable.COLUMN_NAME_ABOUT + TEXT_TYPE + COMMA_SEP + UsersTable.COLUMN_NAME_WEBSITE + TEXT_TYPE + COMMA_SEP + UsersTable.COLUMN_NAME_TWITTER + TEXT_TYPE + COMMA_SEP + UsersTable.COLUMN_NAME_TOPICS_COUNT + INTEGER_TYPE + COMMA_SEP + UsersTable.COLUMN_NAME_POSTS_COUNT + INTEGER_TYPE + COMMA_SEP + UsersTable.COLUMN_NAME_CREATION_DATE + INTEGER_TYPE + COMMA_SEP + UsersTable.COLUMN_NAME_VACATION_DATE + INTEGER_TYPE + COMMA_SEP + UsersTable.COLUMN_NAME_NULLABLE + TEXT_TYPE + ")"; public static final String DELETE_TABLE_USERS = "DROP TABLE IF EXISTS " + UsersTable.TABLE_NAME; public static final String CREATE_TABLE_NOTIFICATIONS = "CREATE TABLE "
+ NotificationsTable.TABLE_NAME + " ("
xiprox/WaniKani-for-Android
WaniKani/src/tr/xip/wanikani/client/task/callback/ThroughDbCallback.java
// Path: WaniKani/src/tr/xip/wanikani/client/error/RetrofitErrorHandler.java // public class RetrofitErrorHandler { // public static void handleError(Throwable throwable) { // // if (throwable != null) { // try { // // Ghhhhh! // Field f = Throwable.class.getDeclaredField("cause"); // f.setAccessible(true); // String message = f.get(throwable).toString(); // // if (message.contains("GaiException") || message.contains("UnknownHostException")) { // Intent intent = new Intent(BroadcastIntents.RETROFIT_ERROR_CONNECTION()); // LocalBroadcastManager.getInstance(App.getContext()).sendBroadcast(intent); // } else { // Intent intent = new Intent(BroadcastIntents.RETROFIT_ERROR_UNKNOWN()); // LocalBroadcastManager.getInstance(App.getContext()).sendBroadcast(intent); // } // } catch (NoSuchFieldException e) { // e.printStackTrace(); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } // } // } // } // // Path: WaniKani/src/tr/xip/wanikani/models/Request.java // public class Request<T> { // public User user_information; // public T requested_information; // public Error error; // } // // Path: WaniKani/src/tr/xip/wanikani/models/Storable.java // public interface Storable { // void save(); // } // // Path: WaniKani/src/tr/xip/wanikani/models/User.java // public class User implements Serializable, Storable { // public String username; // public String gravatar; // public int level; // public String title; // public String about; // public String website; // public String twitter; // public int topics_count; // public int posts_count; // public long creation_date; // public long vacation_date; // // public User(String username, String gravatar, int level, String title, String about, // String website, String twitter, int topicsCount, int postsCount, long creationDate, // long vacationDate) { // this.username = username; // this.gravatar = gravatar; // this.level = level; // this.title = title; // this.about = about; // this.website = website; // this.twitter = twitter; // this.topics_count = topicsCount; // this.posts_count = postsCount; // this.creation_date = creationDate; // this.vacation_date = vacationDate; // } // // public long getCreationDateInMillis() { // return creation_date * 1000; // } // // public long getVacationDateInMillis() { // return vacation_date * 1000; // } // // public boolean isVacationModeActive() { // return getVacationDateInMillis() != 0; // } // // @Override // public void save() { // DatabaseManager.saveUser(this); // } // }
import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import tr.xip.wanikani.client.error.RetrofitErrorHandler; import tr.xip.wanikani.models.Request; import tr.xip.wanikani.models.Storable; import tr.xip.wanikani.models.User;
package tr.xip.wanikani.client.task.callback; public abstract class ThroughDbCallback<T extends Request<B>, B extends Storable> implements Callback<T> { @Override public void onResponse(Call<T> call, Response<T> response) { T result = response.body(); if (result == null) return;
// Path: WaniKani/src/tr/xip/wanikani/client/error/RetrofitErrorHandler.java // public class RetrofitErrorHandler { // public static void handleError(Throwable throwable) { // // if (throwable != null) { // try { // // Ghhhhh! // Field f = Throwable.class.getDeclaredField("cause"); // f.setAccessible(true); // String message = f.get(throwable).toString(); // // if (message.contains("GaiException") || message.contains("UnknownHostException")) { // Intent intent = new Intent(BroadcastIntents.RETROFIT_ERROR_CONNECTION()); // LocalBroadcastManager.getInstance(App.getContext()).sendBroadcast(intent); // } else { // Intent intent = new Intent(BroadcastIntents.RETROFIT_ERROR_UNKNOWN()); // LocalBroadcastManager.getInstance(App.getContext()).sendBroadcast(intent); // } // } catch (NoSuchFieldException e) { // e.printStackTrace(); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } // } // } // } // // Path: WaniKani/src/tr/xip/wanikani/models/Request.java // public class Request<T> { // public User user_information; // public T requested_information; // public Error error; // } // // Path: WaniKani/src/tr/xip/wanikani/models/Storable.java // public interface Storable { // void save(); // } // // Path: WaniKani/src/tr/xip/wanikani/models/User.java // public class User implements Serializable, Storable { // public String username; // public String gravatar; // public int level; // public String title; // public String about; // public String website; // public String twitter; // public int topics_count; // public int posts_count; // public long creation_date; // public long vacation_date; // // public User(String username, String gravatar, int level, String title, String about, // String website, String twitter, int topicsCount, int postsCount, long creationDate, // long vacationDate) { // this.username = username; // this.gravatar = gravatar; // this.level = level; // this.title = title; // this.about = about; // this.website = website; // this.twitter = twitter; // this.topics_count = topicsCount; // this.posts_count = postsCount; // this.creation_date = creationDate; // this.vacation_date = vacationDate; // } // // public long getCreationDateInMillis() { // return creation_date * 1000; // } // // public long getVacationDateInMillis() { // return vacation_date * 1000; // } // // public boolean isVacationModeActive() { // return getVacationDateInMillis() != 0; // } // // @Override // public void save() { // DatabaseManager.saveUser(this); // } // } // Path: WaniKani/src/tr/xip/wanikani/client/task/callback/ThroughDbCallback.java import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import tr.xip.wanikani.client.error.RetrofitErrorHandler; import tr.xip.wanikani.models.Request; import tr.xip.wanikani.models.Storable; import tr.xip.wanikani.models.User; package tr.xip.wanikani.client.task.callback; public abstract class ThroughDbCallback<T extends Request<B>, B extends Storable> implements Callback<T> { @Override public void onResponse(Call<T> call, Response<T> response) { T result = response.body(); if (result == null) return;
final User userInfo = result.user_information;
xiprox/WaniKani-for-Android
WaniKani/src/tr/xip/wanikani/client/task/callback/ThroughDbCallback.java
// Path: WaniKani/src/tr/xip/wanikani/client/error/RetrofitErrorHandler.java // public class RetrofitErrorHandler { // public static void handleError(Throwable throwable) { // // if (throwable != null) { // try { // // Ghhhhh! // Field f = Throwable.class.getDeclaredField("cause"); // f.setAccessible(true); // String message = f.get(throwable).toString(); // // if (message.contains("GaiException") || message.contains("UnknownHostException")) { // Intent intent = new Intent(BroadcastIntents.RETROFIT_ERROR_CONNECTION()); // LocalBroadcastManager.getInstance(App.getContext()).sendBroadcast(intent); // } else { // Intent intent = new Intent(BroadcastIntents.RETROFIT_ERROR_UNKNOWN()); // LocalBroadcastManager.getInstance(App.getContext()).sendBroadcast(intent); // } // } catch (NoSuchFieldException e) { // e.printStackTrace(); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } // } // } // } // // Path: WaniKani/src/tr/xip/wanikani/models/Request.java // public class Request<T> { // public User user_information; // public T requested_information; // public Error error; // } // // Path: WaniKani/src/tr/xip/wanikani/models/Storable.java // public interface Storable { // void save(); // } // // Path: WaniKani/src/tr/xip/wanikani/models/User.java // public class User implements Serializable, Storable { // public String username; // public String gravatar; // public int level; // public String title; // public String about; // public String website; // public String twitter; // public int topics_count; // public int posts_count; // public long creation_date; // public long vacation_date; // // public User(String username, String gravatar, int level, String title, String about, // String website, String twitter, int topicsCount, int postsCount, long creationDate, // long vacationDate) { // this.username = username; // this.gravatar = gravatar; // this.level = level; // this.title = title; // this.about = about; // this.website = website; // this.twitter = twitter; // this.topics_count = topicsCount; // this.posts_count = postsCount; // this.creation_date = creationDate; // this.vacation_date = vacationDate; // } // // public long getCreationDateInMillis() { // return creation_date * 1000; // } // // public long getVacationDateInMillis() { // return vacation_date * 1000; // } // // public boolean isVacationModeActive() { // return getVacationDateInMillis() != 0; // } // // @Override // public void save() { // DatabaseManager.saveUser(this); // } // }
import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import tr.xip.wanikani.client.error.RetrofitErrorHandler; import tr.xip.wanikani.models.Request; import tr.xip.wanikani.models.Storable; import tr.xip.wanikani.models.User;
package tr.xip.wanikani.client.task.callback; public abstract class ThroughDbCallback<T extends Request<B>, B extends Storable> implements Callback<T> { @Override public void onResponse(Call<T> call, Response<T> response) { T result = response.body(); if (result == null) return; final User userInfo = result.user_information; final B requestedInfo = result.requested_information; if (result.error == null && (userInfo != null || requestedInfo != null)) { new Thread(new Runnable() { @Override public void run() { if (userInfo != null) { userInfo.save(); } if (requestedInfo != null) { requestedInfo.save(); } } }).start(); } } @Override public void onFailure(Call<T> call, Throwable t) {
// Path: WaniKani/src/tr/xip/wanikani/client/error/RetrofitErrorHandler.java // public class RetrofitErrorHandler { // public static void handleError(Throwable throwable) { // // if (throwable != null) { // try { // // Ghhhhh! // Field f = Throwable.class.getDeclaredField("cause"); // f.setAccessible(true); // String message = f.get(throwable).toString(); // // if (message.contains("GaiException") || message.contains("UnknownHostException")) { // Intent intent = new Intent(BroadcastIntents.RETROFIT_ERROR_CONNECTION()); // LocalBroadcastManager.getInstance(App.getContext()).sendBroadcast(intent); // } else { // Intent intent = new Intent(BroadcastIntents.RETROFIT_ERROR_UNKNOWN()); // LocalBroadcastManager.getInstance(App.getContext()).sendBroadcast(intent); // } // } catch (NoSuchFieldException e) { // e.printStackTrace(); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } // } // } // } // // Path: WaniKani/src/tr/xip/wanikani/models/Request.java // public class Request<T> { // public User user_information; // public T requested_information; // public Error error; // } // // Path: WaniKani/src/tr/xip/wanikani/models/Storable.java // public interface Storable { // void save(); // } // // Path: WaniKani/src/tr/xip/wanikani/models/User.java // public class User implements Serializable, Storable { // public String username; // public String gravatar; // public int level; // public String title; // public String about; // public String website; // public String twitter; // public int topics_count; // public int posts_count; // public long creation_date; // public long vacation_date; // // public User(String username, String gravatar, int level, String title, String about, // String website, String twitter, int topicsCount, int postsCount, long creationDate, // long vacationDate) { // this.username = username; // this.gravatar = gravatar; // this.level = level; // this.title = title; // this.about = about; // this.website = website; // this.twitter = twitter; // this.topics_count = topicsCount; // this.posts_count = postsCount; // this.creation_date = creationDate; // this.vacation_date = vacationDate; // } // // public long getCreationDateInMillis() { // return creation_date * 1000; // } // // public long getVacationDateInMillis() { // return vacation_date * 1000; // } // // public boolean isVacationModeActive() { // return getVacationDateInMillis() != 0; // } // // @Override // public void save() { // DatabaseManager.saveUser(this); // } // } // Path: WaniKani/src/tr/xip/wanikani/client/task/callback/ThroughDbCallback.java import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import tr.xip.wanikani.client.error.RetrofitErrorHandler; import tr.xip.wanikani.models.Request; import tr.xip.wanikani.models.Storable; import tr.xip.wanikani.models.User; package tr.xip.wanikani.client.task.callback; public abstract class ThroughDbCallback<T extends Request<B>, B extends Storable> implements Callback<T> { @Override public void onResponse(Call<T> call, Response<T> response) { T result = response.body(); if (result == null) return; final User userInfo = result.user_information; final B requestedInfo = result.requested_information; if (result.error == null && (userInfo != null || requestedInfo != null)) { new Thread(new Runnable() { @Override public void run() { if (userInfo != null) { userInfo.save(); } if (requestedInfo != null) { requestedInfo.save(); } } }).start(); } } @Override public void onFailure(Call<T> call, Throwable t) {
RetrofitErrorHandler.handleError(t);
fhoeben/hsac-fitnesse-plugin
src/main/java/nl/hsac/fitnesse/util/iban/IbanGenerator.java
// Path: src/main/java/nl/hsac/fitnesse/util/RandomUtil.java // public class RandomUtil { // private Random random = new SecureRandom(); // // /** // * Generates random number below a certain value. // * // * @param max max (non-inclusive) value for returned number. // * @return random number // */ // public int random(int max) { // return random.nextInt(max); // } // // /** // * Creates a random string consisting only of supplied characters. // * // * @param permitted string consisting of permitted characters. // * @param length length of string to create. // * @return random string. // */ // public String randomString(String permitted, int length) { // StringBuilder result = new StringBuilder(length); // int maxIndex = permitted.length(); // for (int i = 0; i < length; i++) { // int index = random(maxIndex); // char value = permitted.charAt(index); // result.append(value); // } // return result.toString(); // } // // /** // * Picks and returns a random value from the supplied array. // * Does not work for arrays of 'primitives' (e.g. int[] or byte[]). // * // * @param <T> type of element. // * @param elements the array from which a value will be picked. // * @return random element from the array of values. // */ // public <T> T randomElement(T[] elements) { // return elements[random(elements.length)]; // } // // /** // * Creates a random split in an integer, resulting in two integers. // * These two integers added together will result in the original input // * Minimal input value is 2 // * // * @param inputValue integer that needs to be split. // * @return array with two integers. // */ // public int[] getRandomSplit(int inputValue) { // if (inputValue < 2) { // throw new IllegalArgumentException("Minimal possible value to split is 2"); // } // int firstValue = random(inputValue - 1) + 1; //+1 so it will never become 0 // int secondValue = inputValue - firstValue;// // int split[] = {firstValue, secondValue}; // return split; // } // }
import nl.hsac.fitnesse.util.RandomUtil; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.nio.charset.Charset; import java.util.Enumeration; import java.util.List; import java.util.stream.Collectors;
package nl.hsac.fitnesse.util.iban; /** * To select a country and parse the iban request to the proper class */ public class IbanGenerator { private static final Charset UTF8 = Charset.forName("utf-8");
// Path: src/main/java/nl/hsac/fitnesse/util/RandomUtil.java // public class RandomUtil { // private Random random = new SecureRandom(); // // /** // * Generates random number below a certain value. // * // * @param max max (non-inclusive) value for returned number. // * @return random number // */ // public int random(int max) { // return random.nextInt(max); // } // // /** // * Creates a random string consisting only of supplied characters. // * // * @param permitted string consisting of permitted characters. // * @param length length of string to create. // * @return random string. // */ // public String randomString(String permitted, int length) { // StringBuilder result = new StringBuilder(length); // int maxIndex = permitted.length(); // for (int i = 0; i < length; i++) { // int index = random(maxIndex); // char value = permitted.charAt(index); // result.append(value); // } // return result.toString(); // } // // /** // * Picks and returns a random value from the supplied array. // * Does not work for arrays of 'primitives' (e.g. int[] or byte[]). // * // * @param <T> type of element. // * @param elements the array from which a value will be picked. // * @return random element from the array of values. // */ // public <T> T randomElement(T[] elements) { // return elements[random(elements.length)]; // } // // /** // * Creates a random split in an integer, resulting in two integers. // * These two integers added together will result in the original input // * Minimal input value is 2 // * // * @param inputValue integer that needs to be split. // * @return array with two integers. // */ // public int[] getRandomSplit(int inputValue) { // if (inputValue < 2) { // throw new IllegalArgumentException("Minimal possible value to split is 2"); // } // int firstValue = random(inputValue - 1) + 1; //+1 so it will never become 0 // int secondValue = inputValue - firstValue;// // int split[] = {firstValue, secondValue}; // return split; // } // } // Path: src/main/java/nl/hsac/fitnesse/util/iban/IbanGenerator.java import nl.hsac.fitnesse.util.RandomUtil; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.nio.charset.Charset; import java.util.Enumeration; import java.util.List; import java.util.stream.Collectors; package nl.hsac.fitnesse.util.iban; /** * To select a country and parse the iban request to the proper class */ public class IbanGenerator { private static final Charset UTF8 = Charset.forName("utf-8");
protected static final RandomUtil RANDOM_UTIL = new RandomUtil();
fhoeben/hsac-fitnesse-plugin
src/main/java/nl/hsac/fitnesse/slim/AutoArgScenarioTable.java
// Path: src/main/java/nl/hsac/fitnesse/slimcoverage/SlimCoverageTestContextImpl.java // public class SlimCoverageTestContextImpl extends SlimTestContextImpl { // private final SlimScenarioUsagePer usage; // // public SlimCoverageTestContextImpl(TestPage testPage, SlimScenarioUsagePer usageByPage) { // super(testPage); // usage = usageByPage; // } // // @Override // public void addScenario(String scenarioName, ScenarioTable scenarioTable) { // if (usage != null) { // String key = getGroupName(scenarioTable); // usage.addDefinition(key); // } // super.addScenario(scenarioName, scenarioTable); // } // // public ScenarioTable getScenario(String scenarioName) { // ScenarioTable scenarioTable = getScenarioNoCount(scenarioName); // trackUsage(scenarioTable); // return scenarioTable; // } // // public ScenarioTable getScenarioNoCount(String scenarioName) { // return super.getScenario(scenarioName); // } // // @Override // public ScenarioTable getScenarioByPattern(String invokingString) { // ScenarioTable scenarioTable = getScenarioByPatternNoCount(invokingString); // trackUsage(scenarioTable); // return scenarioTable; // } // // public ScenarioTable getScenarioByPatternNoCount(String invokingString) { // return super.getScenarioByPattern(invokingString); // } // // protected void trackUsage(ScenarioTable scenarioTable) { // if (usage != null && scenarioTable != null) { // String key = getGroupName(scenarioTable); // usage.addUsage(key); // } // } // // protected String getGroupName(ScenarioTable scenarioTable) { // String name = scenarioTable.getName(); // int inputCount = scenarioTable.getInputs().size(); // int outputCount = scenarioTable.getOutputs().size(); // String keyPattern; // if (inputCount == 0 && outputCount == 0) { // keyPattern = "%s"; // } else if (outputCount == 0) { // keyPattern = "%s[%s]"; // } else { // keyPattern = "%s[%s,%s]"; // } // return String.format(keyPattern, name, inputCount, outputCount); // } // }
import fitnesse.testsystems.TestExecutionException; import fitnesse.testsystems.slim.SlimTestContext; import fitnesse.testsystems.slim.Table; import fitnesse.testsystems.slim.tables.*; import nl.hsac.fitnesse.slimcoverage.SlimCoverageTestContextImpl; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern;
for (int column = 0; column < columnCount; column++) { String cellContent = table.getCellContents(column, row); addAllMatches(pattern, found, cellContent); } } return found; } private ScenarioTable getCalledScenario(int lastCol, int row) throws SyntaxError { String scenarioName = ScriptTable.RowHelper.getScenarioNameFromAlternatingCells(table, lastCol, row); ScenarioTable scenario = getScenarioByName(scenarioName); if (scenario == null && lastCol == 0) { String cellContents = table.getCellContents(0, row); scenario = getScenarioByPattern(cellContents); } return scenario; } private boolean isAutoArgCallWithoutParameters(ScenarioTable calledScenario, int columnCount) { return calledScenario instanceof AutoArgScenarioTable && columnCount == 1; } private void addNestedScenarioArguments(Set<String> found, boolean addInputs, ScenarioTable scenario) { Set<String> scenarioArgs = addInputs ? scenario.getInputs() : scenario.getOutputs(); found.addAll(scenarioArgs); } private ScenarioTable getScenarioByName(String scenarioName) { SlimTestContext testContext = getTestContext(); ScenarioTable scenario;
// Path: src/main/java/nl/hsac/fitnesse/slimcoverage/SlimCoverageTestContextImpl.java // public class SlimCoverageTestContextImpl extends SlimTestContextImpl { // private final SlimScenarioUsagePer usage; // // public SlimCoverageTestContextImpl(TestPage testPage, SlimScenarioUsagePer usageByPage) { // super(testPage); // usage = usageByPage; // } // // @Override // public void addScenario(String scenarioName, ScenarioTable scenarioTable) { // if (usage != null) { // String key = getGroupName(scenarioTable); // usage.addDefinition(key); // } // super.addScenario(scenarioName, scenarioTable); // } // // public ScenarioTable getScenario(String scenarioName) { // ScenarioTable scenarioTable = getScenarioNoCount(scenarioName); // trackUsage(scenarioTable); // return scenarioTable; // } // // public ScenarioTable getScenarioNoCount(String scenarioName) { // return super.getScenario(scenarioName); // } // // @Override // public ScenarioTable getScenarioByPattern(String invokingString) { // ScenarioTable scenarioTable = getScenarioByPatternNoCount(invokingString); // trackUsage(scenarioTable); // return scenarioTable; // } // // public ScenarioTable getScenarioByPatternNoCount(String invokingString) { // return super.getScenarioByPattern(invokingString); // } // // protected void trackUsage(ScenarioTable scenarioTable) { // if (usage != null && scenarioTable != null) { // String key = getGroupName(scenarioTable); // usage.addUsage(key); // } // } // // protected String getGroupName(ScenarioTable scenarioTable) { // String name = scenarioTable.getName(); // int inputCount = scenarioTable.getInputs().size(); // int outputCount = scenarioTable.getOutputs().size(); // String keyPattern; // if (inputCount == 0 && outputCount == 0) { // keyPattern = "%s"; // } else if (outputCount == 0) { // keyPattern = "%s[%s]"; // } else { // keyPattern = "%s[%s,%s]"; // } // return String.format(keyPattern, name, inputCount, outputCount); // } // } // Path: src/main/java/nl/hsac/fitnesse/slim/AutoArgScenarioTable.java import fitnesse.testsystems.TestExecutionException; import fitnesse.testsystems.slim.SlimTestContext; import fitnesse.testsystems.slim.Table; import fitnesse.testsystems.slim.tables.*; import nl.hsac.fitnesse.slimcoverage.SlimCoverageTestContextImpl; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; for (int column = 0; column < columnCount; column++) { String cellContent = table.getCellContents(column, row); addAllMatches(pattern, found, cellContent); } } return found; } private ScenarioTable getCalledScenario(int lastCol, int row) throws SyntaxError { String scenarioName = ScriptTable.RowHelper.getScenarioNameFromAlternatingCells(table, lastCol, row); ScenarioTable scenario = getScenarioByName(scenarioName); if (scenario == null && lastCol == 0) { String cellContents = table.getCellContents(0, row); scenario = getScenarioByPattern(cellContents); } return scenario; } private boolean isAutoArgCallWithoutParameters(ScenarioTable calledScenario, int columnCount) { return calledScenario instanceof AutoArgScenarioTable && columnCount == 1; } private void addNestedScenarioArguments(Set<String> found, boolean addInputs, ScenarioTable scenario) { Set<String> scenarioArgs = addInputs ? scenario.getInputs() : scenario.getOutputs(); found.addAll(scenarioArgs); } private ScenarioTable getScenarioByName(String scenarioName) { SlimTestContext testContext = getTestContext(); ScenarioTable scenario;
if (testContext instanceof SlimCoverageTestContextImpl) {
fhoeben/hsac-fitnesse-plugin
src/test/java/nl/hsac/fitnesse/util/iban/IbanGeneratorTest.java
// Path: src/main/java/nl/hsac/fitnesse/util/RandomUtil.java // public class RandomUtil { // private Random random = new SecureRandom(); // // /** // * Generates random number below a certain value. // * // * @param max max (non-inclusive) value for returned number. // * @return random number // */ // public int random(int max) { // return random.nextInt(max); // } // // /** // * Creates a random string consisting only of supplied characters. // * // * @param permitted string consisting of permitted characters. // * @param length length of string to create. // * @return random string. // */ // public String randomString(String permitted, int length) { // StringBuilder result = new StringBuilder(length); // int maxIndex = permitted.length(); // for (int i = 0; i < length; i++) { // int index = random(maxIndex); // char value = permitted.charAt(index); // result.append(value); // } // return result.toString(); // } // // /** // * Picks and returns a random value from the supplied array. // * Does not work for arrays of 'primitives' (e.g. int[] or byte[]). // * // * @param <T> type of element. // * @param elements the array from which a value will be picked. // * @return random element from the array of values. // */ // public <T> T randomElement(T[] elements) { // return elements[random(elements.length)]; // } // // /** // * Creates a random split in an integer, resulting in two integers. // * These two integers added together will result in the original input // * Minimal input value is 2 // * // * @param inputValue integer that needs to be split. // * @return array with two integers. // */ // public int[] getRandomSplit(int inputValue) { // if (inputValue < 2) { // throw new IllegalArgumentException("Minimal possible value to split is 2"); // } // int firstValue = random(inputValue - 1) + 1; //+1 so it will never become 0 // int secondValue = inputValue - firstValue;// // int split[] = {firstValue, secondValue}; // return split; // } // }
import nl.hsac.fitnesse.util.RandomUtil; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue;
package nl.hsac.fitnesse.util.iban; /** * Tests IbanUtil. */ public class IbanGeneratorTest { private final IbanGenerator ibanGenerator = new IbanGenerator();
// Path: src/main/java/nl/hsac/fitnesse/util/RandomUtil.java // public class RandomUtil { // private Random random = new SecureRandom(); // // /** // * Generates random number below a certain value. // * // * @param max max (non-inclusive) value for returned number. // * @return random number // */ // public int random(int max) { // return random.nextInt(max); // } // // /** // * Creates a random string consisting only of supplied characters. // * // * @param permitted string consisting of permitted characters. // * @param length length of string to create. // * @return random string. // */ // public String randomString(String permitted, int length) { // StringBuilder result = new StringBuilder(length); // int maxIndex = permitted.length(); // for (int i = 0; i < length; i++) { // int index = random(maxIndex); // char value = permitted.charAt(index); // result.append(value); // } // return result.toString(); // } // // /** // * Picks and returns a random value from the supplied array. // * Does not work for arrays of 'primitives' (e.g. int[] or byte[]). // * // * @param <T> type of element. // * @param elements the array from which a value will be picked. // * @return random element from the array of values. // */ // public <T> T randomElement(T[] elements) { // return elements[random(elements.length)]; // } // // /** // * Creates a random split in an integer, resulting in two integers. // * These two integers added together will result in the original input // * Minimal input value is 2 // * // * @param inputValue integer that needs to be split. // * @return array with two integers. // */ // public int[] getRandomSplit(int inputValue) { // if (inputValue < 2) { // throw new IllegalArgumentException("Minimal possible value to split is 2"); // } // int firstValue = random(inputValue - 1) + 1; //+1 so it will never become 0 // int secondValue = inputValue - firstValue;// // int split[] = {firstValue, secondValue}; // return split; // } // } // Path: src/test/java/nl/hsac/fitnesse/util/iban/IbanGeneratorTest.java import nl.hsac.fitnesse.util.RandomUtil; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; package nl.hsac.fitnesse.util.iban; /** * Tests IbanUtil. */ public class IbanGeneratorTest { private final IbanGenerator ibanGenerator = new IbanGenerator();
private static final RandomUtil RANDOM_UTIL = new RandomUtil();
monster860/FastDMM
src/main/java/com/github/monster860/fastdmm/Util.java
// Path: src/main/java/com/github/monster860/fastdmm/dmirender/RenderInstance.java // public class RenderInstance implements Comparable<RenderInstance> { // public IconSubstate substate; // public Color color; // public float x; // public float y; // public int plane; // public float layer; // public int creationIndex; // // public RenderInstance(int creationIndex) { // this.creationIndex = creationIndex; // } // // @Override // public int compareTo(RenderInstance o) { // float cnA = plane; // float cnB = o.plane; // if(cnA == cnB) { // cnA = layer; // cnB = o.layer; // } // if(cnA == cnB) { // cnA = creationIndex; // cnB = o.creationIndex; // } // return cnA < cnB ? -1 : (cnA == cnB ? 0 : 1); // } // } // // Path: src/main/java/com/github/monster860/fastdmm/dmmmap/Location.java // public class Location { // // public int x; // public int y; // public int z; // // /** // * Constructs a new Location with the given coordinates // * // * @param x The x-coordinate of this new location // * @param y The y-coordinate of this new location // * @param z The z-coordinate of this new location // */ // public Location(int x, int y, int z) { // this.x = x; // this.y = y; // this.z = z; // } // // /** // * Updates the Location with the given coordinates // * // * @param x The x-coordinates // * @param y The y-coordinates // * @param z The z-coordinates // */ // public void set(int x, int y, int z) { // this.x = x; // this.y = y; // this.z = z; // } // // /** // * Takes a step into the given direction. // * // * @param dir The direction to step into. // * @return The new location. // */ // public Location getStep(int dir) { // Location l = new Location(x, y, z); // if ((dir & 1) != 0) // l.y++; // if ((dir & 2) != 0) // l.y--; // if ((dir & 4) != 0) // l.x++; // if ((dir & 8) != 0) // l.x--; // return l; // } // // @Override // public boolean equals(Object other) { // if(!(other instanceof Location)) // return false; // if(other == this) // return false; // Location o = (Location)other; // return x == o.x && y == o.y && z == o.z; // } // // @Override // public int hashCode() { // return (x<<16) + (y<<8) + (z); // } // }
import java.awt.Color; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Set; import com.github.monster860.fastdmm.dmirender.RenderInstance; import com.github.monster860.fastdmm.dmmmap.Location;
/** * Converts all separators to the Windows separator of backslash. * * @param path the path to be changed, null ignored * @return the updated path */ public static String separatorsToWindows(String path) { if (path == null || path.indexOf(UNIX_SEPARATOR) == -1) { return path; } return path.replace(UNIX_SEPARATOR, WINDOWS_SEPARATOR); } /** * Converts all separators to the system separator. * * @param path the path to be changed, null ignored * @return the updated path */ public static String separatorsToSystem(String path) { if (path == null) { return null; } if (isWindowsSystem()) { return separatorsToWindows(path); } else { return separatorsToUnix(path); } }
// Path: src/main/java/com/github/monster860/fastdmm/dmirender/RenderInstance.java // public class RenderInstance implements Comparable<RenderInstance> { // public IconSubstate substate; // public Color color; // public float x; // public float y; // public int plane; // public float layer; // public int creationIndex; // // public RenderInstance(int creationIndex) { // this.creationIndex = creationIndex; // } // // @Override // public int compareTo(RenderInstance o) { // float cnA = plane; // float cnB = o.plane; // if(cnA == cnB) { // cnA = layer; // cnB = o.layer; // } // if(cnA == cnB) { // cnA = creationIndex; // cnB = o.creationIndex; // } // return cnA < cnB ? -1 : (cnA == cnB ? 0 : 1); // } // } // // Path: src/main/java/com/github/monster860/fastdmm/dmmmap/Location.java // public class Location { // // public int x; // public int y; // public int z; // // /** // * Constructs a new Location with the given coordinates // * // * @param x The x-coordinate of this new location // * @param y The y-coordinate of this new location // * @param z The z-coordinate of this new location // */ // public Location(int x, int y, int z) { // this.x = x; // this.y = y; // this.z = z; // } // // /** // * Updates the Location with the given coordinates // * // * @param x The x-coordinates // * @param y The y-coordinates // * @param z The z-coordinates // */ // public void set(int x, int y, int z) { // this.x = x; // this.y = y; // this.z = z; // } // // /** // * Takes a step into the given direction. // * // * @param dir The direction to step into. // * @return The new location. // */ // public Location getStep(int dir) { // Location l = new Location(x, y, z); // if ((dir & 1) != 0) // l.y++; // if ((dir & 2) != 0) // l.y--; // if ((dir & 4) != 0) // l.x++; // if ((dir & 8) != 0) // l.x--; // return l; // } // // @Override // public boolean equals(Object other) { // if(!(other instanceof Location)) // return false; // if(other == this) // return false; // Location o = (Location)other; // return x == o.x && y == o.y && z == o.z; // } // // @Override // public int hashCode() { // return (x<<16) + (y<<8) + (z); // } // } // Path: src/main/java/com/github/monster860/fastdmm/Util.java import java.awt.Color; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Set; import com.github.monster860.fastdmm.dmirender.RenderInstance; import com.github.monster860.fastdmm.dmmmap.Location; /** * Converts all separators to the Windows separator of backslash. * * @param path the path to be changed, null ignored * @return the updated path */ public static String separatorsToWindows(String path) { if (path == null || path.indexOf(UNIX_SEPARATOR) == -1) { return path; } return path.replace(UNIX_SEPARATOR, WINDOWS_SEPARATOR); } /** * Converts all separators to the system separator. * * @param path the path to be changed, null ignored * @return the updated path */ public static String separatorsToSystem(String path) { if (path == null) { return null; } if (isWindowsSystem()) { return separatorsToWindows(path); } else { return separatorsToUnix(path); } }
public static int drawBox(FastDMM editor, Set<RenderInstance> rendInstanceSet, int currCreationIndex, Location a, Location b) {
monster860/FastDMM
src/main/java/com/github/monster860/fastdmm/Util.java
// Path: src/main/java/com/github/monster860/fastdmm/dmirender/RenderInstance.java // public class RenderInstance implements Comparable<RenderInstance> { // public IconSubstate substate; // public Color color; // public float x; // public float y; // public int plane; // public float layer; // public int creationIndex; // // public RenderInstance(int creationIndex) { // this.creationIndex = creationIndex; // } // // @Override // public int compareTo(RenderInstance o) { // float cnA = plane; // float cnB = o.plane; // if(cnA == cnB) { // cnA = layer; // cnB = o.layer; // } // if(cnA == cnB) { // cnA = creationIndex; // cnB = o.creationIndex; // } // return cnA < cnB ? -1 : (cnA == cnB ? 0 : 1); // } // } // // Path: src/main/java/com/github/monster860/fastdmm/dmmmap/Location.java // public class Location { // // public int x; // public int y; // public int z; // // /** // * Constructs a new Location with the given coordinates // * // * @param x The x-coordinate of this new location // * @param y The y-coordinate of this new location // * @param z The z-coordinate of this new location // */ // public Location(int x, int y, int z) { // this.x = x; // this.y = y; // this.z = z; // } // // /** // * Updates the Location with the given coordinates // * // * @param x The x-coordinates // * @param y The y-coordinates // * @param z The z-coordinates // */ // public void set(int x, int y, int z) { // this.x = x; // this.y = y; // this.z = z; // } // // /** // * Takes a step into the given direction. // * // * @param dir The direction to step into. // * @return The new location. // */ // public Location getStep(int dir) { // Location l = new Location(x, y, z); // if ((dir & 1) != 0) // l.y++; // if ((dir & 2) != 0) // l.y--; // if ((dir & 4) != 0) // l.x++; // if ((dir & 8) != 0) // l.x--; // return l; // } // // @Override // public boolean equals(Object other) { // if(!(other instanceof Location)) // return false; // if(other == this) // return false; // Location o = (Location)other; // return x == o.x && y == o.y && z == o.z; // } // // @Override // public int hashCode() { // return (x<<16) + (y<<8) + (z); // } // }
import java.awt.Color; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Set; import com.github.monster860.fastdmm.dmirender.RenderInstance; import com.github.monster860.fastdmm.dmmmap.Location;
/** * Converts all separators to the Windows separator of backslash. * * @param path the path to be changed, null ignored * @return the updated path */ public static String separatorsToWindows(String path) { if (path == null || path.indexOf(UNIX_SEPARATOR) == -1) { return path; } return path.replace(UNIX_SEPARATOR, WINDOWS_SEPARATOR); } /** * Converts all separators to the system separator. * * @param path the path to be changed, null ignored * @return the updated path */ public static String separatorsToSystem(String path) { if (path == null) { return null; } if (isWindowsSystem()) { return separatorsToWindows(path); } else { return separatorsToUnix(path); } }
// Path: src/main/java/com/github/monster860/fastdmm/dmirender/RenderInstance.java // public class RenderInstance implements Comparable<RenderInstance> { // public IconSubstate substate; // public Color color; // public float x; // public float y; // public int plane; // public float layer; // public int creationIndex; // // public RenderInstance(int creationIndex) { // this.creationIndex = creationIndex; // } // // @Override // public int compareTo(RenderInstance o) { // float cnA = plane; // float cnB = o.plane; // if(cnA == cnB) { // cnA = layer; // cnB = o.layer; // } // if(cnA == cnB) { // cnA = creationIndex; // cnB = o.creationIndex; // } // return cnA < cnB ? -1 : (cnA == cnB ? 0 : 1); // } // } // // Path: src/main/java/com/github/monster860/fastdmm/dmmmap/Location.java // public class Location { // // public int x; // public int y; // public int z; // // /** // * Constructs a new Location with the given coordinates // * // * @param x The x-coordinate of this new location // * @param y The y-coordinate of this new location // * @param z The z-coordinate of this new location // */ // public Location(int x, int y, int z) { // this.x = x; // this.y = y; // this.z = z; // } // // /** // * Updates the Location with the given coordinates // * // * @param x The x-coordinates // * @param y The y-coordinates // * @param z The z-coordinates // */ // public void set(int x, int y, int z) { // this.x = x; // this.y = y; // this.z = z; // } // // /** // * Takes a step into the given direction. // * // * @param dir The direction to step into. // * @return The new location. // */ // public Location getStep(int dir) { // Location l = new Location(x, y, z); // if ((dir & 1) != 0) // l.y++; // if ((dir & 2) != 0) // l.y--; // if ((dir & 4) != 0) // l.x++; // if ((dir & 8) != 0) // l.x--; // return l; // } // // @Override // public boolean equals(Object other) { // if(!(other instanceof Location)) // return false; // if(other == this) // return false; // Location o = (Location)other; // return x == o.x && y == o.y && z == o.z; // } // // @Override // public int hashCode() { // return (x<<16) + (y<<8) + (z); // } // } // Path: src/main/java/com/github/monster860/fastdmm/Util.java import java.awt.Color; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Set; import com.github.monster860.fastdmm.dmirender.RenderInstance; import com.github.monster860.fastdmm.dmmmap.Location; /** * Converts all separators to the Windows separator of backslash. * * @param path the path to be changed, null ignored * @return the updated path */ public static String separatorsToWindows(String path) { if (path == null || path.indexOf(UNIX_SEPARATOR) == -1) { return path; } return path.replace(UNIX_SEPARATOR, WINDOWS_SEPARATOR); } /** * Converts all separators to the system separator. * * @param path the path to be changed, null ignored * @return the updated path */ public static String separatorsToSystem(String path) { if (path == null) { return null; } if (isWindowsSystem()) { return separatorsToWindows(path); } else { return separatorsToUnix(path); } }
public static int drawBox(FastDMM editor, Set<RenderInstance> rendInstanceSet, int currCreationIndex, Location a, Location b) {
jankroken/commandline
src/test/java/com/github/jankroken/commandline/error/InvalidArgumentsTests.java
// Path: src/main/java/com/github/jankroken/commandline/ParseResult.java // public class ParseResult<T> { // public enum ErrorType { // OK, // INTERNAL_ERROR, // INVALID_COMMAND_LINE, // INVALID_OPTION_CONFIGURATION, // UNRECOGNIZED_SWITCH, // INVALID_CONFIGURATION // } // // private final ErrorType errorType; // private final boolean success; // private final T value; // private final Exception rootCause; // private final String errorMessage; // // protected ParseResult(Exception e, boolean success, T value) { // errorType = success ? OK : toErrorType(e); // rootCause = e; // errorMessage = e == null ? null : e.getMessage(); // this.success = success; // this.value = value; // } // // protected ParseResult(Exception t) { // this(t, false, null); // } // // protected ParseResult(T value) { // this(null, true, value); // } // // public Optional<T> toOptional() { // if (success) return Optional.of(value); // else return Optional.empty(); // } // // public T get() throws CommandLineWrappedException { // if (success) return value; // throw new CommandLineWrappedException(rootCause); // } // // public <R> ParseResult<R> map(Function<T, R> f) { // if (success) { // return new ParseResult(f.apply(value)); // } else { // return new ParseResult(rootCause); // } // } // // private static ErrorType toErrorType(Exception e) { // if (e instanceof InternalErrorException) return INTERNAL_ERROR; // if (e instanceof InvalidCommandLineException) return INVALID_COMMAND_LINE; // if (e instanceof InvalidOptionConfigurationException) return INVALID_OPTION_CONFIGURATION; // if (e instanceof UnrecognizedSwitchException) return UNRECOGNIZED_SWITCH; // if (e instanceof InvocationTargetException) return INVALID_CONFIGURATION; // if (e instanceof IllegalAccessException) return INVALID_CONFIGURATION; // if (e instanceof InstantiationException) return INVALID_CONFIGURATION; // throw new RuntimeException("Implementation error: unhandled exception", e); // } // // public ErrorType getErrorType() { // return errorType; // } // // public boolean isSuccess() { // return success; // } // // public Exception getRootCause() { // return rootCause; // } // // public String getErrorMessage() { // return errorMessage; // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/CommandLineWrappedException.java // public class CommandLineWrappedException extends CommandLineException { // public CommandLineWrappedException(Throwable cause) { // super(cause); // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/InvalidCommandLineException.java // public class InvalidCommandLineException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InvalidCommandLineException(String message) { // super(message); // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/UnrecognizedSwitchException.java // public class UnrecognizedSwitchException extends CommandLineException { // private static final long serialVersionUID = 2L; // private String _switch; // // public UnrecognizedSwitchException(Class<?> configurationClass, String _switch) { // super(configurationClass + ": " + _switch); // this._switch = _switch; // } // // public String getSwitch() { // return _switch; // } // } // // Path: src/main/java/com/github/jankroken/commandline/CommandLineParser.java // public static <T> T parse(Class<T> optionClass, String[] args, OptionStyle style) // throws IllegalAccessException, InstantiationException, InvocationTargetException { // T spec; // try { // spec = optionClass.getConstructor().newInstance(); // } catch (NoSuchMethodException noSuchMethodException) { // throw new RuntimeException(noSuchMethodException); // } // var optionSet = new OptionSet(spec, MAIN_OPTIONS); // Tokenizer tokenizer; // if (style == SIMPLE) { // tokenizer = new SimpleTokenizer(new PeekIterator<>(new ArrayIterator<>(args))); // } else { // tokenizer = new LongOrCompactTokenizer(new PeekIterator<>(new ArrayIterator<>(args))); // } // optionSet.consumeOptions(tokenizer); // return spec; // } // // Path: src/main/java/com/github/jankroken/commandline/CommandLineParser.java // public static <T> ParseResult<T> tryParse(Class<T> optionClass, String[] args, OptionStyle style) { // try { // return new ParseResult(parse(optionClass, args, style)); // } catch(CommandLineException | IllegalAccessException | InstantiationException | InvocationTargetException e) { // return new ParseResult(e); // } // } // // Path: src/main/java/com/github/jankroken/commandline/util/Constants.java // public static final String[] EMPTY_STRING_ARRAY = new String[]{};
import com.github.jankroken.commandline.ParseResult; import com.github.jankroken.commandline.domain.CommandLineWrappedException; import com.github.jankroken.commandline.domain.InvalidCommandLineException; import com.github.jankroken.commandline.domain.UnrecognizedSwitchException; import org.junit.jupiter.api.Test; import static com.github.jankroken.commandline.CommandLineParser.parse; import static com.github.jankroken.commandline.CommandLineParser.tryParse; import static com.github.jankroken.commandline.OptionStyle.SIMPLE; import static com.github.jankroken.commandline.util.Constants.EMPTY_STRING_ARRAY; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy;
package com.github.jankroken.commandline.error; public class InvalidArgumentsTests { @Test public void testMissingSwitches() {
// Path: src/main/java/com/github/jankroken/commandline/ParseResult.java // public class ParseResult<T> { // public enum ErrorType { // OK, // INTERNAL_ERROR, // INVALID_COMMAND_LINE, // INVALID_OPTION_CONFIGURATION, // UNRECOGNIZED_SWITCH, // INVALID_CONFIGURATION // } // // private final ErrorType errorType; // private final boolean success; // private final T value; // private final Exception rootCause; // private final String errorMessage; // // protected ParseResult(Exception e, boolean success, T value) { // errorType = success ? OK : toErrorType(e); // rootCause = e; // errorMessage = e == null ? null : e.getMessage(); // this.success = success; // this.value = value; // } // // protected ParseResult(Exception t) { // this(t, false, null); // } // // protected ParseResult(T value) { // this(null, true, value); // } // // public Optional<T> toOptional() { // if (success) return Optional.of(value); // else return Optional.empty(); // } // // public T get() throws CommandLineWrappedException { // if (success) return value; // throw new CommandLineWrappedException(rootCause); // } // // public <R> ParseResult<R> map(Function<T, R> f) { // if (success) { // return new ParseResult(f.apply(value)); // } else { // return new ParseResult(rootCause); // } // } // // private static ErrorType toErrorType(Exception e) { // if (e instanceof InternalErrorException) return INTERNAL_ERROR; // if (e instanceof InvalidCommandLineException) return INVALID_COMMAND_LINE; // if (e instanceof InvalidOptionConfigurationException) return INVALID_OPTION_CONFIGURATION; // if (e instanceof UnrecognizedSwitchException) return UNRECOGNIZED_SWITCH; // if (e instanceof InvocationTargetException) return INVALID_CONFIGURATION; // if (e instanceof IllegalAccessException) return INVALID_CONFIGURATION; // if (e instanceof InstantiationException) return INVALID_CONFIGURATION; // throw new RuntimeException("Implementation error: unhandled exception", e); // } // // public ErrorType getErrorType() { // return errorType; // } // // public boolean isSuccess() { // return success; // } // // public Exception getRootCause() { // return rootCause; // } // // public String getErrorMessage() { // return errorMessage; // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/CommandLineWrappedException.java // public class CommandLineWrappedException extends CommandLineException { // public CommandLineWrappedException(Throwable cause) { // super(cause); // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/InvalidCommandLineException.java // public class InvalidCommandLineException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InvalidCommandLineException(String message) { // super(message); // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/UnrecognizedSwitchException.java // public class UnrecognizedSwitchException extends CommandLineException { // private static final long serialVersionUID = 2L; // private String _switch; // // public UnrecognizedSwitchException(Class<?> configurationClass, String _switch) { // super(configurationClass + ": " + _switch); // this._switch = _switch; // } // // public String getSwitch() { // return _switch; // } // } // // Path: src/main/java/com/github/jankroken/commandline/CommandLineParser.java // public static <T> T parse(Class<T> optionClass, String[] args, OptionStyle style) // throws IllegalAccessException, InstantiationException, InvocationTargetException { // T spec; // try { // spec = optionClass.getConstructor().newInstance(); // } catch (NoSuchMethodException noSuchMethodException) { // throw new RuntimeException(noSuchMethodException); // } // var optionSet = new OptionSet(spec, MAIN_OPTIONS); // Tokenizer tokenizer; // if (style == SIMPLE) { // tokenizer = new SimpleTokenizer(new PeekIterator<>(new ArrayIterator<>(args))); // } else { // tokenizer = new LongOrCompactTokenizer(new PeekIterator<>(new ArrayIterator<>(args))); // } // optionSet.consumeOptions(tokenizer); // return spec; // } // // Path: src/main/java/com/github/jankroken/commandline/CommandLineParser.java // public static <T> ParseResult<T> tryParse(Class<T> optionClass, String[] args, OptionStyle style) { // try { // return new ParseResult(parse(optionClass, args, style)); // } catch(CommandLineException | IllegalAccessException | InstantiationException | InvocationTargetException e) { // return new ParseResult(e); // } // } // // Path: src/main/java/com/github/jankroken/commandline/util/Constants.java // public static final String[] EMPTY_STRING_ARRAY = new String[]{}; // Path: src/test/java/com/github/jankroken/commandline/error/InvalidArgumentsTests.java import com.github.jankroken.commandline.ParseResult; import com.github.jankroken.commandline.domain.CommandLineWrappedException; import com.github.jankroken.commandline.domain.InvalidCommandLineException; import com.github.jankroken.commandline.domain.UnrecognizedSwitchException; import org.junit.jupiter.api.Test; import static com.github.jankroken.commandline.CommandLineParser.parse; import static com.github.jankroken.commandline.CommandLineParser.tryParse; import static com.github.jankroken.commandline.OptionStyle.SIMPLE; import static com.github.jankroken.commandline.util.Constants.EMPTY_STRING_ARRAY; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; package com.github.jankroken.commandline.error; public class InvalidArgumentsTests { @Test public void testMissingSwitches() {
var args = EMPTY_STRING_ARRAY;
jankroken/commandline
src/test/java/com/github/jankroken/commandline/error/InvalidArgumentsTests.java
// Path: src/main/java/com/github/jankroken/commandline/ParseResult.java // public class ParseResult<T> { // public enum ErrorType { // OK, // INTERNAL_ERROR, // INVALID_COMMAND_LINE, // INVALID_OPTION_CONFIGURATION, // UNRECOGNIZED_SWITCH, // INVALID_CONFIGURATION // } // // private final ErrorType errorType; // private final boolean success; // private final T value; // private final Exception rootCause; // private final String errorMessage; // // protected ParseResult(Exception e, boolean success, T value) { // errorType = success ? OK : toErrorType(e); // rootCause = e; // errorMessage = e == null ? null : e.getMessage(); // this.success = success; // this.value = value; // } // // protected ParseResult(Exception t) { // this(t, false, null); // } // // protected ParseResult(T value) { // this(null, true, value); // } // // public Optional<T> toOptional() { // if (success) return Optional.of(value); // else return Optional.empty(); // } // // public T get() throws CommandLineWrappedException { // if (success) return value; // throw new CommandLineWrappedException(rootCause); // } // // public <R> ParseResult<R> map(Function<T, R> f) { // if (success) { // return new ParseResult(f.apply(value)); // } else { // return new ParseResult(rootCause); // } // } // // private static ErrorType toErrorType(Exception e) { // if (e instanceof InternalErrorException) return INTERNAL_ERROR; // if (e instanceof InvalidCommandLineException) return INVALID_COMMAND_LINE; // if (e instanceof InvalidOptionConfigurationException) return INVALID_OPTION_CONFIGURATION; // if (e instanceof UnrecognizedSwitchException) return UNRECOGNIZED_SWITCH; // if (e instanceof InvocationTargetException) return INVALID_CONFIGURATION; // if (e instanceof IllegalAccessException) return INVALID_CONFIGURATION; // if (e instanceof InstantiationException) return INVALID_CONFIGURATION; // throw new RuntimeException("Implementation error: unhandled exception", e); // } // // public ErrorType getErrorType() { // return errorType; // } // // public boolean isSuccess() { // return success; // } // // public Exception getRootCause() { // return rootCause; // } // // public String getErrorMessage() { // return errorMessage; // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/CommandLineWrappedException.java // public class CommandLineWrappedException extends CommandLineException { // public CommandLineWrappedException(Throwable cause) { // super(cause); // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/InvalidCommandLineException.java // public class InvalidCommandLineException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InvalidCommandLineException(String message) { // super(message); // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/UnrecognizedSwitchException.java // public class UnrecognizedSwitchException extends CommandLineException { // private static final long serialVersionUID = 2L; // private String _switch; // // public UnrecognizedSwitchException(Class<?> configurationClass, String _switch) { // super(configurationClass + ": " + _switch); // this._switch = _switch; // } // // public String getSwitch() { // return _switch; // } // } // // Path: src/main/java/com/github/jankroken/commandline/CommandLineParser.java // public static <T> T parse(Class<T> optionClass, String[] args, OptionStyle style) // throws IllegalAccessException, InstantiationException, InvocationTargetException { // T spec; // try { // spec = optionClass.getConstructor().newInstance(); // } catch (NoSuchMethodException noSuchMethodException) { // throw new RuntimeException(noSuchMethodException); // } // var optionSet = new OptionSet(spec, MAIN_OPTIONS); // Tokenizer tokenizer; // if (style == SIMPLE) { // tokenizer = new SimpleTokenizer(new PeekIterator<>(new ArrayIterator<>(args))); // } else { // tokenizer = new LongOrCompactTokenizer(new PeekIterator<>(new ArrayIterator<>(args))); // } // optionSet.consumeOptions(tokenizer); // return spec; // } // // Path: src/main/java/com/github/jankroken/commandline/CommandLineParser.java // public static <T> ParseResult<T> tryParse(Class<T> optionClass, String[] args, OptionStyle style) { // try { // return new ParseResult(parse(optionClass, args, style)); // } catch(CommandLineException | IllegalAccessException | InstantiationException | InvocationTargetException e) { // return new ParseResult(e); // } // } // // Path: src/main/java/com/github/jankroken/commandline/util/Constants.java // public static final String[] EMPTY_STRING_ARRAY = new String[]{};
import com.github.jankroken.commandline.ParseResult; import com.github.jankroken.commandline.domain.CommandLineWrappedException; import com.github.jankroken.commandline.domain.InvalidCommandLineException; import com.github.jankroken.commandline.domain.UnrecognizedSwitchException; import org.junit.jupiter.api.Test; import static com.github.jankroken.commandline.CommandLineParser.parse; import static com.github.jankroken.commandline.CommandLineParser.tryParse; import static com.github.jankroken.commandline.OptionStyle.SIMPLE; import static com.github.jankroken.commandline.util.Constants.EMPTY_STRING_ARRAY; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy;
package com.github.jankroken.commandline.error; public class InvalidArgumentsTests { @Test public void testMissingSwitches() { var args = EMPTY_STRING_ARRAY;
// Path: src/main/java/com/github/jankroken/commandline/ParseResult.java // public class ParseResult<T> { // public enum ErrorType { // OK, // INTERNAL_ERROR, // INVALID_COMMAND_LINE, // INVALID_OPTION_CONFIGURATION, // UNRECOGNIZED_SWITCH, // INVALID_CONFIGURATION // } // // private final ErrorType errorType; // private final boolean success; // private final T value; // private final Exception rootCause; // private final String errorMessage; // // protected ParseResult(Exception e, boolean success, T value) { // errorType = success ? OK : toErrorType(e); // rootCause = e; // errorMessage = e == null ? null : e.getMessage(); // this.success = success; // this.value = value; // } // // protected ParseResult(Exception t) { // this(t, false, null); // } // // protected ParseResult(T value) { // this(null, true, value); // } // // public Optional<T> toOptional() { // if (success) return Optional.of(value); // else return Optional.empty(); // } // // public T get() throws CommandLineWrappedException { // if (success) return value; // throw new CommandLineWrappedException(rootCause); // } // // public <R> ParseResult<R> map(Function<T, R> f) { // if (success) { // return new ParseResult(f.apply(value)); // } else { // return new ParseResult(rootCause); // } // } // // private static ErrorType toErrorType(Exception e) { // if (e instanceof InternalErrorException) return INTERNAL_ERROR; // if (e instanceof InvalidCommandLineException) return INVALID_COMMAND_LINE; // if (e instanceof InvalidOptionConfigurationException) return INVALID_OPTION_CONFIGURATION; // if (e instanceof UnrecognizedSwitchException) return UNRECOGNIZED_SWITCH; // if (e instanceof InvocationTargetException) return INVALID_CONFIGURATION; // if (e instanceof IllegalAccessException) return INVALID_CONFIGURATION; // if (e instanceof InstantiationException) return INVALID_CONFIGURATION; // throw new RuntimeException("Implementation error: unhandled exception", e); // } // // public ErrorType getErrorType() { // return errorType; // } // // public boolean isSuccess() { // return success; // } // // public Exception getRootCause() { // return rootCause; // } // // public String getErrorMessage() { // return errorMessage; // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/CommandLineWrappedException.java // public class CommandLineWrappedException extends CommandLineException { // public CommandLineWrappedException(Throwable cause) { // super(cause); // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/InvalidCommandLineException.java // public class InvalidCommandLineException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InvalidCommandLineException(String message) { // super(message); // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/UnrecognizedSwitchException.java // public class UnrecognizedSwitchException extends CommandLineException { // private static final long serialVersionUID = 2L; // private String _switch; // // public UnrecognizedSwitchException(Class<?> configurationClass, String _switch) { // super(configurationClass + ": " + _switch); // this._switch = _switch; // } // // public String getSwitch() { // return _switch; // } // } // // Path: src/main/java/com/github/jankroken/commandline/CommandLineParser.java // public static <T> T parse(Class<T> optionClass, String[] args, OptionStyle style) // throws IllegalAccessException, InstantiationException, InvocationTargetException { // T spec; // try { // spec = optionClass.getConstructor().newInstance(); // } catch (NoSuchMethodException noSuchMethodException) { // throw new RuntimeException(noSuchMethodException); // } // var optionSet = new OptionSet(spec, MAIN_OPTIONS); // Tokenizer tokenizer; // if (style == SIMPLE) { // tokenizer = new SimpleTokenizer(new PeekIterator<>(new ArrayIterator<>(args))); // } else { // tokenizer = new LongOrCompactTokenizer(new PeekIterator<>(new ArrayIterator<>(args))); // } // optionSet.consumeOptions(tokenizer); // return spec; // } // // Path: src/main/java/com/github/jankroken/commandline/CommandLineParser.java // public static <T> ParseResult<T> tryParse(Class<T> optionClass, String[] args, OptionStyle style) { // try { // return new ParseResult(parse(optionClass, args, style)); // } catch(CommandLineException | IllegalAccessException | InstantiationException | InvocationTargetException e) { // return new ParseResult(e); // } // } // // Path: src/main/java/com/github/jankroken/commandline/util/Constants.java // public static final String[] EMPTY_STRING_ARRAY = new String[]{}; // Path: src/test/java/com/github/jankroken/commandline/error/InvalidArgumentsTests.java import com.github.jankroken.commandline.ParseResult; import com.github.jankroken.commandline.domain.CommandLineWrappedException; import com.github.jankroken.commandline.domain.InvalidCommandLineException; import com.github.jankroken.commandline.domain.UnrecognizedSwitchException; import org.junit.jupiter.api.Test; import static com.github.jankroken.commandline.CommandLineParser.parse; import static com.github.jankroken.commandline.CommandLineParser.tryParse; import static com.github.jankroken.commandline.OptionStyle.SIMPLE; import static com.github.jankroken.commandline.util.Constants.EMPTY_STRING_ARRAY; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; package com.github.jankroken.commandline.error; public class InvalidArgumentsTests { @Test public void testMissingSwitches() { var args = EMPTY_STRING_ARRAY;
assertThatThrownBy(() -> parse(RequiredConfiguration.class, args, SIMPLE))
jankroken/commandline
src/test/java/com/github/jankroken/commandline/error/InvalidArgumentsTests.java
// Path: src/main/java/com/github/jankroken/commandline/ParseResult.java // public class ParseResult<T> { // public enum ErrorType { // OK, // INTERNAL_ERROR, // INVALID_COMMAND_LINE, // INVALID_OPTION_CONFIGURATION, // UNRECOGNIZED_SWITCH, // INVALID_CONFIGURATION // } // // private final ErrorType errorType; // private final boolean success; // private final T value; // private final Exception rootCause; // private final String errorMessage; // // protected ParseResult(Exception e, boolean success, T value) { // errorType = success ? OK : toErrorType(e); // rootCause = e; // errorMessage = e == null ? null : e.getMessage(); // this.success = success; // this.value = value; // } // // protected ParseResult(Exception t) { // this(t, false, null); // } // // protected ParseResult(T value) { // this(null, true, value); // } // // public Optional<T> toOptional() { // if (success) return Optional.of(value); // else return Optional.empty(); // } // // public T get() throws CommandLineWrappedException { // if (success) return value; // throw new CommandLineWrappedException(rootCause); // } // // public <R> ParseResult<R> map(Function<T, R> f) { // if (success) { // return new ParseResult(f.apply(value)); // } else { // return new ParseResult(rootCause); // } // } // // private static ErrorType toErrorType(Exception e) { // if (e instanceof InternalErrorException) return INTERNAL_ERROR; // if (e instanceof InvalidCommandLineException) return INVALID_COMMAND_LINE; // if (e instanceof InvalidOptionConfigurationException) return INVALID_OPTION_CONFIGURATION; // if (e instanceof UnrecognizedSwitchException) return UNRECOGNIZED_SWITCH; // if (e instanceof InvocationTargetException) return INVALID_CONFIGURATION; // if (e instanceof IllegalAccessException) return INVALID_CONFIGURATION; // if (e instanceof InstantiationException) return INVALID_CONFIGURATION; // throw new RuntimeException("Implementation error: unhandled exception", e); // } // // public ErrorType getErrorType() { // return errorType; // } // // public boolean isSuccess() { // return success; // } // // public Exception getRootCause() { // return rootCause; // } // // public String getErrorMessage() { // return errorMessage; // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/CommandLineWrappedException.java // public class CommandLineWrappedException extends CommandLineException { // public CommandLineWrappedException(Throwable cause) { // super(cause); // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/InvalidCommandLineException.java // public class InvalidCommandLineException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InvalidCommandLineException(String message) { // super(message); // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/UnrecognizedSwitchException.java // public class UnrecognizedSwitchException extends CommandLineException { // private static final long serialVersionUID = 2L; // private String _switch; // // public UnrecognizedSwitchException(Class<?> configurationClass, String _switch) { // super(configurationClass + ": " + _switch); // this._switch = _switch; // } // // public String getSwitch() { // return _switch; // } // } // // Path: src/main/java/com/github/jankroken/commandline/CommandLineParser.java // public static <T> T parse(Class<T> optionClass, String[] args, OptionStyle style) // throws IllegalAccessException, InstantiationException, InvocationTargetException { // T spec; // try { // spec = optionClass.getConstructor().newInstance(); // } catch (NoSuchMethodException noSuchMethodException) { // throw new RuntimeException(noSuchMethodException); // } // var optionSet = new OptionSet(spec, MAIN_OPTIONS); // Tokenizer tokenizer; // if (style == SIMPLE) { // tokenizer = new SimpleTokenizer(new PeekIterator<>(new ArrayIterator<>(args))); // } else { // tokenizer = new LongOrCompactTokenizer(new PeekIterator<>(new ArrayIterator<>(args))); // } // optionSet.consumeOptions(tokenizer); // return spec; // } // // Path: src/main/java/com/github/jankroken/commandline/CommandLineParser.java // public static <T> ParseResult<T> tryParse(Class<T> optionClass, String[] args, OptionStyle style) { // try { // return new ParseResult(parse(optionClass, args, style)); // } catch(CommandLineException | IllegalAccessException | InstantiationException | InvocationTargetException e) { // return new ParseResult(e); // } // } // // Path: src/main/java/com/github/jankroken/commandline/util/Constants.java // public static final String[] EMPTY_STRING_ARRAY = new String[]{};
import com.github.jankroken.commandline.ParseResult; import com.github.jankroken.commandline.domain.CommandLineWrappedException; import com.github.jankroken.commandline.domain.InvalidCommandLineException; import com.github.jankroken.commandline.domain.UnrecognizedSwitchException; import org.junit.jupiter.api.Test; import static com.github.jankroken.commandline.CommandLineParser.parse; import static com.github.jankroken.commandline.CommandLineParser.tryParse; import static com.github.jankroken.commandline.OptionStyle.SIMPLE; import static com.github.jankroken.commandline.util.Constants.EMPTY_STRING_ARRAY; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy;
package com.github.jankroken.commandline.error; public class InvalidArgumentsTests { @Test public void testMissingSwitches() { var args = EMPTY_STRING_ARRAY; assertThatThrownBy(() -> parse(RequiredConfiguration.class, args, SIMPLE))
// Path: src/main/java/com/github/jankroken/commandline/ParseResult.java // public class ParseResult<T> { // public enum ErrorType { // OK, // INTERNAL_ERROR, // INVALID_COMMAND_LINE, // INVALID_OPTION_CONFIGURATION, // UNRECOGNIZED_SWITCH, // INVALID_CONFIGURATION // } // // private final ErrorType errorType; // private final boolean success; // private final T value; // private final Exception rootCause; // private final String errorMessage; // // protected ParseResult(Exception e, boolean success, T value) { // errorType = success ? OK : toErrorType(e); // rootCause = e; // errorMessage = e == null ? null : e.getMessage(); // this.success = success; // this.value = value; // } // // protected ParseResult(Exception t) { // this(t, false, null); // } // // protected ParseResult(T value) { // this(null, true, value); // } // // public Optional<T> toOptional() { // if (success) return Optional.of(value); // else return Optional.empty(); // } // // public T get() throws CommandLineWrappedException { // if (success) return value; // throw new CommandLineWrappedException(rootCause); // } // // public <R> ParseResult<R> map(Function<T, R> f) { // if (success) { // return new ParseResult(f.apply(value)); // } else { // return new ParseResult(rootCause); // } // } // // private static ErrorType toErrorType(Exception e) { // if (e instanceof InternalErrorException) return INTERNAL_ERROR; // if (e instanceof InvalidCommandLineException) return INVALID_COMMAND_LINE; // if (e instanceof InvalidOptionConfigurationException) return INVALID_OPTION_CONFIGURATION; // if (e instanceof UnrecognizedSwitchException) return UNRECOGNIZED_SWITCH; // if (e instanceof InvocationTargetException) return INVALID_CONFIGURATION; // if (e instanceof IllegalAccessException) return INVALID_CONFIGURATION; // if (e instanceof InstantiationException) return INVALID_CONFIGURATION; // throw new RuntimeException("Implementation error: unhandled exception", e); // } // // public ErrorType getErrorType() { // return errorType; // } // // public boolean isSuccess() { // return success; // } // // public Exception getRootCause() { // return rootCause; // } // // public String getErrorMessage() { // return errorMessage; // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/CommandLineWrappedException.java // public class CommandLineWrappedException extends CommandLineException { // public CommandLineWrappedException(Throwable cause) { // super(cause); // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/InvalidCommandLineException.java // public class InvalidCommandLineException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InvalidCommandLineException(String message) { // super(message); // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/UnrecognizedSwitchException.java // public class UnrecognizedSwitchException extends CommandLineException { // private static final long serialVersionUID = 2L; // private String _switch; // // public UnrecognizedSwitchException(Class<?> configurationClass, String _switch) { // super(configurationClass + ": " + _switch); // this._switch = _switch; // } // // public String getSwitch() { // return _switch; // } // } // // Path: src/main/java/com/github/jankroken/commandline/CommandLineParser.java // public static <T> T parse(Class<T> optionClass, String[] args, OptionStyle style) // throws IllegalAccessException, InstantiationException, InvocationTargetException { // T spec; // try { // spec = optionClass.getConstructor().newInstance(); // } catch (NoSuchMethodException noSuchMethodException) { // throw new RuntimeException(noSuchMethodException); // } // var optionSet = new OptionSet(spec, MAIN_OPTIONS); // Tokenizer tokenizer; // if (style == SIMPLE) { // tokenizer = new SimpleTokenizer(new PeekIterator<>(new ArrayIterator<>(args))); // } else { // tokenizer = new LongOrCompactTokenizer(new PeekIterator<>(new ArrayIterator<>(args))); // } // optionSet.consumeOptions(tokenizer); // return spec; // } // // Path: src/main/java/com/github/jankroken/commandline/CommandLineParser.java // public static <T> ParseResult<T> tryParse(Class<T> optionClass, String[] args, OptionStyle style) { // try { // return new ParseResult(parse(optionClass, args, style)); // } catch(CommandLineException | IllegalAccessException | InstantiationException | InvocationTargetException e) { // return new ParseResult(e); // } // } // // Path: src/main/java/com/github/jankroken/commandline/util/Constants.java // public static final String[] EMPTY_STRING_ARRAY = new String[]{}; // Path: src/test/java/com/github/jankroken/commandline/error/InvalidArgumentsTests.java import com.github.jankroken.commandline.ParseResult; import com.github.jankroken.commandline.domain.CommandLineWrappedException; import com.github.jankroken.commandline.domain.InvalidCommandLineException; import com.github.jankroken.commandline.domain.UnrecognizedSwitchException; import org.junit.jupiter.api.Test; import static com.github.jankroken.commandline.CommandLineParser.parse; import static com.github.jankroken.commandline.CommandLineParser.tryParse; import static com.github.jankroken.commandline.OptionStyle.SIMPLE; import static com.github.jankroken.commandline.util.Constants.EMPTY_STRING_ARRAY; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; package com.github.jankroken.commandline.error; public class InvalidArgumentsTests { @Test public void testMissingSwitches() { var args = EMPTY_STRING_ARRAY; assertThatThrownBy(() -> parse(RequiredConfiguration.class, args, SIMPLE))
.isInstanceOf(InvalidCommandLineException.class);
jankroken/commandline
src/main/java/com/github/jankroken/commandline/domain/internal/OptionSpecification.java
// Path: src/main/java/com/github/jankroken/commandline/domain/InternalErrorException.java // public class InternalErrorException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InternalErrorException(String message) { // super(message); // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/InvalidCommandLineException.java // public class InvalidCommandLineException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InvalidCommandLineException(String message) { // super(message); // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/InvalidOptionConfigurationException.java // public class InvalidOptionConfigurationException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InvalidOptionConfigurationException(String message) { // super(message); // } // }
import com.github.jankroken.commandline.domain.InternalErrorException; import com.github.jankroken.commandline.domain.InvalidCommandLineException; import com.github.jankroken.commandline.domain.InvalidOptionConfigurationException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.Objects;
handleArguments(subset); break; case LOOSE_ARGS: handleArguments(args.next().getValue()); break; default: throw createInternalErrorException("Not implemented: " + argumentConsumption.getType()); } } private void handleArguments(Object args) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { if (occurrences == Occurrences.SINGLE) { method.invoke(spec, args); } else { argumentBuffer.add(args); } } public void flush() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { if (required && !activated) { throw createInvalidCommandLineException("Required argument not specified"); } if (occurrences == Occurrences.MULTIPLE) { method.invoke(spec, argumentBuffer); } }
// Path: src/main/java/com/github/jankroken/commandline/domain/InternalErrorException.java // public class InternalErrorException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InternalErrorException(String message) { // super(message); // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/InvalidCommandLineException.java // public class InvalidCommandLineException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InvalidCommandLineException(String message) { // super(message); // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/InvalidOptionConfigurationException.java // public class InvalidOptionConfigurationException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InvalidOptionConfigurationException(String message) { // super(message); // } // } // Path: src/main/java/com/github/jankroken/commandline/domain/internal/OptionSpecification.java import com.github.jankroken.commandline.domain.InternalErrorException; import com.github.jankroken.commandline.domain.InvalidCommandLineException; import com.github.jankroken.commandline.domain.InvalidOptionConfigurationException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.Objects; handleArguments(subset); break; case LOOSE_ARGS: handleArguments(args.next().getValue()); break; default: throw createInternalErrorException("Not implemented: " + argumentConsumption.getType()); } } private void handleArguments(Object args) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { if (occurrences == Occurrences.SINGLE) { method.invoke(spec, args); } else { argumentBuffer.add(args); } } public void flush() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { if (required && !activated) { throw createInvalidCommandLineException("Required argument not specified"); } if (occurrences == Occurrences.MULTIPLE) { method.invoke(spec, argumentBuffer); } }
private InvalidOptionConfigurationException createInvalidOptionSpecificationException(String description) {
jankroken/commandline
src/main/java/com/github/jankroken/commandline/domain/internal/OptionSpecification.java
// Path: src/main/java/com/github/jankroken/commandline/domain/InternalErrorException.java // public class InternalErrorException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InternalErrorException(String message) { // super(message); // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/InvalidCommandLineException.java // public class InvalidCommandLineException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InvalidCommandLineException(String message) { // super(message); // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/InvalidOptionConfigurationException.java // public class InvalidOptionConfigurationException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InvalidOptionConfigurationException(String message) { // super(message); // } // }
import com.github.jankroken.commandline.domain.InternalErrorException; import com.github.jankroken.commandline.domain.InvalidCommandLineException; import com.github.jankroken.commandline.domain.InvalidOptionConfigurationException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.Objects;
break; default: throw createInternalErrorException("Not implemented: " + argumentConsumption.getType()); } } private void handleArguments(Object args) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { if (occurrences == Occurrences.SINGLE) { method.invoke(spec, args); } else { argumentBuffer.add(args); } } public void flush() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { if (required && !activated) { throw createInvalidCommandLineException("Required argument not specified"); } if (occurrences == Occurrences.MULTIPLE) { method.invoke(spec, argumentBuffer); } } private InvalidOptionConfigurationException createInvalidOptionSpecificationException(String description) { return new InvalidOptionConfigurationException(getOptionId() + ' ' + description); }
// Path: src/main/java/com/github/jankroken/commandline/domain/InternalErrorException.java // public class InternalErrorException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InternalErrorException(String message) { // super(message); // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/InvalidCommandLineException.java // public class InvalidCommandLineException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InvalidCommandLineException(String message) { // super(message); // } // } // // Path: src/main/java/com/github/jankroken/commandline/domain/InvalidOptionConfigurationException.java // public class InvalidOptionConfigurationException extends CommandLineException { // private static final long serialVersionUID = 2L; // // public InvalidOptionConfigurationException(String message) { // super(message); // } // } // Path: src/main/java/com/github/jankroken/commandline/domain/internal/OptionSpecification.java import com.github.jankroken.commandline.domain.InternalErrorException; import com.github.jankroken.commandline.domain.InvalidCommandLineException; import com.github.jankroken.commandline.domain.InvalidOptionConfigurationException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.Objects; break; default: throw createInternalErrorException("Not implemented: " + argumentConsumption.getType()); } } private void handleArguments(Object args) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { if (occurrences == Occurrences.SINGLE) { method.invoke(spec, args); } else { argumentBuffer.add(args); } } public void flush() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { if (required && !activated) { throw createInvalidCommandLineException("Required argument not specified"); } if (occurrences == Occurrences.MULTIPLE) { method.invoke(spec, argumentBuffer); } } private InvalidOptionConfigurationException createInvalidOptionSpecificationException(String description) { return new InvalidOptionConfigurationException(getOptionId() + ' ' + description); }
private InvalidCommandLineException createInvalidCommandLineException(String description) {