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
alaisi/postgres-async-driver
src/main/java/com/github/pgasync/conversion/NumericConversions.java
// Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // } // // Path: src/main/java/com/github/pgasync/Oid.java // public enum Oid { // // UNSPECIFIED(0), // INT2(21), // INT2_ARRAY(1005), // INT4(23), // INT4_ARRAY(1007), // INT8(20), // INT8_ARRAY(1016), // TEXT(25), // TEXT_ARRAY(1009), // NUMERIC(1700), // NUMERIC_ARRAY(1231), // FLOAT4(700), // FLOAT4_ARRAY(1021), // FLOAT8(701), // FLOAT8_ARRAY(1022), // BOOL(16), // BOOL_ARRAY(1000), // DATE(1082), // DATE_ARRAY(1182), // TIME(1083), // TIME_ARRAY(1183), // TIMETZ(1266), // TIMETZ_ARRAY(1270), // TIMESTAMP(1114), // TIMESTAMP_ARRAY(1115), // TIMESTAMPTZ(1184), // TIMESTAMPTZ_ARRAY(1185), // BYTEA(17), // BYTEA_ARRAY(1001), // VARCHAR(1043), // VARCHAR_ARRAY(1015), // OID(26), // OID_ARRAY(1028), // BPCHAR(1042), // BPCHAR_ARRAY(1014), // MONEY(790), // MONEY_ARRAY(791), // NAME(19), // NAME_ARRAY(1003), // BIT(1560), // BIT_ARRAY(1561), // VOID(2278), // INTERVAL(1186), // INTERVAL_ARRAY(1187), // CHAR(18), // CHAR_ARRAY(1002), // VARBIT(1562), // VARBIT_ARRAY(1563), // UUID(2950), // UUID_ARRAY(2951), // XML(142), // XML_ARRAY(143), // POINT(600), // BOX(603), // // Added // JSON(114), // JSONB(3802), // HSTORE(33670) // ; // // final int id; // // Oid(int id) { // this.id = id; // } // // public int getId() { // return id; // } // // public static Oid valueOfId(int id) { // for (Oid oid : values()) { // if (oid.id == id) { // return oid; // } // } // return Oid.UNSPECIFIED; // } // }
import com.pgasync.SqlException; import com.github.pgasync.Oid; import java.math.BigDecimal; import java.math.BigInteger;
package com.github.pgasync.conversion; /** * @author Antti Laisi */ class NumericConversions { static Long toLong(Oid oid, String value) { switch (oid) { case UNSPECIFIED: // fallthrough case INT2: // fallthrough case INT4: // fallthrough case INT8: return Long.valueOf(value); default:
// Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // } // // Path: src/main/java/com/github/pgasync/Oid.java // public enum Oid { // // UNSPECIFIED(0), // INT2(21), // INT2_ARRAY(1005), // INT4(23), // INT4_ARRAY(1007), // INT8(20), // INT8_ARRAY(1016), // TEXT(25), // TEXT_ARRAY(1009), // NUMERIC(1700), // NUMERIC_ARRAY(1231), // FLOAT4(700), // FLOAT4_ARRAY(1021), // FLOAT8(701), // FLOAT8_ARRAY(1022), // BOOL(16), // BOOL_ARRAY(1000), // DATE(1082), // DATE_ARRAY(1182), // TIME(1083), // TIME_ARRAY(1183), // TIMETZ(1266), // TIMETZ_ARRAY(1270), // TIMESTAMP(1114), // TIMESTAMP_ARRAY(1115), // TIMESTAMPTZ(1184), // TIMESTAMPTZ_ARRAY(1185), // BYTEA(17), // BYTEA_ARRAY(1001), // VARCHAR(1043), // VARCHAR_ARRAY(1015), // OID(26), // OID_ARRAY(1028), // BPCHAR(1042), // BPCHAR_ARRAY(1014), // MONEY(790), // MONEY_ARRAY(791), // NAME(19), // NAME_ARRAY(1003), // BIT(1560), // BIT_ARRAY(1561), // VOID(2278), // INTERVAL(1186), // INTERVAL_ARRAY(1187), // CHAR(18), // CHAR_ARRAY(1002), // VARBIT(1562), // VARBIT_ARRAY(1563), // UUID(2950), // UUID_ARRAY(2951), // XML(142), // XML_ARRAY(143), // POINT(600), // BOX(603), // // Added // JSON(114), // JSONB(3802), // HSTORE(33670) // ; // // final int id; // // Oid(int id) { // this.id = id; // } // // public int getId() { // return id; // } // // public static Oid valueOfId(int id) { // for (Oid oid : values()) { // if (oid.id == id) { // return oid; // } // } // return Oid.UNSPECIFIED; // } // } // Path: src/main/java/com/github/pgasync/conversion/NumericConversions.java import com.pgasync.SqlException; import com.github.pgasync.Oid; import java.math.BigDecimal; import java.math.BigInteger; package com.github.pgasync.conversion; /** * @author Antti Laisi */ class NumericConversions { static Long toLong(Oid oid, String value) { switch (oid) { case UNSPECIFIED: // fallthrough case INT2: // fallthrough case INT4: // fallthrough case INT8: return Long.valueOf(value); default:
throw new SqlException("Unsupported conversion " + oid.name() + " -> Long");
alaisi/postgres-async-driver
src/test/java/com/github/pgasync/ScriptResultsTest.java
// Path: src/main/java/com/pgasync/ResultSet.java // public interface ResultSet extends Iterable<Row> { // // Map<String, PgColumn> getColumnsByName(); // // List<PgColumn> getOrderedColumns(); // // /** // * @param index Row index starting from 0 // * @return Row, never null // */ // Row at(int index); // // /** // * @return Amount of result rows. // */ // int size(); // // /** // * @return Amount of modified rows. // */ // int affectedRows(); // // } // // Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // }
import com.pgasync.ResultSet; import com.pgasync.SqlException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import java.util.ArrayList; import java.util.List;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync; /** * Tests for results of script execution. * * @author Marat Gainullin */ public class ScriptResultsTest { @ClassRule public static DatabaseRule dbr = new DatabaseRule(); @BeforeClass public static void create() { drop(); dbr.query("CREATE TABLE SCRIPT_TEST(ID INT8)"); } @AfterClass public static void drop() { dbr.query("DROP TABLE IF EXISTS SCRIPT_TEST"); } @Test public void shouldReturnMultipleResultSets() {
// Path: src/main/java/com/pgasync/ResultSet.java // public interface ResultSet extends Iterable<Row> { // // Map<String, PgColumn> getColumnsByName(); // // List<PgColumn> getOrderedColumns(); // // /** // * @param index Row index starting from 0 // * @return Row, never null // */ // Row at(int index); // // /** // * @return Amount of result rows. // */ // int size(); // // /** // * @return Amount of modified rows. // */ // int affectedRows(); // // } // // Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // } // Path: src/test/java/com/github/pgasync/ScriptResultsTest.java import com.pgasync.ResultSet; import com.pgasync.SqlException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import java.util.ArrayList; import java.util.List; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync; /** * Tests for results of script execution. * * @author Marat Gainullin */ public class ScriptResultsTest { @ClassRule public static DatabaseRule dbr = new DatabaseRule(); @BeforeClass public static void create() { drop(); dbr.query("CREATE TABLE SCRIPT_TEST(ID INT8)"); } @AfterClass public static void drop() { dbr.query("DROP TABLE IF EXISTS SCRIPT_TEST"); } @Test public void shouldReturnMultipleResultSets() {
List<ResultSet> results = new ArrayList<>(dbr.script("" +
alaisi/postgres-async-driver
src/test/java/com/github/pgasync/ScriptResultsTest.java
// Path: src/main/java/com/pgasync/ResultSet.java // public interface ResultSet extends Iterable<Row> { // // Map<String, PgColumn> getColumnsByName(); // // List<PgColumn> getOrderedColumns(); // // /** // * @param index Row index starting from 0 // * @return Row, never null // */ // Row at(int index); // // /** // * @return Amount of result rows. // */ // int size(); // // /** // * @return Amount of modified rows. // */ // int affectedRows(); // // } // // Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // }
import com.pgasync.ResultSet; import com.pgasync.SqlException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import java.util.ArrayList; import java.util.List;
ResultSet firstSelectResult = results.get(1); Assert.assertEquals(0, firstSelectResult.affectedRows()); Assert.assertEquals(2, firstSelectResult.size()); Assert.assertEquals(1, firstSelectResult.at(0).getLong("first_id").intValue()); Assert.assertEquals(2, firstSelectResult.at(1).getLong("first_id").intValue()); Assert.assertEquals(1, firstSelectResult.getOrderedColumns().size()); Assert.assertEquals("first_id", firstSelectResult.getOrderedColumns().get(0).getName()); Assert.assertEquals(1, firstSelectResult.getColumnsByName().size()); Assert.assertTrue(firstSelectResult.getColumnsByName().containsKey("first_id")); ResultSet secondInsertResult = results.get(2); Assert.assertEquals(3, secondInsertResult.affectedRows()); Assert.assertEquals(0, secondInsertResult.size()); Assert.assertTrue(secondInsertResult.getOrderedColumns().isEmpty()); Assert.assertTrue(secondInsertResult.getColumnsByName().isEmpty()); ResultSet secondSelectResult = results.get(3); Assert.assertEquals(0, secondSelectResult.affectedRows()); Assert.assertEquals(3, secondSelectResult.size()); Assert.assertEquals(3, secondSelectResult.at(0).getLong("second_id").intValue()); Assert.assertEquals(4, secondSelectResult.at(1).getLong("second_id").intValue()); Assert.assertEquals(5, secondSelectResult.at(2).getLong("second_id").intValue()); Assert.assertEquals(1, secondSelectResult.getOrderedColumns().size()); Assert.assertEquals("second_id", secondSelectResult.getOrderedColumns().get(0).getName()); Assert.assertEquals(1, secondSelectResult.getColumnsByName().size()); Assert.assertTrue(secondSelectResult.getColumnsByName().containsKey("second_id")); }
// Path: src/main/java/com/pgasync/ResultSet.java // public interface ResultSet extends Iterable<Row> { // // Map<String, PgColumn> getColumnsByName(); // // List<PgColumn> getOrderedColumns(); // // /** // * @param index Row index starting from 0 // * @return Row, never null // */ // Row at(int index); // // /** // * @return Amount of result rows. // */ // int size(); // // /** // * @return Amount of modified rows. // */ // int affectedRows(); // // } // // Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // } // Path: src/test/java/com/github/pgasync/ScriptResultsTest.java import com.pgasync.ResultSet; import com.pgasync.SqlException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import java.util.ArrayList; import java.util.List; ResultSet firstSelectResult = results.get(1); Assert.assertEquals(0, firstSelectResult.affectedRows()); Assert.assertEquals(2, firstSelectResult.size()); Assert.assertEquals(1, firstSelectResult.at(0).getLong("first_id").intValue()); Assert.assertEquals(2, firstSelectResult.at(1).getLong("first_id").intValue()); Assert.assertEquals(1, firstSelectResult.getOrderedColumns().size()); Assert.assertEquals("first_id", firstSelectResult.getOrderedColumns().get(0).getName()); Assert.assertEquals(1, firstSelectResult.getColumnsByName().size()); Assert.assertTrue(firstSelectResult.getColumnsByName().containsKey("first_id")); ResultSet secondInsertResult = results.get(2); Assert.assertEquals(3, secondInsertResult.affectedRows()); Assert.assertEquals(0, secondInsertResult.size()); Assert.assertTrue(secondInsertResult.getOrderedColumns().isEmpty()); Assert.assertTrue(secondInsertResult.getColumnsByName().isEmpty()); ResultSet secondSelectResult = results.get(3); Assert.assertEquals(0, secondSelectResult.affectedRows()); Assert.assertEquals(3, secondSelectResult.size()); Assert.assertEquals(3, secondSelectResult.at(0).getLong("second_id").intValue()); Assert.assertEquals(4, secondSelectResult.at(1).getLong("second_id").intValue()); Assert.assertEquals(5, secondSelectResult.at(2).getLong("second_id").intValue()); Assert.assertEquals(1, secondSelectResult.getOrderedColumns().size()); Assert.assertEquals("second_id", secondSelectResult.getOrderedColumns().get(0).getName()); Assert.assertEquals(1, secondSelectResult.getColumnsByName().size()); Assert.assertTrue(secondSelectResult.getColumnsByName().containsKey("second_id")); }
@Test(expected = SqlException.class)
alaisi/postgres-async-driver
src/main/java/com/github/pgasync/message/frontend/Parse.java
// Path: src/main/java/com/github/pgasync/Oid.java // public enum Oid { // // UNSPECIFIED(0), // INT2(21), // INT2_ARRAY(1005), // INT4(23), // INT4_ARRAY(1007), // INT8(20), // INT8_ARRAY(1016), // TEXT(25), // TEXT_ARRAY(1009), // NUMERIC(1700), // NUMERIC_ARRAY(1231), // FLOAT4(700), // FLOAT4_ARRAY(1021), // FLOAT8(701), // FLOAT8_ARRAY(1022), // BOOL(16), // BOOL_ARRAY(1000), // DATE(1082), // DATE_ARRAY(1182), // TIME(1083), // TIME_ARRAY(1183), // TIMETZ(1266), // TIMETZ_ARRAY(1270), // TIMESTAMP(1114), // TIMESTAMP_ARRAY(1115), // TIMESTAMPTZ(1184), // TIMESTAMPTZ_ARRAY(1185), // BYTEA(17), // BYTEA_ARRAY(1001), // VARCHAR(1043), // VARCHAR_ARRAY(1015), // OID(26), // OID_ARRAY(1028), // BPCHAR(1042), // BPCHAR_ARRAY(1014), // MONEY(790), // MONEY_ARRAY(791), // NAME(19), // NAME_ARRAY(1003), // BIT(1560), // BIT_ARRAY(1561), // VOID(2278), // INTERVAL(1186), // INTERVAL_ARRAY(1187), // CHAR(18), // CHAR_ARRAY(1002), // VARBIT(1562), // VARBIT_ARRAY(1563), // UUID(2950), // UUID_ARRAY(2951), // XML(142), // XML_ARRAY(143), // POINT(600), // BOX(603), // // Added // JSON(114), // JSONB(3802), // HSTORE(33670) // ; // // final int id; // // Oid(int id) { // this.id = id; // } // // public int getId() { // return id; // } // // public static Oid valueOfId(int id) { // for (Oid oid : values()) { // if (oid.id == id) { // return oid; // } // } // return Oid.UNSPECIFIED; // } // } // // Path: src/main/java/com/github/pgasync/message/ExtendedQueryMessage.java // public interface ExtendedQueryMessage extends Message { // }
import com.github.pgasync.Oid; import com.github.pgasync.message.ExtendedQueryMessage;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync.message.frontend; /** * @author Antti Laisi */ public class Parse implements ExtendedQueryMessage { private final String sql; private final String sname;
// Path: src/main/java/com/github/pgasync/Oid.java // public enum Oid { // // UNSPECIFIED(0), // INT2(21), // INT2_ARRAY(1005), // INT4(23), // INT4_ARRAY(1007), // INT8(20), // INT8_ARRAY(1016), // TEXT(25), // TEXT_ARRAY(1009), // NUMERIC(1700), // NUMERIC_ARRAY(1231), // FLOAT4(700), // FLOAT4_ARRAY(1021), // FLOAT8(701), // FLOAT8_ARRAY(1022), // BOOL(16), // BOOL_ARRAY(1000), // DATE(1082), // DATE_ARRAY(1182), // TIME(1083), // TIME_ARRAY(1183), // TIMETZ(1266), // TIMETZ_ARRAY(1270), // TIMESTAMP(1114), // TIMESTAMP_ARRAY(1115), // TIMESTAMPTZ(1184), // TIMESTAMPTZ_ARRAY(1185), // BYTEA(17), // BYTEA_ARRAY(1001), // VARCHAR(1043), // VARCHAR_ARRAY(1015), // OID(26), // OID_ARRAY(1028), // BPCHAR(1042), // BPCHAR_ARRAY(1014), // MONEY(790), // MONEY_ARRAY(791), // NAME(19), // NAME_ARRAY(1003), // BIT(1560), // BIT_ARRAY(1561), // VOID(2278), // INTERVAL(1186), // INTERVAL_ARRAY(1187), // CHAR(18), // CHAR_ARRAY(1002), // VARBIT(1562), // VARBIT_ARRAY(1563), // UUID(2950), // UUID_ARRAY(2951), // XML(142), // XML_ARRAY(143), // POINT(600), // BOX(603), // // Added // JSON(114), // JSONB(3802), // HSTORE(33670) // ; // // final int id; // // Oid(int id) { // this.id = id; // } // // public int getId() { // return id; // } // // public static Oid valueOfId(int id) { // for (Oid oid : values()) { // if (oid.id == id) { // return oid; // } // } // return Oid.UNSPECIFIED; // } // } // // Path: src/main/java/com/github/pgasync/message/ExtendedQueryMessage.java // public interface ExtendedQueryMessage extends Message { // } // Path: src/main/java/com/github/pgasync/message/frontend/Parse.java import com.github.pgasync.Oid; import com.github.pgasync.message.ExtendedQueryMessage; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync.message.frontend; /** * @author Antti Laisi */ public class Parse implements ExtendedQueryMessage { private final String sql; private final String sname;
private final Oid[] types;
alaisi/postgres-async-driver
src/main/java/com/pgasync/QueryExecutor.java
// Path: src/main/java/com/github/pgasync/PgColumn.java // public class PgColumn { // // private final int index; // private final String name; // private final Oid type; // // public PgColumn(int index, String name, Oid type) { // this.index = index; // this.name = name; // this.type = type; // } // // public Oid getType() { // return type; // } // // public String getName() { // return name; // } // // public int at() { // return index; // } // } // // Path: src/main/java/com/github/pgasync/PgResultSet.java // public class PgResultSet implements ResultSet { // // private final List<Row> rows; // private final Map<String, PgColumn> columnsByName; // private final List<PgColumn> orderedColumns; // private final int affectedRows; // // public PgResultSet(Map<String, PgColumn> columnsByName, List<PgColumn> orderedColumns, List<Row> rows, int affectedRows) { // this.columnsByName = columnsByName; // this.orderedColumns = orderedColumns; // this.rows = rows; // this.affectedRows = affectedRows; // } // // @Override // public Map<String, PgColumn> getColumnsByName() { // return columnsByName != null ? columnsByName : Map.of(); // } // // @Override // public List<PgColumn> getOrderedColumns() { // return orderedColumns; // } // // @Override // public Iterator<Row> iterator() { // return rows != null ? rows.iterator() : Collections.emptyIterator(); // } // // @Override // public Row at(int index) { // if (rows == null) { // throw new IndexOutOfBoundsException(); // } // return rows.get(index); // } // // @Override // public int size() { // return rows != null ? rows.size() : 0; // } // // @Override // public int affectedRows() { // return affectedRows; // } // // }
import com.github.pgasync.PgColumn; import com.github.pgasync.PgResultSet; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.function.BiConsumer; import java.util.function.Consumer;
package com.pgasync; /** * QueryExecutor submits SQL for execution. * * @author Antti Laisi */ public interface QueryExecutor { /** * Begins a transaction. */ CompletableFuture<Transaction> begin(); /** * Sends parameter less query script. The script may be multi query. Queries are separated with semicolons. * Accumulates fetched columns, rows and affected rows counts into memory and transforms them into a ResultSet when each {@link ResultSet} is fetched. * Completes returned {@link CompletableFuture} when the whole process of multiple {@link ResultSet}s fetching ends. * * @param sql Sql Script text. * @return CompletableFuture that is completed with a collection of fetched {@link ResultSet}s. */ default CompletableFuture<Collection<ResultSet>> completeScript(String sql) { List<ResultSet> results = new ArrayList<>(); class ResultSetAssembly {
// Path: src/main/java/com/github/pgasync/PgColumn.java // public class PgColumn { // // private final int index; // private final String name; // private final Oid type; // // public PgColumn(int index, String name, Oid type) { // this.index = index; // this.name = name; // this.type = type; // } // // public Oid getType() { // return type; // } // // public String getName() { // return name; // } // // public int at() { // return index; // } // } // // Path: src/main/java/com/github/pgasync/PgResultSet.java // public class PgResultSet implements ResultSet { // // private final List<Row> rows; // private final Map<String, PgColumn> columnsByName; // private final List<PgColumn> orderedColumns; // private final int affectedRows; // // public PgResultSet(Map<String, PgColumn> columnsByName, List<PgColumn> orderedColumns, List<Row> rows, int affectedRows) { // this.columnsByName = columnsByName; // this.orderedColumns = orderedColumns; // this.rows = rows; // this.affectedRows = affectedRows; // } // // @Override // public Map<String, PgColumn> getColumnsByName() { // return columnsByName != null ? columnsByName : Map.of(); // } // // @Override // public List<PgColumn> getOrderedColumns() { // return orderedColumns; // } // // @Override // public Iterator<Row> iterator() { // return rows != null ? rows.iterator() : Collections.emptyIterator(); // } // // @Override // public Row at(int index) { // if (rows == null) { // throw new IndexOutOfBoundsException(); // } // return rows.get(index); // } // // @Override // public int size() { // return rows != null ? rows.size() : 0; // } // // @Override // public int affectedRows() { // return affectedRows; // } // // } // Path: src/main/java/com/pgasync/QueryExecutor.java import com.github.pgasync.PgColumn; import com.github.pgasync.PgResultSet; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.function.BiConsumer; import java.util.function.Consumer; package com.pgasync; /** * QueryExecutor submits SQL for execution. * * @author Antti Laisi */ public interface QueryExecutor { /** * Begins a transaction. */ CompletableFuture<Transaction> begin(); /** * Sends parameter less query script. The script may be multi query. Queries are separated with semicolons. * Accumulates fetched columns, rows and affected rows counts into memory and transforms them into a ResultSet when each {@link ResultSet} is fetched. * Completes returned {@link CompletableFuture} when the whole process of multiple {@link ResultSet}s fetching ends. * * @param sql Sql Script text. * @return CompletableFuture that is completed with a collection of fetched {@link ResultSet}s. */ default CompletableFuture<Collection<ResultSet>> completeScript(String sql) { List<ResultSet> results = new ArrayList<>(); class ResultSetAssembly {
private Map<String, PgColumn> columnsByName;
alaisi/postgres-async-driver
src/main/java/com/pgasync/QueryExecutor.java
// Path: src/main/java/com/github/pgasync/PgColumn.java // public class PgColumn { // // private final int index; // private final String name; // private final Oid type; // // public PgColumn(int index, String name, Oid type) { // this.index = index; // this.name = name; // this.type = type; // } // // public Oid getType() { // return type; // } // // public String getName() { // return name; // } // // public int at() { // return index; // } // } // // Path: src/main/java/com/github/pgasync/PgResultSet.java // public class PgResultSet implements ResultSet { // // private final List<Row> rows; // private final Map<String, PgColumn> columnsByName; // private final List<PgColumn> orderedColumns; // private final int affectedRows; // // public PgResultSet(Map<String, PgColumn> columnsByName, List<PgColumn> orderedColumns, List<Row> rows, int affectedRows) { // this.columnsByName = columnsByName; // this.orderedColumns = orderedColumns; // this.rows = rows; // this.affectedRows = affectedRows; // } // // @Override // public Map<String, PgColumn> getColumnsByName() { // return columnsByName != null ? columnsByName : Map.of(); // } // // @Override // public List<PgColumn> getOrderedColumns() { // return orderedColumns; // } // // @Override // public Iterator<Row> iterator() { // return rows != null ? rows.iterator() : Collections.emptyIterator(); // } // // @Override // public Row at(int index) { // if (rows == null) { // throw new IndexOutOfBoundsException(); // } // return rows.get(index); // } // // @Override // public int size() { // return rows != null ? rows.size() : 0; // } // // @Override // public int affectedRows() { // return affectedRows; // } // // }
import com.github.pgasync.PgColumn; import com.github.pgasync.PgResultSet; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.function.BiConsumer; import java.util.function.Consumer;
package com.pgasync; /** * QueryExecutor submits SQL for execution. * * @author Antti Laisi */ public interface QueryExecutor { /** * Begins a transaction. */ CompletableFuture<Transaction> begin(); /** * Sends parameter less query script. The script may be multi query. Queries are separated with semicolons. * Accumulates fetched columns, rows and affected rows counts into memory and transforms them into a ResultSet when each {@link ResultSet} is fetched. * Completes returned {@link CompletableFuture} when the whole process of multiple {@link ResultSet}s fetching ends. * * @param sql Sql Script text. * @return CompletableFuture that is completed with a collection of fetched {@link ResultSet}s. */ default CompletableFuture<Collection<ResultSet>> completeScript(String sql) { List<ResultSet> results = new ArrayList<>(); class ResultSetAssembly { private Map<String, PgColumn> columnsByName; private PgColumn[] orderedColumns; private List<Row> rows; private void reset() { columnsByName = null; orderedColumns = null; rows = null; } } ResultSetAssembly assembly = new ResultSetAssembly(); return script( (columnsByName, orderedColumns) -> { assembly.columnsByName = columnsByName; assembly.orderedColumns = orderedColumns; assembly.rows = new ArrayList<>(); }, row -> assembly.rows.add(row), affected -> {
// Path: src/main/java/com/github/pgasync/PgColumn.java // public class PgColumn { // // private final int index; // private final String name; // private final Oid type; // // public PgColumn(int index, String name, Oid type) { // this.index = index; // this.name = name; // this.type = type; // } // // public Oid getType() { // return type; // } // // public String getName() { // return name; // } // // public int at() { // return index; // } // } // // Path: src/main/java/com/github/pgasync/PgResultSet.java // public class PgResultSet implements ResultSet { // // private final List<Row> rows; // private final Map<String, PgColumn> columnsByName; // private final List<PgColumn> orderedColumns; // private final int affectedRows; // // public PgResultSet(Map<String, PgColumn> columnsByName, List<PgColumn> orderedColumns, List<Row> rows, int affectedRows) { // this.columnsByName = columnsByName; // this.orderedColumns = orderedColumns; // this.rows = rows; // this.affectedRows = affectedRows; // } // // @Override // public Map<String, PgColumn> getColumnsByName() { // return columnsByName != null ? columnsByName : Map.of(); // } // // @Override // public List<PgColumn> getOrderedColumns() { // return orderedColumns; // } // // @Override // public Iterator<Row> iterator() { // return rows != null ? rows.iterator() : Collections.emptyIterator(); // } // // @Override // public Row at(int index) { // if (rows == null) { // throw new IndexOutOfBoundsException(); // } // return rows.get(index); // } // // @Override // public int size() { // return rows != null ? rows.size() : 0; // } // // @Override // public int affectedRows() { // return affectedRows; // } // // } // Path: src/main/java/com/pgasync/QueryExecutor.java import com.github.pgasync.PgColumn; import com.github.pgasync.PgResultSet; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.function.BiConsumer; import java.util.function.Consumer; package com.pgasync; /** * QueryExecutor submits SQL for execution. * * @author Antti Laisi */ public interface QueryExecutor { /** * Begins a transaction. */ CompletableFuture<Transaction> begin(); /** * Sends parameter less query script. The script may be multi query. Queries are separated with semicolons. * Accumulates fetched columns, rows and affected rows counts into memory and transforms them into a ResultSet when each {@link ResultSet} is fetched. * Completes returned {@link CompletableFuture} when the whole process of multiple {@link ResultSet}s fetching ends. * * @param sql Sql Script text. * @return CompletableFuture that is completed with a collection of fetched {@link ResultSet}s. */ default CompletableFuture<Collection<ResultSet>> completeScript(String sql) { List<ResultSet> results = new ArrayList<>(); class ResultSetAssembly { private Map<String, PgColumn> columnsByName; private PgColumn[] orderedColumns; private List<Row> rows; private void reset() { columnsByName = null; orderedColumns = null; rows = null; } } ResultSetAssembly assembly = new ResultSetAssembly(); return script( (columnsByName, orderedColumns) -> { assembly.columnsByName = columnsByName; assembly.orderedColumns = orderedColumns; assembly.rows = new ArrayList<>(); }, row -> assembly.rows.add(row), affected -> {
results.add(new PgResultSet(
alaisi/postgres-async-driver
src/test/java/com/github/pgasync/ArrayConversionsTest.java
// Path: src/main/java/com/pgasync/Row.java // public interface Row { // // String getString(int index); // // String getString(String column); // // Byte getByte(int index); // // Byte getByte(String column); // // Character getChar(int index); // // Character getChar(String column); // // Short getShort(int index); // // Short getShort(String column); // // Integer getInt(int index); // // Integer getInt(String column); // // Long getLong(int index); // // Long getLong(String column); // // BigInteger getBigInteger(int index); // // BigInteger getBigInteger(String column); // // BigDecimal getBigDecimal(int index); // // BigDecimal getBigDecimal(String column); // // Double getDouble(int index); // // Double getDouble(String column); // // Date getDate(int index); // // Date getDate(String column); // // Time getTime(int index); // // Time getTime(String column); // // Timestamp getTimestamp(int index); // // Timestamp getTimestamp(String column); // // byte[] getBytes(int index); // // byte[] getBytes(String column); // // Boolean getBoolean(int index); // // Boolean getBoolean(String column); // // <T> T get(int index, Class<T> type); // // <T> T get(String column, Class<T> type); // // <TArray> TArray getArray(String column, Class<TArray> arrayType); // // <TArray> TArray getArray(int index, Class<TArray> arrayType); // // }
import com.pgasync.Row; import org.junit.*; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import java.sql.Timestamp; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals;
package com.github.pgasync; public class ArrayConversionsTest { @ClassRule public static DatabaseRule dbr = new DatabaseRule(); @BeforeClass public static void create() { drop(); dbr.query("CREATE TABLE CA_TEST (" + "TEXTA TEXT[], SHORTA INT2[], INTA INT4[], LONGA INT8[], FLOATA FLOAT4[], TIMESTAMPA TIMESTAMP[], BYTEAA BYTEA[])"); } @AfterClass public static void drop() { dbr.query("DROP TABLE IF EXISTS CA_TEST"); } @After public void empty() { dbr.query("DELETE FROM CA_TEST"); }
// Path: src/main/java/com/pgasync/Row.java // public interface Row { // // String getString(int index); // // String getString(String column); // // Byte getByte(int index); // // Byte getByte(String column); // // Character getChar(int index); // // Character getChar(String column); // // Short getShort(int index); // // Short getShort(String column); // // Integer getInt(int index); // // Integer getInt(String column); // // Long getLong(int index); // // Long getLong(String column); // // BigInteger getBigInteger(int index); // // BigInteger getBigInteger(String column); // // BigDecimal getBigDecimal(int index); // // BigDecimal getBigDecimal(String column); // // Double getDouble(int index); // // Double getDouble(String column); // // Date getDate(int index); // // Date getDate(String column); // // Time getTime(int index); // // Time getTime(String column); // // Timestamp getTimestamp(int index); // // Timestamp getTimestamp(String column); // // byte[] getBytes(int index); // // byte[] getBytes(String column); // // Boolean getBoolean(int index); // // Boolean getBoolean(String column); // // <T> T get(int index, Class<T> type); // // <T> T get(String column, Class<T> type); // // <TArray> TArray getArray(String column, Class<TArray> arrayType); // // <TArray> TArray getArray(int index, Class<TArray> arrayType); // // } // Path: src/test/java/com/github/pgasync/ArrayConversionsTest.java import com.pgasync.Row; import org.junit.*; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import java.sql.Timestamp; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; package com.github.pgasync; public class ArrayConversionsTest { @ClassRule public static DatabaseRule dbr = new DatabaseRule(); @BeforeClass public static void create() { drop(); dbr.query("CREATE TABLE CA_TEST (" + "TEXTA TEXT[], SHORTA INT2[], INTA INT4[], LONGA INT8[], FLOATA FLOAT4[], TIMESTAMPA TIMESTAMP[], BYTEAA BYTEA[])"); } @AfterClass public static void drop() { dbr.query("DROP TABLE IF EXISTS CA_TEST"); } @After public void empty() { dbr.query("DELETE FROM CA_TEST"); }
private Row getRow() {
alaisi/postgres-async-driver
src/main/java/com/github/pgasync/io/backend/LogResponseDecoder.java
// Path: src/main/java/com/github/pgasync/io/Decoder.java // public interface Decoder<T extends Message> { // // /** // * @return Protocol message id // */ // byte getMessageId(); // // /** // * @return Decoded message // */ // T read(ByteBuffer buffer, Charset encoding); // // } // // Path: src/main/java/com/github/pgasync/message/backend/LogResponse.java // public class LogResponse implements Message { // // protected final String level; // protected final String code; // protected final String message; // // public LogResponse(String level, String code, String message) { // this.level = level; // this.code = code; // this.message = message; // } // // public String getLevel() { // return level; // } // // public String getCode() { // return code; // } // // public String getMessage() { // return message; // } // // } // // Path: src/main/java/com/github/pgasync/io/IO.java // public class IO { // // public static String getCString(ByteBuffer buffer, Charset charset) { // ByteArrayOutputStream readBuffer = new ByteArrayOutputStream(255); // for (int c = buffer.get(); c != 0; c = buffer.get()) { // readBuffer.write(c); // } // return new String(readBuffer.toByteArray(), charset); // } // // public static void putCString(ByteBuffer buffer, String value, Charset charset) { // if (!value.isEmpty()) { // buffer.put(value.getBytes(charset)); // } // buffer.put((byte) 0); // } // // }
import com.github.pgasync.io.Decoder; import com.github.pgasync.message.backend.LogResponse; import com.github.pgasync.io.IO; import java.nio.ByteBuffer; import java.nio.charset.Charset;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync.io.backend; /** * Base class for NoticeResponse and for ErrorResponse. * * @param <M> Specific message type. * @author Marat Gainullin */ public abstract class LogResponseDecoder<M extends LogResponse> implements Decoder<M> { @Override public M read(ByteBuffer buffer, Charset encoding) { String level = null; String code = null; String message = null; for (byte type = buffer.get(); type != 0; type = buffer.get()) {
// Path: src/main/java/com/github/pgasync/io/Decoder.java // public interface Decoder<T extends Message> { // // /** // * @return Protocol message id // */ // byte getMessageId(); // // /** // * @return Decoded message // */ // T read(ByteBuffer buffer, Charset encoding); // // } // // Path: src/main/java/com/github/pgasync/message/backend/LogResponse.java // public class LogResponse implements Message { // // protected final String level; // protected final String code; // protected final String message; // // public LogResponse(String level, String code, String message) { // this.level = level; // this.code = code; // this.message = message; // } // // public String getLevel() { // return level; // } // // public String getCode() { // return code; // } // // public String getMessage() { // return message; // } // // } // // Path: src/main/java/com/github/pgasync/io/IO.java // public class IO { // // public static String getCString(ByteBuffer buffer, Charset charset) { // ByteArrayOutputStream readBuffer = new ByteArrayOutputStream(255); // for (int c = buffer.get(); c != 0; c = buffer.get()) { // readBuffer.write(c); // } // return new String(readBuffer.toByteArray(), charset); // } // // public static void putCString(ByteBuffer buffer, String value, Charset charset) { // if (!value.isEmpty()) { // buffer.put(value.getBytes(charset)); // } // buffer.put((byte) 0); // } // // } // Path: src/main/java/com/github/pgasync/io/backend/LogResponseDecoder.java import com.github.pgasync.io.Decoder; import com.github.pgasync.message.backend.LogResponse; import com.github.pgasync.io.IO; import java.nio.ByteBuffer; import java.nio.charset.Charset; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync.io.backend; /** * Base class for NoticeResponse and for ErrorResponse. * * @param <M> Specific message type. * @author Marat Gainullin */ public abstract class LogResponseDecoder<M extends LogResponse> implements Decoder<M> { @Override public M read(ByteBuffer buffer, Charset encoding) { String level = null; String code = null; String message = null; for (byte type = buffer.get(); type != 0; type = buffer.get()) {
String value = IO.getCString(buffer, encoding);
alaisi/postgres-async-driver
src/main/java/com/github/pgasync/conversion/BlobConversions.java
// Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // } // // Path: src/main/java/com/github/pgasync/Oid.java // public enum Oid { // // UNSPECIFIED(0), // INT2(21), // INT2_ARRAY(1005), // INT4(23), // INT4_ARRAY(1007), // INT8(20), // INT8_ARRAY(1016), // TEXT(25), // TEXT_ARRAY(1009), // NUMERIC(1700), // NUMERIC_ARRAY(1231), // FLOAT4(700), // FLOAT4_ARRAY(1021), // FLOAT8(701), // FLOAT8_ARRAY(1022), // BOOL(16), // BOOL_ARRAY(1000), // DATE(1082), // DATE_ARRAY(1182), // TIME(1083), // TIME_ARRAY(1183), // TIMETZ(1266), // TIMETZ_ARRAY(1270), // TIMESTAMP(1114), // TIMESTAMP_ARRAY(1115), // TIMESTAMPTZ(1184), // TIMESTAMPTZ_ARRAY(1185), // BYTEA(17), // BYTEA_ARRAY(1001), // VARCHAR(1043), // VARCHAR_ARRAY(1015), // OID(26), // OID_ARRAY(1028), // BPCHAR(1042), // BPCHAR_ARRAY(1014), // MONEY(790), // MONEY_ARRAY(791), // NAME(19), // NAME_ARRAY(1003), // BIT(1560), // BIT_ARRAY(1561), // VOID(2278), // INTERVAL(1186), // INTERVAL_ARRAY(1187), // CHAR(18), // CHAR_ARRAY(1002), // VARBIT(1562), // VARBIT_ARRAY(1563), // UUID(2950), // UUID_ARRAY(2951), // XML(142), // XML_ARRAY(143), // POINT(600), // BOX(603), // // Added // JSON(114), // JSONB(3802), // HSTORE(33670) // ; // // final int id; // // Oid(int id) { // this.id = id; // } // // public int getId() { // return id; // } // // public static Oid valueOfId(int id) { // for (Oid oid : values()) { // if (oid.id == id) { // return oid; // } // } // return Oid.UNSPECIFIED; // } // }
import com.pgasync.SqlException; import com.github.pgasync.Oid; import static javax.xml.bind.DatatypeConverter.parseHexBinary; import static javax.xml.bind.DatatypeConverter.printHexBinary;
package com.github.pgasync.conversion; /** * @author Antti Laisi */ class BlobConversions { static byte[] toBytes(Oid oid, String value) { switch (oid) { case UNSPECIFIED: // fallthrough case BYTEA: return parseHexBinary(value); // TODO: Add theses considerations somewhere to the code: 1. (2, length-2) 2. According to postgres rules bytea should be encoded as ASCII sequence default:
// Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // } // // Path: src/main/java/com/github/pgasync/Oid.java // public enum Oid { // // UNSPECIFIED(0), // INT2(21), // INT2_ARRAY(1005), // INT4(23), // INT4_ARRAY(1007), // INT8(20), // INT8_ARRAY(1016), // TEXT(25), // TEXT_ARRAY(1009), // NUMERIC(1700), // NUMERIC_ARRAY(1231), // FLOAT4(700), // FLOAT4_ARRAY(1021), // FLOAT8(701), // FLOAT8_ARRAY(1022), // BOOL(16), // BOOL_ARRAY(1000), // DATE(1082), // DATE_ARRAY(1182), // TIME(1083), // TIME_ARRAY(1183), // TIMETZ(1266), // TIMETZ_ARRAY(1270), // TIMESTAMP(1114), // TIMESTAMP_ARRAY(1115), // TIMESTAMPTZ(1184), // TIMESTAMPTZ_ARRAY(1185), // BYTEA(17), // BYTEA_ARRAY(1001), // VARCHAR(1043), // VARCHAR_ARRAY(1015), // OID(26), // OID_ARRAY(1028), // BPCHAR(1042), // BPCHAR_ARRAY(1014), // MONEY(790), // MONEY_ARRAY(791), // NAME(19), // NAME_ARRAY(1003), // BIT(1560), // BIT_ARRAY(1561), // VOID(2278), // INTERVAL(1186), // INTERVAL_ARRAY(1187), // CHAR(18), // CHAR_ARRAY(1002), // VARBIT(1562), // VARBIT_ARRAY(1563), // UUID(2950), // UUID_ARRAY(2951), // XML(142), // XML_ARRAY(143), // POINT(600), // BOX(603), // // Added // JSON(114), // JSONB(3802), // HSTORE(33670) // ; // // final int id; // // Oid(int id) { // this.id = id; // } // // public int getId() { // return id; // } // // public static Oid valueOfId(int id) { // for (Oid oid : values()) { // if (oid.id == id) { // return oid; // } // } // return Oid.UNSPECIFIED; // } // } // Path: src/main/java/com/github/pgasync/conversion/BlobConversions.java import com.pgasync.SqlException; import com.github.pgasync.Oid; import static javax.xml.bind.DatatypeConverter.parseHexBinary; import static javax.xml.bind.DatatypeConverter.printHexBinary; package com.github.pgasync.conversion; /** * @author Antti Laisi */ class BlobConversions { static byte[] toBytes(Oid oid, String value) { switch (oid) { case UNSPECIFIED: // fallthrough case BYTEA: return parseHexBinary(value); // TODO: Add theses considerations somewhere to the code: 1. (2, length-2) 2. According to postgres rules bytea should be encoded as ASCII sequence default:
throw new SqlException("Unsupported conversion " + oid.name() + " -> byte[]");
alaisi/postgres-async-driver
src/test/java/com/github/pgasync/AuthenticationTest.java
// Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/ResultSet.java // public interface ResultSet extends Iterable<Row> { // // Map<String, PgColumn> getColumnsByName(); // // List<PgColumn> getOrderedColumns(); // // /** // * @param index Row index starting from 0 // * @return Row, never null // */ // Row at(int index); // // /** // * @return Amount of result rows. // */ // int size(); // // /** // * @return Amount of modified rows. // */ // int affectedRows(); // // } // // Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // } // // Path: src/test/java/com/github/pgasync/DatabaseRule.java // static NettyConnectibleBuilder createPoolBuilder(int size) { // String db = getenv("PG_DATABASE"); // String user = getenv("PG_USERNAME"); // String pass = getenv("PG_PASSWORD"); // // if (db == null && user == null && pass == null) { // return new EmbeddedConnectionPoolBuilder().maxConnections(size); // } else { // return new EmbeddedConnectionPoolBuilder() // .database(envOrDefault("PG_DATABASE", "postgres")) // .username(envOrDefault("PG_USERNAME", "postgres")) // .password(envOrDefault("PG_PASSWORD", "postgres")) // .ssl(true) // .maxConnections(size); // } // }
import com.pgasync.Connectible; import com.pgasync.ResultSet; import com.pgasync.SqlException; import org.junit.ClassRule; import org.junit.Test; import static com.github.pgasync.DatabaseRule.createPoolBuilder; import static org.junit.Assert.assertEquals;
package com.github.pgasync; public class AuthenticationTest { @ClassRule
// Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/ResultSet.java // public interface ResultSet extends Iterable<Row> { // // Map<String, PgColumn> getColumnsByName(); // // List<PgColumn> getOrderedColumns(); // // /** // * @param index Row index starting from 0 // * @return Row, never null // */ // Row at(int index); // // /** // * @return Amount of result rows. // */ // int size(); // // /** // * @return Amount of modified rows. // */ // int affectedRows(); // // } // // Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // } // // Path: src/test/java/com/github/pgasync/DatabaseRule.java // static NettyConnectibleBuilder createPoolBuilder(int size) { // String db = getenv("PG_DATABASE"); // String user = getenv("PG_USERNAME"); // String pass = getenv("PG_PASSWORD"); // // if (db == null && user == null && pass == null) { // return new EmbeddedConnectionPoolBuilder().maxConnections(size); // } else { // return new EmbeddedConnectionPoolBuilder() // .database(envOrDefault("PG_DATABASE", "postgres")) // .username(envOrDefault("PG_USERNAME", "postgres")) // .password(envOrDefault("PG_PASSWORD", "postgres")) // .ssl(true) // .maxConnections(size); // } // } // Path: src/test/java/com/github/pgasync/AuthenticationTest.java import com.pgasync.Connectible; import com.pgasync.ResultSet; import com.pgasync.SqlException; import org.junit.ClassRule; import org.junit.Test; import static com.github.pgasync.DatabaseRule.createPoolBuilder; import static org.junit.Assert.assertEquals; package com.github.pgasync; public class AuthenticationTest { @ClassRule
public static DatabaseRule dbr = new DatabaseRule(createPoolBuilder(1));
alaisi/postgres-async-driver
src/test/java/com/github/pgasync/AuthenticationTest.java
// Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/ResultSet.java // public interface ResultSet extends Iterable<Row> { // // Map<String, PgColumn> getColumnsByName(); // // List<PgColumn> getOrderedColumns(); // // /** // * @param index Row index starting from 0 // * @return Row, never null // */ // Row at(int index); // // /** // * @return Amount of result rows. // */ // int size(); // // /** // * @return Amount of modified rows. // */ // int affectedRows(); // // } // // Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // } // // Path: src/test/java/com/github/pgasync/DatabaseRule.java // static NettyConnectibleBuilder createPoolBuilder(int size) { // String db = getenv("PG_DATABASE"); // String user = getenv("PG_USERNAME"); // String pass = getenv("PG_PASSWORD"); // // if (db == null && user == null && pass == null) { // return new EmbeddedConnectionPoolBuilder().maxConnections(size); // } else { // return new EmbeddedConnectionPoolBuilder() // .database(envOrDefault("PG_DATABASE", "postgres")) // .username(envOrDefault("PG_USERNAME", "postgres")) // .password(envOrDefault("PG_PASSWORD", "postgres")) // .ssl(true) // .maxConnections(size); // } // }
import com.pgasync.Connectible; import com.pgasync.ResultSet; import com.pgasync.SqlException; import org.junit.ClassRule; import org.junit.Test; import static com.github.pgasync.DatabaseRule.createPoolBuilder; import static org.junit.Assert.assertEquals;
package com.github.pgasync; public class AuthenticationTest { @ClassRule public static DatabaseRule dbr = new DatabaseRule(createPoolBuilder(1));
// Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/ResultSet.java // public interface ResultSet extends Iterable<Row> { // // Map<String, PgColumn> getColumnsByName(); // // List<PgColumn> getOrderedColumns(); // // /** // * @param index Row index starting from 0 // * @return Row, never null // */ // Row at(int index); // // /** // * @return Amount of result rows. // */ // int size(); // // /** // * @return Amount of modified rows. // */ // int affectedRows(); // // } // // Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // } // // Path: src/test/java/com/github/pgasync/DatabaseRule.java // static NettyConnectibleBuilder createPoolBuilder(int size) { // String db = getenv("PG_DATABASE"); // String user = getenv("PG_USERNAME"); // String pass = getenv("PG_PASSWORD"); // // if (db == null && user == null && pass == null) { // return new EmbeddedConnectionPoolBuilder().maxConnections(size); // } else { // return new EmbeddedConnectionPoolBuilder() // .database(envOrDefault("PG_DATABASE", "postgres")) // .username(envOrDefault("PG_USERNAME", "postgres")) // .password(envOrDefault("PG_PASSWORD", "postgres")) // .ssl(true) // .maxConnections(size); // } // } // Path: src/test/java/com/github/pgasync/AuthenticationTest.java import com.pgasync.Connectible; import com.pgasync.ResultSet; import com.pgasync.SqlException; import org.junit.ClassRule; import org.junit.Test; import static com.github.pgasync.DatabaseRule.createPoolBuilder; import static org.junit.Assert.assertEquals; package com.github.pgasync; public class AuthenticationTest { @ClassRule public static DatabaseRule dbr = new DatabaseRule(createPoolBuilder(1));
@Test(expected = SqlException.class)
alaisi/postgres-async-driver
src/test/java/com/github/pgasync/AuthenticationTest.java
// Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/ResultSet.java // public interface ResultSet extends Iterable<Row> { // // Map<String, PgColumn> getColumnsByName(); // // List<PgColumn> getOrderedColumns(); // // /** // * @param index Row index starting from 0 // * @return Row, never null // */ // Row at(int index); // // /** // * @return Amount of result rows. // */ // int size(); // // /** // * @return Amount of modified rows. // */ // int affectedRows(); // // } // // Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // } // // Path: src/test/java/com/github/pgasync/DatabaseRule.java // static NettyConnectibleBuilder createPoolBuilder(int size) { // String db = getenv("PG_DATABASE"); // String user = getenv("PG_USERNAME"); // String pass = getenv("PG_PASSWORD"); // // if (db == null && user == null && pass == null) { // return new EmbeddedConnectionPoolBuilder().maxConnections(size); // } else { // return new EmbeddedConnectionPoolBuilder() // .database(envOrDefault("PG_DATABASE", "postgres")) // .username(envOrDefault("PG_USERNAME", "postgres")) // .password(envOrDefault("PG_PASSWORD", "postgres")) // .ssl(true) // .maxConnections(size); // } // }
import com.pgasync.Connectible; import com.pgasync.ResultSet; import com.pgasync.SqlException; import org.junit.ClassRule; import org.junit.Test; import static com.github.pgasync.DatabaseRule.createPoolBuilder; import static org.junit.Assert.assertEquals;
package com.github.pgasync; public class AuthenticationTest { @ClassRule public static DatabaseRule dbr = new DatabaseRule(createPoolBuilder(1)); @Test(expected = SqlException.class) public void shouldThrowExceptionOnInvalidCredentials() throws Exception {
// Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/ResultSet.java // public interface ResultSet extends Iterable<Row> { // // Map<String, PgColumn> getColumnsByName(); // // List<PgColumn> getOrderedColumns(); // // /** // * @param index Row index starting from 0 // * @return Row, never null // */ // Row at(int index); // // /** // * @return Amount of result rows. // */ // int size(); // // /** // * @return Amount of modified rows. // */ // int affectedRows(); // // } // // Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // } // // Path: src/test/java/com/github/pgasync/DatabaseRule.java // static NettyConnectibleBuilder createPoolBuilder(int size) { // String db = getenv("PG_DATABASE"); // String user = getenv("PG_USERNAME"); // String pass = getenv("PG_PASSWORD"); // // if (db == null && user == null && pass == null) { // return new EmbeddedConnectionPoolBuilder().maxConnections(size); // } else { // return new EmbeddedConnectionPoolBuilder() // .database(envOrDefault("PG_DATABASE", "postgres")) // .username(envOrDefault("PG_USERNAME", "postgres")) // .password(envOrDefault("PG_PASSWORD", "postgres")) // .ssl(true) // .maxConnections(size); // } // } // Path: src/test/java/com/github/pgasync/AuthenticationTest.java import com.pgasync.Connectible; import com.pgasync.ResultSet; import com.pgasync.SqlException; import org.junit.ClassRule; import org.junit.Test; import static com.github.pgasync.DatabaseRule.createPoolBuilder; import static org.junit.Assert.assertEquals; package com.github.pgasync; public class AuthenticationTest { @ClassRule public static DatabaseRule dbr = new DatabaseRule(createPoolBuilder(1)); @Test(expected = SqlException.class) public void shouldThrowExceptionOnInvalidCredentials() throws Exception {
Connectible pool = dbr.builder
alaisi/postgres-async-driver
src/test/java/com/github/pgasync/AuthenticationTest.java
// Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/ResultSet.java // public interface ResultSet extends Iterable<Row> { // // Map<String, PgColumn> getColumnsByName(); // // List<PgColumn> getOrderedColumns(); // // /** // * @param index Row index starting from 0 // * @return Row, never null // */ // Row at(int index); // // /** // * @return Amount of result rows. // */ // int size(); // // /** // * @return Amount of modified rows. // */ // int affectedRows(); // // } // // Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // } // // Path: src/test/java/com/github/pgasync/DatabaseRule.java // static NettyConnectibleBuilder createPoolBuilder(int size) { // String db = getenv("PG_DATABASE"); // String user = getenv("PG_USERNAME"); // String pass = getenv("PG_PASSWORD"); // // if (db == null && user == null && pass == null) { // return new EmbeddedConnectionPoolBuilder().maxConnections(size); // } else { // return new EmbeddedConnectionPoolBuilder() // .database(envOrDefault("PG_DATABASE", "postgres")) // .username(envOrDefault("PG_USERNAME", "postgres")) // .password(envOrDefault("PG_PASSWORD", "postgres")) // .ssl(true) // .maxConnections(size); // } // }
import com.pgasync.Connectible; import com.pgasync.ResultSet; import com.pgasync.SqlException; import org.junit.ClassRule; import org.junit.Test; import static com.github.pgasync.DatabaseRule.createPoolBuilder; import static org.junit.Assert.assertEquals;
package com.github.pgasync; public class AuthenticationTest { @ClassRule public static DatabaseRule dbr = new DatabaseRule(createPoolBuilder(1)); @Test(expected = SqlException.class) public void shouldThrowExceptionOnInvalidCredentials() throws Exception { Connectible pool = dbr.builder .password("_invalid_") .pool(); try { pool.completeQuery("SELECT 1").get(); } catch (Exception ex) { SqlException.ifCause(ex, sqlException -> { assertEquals("28P01", sqlException.getCode()); throw sqlException; }, () -> { throw ex; }); } finally { pool.close().get(); } } @Test public void shouldGetResultOnValidCredentials() throws Exception { Connectible pool = dbr.builder .password("async-pg") .pool(); try {
// Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/ResultSet.java // public interface ResultSet extends Iterable<Row> { // // Map<String, PgColumn> getColumnsByName(); // // List<PgColumn> getOrderedColumns(); // // /** // * @param index Row index starting from 0 // * @return Row, never null // */ // Row at(int index); // // /** // * @return Amount of result rows. // */ // int size(); // // /** // * @return Amount of modified rows. // */ // int affectedRows(); // // } // // Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // } // // Path: src/test/java/com/github/pgasync/DatabaseRule.java // static NettyConnectibleBuilder createPoolBuilder(int size) { // String db = getenv("PG_DATABASE"); // String user = getenv("PG_USERNAME"); // String pass = getenv("PG_PASSWORD"); // // if (db == null && user == null && pass == null) { // return new EmbeddedConnectionPoolBuilder().maxConnections(size); // } else { // return new EmbeddedConnectionPoolBuilder() // .database(envOrDefault("PG_DATABASE", "postgres")) // .username(envOrDefault("PG_USERNAME", "postgres")) // .password(envOrDefault("PG_PASSWORD", "postgres")) // .ssl(true) // .maxConnections(size); // } // } // Path: src/test/java/com/github/pgasync/AuthenticationTest.java import com.pgasync.Connectible; import com.pgasync.ResultSet; import com.pgasync.SqlException; import org.junit.ClassRule; import org.junit.Test; import static com.github.pgasync.DatabaseRule.createPoolBuilder; import static org.junit.Assert.assertEquals; package com.github.pgasync; public class AuthenticationTest { @ClassRule public static DatabaseRule dbr = new DatabaseRule(createPoolBuilder(1)); @Test(expected = SqlException.class) public void shouldThrowExceptionOnInvalidCredentials() throws Exception { Connectible pool = dbr.builder .password("_invalid_") .pool(); try { pool.completeQuery("SELECT 1").get(); } catch (Exception ex) { SqlException.ifCause(ex, sqlException -> { assertEquals("28P01", sqlException.getCode()); throw sqlException; }, () -> { throw ex; }); } finally { pool.close().get(); } } @Test public void shouldGetResultOnValidCredentials() throws Exception { Connectible pool = dbr.builder .password("async-pg") .pool(); try {
ResultSet rs = pool.completeQuery("SELECT 1").get();
alaisi/postgres-async-driver
src/main/java/com/pgasync/PreparedStatement.java
// Path: src/main/java/com/github/pgasync/PgColumn.java // public class PgColumn { // // private final int index; // private final String name; // private final Oid type; // // public PgColumn(int index, String name, Oid type) { // this.index = index; // this.name = name; // this.type = type; // } // // public Oid getType() { // return type; // } // // public String getName() { // return name; // } // // public int at() { // return index; // } // } // // Path: src/main/java/com/github/pgasync/message/backend/DataRow.java // public class DataRow implements Message { // // private final byte[][] values; // // public DataRow(byte[][] values) { // this.values = values; // } // // public byte[] getValue(int i) { // return values[i]; // } // }
import com.github.pgasync.PgColumn; import com.github.pgasync.message.backend.DataRow; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.function.BiConsumer; import java.util.function.Consumer;
package com.pgasync; /** * Prepared statement in terms of Postgres. * It lives during database session. It should be reused multiple times and it should be closed after using. * Doesn't support function call feature because of its deprecation. * @see <a href="https://www.postgresql.org/docs/11/protocol-flow.html#id-1.10.5.7.6"/>. * * Concurrent using of implementations is impossible. * {@link PreparedStatement} implementations are never thread-safe. * They are designed to be used in context of single {@link CompletableFuture} completion at a time. */ public interface PreparedStatement { /** * Fetches the whole row set and returns a {@link CompletableFuture} completed with an instance of {@link ResultSet}. * This future may be completed with an error. Use this method if you are sure, that all data, returned by the query can be placed into memory. * * @param params Array of query parameters values. * @return An instance of {@link ResultSet} with data. */ CompletableFuture<ResultSet> query(Object... params); /** * Fetches data rows from Postgres one by one. Use this method when you are unsure, that all data, returned by the query can be placed into memory. * * @param onColumns {@link Consumer} of parameters by name map. Gets called when bind/describe chain succeeded. * @param processor {@link Consumer} of single data row. Performs transformation from {@link DataRow} message * to {@link Row} implementation instance. * @param params Array of query parameters values. * @return CompletableFuture that completes when the whole process ends or when an error occurs. Future's value will indicate the number of rows affected by the query. */
// Path: src/main/java/com/github/pgasync/PgColumn.java // public class PgColumn { // // private final int index; // private final String name; // private final Oid type; // // public PgColumn(int index, String name, Oid type) { // this.index = index; // this.name = name; // this.type = type; // } // // public Oid getType() { // return type; // } // // public String getName() { // return name; // } // // public int at() { // return index; // } // } // // Path: src/main/java/com/github/pgasync/message/backend/DataRow.java // public class DataRow implements Message { // // private final byte[][] values; // // public DataRow(byte[][] values) { // this.values = values; // } // // public byte[] getValue(int i) { // return values[i]; // } // } // Path: src/main/java/com/pgasync/PreparedStatement.java import com.github.pgasync.PgColumn; import com.github.pgasync.message.backend.DataRow; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.function.BiConsumer; import java.util.function.Consumer; package com.pgasync; /** * Prepared statement in terms of Postgres. * It lives during database session. It should be reused multiple times and it should be closed after using. * Doesn't support function call feature because of its deprecation. * @see <a href="https://www.postgresql.org/docs/11/protocol-flow.html#id-1.10.5.7.6"/>. * * Concurrent using of implementations is impossible. * {@link PreparedStatement} implementations are never thread-safe. * They are designed to be used in context of single {@link CompletableFuture} completion at a time. */ public interface PreparedStatement { /** * Fetches the whole row set and returns a {@link CompletableFuture} completed with an instance of {@link ResultSet}. * This future may be completed with an error. Use this method if you are sure, that all data, returned by the query can be placed into memory. * * @param params Array of query parameters values. * @return An instance of {@link ResultSet} with data. */ CompletableFuture<ResultSet> query(Object... params); /** * Fetches data rows from Postgres one by one. Use this method when you are unsure, that all data, returned by the query can be placed into memory. * * @param onColumns {@link Consumer} of parameters by name map. Gets called when bind/describe chain succeeded. * @param processor {@link Consumer} of single data row. Performs transformation from {@link DataRow} message * to {@link Row} implementation instance. * @param params Array of query parameters values. * @return CompletableFuture that completes when the whole process ends or when an error occurs. Future's value will indicate the number of rows affected by the query. */
CompletableFuture<Integer> fetch(BiConsumer<Map<String, PgColumn>, PgColumn[]> onColumns, Consumer<Row> processor, Object... params);
alaisi/postgres-async-driver
src/main/java/com/github/pgasync/conversion/StringConversions.java
// Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // } // // Path: src/main/java/com/github/pgasync/Oid.java // public enum Oid { // // UNSPECIFIED(0), // INT2(21), // INT2_ARRAY(1005), // INT4(23), // INT4_ARRAY(1007), // INT8(20), // INT8_ARRAY(1016), // TEXT(25), // TEXT_ARRAY(1009), // NUMERIC(1700), // NUMERIC_ARRAY(1231), // FLOAT4(700), // FLOAT4_ARRAY(1021), // FLOAT8(701), // FLOAT8_ARRAY(1022), // BOOL(16), // BOOL_ARRAY(1000), // DATE(1082), // DATE_ARRAY(1182), // TIME(1083), // TIME_ARRAY(1183), // TIMETZ(1266), // TIMETZ_ARRAY(1270), // TIMESTAMP(1114), // TIMESTAMP_ARRAY(1115), // TIMESTAMPTZ(1184), // TIMESTAMPTZ_ARRAY(1185), // BYTEA(17), // BYTEA_ARRAY(1001), // VARCHAR(1043), // VARCHAR_ARRAY(1015), // OID(26), // OID_ARRAY(1028), // BPCHAR(1042), // BPCHAR_ARRAY(1014), // MONEY(790), // MONEY_ARRAY(791), // NAME(19), // NAME_ARRAY(1003), // BIT(1560), // BIT_ARRAY(1561), // VOID(2278), // INTERVAL(1186), // INTERVAL_ARRAY(1187), // CHAR(18), // CHAR_ARRAY(1002), // VARBIT(1562), // VARBIT_ARRAY(1563), // UUID(2950), // UUID_ARRAY(2951), // XML(142), // XML_ARRAY(143), // POINT(600), // BOX(603), // // Added // JSON(114), // JSONB(3802), // HSTORE(33670) // ; // // final int id; // // Oid(int id) { // this.id = id; // } // // public int getId() { // return id; // } // // public static Oid valueOfId(int id) { // for (Oid oid : values()) { // if (oid.id == id) { // return oid; // } // } // return Oid.UNSPECIFIED; // } // }
import com.pgasync.SqlException; import com.github.pgasync.Oid;
package com.github.pgasync.conversion; /** * @author Antti Laisi */ class StringConversions { static String toString(Oid oid, String value) { switch (oid) { case UNSPECIFIED: // fallthrough case TEXT: // fallthrough case CHAR: // fallthrough case BPCHAR: // fallthrough case UUID: // fallthrough case VARCHAR: return value; default:
// Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // } // // Path: src/main/java/com/github/pgasync/Oid.java // public enum Oid { // // UNSPECIFIED(0), // INT2(21), // INT2_ARRAY(1005), // INT4(23), // INT4_ARRAY(1007), // INT8(20), // INT8_ARRAY(1016), // TEXT(25), // TEXT_ARRAY(1009), // NUMERIC(1700), // NUMERIC_ARRAY(1231), // FLOAT4(700), // FLOAT4_ARRAY(1021), // FLOAT8(701), // FLOAT8_ARRAY(1022), // BOOL(16), // BOOL_ARRAY(1000), // DATE(1082), // DATE_ARRAY(1182), // TIME(1083), // TIME_ARRAY(1183), // TIMETZ(1266), // TIMETZ_ARRAY(1270), // TIMESTAMP(1114), // TIMESTAMP_ARRAY(1115), // TIMESTAMPTZ(1184), // TIMESTAMPTZ_ARRAY(1185), // BYTEA(17), // BYTEA_ARRAY(1001), // VARCHAR(1043), // VARCHAR_ARRAY(1015), // OID(26), // OID_ARRAY(1028), // BPCHAR(1042), // BPCHAR_ARRAY(1014), // MONEY(790), // MONEY_ARRAY(791), // NAME(19), // NAME_ARRAY(1003), // BIT(1560), // BIT_ARRAY(1561), // VOID(2278), // INTERVAL(1186), // INTERVAL_ARRAY(1187), // CHAR(18), // CHAR_ARRAY(1002), // VARBIT(1562), // VARBIT_ARRAY(1563), // UUID(2950), // UUID_ARRAY(2951), // XML(142), // XML_ARRAY(143), // POINT(600), // BOX(603), // // Added // JSON(114), // JSONB(3802), // HSTORE(33670) // ; // // final int id; // // Oid(int id) { // this.id = id; // } // // public int getId() { // return id; // } // // public static Oid valueOfId(int id) { // for (Oid oid : values()) { // if (oid.id == id) { // return oid; // } // } // return Oid.UNSPECIFIED; // } // } // Path: src/main/java/com/github/pgasync/conversion/StringConversions.java import com.pgasync.SqlException; import com.github.pgasync.Oid; package com.github.pgasync.conversion; /** * @author Antti Laisi */ class StringConversions { static String toString(Oid oid, String value) { switch (oid) { case UNSPECIFIED: // fallthrough case TEXT: // fallthrough case CHAR: // fallthrough case BPCHAR: // fallthrough case UUID: // fallthrough case VARCHAR: return value; default:
throw new SqlException("Unsupported conversion " + oid.name() + " -> String");
alaisi/postgres-async-driver
src/main/java/com/github/pgasync/io/frontend/ExecuteEncoder.java
// Path: src/main/java/com/github/pgasync/io/IO.java // public class IO { // // public static String getCString(ByteBuffer buffer, Charset charset) { // ByteArrayOutputStream readBuffer = new ByteArrayOutputStream(255); // for (int c = buffer.get(); c != 0; c = buffer.get()) { // readBuffer.write(c); // } // return new String(readBuffer.toByteArray(), charset); // } // // public static void putCString(ByteBuffer buffer, String value, Charset charset) { // if (!value.isEmpty()) { // buffer.put(value.getBytes(charset)); // } // buffer.put((byte) 0); // } // // } // // Path: src/main/java/com/github/pgasync/message/frontend/Execute.java // public class Execute implements ExtendedQueryMessage { // // public Execute() { // } // // }
import com.github.pgasync.io.IO; import com.github.pgasync.message.frontend.Execute; import java.nio.ByteBuffer; import java.nio.charset.Charset;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync.io.frontend; /** * See <a href="https://www.postgresql.org/docs/11/protocol-message-formats.html">Postgres message formats</a> * * <pre> * Execute (F) * Byte1('E') * Identifies the message as an Execute command. * * Int32 * Length of message contents in bytes, including self. * * String * The name of the portal to execute (an empty string selects the unnamed portal). * * Int32 * Maximum number of rows to return, if portal contains a query that returns rows (ignored otherwise). Zero denotes “no limit”. * </pre> * * @author Marat Gainullin */ public class ExecuteEncoder extends ExtendedQueryEncoder<Execute> { @Override public Class<Execute> getMessageType() { return Execute.class; } @Override protected byte getMessageId() { return (byte) 'E'; } @Override public void writeBody(Execute msg, ByteBuffer buffer, Charset encoding) {
// Path: src/main/java/com/github/pgasync/io/IO.java // public class IO { // // public static String getCString(ByteBuffer buffer, Charset charset) { // ByteArrayOutputStream readBuffer = new ByteArrayOutputStream(255); // for (int c = buffer.get(); c != 0; c = buffer.get()) { // readBuffer.write(c); // } // return new String(readBuffer.toByteArray(), charset); // } // // public static void putCString(ByteBuffer buffer, String value, Charset charset) { // if (!value.isEmpty()) { // buffer.put(value.getBytes(charset)); // } // buffer.put((byte) 0); // } // // } // // Path: src/main/java/com/github/pgasync/message/frontend/Execute.java // public class Execute implements ExtendedQueryMessage { // // public Execute() { // } // // } // Path: src/main/java/com/github/pgasync/io/frontend/ExecuteEncoder.java import com.github.pgasync.io.IO; import com.github.pgasync.message.frontend.Execute; import java.nio.ByteBuffer; import java.nio.charset.Charset; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync.io.frontend; /** * See <a href="https://www.postgresql.org/docs/11/protocol-message-formats.html">Postgres message formats</a> * * <pre> * Execute (F) * Byte1('E') * Identifies the message as an Execute command. * * Int32 * Length of message contents in bytes, including self. * * String * The name of the portal to execute (an empty string selects the unnamed portal). * * Int32 * Maximum number of rows to return, if portal contains a query that returns rows (ignored otherwise). Zero denotes “no limit”. * </pre> * * @author Marat Gainullin */ public class ExecuteEncoder extends ExtendedQueryEncoder<Execute> { @Override public Class<Execute> getMessageType() { return Execute.class; } @Override protected byte getMessageId() { return (byte) 'E'; } @Override public void writeBody(Execute msg, ByteBuffer buffer, Charset encoding) {
IO.putCString(buffer, "", encoding); // unnamed portal
alaisi/postgres-async-driver
src/main/java/com/github/pgasync/io/frontend/QueryEncoder.java
// Path: src/main/java/com/github/pgasync/message/frontend/Query.java // public class Query implements Message { // // private final String sql; // // public Query(String sql) { // this.sql = sql; // } // // public String getQuery() { // return sql; // } // } // // Path: src/main/java/com/github/pgasync/io/IO.java // public class IO { // // public static String getCString(ByteBuffer buffer, Charset charset) { // ByteArrayOutputStream readBuffer = new ByteArrayOutputStream(255); // for (int c = buffer.get(); c != 0; c = buffer.get()) { // readBuffer.write(c); // } // return new String(readBuffer.toByteArray(), charset); // } // // public static void putCString(ByteBuffer buffer, String value, Charset charset) { // if (!value.isEmpty()) { // buffer.put(value.getBytes(charset)); // } // buffer.put((byte) 0); // } // // }
import com.github.pgasync.message.frontend.Query; import com.github.pgasync.io.IO; import java.nio.ByteBuffer; import java.nio.charset.Charset;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync.io.frontend; /** * See <a href="https://www.postgresql.org/docs/11/protocol-message-formats.html">Postgres message formats</a> * * <pre> * Query (F) * Byte1('Q') * Identifies the message as a simple query. * Int32 * Length of message contents in bytes, including self. * String * The query string itself. * </pre> * * @author Antti Laisi */ public class QueryEncoder extends SkipableEncoder<Query> { @Override public Class<Query> getMessageType() { return Query.class; } @Override protected byte getMessageId() { return (byte) 'Q'; } @Override public void writeBody(Query msg, ByteBuffer buffer, Charset encoding) {
// Path: src/main/java/com/github/pgasync/message/frontend/Query.java // public class Query implements Message { // // private final String sql; // // public Query(String sql) { // this.sql = sql; // } // // public String getQuery() { // return sql; // } // } // // Path: src/main/java/com/github/pgasync/io/IO.java // public class IO { // // public static String getCString(ByteBuffer buffer, Charset charset) { // ByteArrayOutputStream readBuffer = new ByteArrayOutputStream(255); // for (int c = buffer.get(); c != 0; c = buffer.get()) { // readBuffer.write(c); // } // return new String(readBuffer.toByteArray(), charset); // } // // public static void putCString(ByteBuffer buffer, String value, Charset charset) { // if (!value.isEmpty()) { // buffer.put(value.getBytes(charset)); // } // buffer.put((byte) 0); // } // // } // Path: src/main/java/com/github/pgasync/io/frontend/QueryEncoder.java import com.github.pgasync.message.frontend.Query; import com.github.pgasync.io.IO; import java.nio.ByteBuffer; import java.nio.charset.Charset; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync.io.frontend; /** * See <a href="https://www.postgresql.org/docs/11/protocol-message-formats.html">Postgres message formats</a> * * <pre> * Query (F) * Byte1('Q') * Identifies the message as a simple query. * Int32 * Length of message contents in bytes, including self. * String * The query string itself. * </pre> * * @author Antti Laisi */ public class QueryEncoder extends SkipableEncoder<Query> { @Override public Class<Query> getMessageType() { return Query.class; } @Override protected byte getMessageId() { return (byte) 'Q'; } @Override public void writeBody(Query msg, ByteBuffer buffer, Charset encoding) {
IO.putCString(buffer, msg.getQuery(), encoding);
alaisi/postgres-async-driver
src/test/java/com/github/pgasync/PerformanceTest.java
// Path: src/main/java/com/pgasync/Connection.java // public interface Connection extends QueryExecutor { // // CompletableFuture<PreparedStatement> prepareStatement(String sql, Oid... parametersTypes); // // /** // * The typical scenario of using notifications is as follows: // * - {@link #subscribe(String, Consumer)} // * - Some calls of @onNotification callback // * - {@link Listening#unlisten()} // * // * @param channel Channel name to listen to. // * @param onNotification Callback, thar is cinvoked every time notification arrives. // * @return CompletableFuture instance, completed when subscription will be registered at the backend. // */ // CompletableFuture<Listening> subscribe(String channel, Consumer<String> onNotification); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/test/java/com/github/pgasync/DatabaseRule.java // static NettyConnectibleBuilder createPoolBuilder(int size) { // String db = getenv("PG_DATABASE"); // String user = getenv("PG_USERNAME"); // String pass = getenv("PG_PASSWORD"); // // if (db == null && user == null && pass == null) { // return new EmbeddedConnectionPoolBuilder().maxConnections(size); // } else { // return new EmbeddedConnectionPoolBuilder() // .database(envOrDefault("PG_DATABASE", "postgres")) // .username(envOrDefault("PG_USERNAME", "postgres")) // .password(envOrDefault("PG_PASSWORD", "postgres")) // .ssl(true) // .maxConnections(size); // } // }
import static java.lang.System.currentTimeMillis; import static java.lang.System.out; import com.pgasync.Connection; import com.pgasync.Connectible; import org.junit.*; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.util.*; import java.util.concurrent.*; import java.util.function.Function; import java.util.function.IntFunction; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.LongStream; import static com.github.pgasync.DatabaseRule.createPoolBuilder;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync; @RunWith(Parameterized.class) public class PerformanceTest { private static DatabaseRule dbr; static { System.setProperty("io.netty.eventLoopThreads", "1");
// Path: src/main/java/com/pgasync/Connection.java // public interface Connection extends QueryExecutor { // // CompletableFuture<PreparedStatement> prepareStatement(String sql, Oid... parametersTypes); // // /** // * The typical scenario of using notifications is as follows: // * - {@link #subscribe(String, Consumer)} // * - Some calls of @onNotification callback // * - {@link Listening#unlisten()} // * // * @param channel Channel name to listen to. // * @param onNotification Callback, thar is cinvoked every time notification arrives. // * @return CompletableFuture instance, completed when subscription will be registered at the backend. // */ // CompletableFuture<Listening> subscribe(String channel, Consumer<String> onNotification); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/test/java/com/github/pgasync/DatabaseRule.java // static NettyConnectibleBuilder createPoolBuilder(int size) { // String db = getenv("PG_DATABASE"); // String user = getenv("PG_USERNAME"); // String pass = getenv("PG_PASSWORD"); // // if (db == null && user == null && pass == null) { // return new EmbeddedConnectionPoolBuilder().maxConnections(size); // } else { // return new EmbeddedConnectionPoolBuilder() // .database(envOrDefault("PG_DATABASE", "postgres")) // .username(envOrDefault("PG_USERNAME", "postgres")) // .password(envOrDefault("PG_PASSWORD", "postgres")) // .ssl(true) // .maxConnections(size); // } // } // Path: src/test/java/com/github/pgasync/PerformanceTest.java import static java.lang.System.currentTimeMillis; import static java.lang.System.out; import com.pgasync.Connection; import com.pgasync.Connectible; import org.junit.*; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.util.*; import java.util.concurrent.*; import java.util.function.Function; import java.util.function.IntFunction; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.LongStream; import static com.github.pgasync.DatabaseRule.createPoolBuilder; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync; @RunWith(Parameterized.class) public class PerformanceTest { private static DatabaseRule dbr; static { System.setProperty("io.netty.eventLoopThreads", "1");
dbr = new DatabaseRule(createPoolBuilder(1));
alaisi/postgres-async-driver
src/test/java/com/github/pgasync/PerformanceTest.java
// Path: src/main/java/com/pgasync/Connection.java // public interface Connection extends QueryExecutor { // // CompletableFuture<PreparedStatement> prepareStatement(String sql, Oid... parametersTypes); // // /** // * The typical scenario of using notifications is as follows: // * - {@link #subscribe(String, Consumer)} // * - Some calls of @onNotification callback // * - {@link Listening#unlisten()} // * // * @param channel Channel name to listen to. // * @param onNotification Callback, thar is cinvoked every time notification arrives. // * @return CompletableFuture instance, completed when subscription will be registered at the backend. // */ // CompletableFuture<Listening> subscribe(String channel, Consumer<String> onNotification); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/test/java/com/github/pgasync/DatabaseRule.java // static NettyConnectibleBuilder createPoolBuilder(int size) { // String db = getenv("PG_DATABASE"); // String user = getenv("PG_USERNAME"); // String pass = getenv("PG_PASSWORD"); // // if (db == null && user == null && pass == null) { // return new EmbeddedConnectionPoolBuilder().maxConnections(size); // } else { // return new EmbeddedConnectionPoolBuilder() // .database(envOrDefault("PG_DATABASE", "postgres")) // .username(envOrDefault("PG_USERNAME", "postgres")) // .password(envOrDefault("PG_PASSWORD", "postgres")) // .ssl(true) // .maxConnections(size); // } // }
import static java.lang.System.currentTimeMillis; import static java.lang.System.out; import com.pgasync.Connection; import com.pgasync.Connectible; import org.junit.*; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.util.*; import java.util.concurrent.*; import java.util.function.Function; import java.util.function.IntFunction; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.LongStream; import static com.github.pgasync.DatabaseRule.createPoolBuilder;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync; @RunWith(Parameterized.class) public class PerformanceTest { private static DatabaseRule dbr; static { System.setProperty("io.netty.eventLoopThreads", "1"); dbr = new DatabaseRule(createPoolBuilder(1)); } private static final String SELECT_42 = "select 42"; @Parameters(name = "{index}: maxConnections={0}, threads={1}") public static Iterable<Object[]> data() { List<Object[]> testData = new ArrayList<>(); for (int poolSize = 1; poolSize <= 8; poolSize *= 2) { for (int threads = 1; threads <= 8; threads *= 2) { testData.add(new Object[]{poolSize, threads}); } } return testData; } private static final int batchSize = 1000; private static final int repeats = 5; private static SortedMap<Integer, SortedMap<Integer, Long>> simpleQueryResults = new TreeMap<>(); private static SortedMap<Integer, SortedMap<Integer, Long>> preparedStatementResults = new TreeMap<>(); private final int poolSize; private final int numThreads;
// Path: src/main/java/com/pgasync/Connection.java // public interface Connection extends QueryExecutor { // // CompletableFuture<PreparedStatement> prepareStatement(String sql, Oid... parametersTypes); // // /** // * The typical scenario of using notifications is as follows: // * - {@link #subscribe(String, Consumer)} // * - Some calls of @onNotification callback // * - {@link Listening#unlisten()} // * // * @param channel Channel name to listen to. // * @param onNotification Callback, thar is cinvoked every time notification arrives. // * @return CompletableFuture instance, completed when subscription will be registered at the backend. // */ // CompletableFuture<Listening> subscribe(String channel, Consumer<String> onNotification); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/test/java/com/github/pgasync/DatabaseRule.java // static NettyConnectibleBuilder createPoolBuilder(int size) { // String db = getenv("PG_DATABASE"); // String user = getenv("PG_USERNAME"); // String pass = getenv("PG_PASSWORD"); // // if (db == null && user == null && pass == null) { // return new EmbeddedConnectionPoolBuilder().maxConnections(size); // } else { // return new EmbeddedConnectionPoolBuilder() // .database(envOrDefault("PG_DATABASE", "postgres")) // .username(envOrDefault("PG_USERNAME", "postgres")) // .password(envOrDefault("PG_PASSWORD", "postgres")) // .ssl(true) // .maxConnections(size); // } // } // Path: src/test/java/com/github/pgasync/PerformanceTest.java import static java.lang.System.currentTimeMillis; import static java.lang.System.out; import com.pgasync.Connection; import com.pgasync.Connectible; import org.junit.*; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.util.*; import java.util.concurrent.*; import java.util.function.Function; import java.util.function.IntFunction; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.LongStream; import static com.github.pgasync.DatabaseRule.createPoolBuilder; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync; @RunWith(Parameterized.class) public class PerformanceTest { private static DatabaseRule dbr; static { System.setProperty("io.netty.eventLoopThreads", "1"); dbr = new DatabaseRule(createPoolBuilder(1)); } private static final String SELECT_42 = "select 42"; @Parameters(name = "{index}: maxConnections={0}, threads={1}") public static Iterable<Object[]> data() { List<Object[]> testData = new ArrayList<>(); for (int poolSize = 1; poolSize <= 8; poolSize *= 2) { for (int threads = 1; threads <= 8; threads *= 2) { testData.add(new Object[]{poolSize, threads}); } } return testData; } private static final int batchSize = 1000; private static final int repeats = 5; private static SortedMap<Integer, SortedMap<Integer, Long>> simpleQueryResults = new TreeMap<>(); private static SortedMap<Integer, SortedMap<Integer, Long>> preparedStatementResults = new TreeMap<>(); private final int poolSize; private final int numThreads;
private Connectible pool;
alaisi/postgres-async-driver
src/test/java/com/github/pgasync/PerformanceTest.java
// Path: src/main/java/com/pgasync/Connection.java // public interface Connection extends QueryExecutor { // // CompletableFuture<PreparedStatement> prepareStatement(String sql, Oid... parametersTypes); // // /** // * The typical scenario of using notifications is as follows: // * - {@link #subscribe(String, Consumer)} // * - Some calls of @onNotification callback // * - {@link Listening#unlisten()} // * // * @param channel Channel name to listen to. // * @param onNotification Callback, thar is cinvoked every time notification arrives. // * @return CompletableFuture instance, completed when subscription will be registered at the backend. // */ // CompletableFuture<Listening> subscribe(String channel, Consumer<String> onNotification); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/test/java/com/github/pgasync/DatabaseRule.java // static NettyConnectibleBuilder createPoolBuilder(int size) { // String db = getenv("PG_DATABASE"); // String user = getenv("PG_USERNAME"); // String pass = getenv("PG_PASSWORD"); // // if (db == null && user == null && pass == null) { // return new EmbeddedConnectionPoolBuilder().maxConnections(size); // } else { // return new EmbeddedConnectionPoolBuilder() // .database(envOrDefault("PG_DATABASE", "postgres")) // .username(envOrDefault("PG_USERNAME", "postgres")) // .password(envOrDefault("PG_PASSWORD", "postgres")) // .ssl(true) // .maxConnections(size); // } // }
import static java.lang.System.currentTimeMillis; import static java.lang.System.out; import com.pgasync.Connection; import com.pgasync.Connectible; import org.junit.*; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.util.*; import java.util.concurrent.*; import java.util.function.Function; import java.util.function.IntFunction; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.LongStream; import static com.github.pgasync.DatabaseRule.createPoolBuilder;
List<Object[]> testData = new ArrayList<>(); for (int poolSize = 1; poolSize <= 8; poolSize *= 2) { for (int threads = 1; threads <= 8; threads *= 2) { testData.add(new Object[]{poolSize, threads}); } } return testData; } private static final int batchSize = 1000; private static final int repeats = 5; private static SortedMap<Integer, SortedMap<Integer, Long>> simpleQueryResults = new TreeMap<>(); private static SortedMap<Integer, SortedMap<Integer, Long>> preparedStatementResults = new TreeMap<>(); private final int poolSize; private final int numThreads; private Connectible pool; public PerformanceTest(int poolSize, int numThreads) { this.poolSize = poolSize; this.numThreads = numThreads; } @Before public void setup() { pool = dbr.builder .password("async-pg") .maxConnections(poolSize) .pool(Executors.newFixedThreadPool(numThreads));
// Path: src/main/java/com/pgasync/Connection.java // public interface Connection extends QueryExecutor { // // CompletableFuture<PreparedStatement> prepareStatement(String sql, Oid... parametersTypes); // // /** // * The typical scenario of using notifications is as follows: // * - {@link #subscribe(String, Consumer)} // * - Some calls of @onNotification callback // * - {@link Listening#unlisten()} // * // * @param channel Channel name to listen to. // * @param onNotification Callback, thar is cinvoked every time notification arrives. // * @return CompletableFuture instance, completed when subscription will be registered at the backend. // */ // CompletableFuture<Listening> subscribe(String channel, Consumer<String> onNotification); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/test/java/com/github/pgasync/DatabaseRule.java // static NettyConnectibleBuilder createPoolBuilder(int size) { // String db = getenv("PG_DATABASE"); // String user = getenv("PG_USERNAME"); // String pass = getenv("PG_PASSWORD"); // // if (db == null && user == null && pass == null) { // return new EmbeddedConnectionPoolBuilder().maxConnections(size); // } else { // return new EmbeddedConnectionPoolBuilder() // .database(envOrDefault("PG_DATABASE", "postgres")) // .username(envOrDefault("PG_USERNAME", "postgres")) // .password(envOrDefault("PG_PASSWORD", "postgres")) // .ssl(true) // .maxConnections(size); // } // } // Path: src/test/java/com/github/pgasync/PerformanceTest.java import static java.lang.System.currentTimeMillis; import static java.lang.System.out; import com.pgasync.Connection; import com.pgasync.Connectible; import org.junit.*; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.util.*; import java.util.concurrent.*; import java.util.function.Function; import java.util.function.IntFunction; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.LongStream; import static com.github.pgasync.DatabaseRule.createPoolBuilder; List<Object[]> testData = new ArrayList<>(); for (int poolSize = 1; poolSize <= 8; poolSize *= 2) { for (int threads = 1; threads <= 8; threads *= 2) { testData.add(new Object[]{poolSize, threads}); } } return testData; } private static final int batchSize = 1000; private static final int repeats = 5; private static SortedMap<Integer, SortedMap<Integer, Long>> simpleQueryResults = new TreeMap<>(); private static SortedMap<Integer, SortedMap<Integer, Long>> preparedStatementResults = new TreeMap<>(); private final int poolSize; private final int numThreads; private Connectible pool; public PerformanceTest(int poolSize, int numThreads) { this.poolSize = poolSize; this.numThreads = numThreads; } @Before public void setup() { pool = dbr.builder .password("async-pg") .maxConnections(poolSize) .pool(Executors.newFixedThreadPool(numThreads));
List<Connection> connections = IntStream.range(0, poolSize)
alaisi/postgres-async-driver
src/main/java/com/github/pgasync/message/backend/RowDescription.java
// Path: src/main/java/com/github/pgasync/Oid.java // public enum Oid { // // UNSPECIFIED(0), // INT2(21), // INT2_ARRAY(1005), // INT4(23), // INT4_ARRAY(1007), // INT8(20), // INT8_ARRAY(1016), // TEXT(25), // TEXT_ARRAY(1009), // NUMERIC(1700), // NUMERIC_ARRAY(1231), // FLOAT4(700), // FLOAT4_ARRAY(1021), // FLOAT8(701), // FLOAT8_ARRAY(1022), // BOOL(16), // BOOL_ARRAY(1000), // DATE(1082), // DATE_ARRAY(1182), // TIME(1083), // TIME_ARRAY(1183), // TIMETZ(1266), // TIMETZ_ARRAY(1270), // TIMESTAMP(1114), // TIMESTAMP_ARRAY(1115), // TIMESTAMPTZ(1184), // TIMESTAMPTZ_ARRAY(1185), // BYTEA(17), // BYTEA_ARRAY(1001), // VARCHAR(1043), // VARCHAR_ARRAY(1015), // OID(26), // OID_ARRAY(1028), // BPCHAR(1042), // BPCHAR_ARRAY(1014), // MONEY(790), // MONEY_ARRAY(791), // NAME(19), // NAME_ARRAY(1003), // BIT(1560), // BIT_ARRAY(1561), // VOID(2278), // INTERVAL(1186), // INTERVAL_ARRAY(1187), // CHAR(18), // CHAR_ARRAY(1002), // VARBIT(1562), // VARBIT_ARRAY(1563), // UUID(2950), // UUID_ARRAY(2951), // XML(142), // XML_ARRAY(143), // POINT(600), // BOX(603), // // Added // JSON(114), // JSONB(3802), // HSTORE(33670) // ; // // final int id; // // Oid(int id) { // this.id = id; // } // // public int getId() { // return id; // } // // public static Oid valueOfId(int id) { // for (Oid oid : values()) { // if (oid.id == id) { // return oid; // } // } // return Oid.UNSPECIFIED; // } // } // // Path: src/main/java/com/github/pgasync/message/Message.java // public interface Message { // // }
import com.github.pgasync.Oid; import com.github.pgasync.message.Message;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync.message.backend; /** * @author Antti Laisi */ public class RowDescription implements Message { public static class ColumnDescription { final String name;
// Path: src/main/java/com/github/pgasync/Oid.java // public enum Oid { // // UNSPECIFIED(0), // INT2(21), // INT2_ARRAY(1005), // INT4(23), // INT4_ARRAY(1007), // INT8(20), // INT8_ARRAY(1016), // TEXT(25), // TEXT_ARRAY(1009), // NUMERIC(1700), // NUMERIC_ARRAY(1231), // FLOAT4(700), // FLOAT4_ARRAY(1021), // FLOAT8(701), // FLOAT8_ARRAY(1022), // BOOL(16), // BOOL_ARRAY(1000), // DATE(1082), // DATE_ARRAY(1182), // TIME(1083), // TIME_ARRAY(1183), // TIMETZ(1266), // TIMETZ_ARRAY(1270), // TIMESTAMP(1114), // TIMESTAMP_ARRAY(1115), // TIMESTAMPTZ(1184), // TIMESTAMPTZ_ARRAY(1185), // BYTEA(17), // BYTEA_ARRAY(1001), // VARCHAR(1043), // VARCHAR_ARRAY(1015), // OID(26), // OID_ARRAY(1028), // BPCHAR(1042), // BPCHAR_ARRAY(1014), // MONEY(790), // MONEY_ARRAY(791), // NAME(19), // NAME_ARRAY(1003), // BIT(1560), // BIT_ARRAY(1561), // VOID(2278), // INTERVAL(1186), // INTERVAL_ARRAY(1187), // CHAR(18), // CHAR_ARRAY(1002), // VARBIT(1562), // VARBIT_ARRAY(1563), // UUID(2950), // UUID_ARRAY(2951), // XML(142), // XML_ARRAY(143), // POINT(600), // BOX(603), // // Added // JSON(114), // JSONB(3802), // HSTORE(33670) // ; // // final int id; // // Oid(int id) { // this.id = id; // } // // public int getId() { // return id; // } // // public static Oid valueOfId(int id) { // for (Oid oid : values()) { // if (oid.id == id) { // return oid; // } // } // return Oid.UNSPECIFIED; // } // } // // Path: src/main/java/com/github/pgasync/message/Message.java // public interface Message { // // } // Path: src/main/java/com/github/pgasync/message/backend/RowDescription.java import com.github.pgasync.Oid; import com.github.pgasync.message.Message; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync.message.backend; /** * @author Antti Laisi */ public class RowDescription implements Message { public static class ColumnDescription { final String name;
final Oid type;
alaisi/postgres-async-driver
src/test/java/com/github/pgasync/TransactionTest.java
// Path: src/main/java/com/pgasync/ResultSet.java // public interface ResultSet extends Iterable<Row> { // // Map<String, PgColumn> getColumnsByName(); // // List<PgColumn> getOrderedColumns(); // // /** // * @param index Row index starting from 0 // * @return Row, never null // */ // Row at(int index); // // /** // * @return Amount of result rows. // */ // int size(); // // /** // * @return Amount of modified rows. // */ // int affectedRows(); // // } // // Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // }
import com.pgasync.ResultSet; import com.pgasync.SqlException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.function.Function; import static org.junit.Assert.assertEquals;
.get(5, TimeUnit.SECONDS); assertEquals(35L, id); } @Test public void shouldRollbackTransaction() throws Exception { dbr.pool().begin() .thenApply(transaction -> transaction.completeQuery("INSERT INTO TX_TEST(ID) VALUES(9)") .thenApply(result -> { Assert.assertEquals(1, result.affectedRows()); return transaction.rollback(); }) .thenCompose(Function.identity()) .handle((v, th) -> transaction.getConnection().close() .thenAccept(_v -> { if (th != null) { throw new RuntimeException(th); } }) ) .thenCompose(Function.identity()) ) .thenCompose(Function.identity()) .get(5, TimeUnit.SECONDS); Assert.assertEquals(0L, dbr.query("SELECT ID FROM TX_TEST WHERE ID = 9").size()); }
// Path: src/main/java/com/pgasync/ResultSet.java // public interface ResultSet extends Iterable<Row> { // // Map<String, PgColumn> getColumnsByName(); // // List<PgColumn> getOrderedColumns(); // // /** // * @param index Row index starting from 0 // * @return Row, never null // */ // Row at(int index); // // /** // * @return Amount of result rows. // */ // int size(); // // /** // * @return Amount of modified rows. // */ // int affectedRows(); // // } // // Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // } // Path: src/test/java/com/github/pgasync/TransactionTest.java import com.pgasync.ResultSet; import com.pgasync.SqlException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.function.Function; import static org.junit.Assert.assertEquals; .get(5, TimeUnit.SECONDS); assertEquals(35L, id); } @Test public void shouldRollbackTransaction() throws Exception { dbr.pool().begin() .thenApply(transaction -> transaction.completeQuery("INSERT INTO TX_TEST(ID) VALUES(9)") .thenApply(result -> { Assert.assertEquals(1, result.affectedRows()); return transaction.rollback(); }) .thenCompose(Function.identity()) .handle((v, th) -> transaction.getConnection().close() .thenAccept(_v -> { if (th != null) { throw new RuntimeException(th); } }) ) .thenCompose(Function.identity()) ) .thenCompose(Function.identity()) .get(5, TimeUnit.SECONDS); Assert.assertEquals(0L, dbr.query("SELECT ID FROM TX_TEST WHERE ID = 9").size()); }
@Test(expected = SqlException.class)
alaisi/postgres-async-driver
src/test/java/com/github/pgasync/TransactionTest.java
// Path: src/main/java/com/pgasync/ResultSet.java // public interface ResultSet extends Iterable<Row> { // // Map<String, PgColumn> getColumnsByName(); // // List<PgColumn> getOrderedColumns(); // // /** // * @param index Row index starting from 0 // * @return Row, never null // */ // Row at(int index); // // /** // * @return Amount of result rows. // */ // int size(); // // /** // * @return Amount of modified rows. // */ // int affectedRows(); // // } // // Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // }
import com.pgasync.ResultSet; import com.pgasync.SqlException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.function.Function; import static org.junit.Assert.assertEquals;
.thenCompose(Function.identity()) .handle((v, th) -> transaction.getConnection().close() .thenAccept(_v -> { if (th != null) { throw new RuntimeException(th); } }) ) .thenCompose(Function.identity()) ) .thenCompose(Function.identity()) .get(5, TimeUnit.SECONDS); } catch (Exception ex) { SqlException.ifCause(ex, sqlException -> { Assert.assertEquals(0, dbr.query("SELECT ID FROM TX_TEST WHERE ID = 11").size()); throw sqlException; }, () -> { throw ex; }); } } @Test public void shouldRollbackTransactionAfterBackendError() throws Exception { dbr.pool().begin() .thenApply(transaction -> transaction.completeQuery("INSERT INTO TX_TEST(ID) VALUES(22)") .thenApply(result -> { Assert.assertEquals(1, result.affectedRows()); return transaction.completeQuery("INSERT INTO TX_TEST(ID) VALUES(22)")
// Path: src/main/java/com/pgasync/ResultSet.java // public interface ResultSet extends Iterable<Row> { // // Map<String, PgColumn> getColumnsByName(); // // List<PgColumn> getOrderedColumns(); // // /** // * @param index Row index starting from 0 // * @return Row, never null // */ // Row at(int index); // // /** // * @return Amount of result rows. // */ // int size(); // // /** // * @return Amount of modified rows. // */ // int affectedRows(); // // } // // Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // } // Path: src/test/java/com/github/pgasync/TransactionTest.java import com.pgasync.ResultSet; import com.pgasync.SqlException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.function.Function; import static org.junit.Assert.assertEquals; .thenCompose(Function.identity()) .handle((v, th) -> transaction.getConnection().close() .thenAccept(_v -> { if (th != null) { throw new RuntimeException(th); } }) ) .thenCompose(Function.identity()) ) .thenCompose(Function.identity()) .get(5, TimeUnit.SECONDS); } catch (Exception ex) { SqlException.ifCause(ex, sqlException -> { Assert.assertEquals(0, dbr.query("SELECT ID FROM TX_TEST WHERE ID = 11").size()); throw sqlException; }, () -> { throw ex; }); } } @Test public void shouldRollbackTransactionAfterBackendError() throws Exception { dbr.pool().begin() .thenApply(transaction -> transaction.completeQuery("INSERT INTO TX_TEST(ID) VALUES(22)") .thenApply(result -> { Assert.assertEquals(1, result.affectedRows()); return transaction.completeQuery("INSERT INTO TX_TEST(ID) VALUES(22)")
.thenApply(rs -> CompletableFuture.<ResultSet>failedFuture(new IllegalStateException("The transaction should fail")))
alaisi/postgres-async-driver
src/main/java/com/github/pgasync/conversion/DataConverter.java
// Path: src/main/java/com/pgasync/Converter.java // public interface Converter<T> { // // /** // * @return Class to convert // */ // Class<T> type(); // // /** // * @param o Object to convert, never null // * @return data in backend format // */ // String from(T o); // // /** // * @param oid Value oid // * @param value Value in backend format, never null // * @return Converted object, never null // */ // T to(Oid oid, String value); // // } // // Path: src/main/java/com/github/pgasync/Oid.java // public enum Oid { // // UNSPECIFIED(0), // INT2(21), // INT2_ARRAY(1005), // INT4(23), // INT4_ARRAY(1007), // INT8(20), // INT8_ARRAY(1016), // TEXT(25), // TEXT_ARRAY(1009), // NUMERIC(1700), // NUMERIC_ARRAY(1231), // FLOAT4(700), // FLOAT4_ARRAY(1021), // FLOAT8(701), // FLOAT8_ARRAY(1022), // BOOL(16), // BOOL_ARRAY(1000), // DATE(1082), // DATE_ARRAY(1182), // TIME(1083), // TIME_ARRAY(1183), // TIMETZ(1266), // TIMETZ_ARRAY(1270), // TIMESTAMP(1114), // TIMESTAMP_ARRAY(1115), // TIMESTAMPTZ(1184), // TIMESTAMPTZ_ARRAY(1185), // BYTEA(17), // BYTEA_ARRAY(1001), // VARCHAR(1043), // VARCHAR_ARRAY(1015), // OID(26), // OID_ARRAY(1028), // BPCHAR(1042), // BPCHAR_ARRAY(1014), // MONEY(790), // MONEY_ARRAY(791), // NAME(19), // NAME_ARRAY(1003), // BIT(1560), // BIT_ARRAY(1561), // VOID(2278), // INTERVAL(1186), // INTERVAL_ARRAY(1187), // CHAR(18), // CHAR_ARRAY(1002), // VARBIT(1562), // VARBIT_ARRAY(1563), // UUID(2950), // UUID_ARRAY(2951), // XML(142), // XML_ARRAY(143), // POINT(600), // BOX(603), // // Added // JSON(114), // JSONB(3802), // HSTORE(33670) // ; // // final int id; // // Oid(int id) { // this.id = id; // } // // public int getId() { // return id; // } // // public static Oid valueOfId(int id) { // for (Oid oid : values()) { // if (oid.id == id) { // return oid; // } // } // return Oid.UNSPECIFIED; // } // }
import com.pgasync.Converter; import com.github.pgasync.Oid; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.charset.Charset; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; import java.time.Instant; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.OffsetDateTime; import java.time.OffsetTime; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import static javax.xml.bind.DatatypeConverter.parseHexBinary;
package com.github.pgasync.conversion; /** * @author Antti Laisi */ public class DataConverter { private final Map<Class<?>, Converter<?>> typeToConverter; private final Charset encoding; public DataConverter(List<Converter<?>> converters, Charset encoding) { this.typeToConverter = converters.stream() .collect(Collectors.toMap(Converter::type, Function.identity())); this.encoding = encoding; } public DataConverter(Charset encoding) { this(List.of(), encoding); }
// Path: src/main/java/com/pgasync/Converter.java // public interface Converter<T> { // // /** // * @return Class to convert // */ // Class<T> type(); // // /** // * @param o Object to convert, never null // * @return data in backend format // */ // String from(T o); // // /** // * @param oid Value oid // * @param value Value in backend format, never null // * @return Converted object, never null // */ // T to(Oid oid, String value); // // } // // Path: src/main/java/com/github/pgasync/Oid.java // public enum Oid { // // UNSPECIFIED(0), // INT2(21), // INT2_ARRAY(1005), // INT4(23), // INT4_ARRAY(1007), // INT8(20), // INT8_ARRAY(1016), // TEXT(25), // TEXT_ARRAY(1009), // NUMERIC(1700), // NUMERIC_ARRAY(1231), // FLOAT4(700), // FLOAT4_ARRAY(1021), // FLOAT8(701), // FLOAT8_ARRAY(1022), // BOOL(16), // BOOL_ARRAY(1000), // DATE(1082), // DATE_ARRAY(1182), // TIME(1083), // TIME_ARRAY(1183), // TIMETZ(1266), // TIMETZ_ARRAY(1270), // TIMESTAMP(1114), // TIMESTAMP_ARRAY(1115), // TIMESTAMPTZ(1184), // TIMESTAMPTZ_ARRAY(1185), // BYTEA(17), // BYTEA_ARRAY(1001), // VARCHAR(1043), // VARCHAR_ARRAY(1015), // OID(26), // OID_ARRAY(1028), // BPCHAR(1042), // BPCHAR_ARRAY(1014), // MONEY(790), // MONEY_ARRAY(791), // NAME(19), // NAME_ARRAY(1003), // BIT(1560), // BIT_ARRAY(1561), // VOID(2278), // INTERVAL(1186), // INTERVAL_ARRAY(1187), // CHAR(18), // CHAR_ARRAY(1002), // VARBIT(1562), // VARBIT_ARRAY(1563), // UUID(2950), // UUID_ARRAY(2951), // XML(142), // XML_ARRAY(143), // POINT(600), // BOX(603), // // Added // JSON(114), // JSONB(3802), // HSTORE(33670) // ; // // final int id; // // Oid(int id) { // this.id = id; // } // // public int getId() { // return id; // } // // public static Oid valueOfId(int id) { // for (Oid oid : values()) { // if (oid.id == id) { // return oid; // } // } // return Oid.UNSPECIFIED; // } // } // Path: src/main/java/com/github/pgasync/conversion/DataConverter.java import com.pgasync.Converter; import com.github.pgasync.Oid; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.charset.Charset; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; import java.time.Instant; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.OffsetDateTime; import java.time.OffsetTime; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import static javax.xml.bind.DatatypeConverter.parseHexBinary; package com.github.pgasync.conversion; /** * @author Antti Laisi */ public class DataConverter { private final Map<Class<?>, Converter<?>> typeToConverter; private final Charset encoding; public DataConverter(List<Converter<?>> converters, Charset encoding) { this.typeToConverter = converters.stream() .collect(Collectors.toMap(Converter::type, Function.identity())); this.encoding = encoding; } public DataConverter(Charset encoding) { this(List.of(), encoding); }
public String toString(Oid oid, byte[] value) {
alaisi/postgres-async-driver
src/test/java/com/github/pgasync/PipelineTest.java
// Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/Connection.java // public interface Connection extends QueryExecutor { // // CompletableFuture<PreparedStatement> prepareStatement(String sql, Oid... parametersTypes); // // /** // * The typical scenario of using notifications is as follows: // * - {@link #subscribe(String, Consumer)} // * - Some calls of @onNotification callback // * - {@link Listening#unlisten()} // * // * @param channel Channel name to listen to. // * @param onNotification Callback, thar is cinvoked every time notification arrives. // * @return CompletableFuture instance, completed when subscription will be registered at the backend. // */ // CompletableFuture<Listening> subscribe(String channel, Consumer<String> onNotification); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // }
import static java.util.concurrent.TimeUnit.SECONDS; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.assertThat; import com.pgasync.Connectible; import com.pgasync.Connection; import com.pgasync.SqlException; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import java.util.Deque; import java.util.concurrent.CompletableFuture; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.SynchronousQueue; import java.util.stream.IntStream; import static java.lang.System.currentTimeMillis; import static java.util.concurrent.TimeUnit.MILLISECONDS;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync; /** * Tests for statements pipelining. * * @author Mikko Tiihonen * @author Marat Gainullin */ public class PipelineTest { @ClassRule public static DatabaseRule dbr = new DatabaseRule();
// Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/Connection.java // public interface Connection extends QueryExecutor { // // CompletableFuture<PreparedStatement> prepareStatement(String sql, Oid... parametersTypes); // // /** // * The typical scenario of using notifications is as follows: // * - {@link #subscribe(String, Consumer)} // * - Some calls of @onNotification callback // * - {@link Listening#unlisten()} // * // * @param channel Channel name to listen to. // * @param onNotification Callback, thar is cinvoked every time notification arrives. // * @return CompletableFuture instance, completed when subscription will be registered at the backend. // */ // CompletableFuture<Listening> subscribe(String channel, Consumer<String> onNotification); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // } // Path: src/test/java/com/github/pgasync/PipelineTest.java import static java.util.concurrent.TimeUnit.SECONDS; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.assertThat; import com.pgasync.Connectible; import com.pgasync.Connection; import com.pgasync.SqlException; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import java.util.Deque; import java.util.concurrent.CompletableFuture; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.SynchronousQueue; import java.util.stream.IntStream; import static java.lang.System.currentTimeMillis; import static java.util.concurrent.TimeUnit.MILLISECONDS; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync; /** * Tests for statements pipelining. * * @author Mikko Tiihonen * @author Marat Gainullin */ public class PipelineTest { @ClassRule public static DatabaseRule dbr = new DatabaseRule();
private Connection c;
alaisi/postgres-async-driver
src/test/java/com/github/pgasync/PipelineTest.java
// Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/Connection.java // public interface Connection extends QueryExecutor { // // CompletableFuture<PreparedStatement> prepareStatement(String sql, Oid... parametersTypes); // // /** // * The typical scenario of using notifications is as follows: // * - {@link #subscribe(String, Consumer)} // * - Some calls of @onNotification callback // * - {@link Listening#unlisten()} // * // * @param channel Channel name to listen to. // * @param onNotification Callback, thar is cinvoked every time notification arrives. // * @return CompletableFuture instance, completed when subscription will be registered at the backend. // */ // CompletableFuture<Listening> subscribe(String channel, Consumer<String> onNotification); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // }
import static java.util.concurrent.TimeUnit.SECONDS; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.assertThat; import com.pgasync.Connectible; import com.pgasync.Connection; import com.pgasync.SqlException; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import java.util.Deque; import java.util.concurrent.CompletableFuture; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.SynchronousQueue; import java.util.stream.IntStream; import static java.lang.System.currentTimeMillis; import static java.util.concurrent.TimeUnit.MILLISECONDS;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync; /** * Tests for statements pipelining. * * @author Mikko Tiihonen * @author Marat Gainullin */ public class PipelineTest { @ClassRule public static DatabaseRule dbr = new DatabaseRule(); private Connection c;
// Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/Connection.java // public interface Connection extends QueryExecutor { // // CompletableFuture<PreparedStatement> prepareStatement(String sql, Oid... parametersTypes); // // /** // * The typical scenario of using notifications is as follows: // * - {@link #subscribe(String, Consumer)} // * - Some calls of @onNotification callback // * - {@link Listening#unlisten()} // * // * @param channel Channel name to listen to. // * @param onNotification Callback, thar is cinvoked every time notification arrives. // * @return CompletableFuture instance, completed when subscription will be registered at the backend. // */ // CompletableFuture<Listening> subscribe(String channel, Consumer<String> onNotification); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // } // Path: src/test/java/com/github/pgasync/PipelineTest.java import static java.util.concurrent.TimeUnit.SECONDS; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.assertThat; import com.pgasync.Connectible; import com.pgasync.Connection; import com.pgasync.SqlException; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import java.util.Deque; import java.util.concurrent.CompletableFuture; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.SynchronousQueue; import java.util.stream.IntStream; import static java.lang.System.currentTimeMillis; import static java.util.concurrent.TimeUnit.MILLISECONDS; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync; /** * Tests for statements pipelining. * * @author Mikko Tiihonen * @author Marat Gainullin */ public class PipelineTest { @ClassRule public static DatabaseRule dbr = new DatabaseRule(); private Connection c;
private Connectible pool;
alaisi/postgres-async-driver
src/test/java/com/github/pgasync/PipelineTest.java
// Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/Connection.java // public interface Connection extends QueryExecutor { // // CompletableFuture<PreparedStatement> prepareStatement(String sql, Oid... parametersTypes); // // /** // * The typical scenario of using notifications is as follows: // * - {@link #subscribe(String, Consumer)} // * - Some calls of @onNotification callback // * - {@link Listening#unlisten()} // * // * @param channel Channel name to listen to. // * @param onNotification Callback, thar is cinvoked every time notification arrives. // * @return CompletableFuture instance, completed when subscription will be registered at the backend. // */ // CompletableFuture<Listening> subscribe(String channel, Consumer<String> onNotification); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // }
import static java.util.concurrent.TimeUnit.SECONDS; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.assertThat; import com.pgasync.Connectible; import com.pgasync.Connection; import com.pgasync.SqlException; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import java.util.Deque; import java.util.concurrent.CompletableFuture; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.SynchronousQueue; import java.util.stream.IntStream; import static java.lang.System.currentTimeMillis; import static java.util.concurrent.TimeUnit.MILLISECONDS;
public void connectionPoolPipelinesQueries() throws InterruptedException { int count = 5; double sleep = 0.5; Deque<Long> results = new LinkedBlockingDeque<>(); long startWrite = currentTimeMillis(); for (int i = 0; i < count; ++i) { pool.completeQuery("select " + i + ", pg_sleep(" + sleep + ")") .thenAccept(r -> results.add(currentTimeMillis())) .exceptionally(th -> { throw new AssertionError("failed", th); }); } long writeTime = currentTimeMillis() - startWrite; long remoteWaitTimeSeconds = (long) (sleep * count); SECONDS.sleep(2 + remoteWaitTimeSeconds); long readTime = results.getLast() - results.getFirst(); assertThat(results.size(), is(count)); assertThat(MILLISECONDS.toSeconds(writeTime), is(0L)); assertThat(MILLISECONDS.toSeconds(readTime + 999) >= remoteWaitTimeSeconds, is(true)); } private Connection getConnection() throws InterruptedException { SynchronousQueue<Connection> connQueue = new SynchronousQueue<>(); pool.getConnection() .thenAccept(connQueue::offer); return c = connQueue.take(); }
// Path: src/main/java/com/pgasync/Connectible.java // public interface Connectible extends QueryExecutor { // // CompletableFuture<Connection> getConnection(); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/Connection.java // public interface Connection extends QueryExecutor { // // CompletableFuture<PreparedStatement> prepareStatement(String sql, Oid... parametersTypes); // // /** // * The typical scenario of using notifications is as follows: // * - {@link #subscribe(String, Consumer)} // * - Some calls of @onNotification callback // * - {@link Listening#unlisten()} // * // * @param channel Channel name to listen to. // * @param onNotification Callback, thar is cinvoked every time notification arrives. // * @return CompletableFuture instance, completed when subscription will be registered at the backend. // */ // CompletableFuture<Listening> subscribe(String channel, Consumer<String> onNotification); // // CompletableFuture<Void> close(); // } // // Path: src/main/java/com/pgasync/SqlException.java // public class SqlException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final int MAX_CAUSE_DEPTH = 100; // // final String code; // // public SqlException(String level, String code, String message) { // super(level + ": SQLSTATE=" + code + ", MESSAGE=" + message); // this.code = code; // } // // public SqlException(String message) { // super(message); // this.code = null; // } // // public SqlException(Throwable cause) { // super(cause); // this.code = null; // } // // public String getCode() { // return code; // } // // @FunctionalInterface // public interface CheckedRunnable { // // void run() throws Exception; // } // // public static boolean ifCause(Throwable th, Consumer<SqlException> action, CheckedRunnable others) throws Exception { // int depth = 1; // while (depth++ < MAX_CAUSE_DEPTH && th != null && !(th instanceof SqlException)) { // th = th.getCause(); // } // if (th instanceof SqlException) { // action.accept((SqlException) th); // return true; // } else { // others.run(); // return false; // } // } // } // Path: src/test/java/com/github/pgasync/PipelineTest.java import static java.util.concurrent.TimeUnit.SECONDS; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.assertThat; import com.pgasync.Connectible; import com.pgasync.Connection; import com.pgasync.SqlException; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import java.util.Deque; import java.util.concurrent.CompletableFuture; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.SynchronousQueue; import java.util.stream.IntStream; import static java.lang.System.currentTimeMillis; import static java.util.concurrent.TimeUnit.MILLISECONDS; public void connectionPoolPipelinesQueries() throws InterruptedException { int count = 5; double sleep = 0.5; Deque<Long> results = new LinkedBlockingDeque<>(); long startWrite = currentTimeMillis(); for (int i = 0; i < count; ++i) { pool.completeQuery("select " + i + ", pg_sleep(" + sleep + ")") .thenAccept(r -> results.add(currentTimeMillis())) .exceptionally(th -> { throw new AssertionError("failed", th); }); } long writeTime = currentTimeMillis() - startWrite; long remoteWaitTimeSeconds = (long) (sleep * count); SECONDS.sleep(2 + remoteWaitTimeSeconds); long readTime = results.getLast() - results.getFirst(); assertThat(results.size(), is(count)); assertThat(MILLISECONDS.toSeconds(writeTime), is(0L)); assertThat(MILLISECONDS.toSeconds(readTime + 999) >= remoteWaitTimeSeconds, is(true)); } private Connection getConnection() throws InterruptedException { SynchronousQueue<Connection> connQueue = new SynchronousQueue<>(); pool.getConnection() .thenAccept(connQueue::offer); return c = connQueue.take(); }
@Test(expected = SqlException.class)
alaisi/postgres-async-driver
src/main/java/com/github/pgasync/io/frontend/StartupMessageEncoder.java
// Path: src/main/java/com/github/pgasync/io/Encoder.java // public interface Encoder<T extends Message> { // // /** // * @return Message class // */ // Class<T> getMessageType(); // // /** // * @param msg Protocol message // * @param buffer Target buffer // */ // void write(T msg, ByteBuffer buffer, Charset encoding); // // } // // Path: src/main/java/com/github/pgasync/message/frontend/StartupMessage.java // public class StartupMessage implements Message { // // private static final int protocol = 196608; // private final String username; // private final String database; // // public StartupMessage(String username, String database) { // this.username = username; // this.database = database; // } // // public int getProtocol() { // return protocol; // } // // public String getUsername() { // return username; // } // // public String getDatabase() { // return database; // } // } // // Path: src/main/java/com/github/pgasync/io/IO.java // public class IO { // // public static String getCString(ByteBuffer buffer, Charset charset) { // ByteArrayOutputStream readBuffer = new ByteArrayOutputStream(255); // for (int c = buffer.get(); c != 0; c = buffer.get()) { // readBuffer.write(c); // } // return new String(readBuffer.toByteArray(), charset); // } // // public static void putCString(ByteBuffer buffer, String value, Charset charset) { // if (!value.isEmpty()) { // buffer.put(value.getBytes(charset)); // } // buffer.put((byte) 0); // } // // }
import com.github.pgasync.io.Encoder; import com.github.pgasync.message.frontend.StartupMessage; import com.github.pgasync.io.IO; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync.io.frontend; /** * See <a href="www.postgresql.org/docs/9.3/static/protocol-message-formats.html">Postgres message formats</a> * * <pre> * StartupMessage (F) * Int32 * Length of message contents in bytes, including self. * Int32(196608) * The protocol version number. The most significant 16 bits are the major version number (3 for the protocol described here). The least significant 16 bits are the minor version number (0 for the protocol described here). * The protocol version number is followed by one or more pairs of parameter name and value strings. A zero byte is required as a terminator after the last name/value pair. Parameters can appear in any order. user is required, others are optional. Each parameter is specified as: * String * The parameter name. Currently recognized names are: * user * The database user name to connect as. Required; there is no default. * database * The database to connect to. Defaults to the user name. * options * Command-line arguments for the backend. (This is deprecated in favor of setting individual run-time parameters.) * In addition to the above, any run-time parameter that can be set at backend start time might be listed. Such settings will be applied during backend start (after parsing the command-line options if any). The values will act as session defaults. * String * The parameter value. * </pre> * * @author Antti Laisi */ public class StartupMessageEncoder implements Encoder<StartupMessage> { @Override public Class<StartupMessage> getMessageType() { return StartupMessage.class; } @Override public void write(StartupMessage msg, ByteBuffer buffer, Charset encoding) { buffer.putInt(0); buffer.putInt(msg.getProtocol()); for (String s : new String[]{ "user", msg.getUsername(), "database", msg.getDatabase(), "client_encoding", encoding.name() }) {
// Path: src/main/java/com/github/pgasync/io/Encoder.java // public interface Encoder<T extends Message> { // // /** // * @return Message class // */ // Class<T> getMessageType(); // // /** // * @param msg Protocol message // * @param buffer Target buffer // */ // void write(T msg, ByteBuffer buffer, Charset encoding); // // } // // Path: src/main/java/com/github/pgasync/message/frontend/StartupMessage.java // public class StartupMessage implements Message { // // private static final int protocol = 196608; // private final String username; // private final String database; // // public StartupMessage(String username, String database) { // this.username = username; // this.database = database; // } // // public int getProtocol() { // return protocol; // } // // public String getUsername() { // return username; // } // // public String getDatabase() { // return database; // } // } // // Path: src/main/java/com/github/pgasync/io/IO.java // public class IO { // // public static String getCString(ByteBuffer buffer, Charset charset) { // ByteArrayOutputStream readBuffer = new ByteArrayOutputStream(255); // for (int c = buffer.get(); c != 0; c = buffer.get()) { // readBuffer.write(c); // } // return new String(readBuffer.toByteArray(), charset); // } // // public static void putCString(ByteBuffer buffer, String value, Charset charset) { // if (!value.isEmpty()) { // buffer.put(value.getBytes(charset)); // } // buffer.put((byte) 0); // } // // } // Path: src/main/java/com/github/pgasync/io/frontend/StartupMessageEncoder.java import com.github.pgasync.io.Encoder; import com.github.pgasync.message.frontend.StartupMessage; import com.github.pgasync.io.IO; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync.io.frontend; /** * See <a href="www.postgresql.org/docs/9.3/static/protocol-message-formats.html">Postgres message formats</a> * * <pre> * StartupMessage (F) * Int32 * Length of message contents in bytes, including self. * Int32(196608) * The protocol version number. The most significant 16 bits are the major version number (3 for the protocol described here). The least significant 16 bits are the minor version number (0 for the protocol described here). * The protocol version number is followed by one or more pairs of parameter name and value strings. A zero byte is required as a terminator after the last name/value pair. Parameters can appear in any order. user is required, others are optional. Each parameter is specified as: * String * The parameter name. Currently recognized names are: * user * The database user name to connect as. Required; there is no default. * database * The database to connect to. Defaults to the user name. * options * Command-line arguments for the backend. (This is deprecated in favor of setting individual run-time parameters.) * In addition to the above, any run-time parameter that can be set at backend start time might be listed. Such settings will be applied during backend start (after parsing the command-line options if any). The values will act as session defaults. * String * The parameter value. * </pre> * * @author Antti Laisi */ public class StartupMessageEncoder implements Encoder<StartupMessage> { @Override public Class<StartupMessage> getMessageType() { return StartupMessage.class; } @Override public void write(StartupMessage msg, ByteBuffer buffer, Charset encoding) { buffer.putInt(0); buffer.putInt(msg.getProtocol()); for (String s : new String[]{ "user", msg.getUsername(), "database", msg.getDatabase(), "client_encoding", encoding.name() }) {
IO.putCString(buffer, s, StandardCharsets.US_ASCII);
alaisi/postgres-async-driver
src/test/java/com/github/pgasync/ConnectionPoolingTest.java
// Path: src/main/java/com/pgasync/ResultSet.java // public interface ResultSet extends Iterable<Row> { // // Map<String, PgColumn> getColumnsByName(); // // List<PgColumn> getOrderedColumns(); // // /** // * @param index Row index starting from 0 // * @return Row, never null // */ // Row at(int index); // // /** // * @return Amount of result rows. // */ // int size(); // // /** // * @return Amount of modified rows. // */ // int affectedRows(); // // }
import static org.junit.Assert.assertEquals; import com.pgasync.ResultSet; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.function.IntFunction; import java.util.stream.IntStream; import static java.util.Collections.singletonList; import static java.util.stream.Collectors.toList;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync; /** * Tests for connection pool concurrency. * * @author Antti Laisi */ public class ConnectionPoolingTest { @Rule public final DatabaseRule dbr = new DatabaseRule(); @Before public void create() { dbr.script( "DROP TABLE IF EXISTS CP_TEST;" + "CREATE TABLE CP_TEST (ID VARCHAR(255) PRIMARY KEY)" ); } @After public void drop() { dbr.query("DROP TABLE CP_TEST"); } @Test public void shouldRunAllQueuedCallbacks() throws Exception { final int count = 1000;
// Path: src/main/java/com/pgasync/ResultSet.java // public interface ResultSet extends Iterable<Row> { // // Map<String, PgColumn> getColumnsByName(); // // List<PgColumn> getOrderedColumns(); // // /** // * @param index Row index starting from 0 // * @return Row, never null // */ // Row at(int index); // // /** // * @return Amount of result rows. // */ // int size(); // // /** // * @return Amount of modified rows. // */ // int affectedRows(); // // } // Path: src/test/java/com/github/pgasync/ConnectionPoolingTest.java import static org.junit.Assert.assertEquals; import com.pgasync.ResultSet; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.function.IntFunction; import java.util.stream.IntStream; import static java.util.Collections.singletonList; import static java.util.stream.Collectors.toList; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pgasync; /** * Tests for connection pool concurrency. * * @author Antti Laisi */ public class ConnectionPoolingTest { @Rule public final DatabaseRule dbr = new DatabaseRule(); @Before public void create() { dbr.script( "DROP TABLE IF EXISTS CP_TEST;" + "CREATE TABLE CP_TEST (ID VARCHAR(255) PRIMARY KEY)" ); } @After public void drop() { dbr.query("DROP TABLE CP_TEST"); } @Test public void shouldRunAllQueuedCallbacks() throws Exception { final int count = 1000;
IntFunction<Callable<ResultSet>> insert = value -> () -> dbr.query("INSERT INTO CP_TEST VALUES($1)", singletonList(value));
paulhoule/centipede
centipede-parser/src/test/java/com/ontology2/centipede/parser/TestParsing.java
// Path: centipede-parser/src/main/java/com/ontology2/centipede/errors/UnparsableDefaultException.java // public class UnparsableDefaultException extends RuntimeException { // private final String optionName; // private final String invalidValue; // private final Type targetType; // // public UnparsableDefaultException( // String optionName // ,String invalidValue // ,Type targetType // ,Throwable innerException) { // super("Could not parse ["+invalidValue+"] for option ["+optionName+"] with target type ["+targetType+"]",innerException); // this.optionName=optionName; // this.invalidValue=invalidValue; // this.targetType=targetType; // } // // public UnparsableDefaultException( // String optionName // ,String invalidValue // ,Type targetType // ) { // this(optionName,invalidValue,targetType,null); // } // // public String getOptionName() { // return optionName; // } // // public String getInvalidValue() { // return invalidValue; // } // // public Type getTargetType() { // return targetType; // } // } // // Path: centipede-parser/src/main/java/com/ontology2/centipede/errors/UnparsableOptionException.java // public class UnparsableOptionException extends RuntimeException { // private final String optionName; // private final String invalidValue; // private final Type targetType; // // public UnparsableOptionException( // String optionName // ,String invalidValue // ,Type targetType // ,Throwable innerException) { // super("Could not parse ["+invalidValue+"] for option ["+optionName+"] with target type ["+targetType+"]",innerException); // this.optionName=optionName; // this.invalidValue=invalidValue; // this.targetType=targetType; // } // // public UnparsableOptionException( // String optionName // ,String invalidValue // ,Type targetType // ) { // this(optionName,invalidValue,targetType,null); // } // // public String getOptionName() { // return optionName; // } // // public String getInvalidValue() { // return invalidValue; // } // // public Type getTargetType() { // return targetType; // } // }
import com.google.common.collect.Lists; import com.ontology2.centipede.errors.UnparsableDefaultException; import com.ontology2.centipede.errors.UnparsableOptionException; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; import static com.google.common.collect.Lists.*; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List;
@Test public void testCaseTwo() throws IllegalAccessException, InstantiationException { InheritedOptionExample ioe = (InheritedOptionExample) exampleOne.parse( new ArrayList<String>() {{ add("-badass"); add("-johnny"); add("77"); }} ); assertEquals(77L, (long) ioe.john); assertEquals(true, ioe.badass); assertEquals(0,ioe.jimmy); assertTrue(ioe.numbers.isEmpty()); } @Test public void assignToJimmy() throws IllegalAccessException, InstantiationException { InheritedOptionExample ioe = (InheritedOptionExample) exampleOne.parse( new ArrayList<String>() {{ add("-jimmy"); add("419"); }} ); assertEquals(ioe.jimmy,419); } @Test public void unparsableOptionFailsAppropriately() throws IllegalAccessException {
// Path: centipede-parser/src/main/java/com/ontology2/centipede/errors/UnparsableDefaultException.java // public class UnparsableDefaultException extends RuntimeException { // private final String optionName; // private final String invalidValue; // private final Type targetType; // // public UnparsableDefaultException( // String optionName // ,String invalidValue // ,Type targetType // ,Throwable innerException) { // super("Could not parse ["+invalidValue+"] for option ["+optionName+"] with target type ["+targetType+"]",innerException); // this.optionName=optionName; // this.invalidValue=invalidValue; // this.targetType=targetType; // } // // public UnparsableDefaultException( // String optionName // ,String invalidValue // ,Type targetType // ) { // this(optionName,invalidValue,targetType,null); // } // // public String getOptionName() { // return optionName; // } // // public String getInvalidValue() { // return invalidValue; // } // // public Type getTargetType() { // return targetType; // } // } // // Path: centipede-parser/src/main/java/com/ontology2/centipede/errors/UnparsableOptionException.java // public class UnparsableOptionException extends RuntimeException { // private final String optionName; // private final String invalidValue; // private final Type targetType; // // public UnparsableOptionException( // String optionName // ,String invalidValue // ,Type targetType // ,Throwable innerException) { // super("Could not parse ["+invalidValue+"] for option ["+optionName+"] with target type ["+targetType+"]",innerException); // this.optionName=optionName; // this.invalidValue=invalidValue; // this.targetType=targetType; // } // // public UnparsableOptionException( // String optionName // ,String invalidValue // ,Type targetType // ) { // this(optionName,invalidValue,targetType,null); // } // // public String getOptionName() { // return optionName; // } // // public String getInvalidValue() { // return invalidValue; // } // // public Type getTargetType() { // return targetType; // } // } // Path: centipede-parser/src/test/java/com/ontology2/centipede/parser/TestParsing.java import com.google.common.collect.Lists; import com.ontology2.centipede.errors.UnparsableDefaultException; import com.ontology2.centipede.errors.UnparsableOptionException; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; import static com.google.common.collect.Lists.*; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; @Test public void testCaseTwo() throws IllegalAccessException, InstantiationException { InheritedOptionExample ioe = (InheritedOptionExample) exampleOne.parse( new ArrayList<String>() {{ add("-badass"); add("-johnny"); add("77"); }} ); assertEquals(77L, (long) ioe.john); assertEquals(true, ioe.badass); assertEquals(0,ioe.jimmy); assertTrue(ioe.numbers.isEmpty()); } @Test public void assignToJimmy() throws IllegalAccessException, InstantiationException { InheritedOptionExample ioe = (InheritedOptionExample) exampleOne.parse( new ArrayList<String>() {{ add("-jimmy"); add("419"); }} ); assertEquals(ioe.jimmy,419); } @Test public void unparsableOptionFailsAppropriately() throws IllegalAccessException {
UnparsableOptionException blowup = null;
paulhoule/centipede
centipede-parser/src/test/java/com/ontology2/centipede/parser/TestParsing.java
// Path: centipede-parser/src/main/java/com/ontology2/centipede/errors/UnparsableDefaultException.java // public class UnparsableDefaultException extends RuntimeException { // private final String optionName; // private final String invalidValue; // private final Type targetType; // // public UnparsableDefaultException( // String optionName // ,String invalidValue // ,Type targetType // ,Throwable innerException) { // super("Could not parse ["+invalidValue+"] for option ["+optionName+"] with target type ["+targetType+"]",innerException); // this.optionName=optionName; // this.invalidValue=invalidValue; // this.targetType=targetType; // } // // public UnparsableDefaultException( // String optionName // ,String invalidValue // ,Type targetType // ) { // this(optionName,invalidValue,targetType,null); // } // // public String getOptionName() { // return optionName; // } // // public String getInvalidValue() { // return invalidValue; // } // // public Type getTargetType() { // return targetType; // } // } // // Path: centipede-parser/src/main/java/com/ontology2/centipede/errors/UnparsableOptionException.java // public class UnparsableOptionException extends RuntimeException { // private final String optionName; // private final String invalidValue; // private final Type targetType; // // public UnparsableOptionException( // String optionName // ,String invalidValue // ,Type targetType // ,Throwable innerException) { // super("Could not parse ["+invalidValue+"] for option ["+optionName+"] with target type ["+targetType+"]",innerException); // this.optionName=optionName; // this.invalidValue=invalidValue; // this.targetType=targetType; // } // // public UnparsableOptionException( // String optionName // ,String invalidValue // ,Type targetType // ) { // this(optionName,invalidValue,targetType,null); // } // // public String getOptionName() { // return optionName; // } // // public String getInvalidValue() { // return invalidValue; // } // // public Type getTargetType() { // return targetType; // } // }
import com.google.common.collect.Lists; import com.ontology2.centipede.errors.UnparsableDefaultException; import com.ontology2.centipede.errors.UnparsableOptionException; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; import static com.google.common.collect.Lists.*; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List;
}} ); assertEquals(ioe.jimmy,419); } @Test public void unparsableOptionFailsAppropriately() throws IllegalAccessException { UnparsableOptionException blowup = null; try { InheritedOptionExample ioe = (InheritedOptionExample) exampleOne.parse( new ArrayList<String>() {{ add("-johnny"); add("-badass"); add("421"); }} ); } catch (UnparsableOptionException x) { blowup = x; } assertNotNull(blowup); assertEquals("johnny", blowup.getOptionName()); assertEquals("-badass", blowup.getInvalidValue()); assertEquals(Long.class, blowup.getTargetType()); } @Test public void unparsableDefaultFailsAppropriately() throws IllegalAccessException {
// Path: centipede-parser/src/main/java/com/ontology2/centipede/errors/UnparsableDefaultException.java // public class UnparsableDefaultException extends RuntimeException { // private final String optionName; // private final String invalidValue; // private final Type targetType; // // public UnparsableDefaultException( // String optionName // ,String invalidValue // ,Type targetType // ,Throwable innerException) { // super("Could not parse ["+invalidValue+"] for option ["+optionName+"] with target type ["+targetType+"]",innerException); // this.optionName=optionName; // this.invalidValue=invalidValue; // this.targetType=targetType; // } // // public UnparsableDefaultException( // String optionName // ,String invalidValue // ,Type targetType // ) { // this(optionName,invalidValue,targetType,null); // } // // public String getOptionName() { // return optionName; // } // // public String getInvalidValue() { // return invalidValue; // } // // public Type getTargetType() { // return targetType; // } // } // // Path: centipede-parser/src/main/java/com/ontology2/centipede/errors/UnparsableOptionException.java // public class UnparsableOptionException extends RuntimeException { // private final String optionName; // private final String invalidValue; // private final Type targetType; // // public UnparsableOptionException( // String optionName // ,String invalidValue // ,Type targetType // ,Throwable innerException) { // super("Could not parse ["+invalidValue+"] for option ["+optionName+"] with target type ["+targetType+"]",innerException); // this.optionName=optionName; // this.invalidValue=invalidValue; // this.targetType=targetType; // } // // public UnparsableOptionException( // String optionName // ,String invalidValue // ,Type targetType // ) { // this(optionName,invalidValue,targetType,null); // } // // public String getOptionName() { // return optionName; // } // // public String getInvalidValue() { // return invalidValue; // } // // public Type getTargetType() { // return targetType; // } // } // Path: centipede-parser/src/test/java/com/ontology2/centipede/parser/TestParsing.java import com.google.common.collect.Lists; import com.ontology2.centipede.errors.UnparsableDefaultException; import com.ontology2.centipede.errors.UnparsableOptionException; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; import static com.google.common.collect.Lists.*; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; }} ); assertEquals(ioe.jimmy,419); } @Test public void unparsableOptionFailsAppropriately() throws IllegalAccessException { UnparsableOptionException blowup = null; try { InheritedOptionExample ioe = (InheritedOptionExample) exampleOne.parse( new ArrayList<String>() {{ add("-johnny"); add("-badass"); add("421"); }} ); } catch (UnparsableOptionException x) { blowup = x; } assertNotNull(blowup); assertEquals("johnny", blowup.getOptionName()); assertEquals("-badass", blowup.getInvalidValue()); assertEquals(Long.class, blowup.getTargetType()); } @Test public void unparsableDefaultFailsAppropriately() throws IllegalAccessException {
UnparsableDefaultException blowup = null;
paulhoule/centipede
centipede-parser/src/test/java/com/ontology2/centipede/parser/TestRequiredOption.java
// Path: centipede-parser/src/main/java/com/ontology2/centipede/errors/MissingOptionException.java // public class MissingOptionException extends UsageException { // public MissingOptionException() { // } // // public MissingOptionException(String message) { // super(message); // } // // public MissingOptionException(String message, Throwable cause) { // super(message, cause); // } // // public MissingOptionException(Throwable cause) { // super(cause); // } // // public MissingOptionException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // }
import com.google.common.collect.Lists; import com.ontology2.centipede.errors.MissingOptionException; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; import java.util.ArrayList; import static org.junit.Assert.assertEquals;
package com.ontology2.centipede.parser; public class TestRequiredOption extends SpringSource { @Resource OptionParser requiredOptionExampleParser;
// Path: centipede-parser/src/main/java/com/ontology2/centipede/errors/MissingOptionException.java // public class MissingOptionException extends UsageException { // public MissingOptionException() { // } // // public MissingOptionException(String message) { // super(message); // } // // public MissingOptionException(String message, Throwable cause) { // super(message, cause); // } // // public MissingOptionException(Throwable cause) { // super(cause); // } // // public MissingOptionException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // Path: centipede-parser/src/test/java/com/ontology2/centipede/parser/TestRequiredOption.java import com.google.common.collect.Lists; import com.ontology2.centipede.errors.MissingOptionException; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; import java.util.ArrayList; import static org.junit.Assert.assertEquals; package com.ontology2.centipede.parser; public class TestRequiredOption extends SpringSource { @Resource OptionParser requiredOptionExampleParser;
@Test(expected=MissingOptionException.class)
paulhoule/centipede
centipede-parser/src/main/java/com/ontology2/centipede/parser/RWOption.java
// Path: centipede-parser/src/main/java/com/ontology2/centipede/errors/MisconfigurationException.java // public class MisconfigurationException extends RuntimeException { // public MisconfigurationException() { // } // // public MisconfigurationException(String message) { // super(message); // } // // public MisconfigurationException(String message, Throwable cause) { // super(message, cause); // } // // public MisconfigurationException(Throwable cause) { // super(cause); // } // // public MisconfigurationException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // }
import com.ontology2.centipede.errors.MisconfigurationException; import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.TypeDescriptor; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.List;
package com.ontology2.centipede.parser; public class RWOption { private final Field field; private final Class substitutor; private final boolean isRequired; private String name; private String defaultValue; private String description; private Type type; public RWOption(Field f) { Option o=f.getAnnotation(Option.class); this.isRequired=(f.getAnnotation(Required.class)!=null); this.field=f; this.name=o.name(); this.defaultValue=o.defaultValue(); this.description=o.description(); if(!Object.class.equals(o.contextualConverter()) && !ContextualConverter.class.isAssignableFrom(o.contextualConverter()))
// Path: centipede-parser/src/main/java/com/ontology2/centipede/errors/MisconfigurationException.java // public class MisconfigurationException extends RuntimeException { // public MisconfigurationException() { // } // // public MisconfigurationException(String message) { // super(message); // } // // public MisconfigurationException(String message, Throwable cause) { // super(message, cause); // } // // public MisconfigurationException(Throwable cause) { // super(cause); // } // // public MisconfigurationException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // Path: centipede-parser/src/main/java/com/ontology2/centipede/parser/RWOption.java import com.ontology2.centipede.errors.MisconfigurationException; import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.TypeDescriptor; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.List; package com.ontology2.centipede.parser; public class RWOption { private final Field field; private final Class substitutor; private final boolean isRequired; private String name; private String defaultValue; private String description; private Type type; public RWOption(Field f) { Option o=f.getAnnotation(Option.class); this.isRequired=(f.getAnnotation(Required.class)!=null); this.field=f; this.name=o.name(); this.defaultValue=o.defaultValue(); this.description=o.description(); if(!Object.class.equals(o.contextualConverter()) && !ContextualConverter.class.isAssignableFrom(o.contextualConverter()))
throw new MisconfigurationException("A contextualConverter must be a ContextualConverter for option "+name);
paulhoule/centipede
centipede-parser/src/test/java/com/ontology2/centipede/parser/TestAnnotationExtraction.java
// Path: centipede-parser/src/main/java/com/ontology2/centipede/parser/OptionParser.java // static Object defaultValueFor(Type type) { // if (Byte.TYPE.equals(type)) { // return (byte) 0; // } // ; // // if (Short.TYPE.equals(type)) { // return (short) 0; // } // // if (Integer.TYPE.equals(type)) { // return (int) 0; // } // // if (Long.TYPE.equals(type)) { // return 0L; // } // // if (Float.TYPE.equals(type)) { // return 0.0F; // } // // if (Double.TYPE.equals(type)) { // return 0.0; // } // // if (Boolean.TYPE.equals(type)) { // return false; // } // // if (Character.TYPE.equals(type)) { // return '\0'; // } // // if (String.class.equals(type)) { // return ""; // } // // if (List.class.equals(type)) { // return new ArrayList(); // } // // if (type instanceof ParameterizedType) { // ParameterizedType generic = (ParameterizedType) type; // if (List.class.isAssignableFrom((Class) generic.getRawType())) { // return new ArrayList(); // } // } // // return null; // } // // Path: centipede-parser/src/main/java/com/ontology2/centipede/parser/OptionParser.java // static Field findPositionalParameter(Class that) { // for (Field f : that.getFields()) // if(f.getAnnotation(Positional.class)!=null) { // if(!List.class.isAssignableFrom(f.getType())) // throw new MisconfigurationException("The @Positional parameter must be a List<String>"); // // ParameterizedType generic=(ParameterizedType) f.getGenericType(); // if(!String.class.equals(generic.getActualTypeArguments()[0])) // throw new MisconfigurationException("The @Positional parameter must be a List<String>"); // // return f; // } // return null; // }
import org.junit.Assert; import org.junit.Test; import static com.ontology2.centipede.parser.OptionParser.defaultValueFor; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import java.util.List; import java.util.Map; import static com.ontology2.centipede.parser.OptionParser.findPositionalParameter; import static org.junit.Assert.*;
assertTrue(lookup.containsKey("badass")); RWOption o=lookup.get("badass"); assertEquals("badass", o.getName()); assertEquals("Never a dude like this one", o.getDescription()); assertEquals("", o.getDefaultValue()); } @Test public void inheritanceCase() { Map<String,RWOption> lookup=OptionParser.getStringAnnotationMap(InheritedOptionExample.class); assertEquals(4, lookup.size()); assertTrue(lookup.containsKey("badass")); RWOption o1=lookup.get("badass"); assertEquals("badass", o1.getName()); assertEquals("Never a dude like this one", o1.getDescription()); assertEquals("", o1.getDefaultValue()); RWOption o2=lookup.get("johnny"); assertEquals("johnny", o2.getName()); assertEquals("one hundred feet", o2.getDescription()); assertEquals("1234", o2.getDefaultValue()); RWOption numbers=lookup.get("numbers"); assert(numbers.isList()); assertEquals(Integer.class, numbers.getElementType()); } @Test public void testDefaults() { // 8 primitive types get defaults from the JLS
// Path: centipede-parser/src/main/java/com/ontology2/centipede/parser/OptionParser.java // static Object defaultValueFor(Type type) { // if (Byte.TYPE.equals(type)) { // return (byte) 0; // } // ; // // if (Short.TYPE.equals(type)) { // return (short) 0; // } // // if (Integer.TYPE.equals(type)) { // return (int) 0; // } // // if (Long.TYPE.equals(type)) { // return 0L; // } // // if (Float.TYPE.equals(type)) { // return 0.0F; // } // // if (Double.TYPE.equals(type)) { // return 0.0; // } // // if (Boolean.TYPE.equals(type)) { // return false; // } // // if (Character.TYPE.equals(type)) { // return '\0'; // } // // if (String.class.equals(type)) { // return ""; // } // // if (List.class.equals(type)) { // return new ArrayList(); // } // // if (type instanceof ParameterizedType) { // ParameterizedType generic = (ParameterizedType) type; // if (List.class.isAssignableFrom((Class) generic.getRawType())) { // return new ArrayList(); // } // } // // return null; // } // // Path: centipede-parser/src/main/java/com/ontology2/centipede/parser/OptionParser.java // static Field findPositionalParameter(Class that) { // for (Field f : that.getFields()) // if(f.getAnnotation(Positional.class)!=null) { // if(!List.class.isAssignableFrom(f.getType())) // throw new MisconfigurationException("The @Positional parameter must be a List<String>"); // // ParameterizedType generic=(ParameterizedType) f.getGenericType(); // if(!String.class.equals(generic.getActualTypeArguments()[0])) // throw new MisconfigurationException("The @Positional parameter must be a List<String>"); // // return f; // } // return null; // } // Path: centipede-parser/src/test/java/com/ontology2/centipede/parser/TestAnnotationExtraction.java import org.junit.Assert; import org.junit.Test; import static com.ontology2.centipede.parser.OptionParser.defaultValueFor; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import java.util.List; import java.util.Map; import static com.ontology2.centipede.parser.OptionParser.findPositionalParameter; import static org.junit.Assert.*; assertTrue(lookup.containsKey("badass")); RWOption o=lookup.get("badass"); assertEquals("badass", o.getName()); assertEquals("Never a dude like this one", o.getDescription()); assertEquals("", o.getDefaultValue()); } @Test public void inheritanceCase() { Map<String,RWOption> lookup=OptionParser.getStringAnnotationMap(InheritedOptionExample.class); assertEquals(4, lookup.size()); assertTrue(lookup.containsKey("badass")); RWOption o1=lookup.get("badass"); assertEquals("badass", o1.getName()); assertEquals("Never a dude like this one", o1.getDescription()); assertEquals("", o1.getDefaultValue()); RWOption o2=lookup.get("johnny"); assertEquals("johnny", o2.getName()); assertEquals("one hundred feet", o2.getDescription()); assertEquals("1234", o2.getDefaultValue()); RWOption numbers=lookup.get("numbers"); assert(numbers.isList()); assertEquals(Integer.class, numbers.getElementType()); } @Test public void testDefaults() { // 8 primitive types get defaults from the JLS
assertEquals((byte) 0, defaultValueFor(Byte.TYPE));
paulhoule/centipede
centipede-parser/src/test/java/com/ontology2/centipede/parser/TestAnnotationExtraction.java
// Path: centipede-parser/src/main/java/com/ontology2/centipede/parser/OptionParser.java // static Object defaultValueFor(Type type) { // if (Byte.TYPE.equals(type)) { // return (byte) 0; // } // ; // // if (Short.TYPE.equals(type)) { // return (short) 0; // } // // if (Integer.TYPE.equals(type)) { // return (int) 0; // } // // if (Long.TYPE.equals(type)) { // return 0L; // } // // if (Float.TYPE.equals(type)) { // return 0.0F; // } // // if (Double.TYPE.equals(type)) { // return 0.0; // } // // if (Boolean.TYPE.equals(type)) { // return false; // } // // if (Character.TYPE.equals(type)) { // return '\0'; // } // // if (String.class.equals(type)) { // return ""; // } // // if (List.class.equals(type)) { // return new ArrayList(); // } // // if (type instanceof ParameterizedType) { // ParameterizedType generic = (ParameterizedType) type; // if (List.class.isAssignableFrom((Class) generic.getRawType())) { // return new ArrayList(); // } // } // // return null; // } // // Path: centipede-parser/src/main/java/com/ontology2/centipede/parser/OptionParser.java // static Field findPositionalParameter(Class that) { // for (Field f : that.getFields()) // if(f.getAnnotation(Positional.class)!=null) { // if(!List.class.isAssignableFrom(f.getType())) // throw new MisconfigurationException("The @Positional parameter must be a List<String>"); // // ParameterizedType generic=(ParameterizedType) f.getGenericType(); // if(!String.class.equals(generic.getActualTypeArguments()[0])) // throw new MisconfigurationException("The @Positional parameter must be a List<String>"); // // return f; // } // return null; // }
import org.junit.Assert; import org.junit.Test; import static com.ontology2.centipede.parser.OptionParser.defaultValueFor; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import java.util.List; import java.util.Map; import static com.ontology2.centipede.parser.OptionParser.findPositionalParameter; import static org.junit.Assert.*;
public void testDefaults() { // 8 primitive types get defaults from the JLS assertEquals((byte) 0, defaultValueFor(Byte.TYPE)); assertEquals((short) 0, defaultValueFor(Short.TYPE)); assertEquals(0, defaultValueFor(Integer.TYPE)); assertEquals(0L, defaultValueFor(Long.TYPE)); assertEquals(0.0f, defaultValueFor(Float.TYPE)); assertEquals(0.0, defaultValueFor(Double.TYPE)); assertEquals(false, defaultValueFor(Boolean.TYPE)); assertEquals('\0', defaultValueFor(Character.TYPE)); // For a string we get the empty String assertEquals("", defaultValueFor(String.class)); assertEquals(new ArrayList(), defaultValueFor(List.class)); ParameterizedType t=(ParameterizedType) ((new ArrayList<Exception>()) .getClass() .getGenericSuperclass()); assertEquals(new ArrayList<Exception>(), defaultValueFor(t)); assertEquals(new ArrayList<Long>(), defaultValueFor(t)); } @Test public void extractsPositional() {
// Path: centipede-parser/src/main/java/com/ontology2/centipede/parser/OptionParser.java // static Object defaultValueFor(Type type) { // if (Byte.TYPE.equals(type)) { // return (byte) 0; // } // ; // // if (Short.TYPE.equals(type)) { // return (short) 0; // } // // if (Integer.TYPE.equals(type)) { // return (int) 0; // } // // if (Long.TYPE.equals(type)) { // return 0L; // } // // if (Float.TYPE.equals(type)) { // return 0.0F; // } // // if (Double.TYPE.equals(type)) { // return 0.0; // } // // if (Boolean.TYPE.equals(type)) { // return false; // } // // if (Character.TYPE.equals(type)) { // return '\0'; // } // // if (String.class.equals(type)) { // return ""; // } // // if (List.class.equals(type)) { // return new ArrayList(); // } // // if (type instanceof ParameterizedType) { // ParameterizedType generic = (ParameterizedType) type; // if (List.class.isAssignableFrom((Class) generic.getRawType())) { // return new ArrayList(); // } // } // // return null; // } // // Path: centipede-parser/src/main/java/com/ontology2/centipede/parser/OptionParser.java // static Field findPositionalParameter(Class that) { // for (Field f : that.getFields()) // if(f.getAnnotation(Positional.class)!=null) { // if(!List.class.isAssignableFrom(f.getType())) // throw new MisconfigurationException("The @Positional parameter must be a List<String>"); // // ParameterizedType generic=(ParameterizedType) f.getGenericType(); // if(!String.class.equals(generic.getActualTypeArguments()[0])) // throw new MisconfigurationException("The @Positional parameter must be a List<String>"); // // return f; // } // return null; // } // Path: centipede-parser/src/test/java/com/ontology2/centipede/parser/TestAnnotationExtraction.java import org.junit.Assert; import org.junit.Test; import static com.ontology2.centipede.parser.OptionParser.defaultValueFor; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import java.util.List; import java.util.Map; import static com.ontology2.centipede.parser.OptionParser.findPositionalParameter; import static org.junit.Assert.*; public void testDefaults() { // 8 primitive types get defaults from the JLS assertEquals((byte) 0, defaultValueFor(Byte.TYPE)); assertEquals((short) 0, defaultValueFor(Short.TYPE)); assertEquals(0, defaultValueFor(Integer.TYPE)); assertEquals(0L, defaultValueFor(Long.TYPE)); assertEquals(0.0f, defaultValueFor(Float.TYPE)); assertEquals(0.0, defaultValueFor(Double.TYPE)); assertEquals(false, defaultValueFor(Boolean.TYPE)); assertEquals('\0', defaultValueFor(Character.TYPE)); // For a string we get the empty String assertEquals("", defaultValueFor(String.class)); assertEquals(new ArrayList(), defaultValueFor(List.class)); ParameterizedType t=(ParameterizedType) ((new ArrayList<Exception>()) .getClass() .getGenericSuperclass()); assertEquals(new ArrayList<Exception>(), defaultValueFor(t)); assertEquals(new ArrayList<Long>(), defaultValueFor(t)); } @Test public void extractsPositional() {
Field f=findPositionalParameter(InheritedOptionExample.class);
paulhoule/centipede
centipede/src/test/java/util/TestVersion.java
// Path: centipede/src/main/java/com/ontology2/centipede/util/Version.java // public class Version { // // public static String get(String packageName) { // String lookFor= // "/"+packageName.replace(".","/")+"/version.properties"; // InputStream in=Version.class.getResourceAsStream(lookFor); // Properties p=new Properties(); // try { // p.load(in); // } catch (IOException e) { // return null; // } // // return p.getProperty(packageName+".version"); // } // }
import com.google.common.base.CharMatcher; import com.ontology2.centipede.util.Version; import org.junit.Test; import static org.junit.Assert.*;
package util; public class TestVersion { @Test public void iHaveAVersionNumber() {
// Path: centipede/src/main/java/com/ontology2/centipede/util/Version.java // public class Version { // // public static String get(String packageName) { // String lookFor= // "/"+packageName.replace(".","/")+"/version.properties"; // InputStream in=Version.class.getResourceAsStream(lookFor); // Properties p=new Properties(); // try { // p.load(in); // } catch (IOException e) { // return null; // } // // return p.getProperty(packageName+".version"); // } // } // Path: centipede/src/test/java/util/TestVersion.java import com.google.common.base.CharMatcher; import com.ontology2.centipede.util.Version; import org.junit.Test; import static org.junit.Assert.*; package util; public class TestVersion { @Test public void iHaveAVersionNumber() {
String number= Version.get("com.ontology2.centipede");
paulhoule/centipede
centipede/src/main/java/com/ontology2/centipede/shell/CommandLineApplication.java
// Path: centipede-parser/src/main/java/com/ontology2/centipede/errors/ExitCodeException.java // public class ExitCodeException extends Exception { // final int status; // // // // // want to leave the option of converting to a subclass if desired, to // // implement finer-grained exception types such as one would see in a // // POSIX sysexits.h // // // // http://www.opensource.apple.com/source/Libc/Libc-320/include/sysexits.h // // // // public static ExitCodeException create(int status) { // return new ExitCodeException(status); // } // // protected ExitCodeException(int status) { // super("process exit code "+status); // // if (status<1 || status>255) { // throw new IllegalArgumentException(); // } // // this.status=status; // } // // public int getStatus() { // return status; // } // // // public static int EX_USAGE=64; /* command line usage error */ // public static int EX_DATAERR=65; /* data format error */ // public static int EX_NOINPUT=66; /* cannot open input */ // public static int EX_NOUSER=67; /* addressee unknown */ // public static int EX_NOHOST=68; /* host name unknown */ // // public static int EX_UNAVAILABLE=69; /* service unavailable */ // public static int EX_SOFTWARE=70; /* internal software error */ // public static int EX_OSERR=71; /* system error (e.g., can't fork) */ // public static int EX_OSFILE=72; /* critical OS file missing */ // public static int EX_CANTCREAT=73; /* can't create (user) output file */ // public static int EX_IOERR=74; /* input/output error */ // public static int EX_TEMPFAIL=75; /* temp failure; user is invited to retry */ // public static int EX_PROTOCOL=76; /* remote error in protocol */ // public static int EX_NOPERM=77; /* permission denied */ // public static int EX_CONFIG=78; /* configuration error */ // // } // // Path: centipede-parser/src/main/java/com/ontology2/centipede/errors/ShutTheProcessDown.java // public class ShutTheProcessDown extends RuntimeException { // // public ShutTheProcessDown() { // super("process shutdown requested"); // } // // }
import com.ontology2.centipede.errors.ExitCodeException; import com.ontology2.centipede.errors.ShutTheProcessDown; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory;
package com.ontology2.centipede.shell; public abstract class CommandLineApplication extends ResourceAwareObject { private static Log logger = LogFactory.getLog(CommandLineApplication.class); public void run(String[] arguments) { try { _run(arguments);
// Path: centipede-parser/src/main/java/com/ontology2/centipede/errors/ExitCodeException.java // public class ExitCodeException extends Exception { // final int status; // // // // // want to leave the option of converting to a subclass if desired, to // // implement finer-grained exception types such as one would see in a // // POSIX sysexits.h // // // // http://www.opensource.apple.com/source/Libc/Libc-320/include/sysexits.h // // // // public static ExitCodeException create(int status) { // return new ExitCodeException(status); // } // // protected ExitCodeException(int status) { // super("process exit code "+status); // // if (status<1 || status>255) { // throw new IllegalArgumentException(); // } // // this.status=status; // } // // public int getStatus() { // return status; // } // // // public static int EX_USAGE=64; /* command line usage error */ // public static int EX_DATAERR=65; /* data format error */ // public static int EX_NOINPUT=66; /* cannot open input */ // public static int EX_NOUSER=67; /* addressee unknown */ // public static int EX_NOHOST=68; /* host name unknown */ // // public static int EX_UNAVAILABLE=69; /* service unavailable */ // public static int EX_SOFTWARE=70; /* internal software error */ // public static int EX_OSERR=71; /* system error (e.g., can't fork) */ // public static int EX_OSFILE=72; /* critical OS file missing */ // public static int EX_CANTCREAT=73; /* can't create (user) output file */ // public static int EX_IOERR=74; /* input/output error */ // public static int EX_TEMPFAIL=75; /* temp failure; user is invited to retry */ // public static int EX_PROTOCOL=76; /* remote error in protocol */ // public static int EX_NOPERM=77; /* permission denied */ // public static int EX_CONFIG=78; /* configuration error */ // // } // // Path: centipede-parser/src/main/java/com/ontology2/centipede/errors/ShutTheProcessDown.java // public class ShutTheProcessDown extends RuntimeException { // // public ShutTheProcessDown() { // super("process shutdown requested"); // } // // } // Path: centipede/src/main/java/com/ontology2/centipede/shell/CommandLineApplication.java import com.ontology2.centipede.errors.ExitCodeException; import com.ontology2.centipede.errors.ShutTheProcessDown; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; package com.ontology2.centipede.shell; public abstract class CommandLineApplication extends ResourceAwareObject { private static Log logger = LogFactory.getLog(CommandLineApplication.class); public void run(String[] arguments) { try { _run(arguments);
} catch (ExitCodeException e) {
paulhoule/centipede
centipede/src/main/java/com/ontology2/centipede/shell/CommandLineApplication.java
// Path: centipede-parser/src/main/java/com/ontology2/centipede/errors/ExitCodeException.java // public class ExitCodeException extends Exception { // final int status; // // // // // want to leave the option of converting to a subclass if desired, to // // implement finer-grained exception types such as one would see in a // // POSIX sysexits.h // // // // http://www.opensource.apple.com/source/Libc/Libc-320/include/sysexits.h // // // // public static ExitCodeException create(int status) { // return new ExitCodeException(status); // } // // protected ExitCodeException(int status) { // super("process exit code "+status); // // if (status<1 || status>255) { // throw new IllegalArgumentException(); // } // // this.status=status; // } // // public int getStatus() { // return status; // } // // // public static int EX_USAGE=64; /* command line usage error */ // public static int EX_DATAERR=65; /* data format error */ // public static int EX_NOINPUT=66; /* cannot open input */ // public static int EX_NOUSER=67; /* addressee unknown */ // public static int EX_NOHOST=68; /* host name unknown */ // // public static int EX_UNAVAILABLE=69; /* service unavailable */ // public static int EX_SOFTWARE=70; /* internal software error */ // public static int EX_OSERR=71; /* system error (e.g., can't fork) */ // public static int EX_OSFILE=72; /* critical OS file missing */ // public static int EX_CANTCREAT=73; /* can't create (user) output file */ // public static int EX_IOERR=74; /* input/output error */ // public static int EX_TEMPFAIL=75; /* temp failure; user is invited to retry */ // public static int EX_PROTOCOL=76; /* remote error in protocol */ // public static int EX_NOPERM=77; /* permission denied */ // public static int EX_CONFIG=78; /* configuration error */ // // } // // Path: centipede-parser/src/main/java/com/ontology2/centipede/errors/ShutTheProcessDown.java // public class ShutTheProcessDown extends RuntimeException { // // public ShutTheProcessDown() { // super("process shutdown requested"); // } // // }
import com.ontology2.centipede.errors.ExitCodeException; import com.ontology2.centipede.errors.ShutTheProcessDown; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory;
package com.ontology2.centipede.shell; public abstract class CommandLineApplication extends ResourceAwareObject { private static Log logger = LogFactory.getLog(CommandLineApplication.class); public void run(String[] arguments) { try { _run(arguments); } catch (ExitCodeException e) { logger.error("process failed with exit code"+e.getStatus(),e); System.exit(e.getStatus());
// Path: centipede-parser/src/main/java/com/ontology2/centipede/errors/ExitCodeException.java // public class ExitCodeException extends Exception { // final int status; // // // // // want to leave the option of converting to a subclass if desired, to // // implement finer-grained exception types such as one would see in a // // POSIX sysexits.h // // // // http://www.opensource.apple.com/source/Libc/Libc-320/include/sysexits.h // // // // public static ExitCodeException create(int status) { // return new ExitCodeException(status); // } // // protected ExitCodeException(int status) { // super("process exit code "+status); // // if (status<1 || status>255) { // throw new IllegalArgumentException(); // } // // this.status=status; // } // // public int getStatus() { // return status; // } // // // public static int EX_USAGE=64; /* command line usage error */ // public static int EX_DATAERR=65; /* data format error */ // public static int EX_NOINPUT=66; /* cannot open input */ // public static int EX_NOUSER=67; /* addressee unknown */ // public static int EX_NOHOST=68; /* host name unknown */ // // public static int EX_UNAVAILABLE=69; /* service unavailable */ // public static int EX_SOFTWARE=70; /* internal software error */ // public static int EX_OSERR=71; /* system error (e.g., can't fork) */ // public static int EX_OSFILE=72; /* critical OS file missing */ // public static int EX_CANTCREAT=73; /* can't create (user) output file */ // public static int EX_IOERR=74; /* input/output error */ // public static int EX_TEMPFAIL=75; /* temp failure; user is invited to retry */ // public static int EX_PROTOCOL=76; /* remote error in protocol */ // public static int EX_NOPERM=77; /* permission denied */ // public static int EX_CONFIG=78; /* configuration error */ // // } // // Path: centipede-parser/src/main/java/com/ontology2/centipede/errors/ShutTheProcessDown.java // public class ShutTheProcessDown extends RuntimeException { // // public ShutTheProcessDown() { // super("process shutdown requested"); // } // // } // Path: centipede/src/main/java/com/ontology2/centipede/shell/CommandLineApplication.java import com.ontology2.centipede.errors.ExitCodeException; import com.ontology2.centipede.errors.ShutTheProcessDown; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; package com.ontology2.centipede.shell; public abstract class CommandLineApplication extends ResourceAwareObject { private static Log logger = LogFactory.getLog(CommandLineApplication.class); public void run(String[] arguments) { try { _run(arguments); } catch (ExitCodeException e) { logger.error("process failed with exit code"+e.getStatus(),e); System.exit(e.getStatus());
} catch(ShutTheProcessDown e) {
paulhoule/centipede
centipede/src/test/java/util/TestExitStatus.java
// Path: centipede/src/main/java/com/ontology2/centipede/util/ExitStatus.java // public class ExitStatus { // final public static int OK= 0; /* successful termination */ // final public static int USAGE = 64; /* command line usage error */ // final public static int DATAERR = 65; /* data format error */ // final public static int NOINPUT = 66; /* cannot open input */ // final public static int NOUSER = 67; /* addressee unknown */ // final public static int NOHOST = 68; /* host name unknown */ // final public static int UNAVAILABLE = 69; /* service unavailable */ // final public static int SOFTWARE = 70; /* internal software error */ // final public static int OSERR =71; /* system error (e.g., can't fork) */ // final public static int OSFILE = 72; /* critical OS file missing */ // final public static int CANTCREAT = 73; /* can't create (user) output file */ // final public static int IOERR = 74; /* input/output error */ // final public static int TEMPFAIL = 75; /* temp failure; user is invited to retry */ // final public static int PROTOCOL = 76; /* remote error in protocol */ // final public static int NOPERM = 77; /* permission denied */ // final public static int CONFIG = 78; /* configuration error */ // }
import com.ontology2.centipede.util.ExitStatus; import org.junit.Test; import static org.junit.Assert.assertEquals;
package util; public class TestExitStatus { @Test public void testOK() {
// Path: centipede/src/main/java/com/ontology2/centipede/util/ExitStatus.java // public class ExitStatus { // final public static int OK= 0; /* successful termination */ // final public static int USAGE = 64; /* command line usage error */ // final public static int DATAERR = 65; /* data format error */ // final public static int NOINPUT = 66; /* cannot open input */ // final public static int NOUSER = 67; /* addressee unknown */ // final public static int NOHOST = 68; /* host name unknown */ // final public static int UNAVAILABLE = 69; /* service unavailable */ // final public static int SOFTWARE = 70; /* internal software error */ // final public static int OSERR =71; /* system error (e.g., can't fork) */ // final public static int OSFILE = 72; /* critical OS file missing */ // final public static int CANTCREAT = 73; /* can't create (user) output file */ // final public static int IOERR = 74; /* input/output error */ // final public static int TEMPFAIL = 75; /* temp failure; user is invited to retry */ // final public static int PROTOCOL = 76; /* remote error in protocol */ // final public static int NOPERM = 77; /* permission denied */ // final public static int CONFIG = 78; /* configuration error */ // } // Path: centipede/src/test/java/util/TestExitStatus.java import com.ontology2.centipede.util.ExitStatus; import org.junit.Test; import static org.junit.Assert.assertEquals; package util; public class TestExitStatus { @Test public void testOK() {
assertEquals(0, ExitStatus.OK);
tohodog/QSHttp
qshttp/src/main/java/org/song/http/framework/java/ReadHelp.java
// Path: qshttp/src/main/java/org/song/http/framework/ability/IHttpProgress.java // public interface IHttpProgress { // //当前进度 文件大小 文件名/标记 // void onProgress(long rwLen, long allLen, String mark); // // }
import org.song.http.framework.ability.IHttpProgress; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset;
package org.song.http.framework.java; /** * Created by song on 2017/1/19. */ public class ReadHelp { private InputStream is;
// Path: qshttp/src/main/java/org/song/http/framework/ability/IHttpProgress.java // public interface IHttpProgress { // //当前进度 文件大小 文件名/标记 // void onProgress(long rwLen, long allLen, String mark); // // } // Path: qshttp/src/main/java/org/song/http/framework/java/ReadHelp.java import org.song.http.framework.ability.IHttpProgress; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; package org.song.http.framework.java; /** * Created by song on 2017/1/19. */ public class ReadHelp { private InputStream is;
private IHttpProgress hp;
tohodog/QSHttp
qshttp/src/main/java/org/song/http/framework/HttpResultHandler.java
// Path: qshttp/src/main/java/org/song/http/framework/util/HttpCache.java // public class HttpCache { // // private static HttpCache instance; // private final String TAG = Utils.TAG; // private String path; // // public static HttpCache instance() { // if (instance == null) // instance = new HttpCache(); // instance.path = Utils.getDiskCacheDir(); // return instance; // } // // private HttpCache() { // } // // //检测使用缓存-联网前 // public ResponseParams checkAndGetCache(RequestParams request) { // if (request.cacheMode() == CacheMode.CLIENT_CACHE) { // int cacheTime = request.cacheTime(); // String file_name = getRequestMD5(request) + "_" + cacheTime; // File file = new File(path, file_name); // if (!file.exists()) // return null; // long lastTime = file.lastModified(); // if (lastTime + cacheTime * 1000 < System.currentTimeMillis()) { // file.delete(); // return null; // } // // ResponseParams response = new ResponseParams(); // response.setRequestParams(request); // response.setResultType(request.resultType()); // if (read(response, file_name)) // return response; // } // return null; // } // // // //检测使用缓存-联网失败后 // public boolean checkAndGetErrCache(ResponseParams response) { // if (response.requestParams().cacheMode() != CacheMode.ERR_CACHE) // return false; // String MD5 = getRequestMD5(response.requestParams()); // return read(response, MD5); // } // // //检测持久化缓存-联网成功后 // public boolean checkAndSaveCache(ResponseParams response) { // if (response.isCache()) // return false; // String MD5 = getRequestMD5(response.requestParams()); // // if (response.requestParams().cacheMode() == CacheMode.ERR_CACHE) { // return write(response, MD5); // // } // // if (response.requestParams().cacheMode() == CacheMode.CLIENT_CACHE) { // int time = response.requestParams().cacheTime(); // String file_name = MD5 + "_" + time; // return write(response, file_name); // // } // //... // // return false; // } // // // private boolean read(ResponseParams response, String fileName) { // RequestParams request = response.requestParams(); // String filePath = path + "/" + fileName; // switch (request.resultType()) { // case STRING: // String s = Utils.readString(filePath); // if (s == null) // return false; // Log.i(TAG, "getCache->" + request.url() + "\n" + request.cacheMode() + "->" + s); // response.setString(s); // return true; // case FILE: // response.setFile(request.downloadPath()); // if (Utils.fileCopy(filePath, response.file())) { // Log.i(TAG, "getCache->" + request.url() + "\n" + request.cacheMode() + "->" + response.file()); // return true; // } // case BYTES: // byte[] b = Utils.readBytes(filePath); // if (b == null || b.length == 0) // return false; // Log.i(TAG, "getCache->" + request.url() + "\n" + request.cacheMode() + "->" + b.length); // response.setBytes(b); // return true; // } // return false; // } // // private boolean write(ResponseParams response, String fileName) { // String filePath = path + "/" + fileName; // Log.i(TAG, "saveCache->" + response.requestParams().url() + "\n" + response.requestParams().cacheMode() + "->" + filePath); // switch (response.requestParams().resultType()) { // case STRING: // return Utils.writerString(filePath, response.string()); // case FILE: // return Utils.fileCopy(response.file(), filePath); // case BYTES: // return Utils.writerBytes(filePath, response.bytes()); // } // return false; // } // // // private String getRequestMD5(RequestParams params) { // if (params.requestBody() != null) // return StringToMD5(params.url() + params.requestBody().getContent()); // else // return StringToMD5(params.urlEncode()); // } // // private static String StringToMD5(String string) { // byte[] hash; // // try { // hash = MessageDigest.getInstance("MD5").digest( // string.getBytes("UTF-8")); // } catch (NoSuchAlgorithmException e) { // e.printStackTrace(); // return ""; // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // return ""; // } // // StringBuilder hex = new StringBuilder(hash.length * 2); // for (byte b : hash) { // if ((b & 0xFF) < 0x10) // hex.append("0"); // hex.append(Integer.toHexString(b & 0xFF)); // } // // return hex.toString(); // } // }
import com.alibaba.fastjson.JSON; import org.song.http.framework.util.HttpCache;
package org.song.http.framework; /** * Created by song on 2016/9/18. */ public class HttpResultHandler { /** * 联网完成后进行数据处理 */ public static void onComplete(ResponseParams response, boolean isSync) { if (response.isSuccess()) ThreadHandler.Success(response, isSync); else ThreadHandler.Failure(response, isSync); } public static void dealCache(ResponseParams response) {
// Path: qshttp/src/main/java/org/song/http/framework/util/HttpCache.java // public class HttpCache { // // private static HttpCache instance; // private final String TAG = Utils.TAG; // private String path; // // public static HttpCache instance() { // if (instance == null) // instance = new HttpCache(); // instance.path = Utils.getDiskCacheDir(); // return instance; // } // // private HttpCache() { // } // // //检测使用缓存-联网前 // public ResponseParams checkAndGetCache(RequestParams request) { // if (request.cacheMode() == CacheMode.CLIENT_CACHE) { // int cacheTime = request.cacheTime(); // String file_name = getRequestMD5(request) + "_" + cacheTime; // File file = new File(path, file_name); // if (!file.exists()) // return null; // long lastTime = file.lastModified(); // if (lastTime + cacheTime * 1000 < System.currentTimeMillis()) { // file.delete(); // return null; // } // // ResponseParams response = new ResponseParams(); // response.setRequestParams(request); // response.setResultType(request.resultType()); // if (read(response, file_name)) // return response; // } // return null; // } // // // //检测使用缓存-联网失败后 // public boolean checkAndGetErrCache(ResponseParams response) { // if (response.requestParams().cacheMode() != CacheMode.ERR_CACHE) // return false; // String MD5 = getRequestMD5(response.requestParams()); // return read(response, MD5); // } // // //检测持久化缓存-联网成功后 // public boolean checkAndSaveCache(ResponseParams response) { // if (response.isCache()) // return false; // String MD5 = getRequestMD5(response.requestParams()); // // if (response.requestParams().cacheMode() == CacheMode.ERR_CACHE) { // return write(response, MD5); // // } // // if (response.requestParams().cacheMode() == CacheMode.CLIENT_CACHE) { // int time = response.requestParams().cacheTime(); // String file_name = MD5 + "_" + time; // return write(response, file_name); // // } // //... // // return false; // } // // // private boolean read(ResponseParams response, String fileName) { // RequestParams request = response.requestParams(); // String filePath = path + "/" + fileName; // switch (request.resultType()) { // case STRING: // String s = Utils.readString(filePath); // if (s == null) // return false; // Log.i(TAG, "getCache->" + request.url() + "\n" + request.cacheMode() + "->" + s); // response.setString(s); // return true; // case FILE: // response.setFile(request.downloadPath()); // if (Utils.fileCopy(filePath, response.file())) { // Log.i(TAG, "getCache->" + request.url() + "\n" + request.cacheMode() + "->" + response.file()); // return true; // } // case BYTES: // byte[] b = Utils.readBytes(filePath); // if (b == null || b.length == 0) // return false; // Log.i(TAG, "getCache->" + request.url() + "\n" + request.cacheMode() + "->" + b.length); // response.setBytes(b); // return true; // } // return false; // } // // private boolean write(ResponseParams response, String fileName) { // String filePath = path + "/" + fileName; // Log.i(TAG, "saveCache->" + response.requestParams().url() + "\n" + response.requestParams().cacheMode() + "->" + filePath); // switch (response.requestParams().resultType()) { // case STRING: // return Utils.writerString(filePath, response.string()); // case FILE: // return Utils.fileCopy(response.file(), filePath); // case BYTES: // return Utils.writerBytes(filePath, response.bytes()); // } // return false; // } // // // private String getRequestMD5(RequestParams params) { // if (params.requestBody() != null) // return StringToMD5(params.url() + params.requestBody().getContent()); // else // return StringToMD5(params.urlEncode()); // } // // private static String StringToMD5(String string) { // byte[] hash; // // try { // hash = MessageDigest.getInstance("MD5").digest( // string.getBytes("UTF-8")); // } catch (NoSuchAlgorithmException e) { // e.printStackTrace(); // return ""; // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // return ""; // } // // StringBuilder hex = new StringBuilder(hash.length * 2); // for (byte b : hash) { // if ((b & 0xFF) < 0x10) // hex.append("0"); // hex.append(Integer.toHexString(b & 0xFF)); // } // // return hex.toString(); // } // } // Path: qshttp/src/main/java/org/song/http/framework/HttpResultHandler.java import com.alibaba.fastjson.JSON; import org.song.http.framework.util.HttpCache; package org.song.http.framework; /** * Created by song on 2016/9/18. */ public class HttpResultHandler { /** * 联网完成后进行数据处理 */ public static void onComplete(ResponseParams response, boolean isSync) { if (response.isSuccess()) ThreadHandler.Success(response, isSync); else ThreadHandler.Failure(response, isSync); } public static void dealCache(ResponseParams response) {
HttpCache httpCache = HttpCache.instance();
tohodog/QSHttp
qshttp/src/main/java/org/song/http/framework/ok/ResponseBodyProgress.java
// Path: qshttp/src/main/java/org/song/http/framework/ability/IHttpProgress.java // public interface IHttpProgress { // //当前进度 文件大小 文件名/标记 // void onProgress(long rwLen, long allLen, String mark); // // }
import org.song.http.framework.ability.IHttpProgress; import java.io.IOException; import okhttp3.MediaType; import okhttp3.ResponseBody; import okio.Buffer; import okio.BufferedSource; import okio.ForwardingSource; import okio.Okio; import okio.Source;
package org.song.http.framework.ok; /** * Created by song on 2016/9/24. * 包装添加了文件下载进度的ResponseBody */ public class ResponseBodyProgress extends ResponseBody { private ResponseBody responseBody;
// Path: qshttp/src/main/java/org/song/http/framework/ability/IHttpProgress.java // public interface IHttpProgress { // //当前进度 文件大小 文件名/标记 // void onProgress(long rwLen, long allLen, String mark); // // } // Path: qshttp/src/main/java/org/song/http/framework/ok/ResponseBodyProgress.java import org.song.http.framework.ability.IHttpProgress; import java.io.IOException; import okhttp3.MediaType; import okhttp3.ResponseBody; import okio.Buffer; import okio.BufferedSource; import okio.ForwardingSource; import okio.Okio; import okio.Source; package org.song.http.framework.ok; /** * Created by song on 2016/9/24. * 包装添加了文件下载进度的ResponseBody */ public class ResponseBodyProgress extends ResponseBody { private ResponseBody responseBody;
private IHttpProgress iHttpProgress;
tohodog/QSHttp
qshttp/src/main/java/org/song/http/framework/java/WriteHelp.java
// Path: qshttp/src/main/java/org/song/http/framework/ability/IHttpProgress.java // public interface IHttpProgress { // //当前进度 文件大小 文件名/标记 // void onProgress(long rwLen, long allLen, String mark); // // }
import org.song.http.framework.ability.IHttpProgress; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream;
package org.song.http.framework.java; /** * Created by song on 2017/1/19. */ public class WriteHelp { private OutputStream os;
// Path: qshttp/src/main/java/org/song/http/framework/ability/IHttpProgress.java // public interface IHttpProgress { // //当前进度 文件大小 文件名/标记 // void onProgress(long rwLen, long allLen, String mark); // // } // Path: qshttp/src/main/java/org/song/http/framework/java/WriteHelp.java import org.song.http.framework.ability.IHttpProgress; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; package org.song.http.framework.java; /** * Created by song on 2017/1/19. */ public class WriteHelp { private OutputStream os;
private IHttpProgress hp;
tohodog/QSHttp
qshttp/src/main/java/org/song/http/framework/ThreadHandler.java
// Path: qshttp/src/main/java/org/song/http/framework/ability/HttpCallback.java // public interface HttpCallback { // // void onSuccess(ResponseParams response); // // void onFailure(HttpException e); // // } // // Path: qshttp/src/main/java/org/song/http/framework/ability/HttpCallbackEx.java // public interface HttpCallbackEx extends HttpCallback { // // void onStart(); // // void onEnd(); // // //返回true 则不会回调 // boolean isDestroy(); // } // // Path: qshttp/src/main/java/org/song/http/framework/ability/IHttpProgress.java // public interface IHttpProgress { // //当前进度 文件大小 文件名/标记 // void onProgress(long rwLen, long allLen, String mark); // // }
import android.os.Handler; import android.os.Looper; import android.os.Message; import org.song.http.framework.ability.HttpCallback; import org.song.http.framework.ability.HttpCallbackEx; import org.song.http.framework.ability.IHttpProgress; import java.util.Map; import java.util.concurrent.ConcurrentHashMap;
package org.song.http.framework; /* * Created by song on 2016/9/18. * 子线程联网任务 回调主线程 类 */ public class ThreadHandler extends Handler { private int mThreadWhat = 19930411;
// Path: qshttp/src/main/java/org/song/http/framework/ability/HttpCallback.java // public interface HttpCallback { // // void onSuccess(ResponseParams response); // // void onFailure(HttpException e); // // } // // Path: qshttp/src/main/java/org/song/http/framework/ability/HttpCallbackEx.java // public interface HttpCallbackEx extends HttpCallback { // // void onStart(); // // void onEnd(); // // //返回true 则不会回调 // boolean isDestroy(); // } // // Path: qshttp/src/main/java/org/song/http/framework/ability/IHttpProgress.java // public interface IHttpProgress { // //当前进度 文件大小 文件名/标记 // void onProgress(long rwLen, long allLen, String mark); // // } // Path: qshttp/src/main/java/org/song/http/framework/ThreadHandler.java import android.os.Handler; import android.os.Looper; import android.os.Message; import org.song.http.framework.ability.HttpCallback; import org.song.http.framework.ability.HttpCallbackEx; import org.song.http.framework.ability.IHttpProgress; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; package org.song.http.framework; /* * Created by song on 2016/9/18. * 子线程联网任务 回调主线程 类 */ public class ThreadHandler extends Handler { private int mThreadWhat = 19930411;
private Map<Integer, HttpCallback> sparseArray = new ConcurrentHashMap<>();
tohodog/QSHttp
qshttp/src/main/java/org/song/http/framework/ThreadHandler.java
// Path: qshttp/src/main/java/org/song/http/framework/ability/HttpCallback.java // public interface HttpCallback { // // void onSuccess(ResponseParams response); // // void onFailure(HttpException e); // // } // // Path: qshttp/src/main/java/org/song/http/framework/ability/HttpCallbackEx.java // public interface HttpCallbackEx extends HttpCallback { // // void onStart(); // // void onEnd(); // // //返回true 则不会回调 // boolean isDestroy(); // } // // Path: qshttp/src/main/java/org/song/http/framework/ability/IHttpProgress.java // public interface IHttpProgress { // //当前进度 文件大小 文件名/标记 // void onProgress(long rwLen, long allLen, String mark); // // }
import android.os.Handler; import android.os.Looper; import android.os.Message; import org.song.http.framework.ability.HttpCallback; import org.song.http.framework.ability.HttpCallbackEx; import org.song.http.framework.ability.IHttpProgress; import java.util.Map; import java.util.concurrent.ConcurrentHashMap;
package org.song.http.framework; /* * Created by song on 2016/9/18. * 子线程联网任务 回调主线程 类 */ public class ThreadHandler extends Handler { private int mThreadWhat = 19930411; private Map<Integer, HttpCallback> sparseArray = new ConcurrentHashMap<>(); // private SparseArray<HttpCallback> sparseArray = new SparseArray<>(); private ThreadHandler() { super(Looper.getMainLooper()); } private static ThreadHandler instance; private static ThreadHandler getInstance() { if (instance == null) instance = new ThreadHandler(); return instance; } public synchronized int addHttpDataCallback(final HttpCallback cb) { mThreadWhat++; sparseArray.put(mThreadWhat, cb);
// Path: qshttp/src/main/java/org/song/http/framework/ability/HttpCallback.java // public interface HttpCallback { // // void onSuccess(ResponseParams response); // // void onFailure(HttpException e); // // } // // Path: qshttp/src/main/java/org/song/http/framework/ability/HttpCallbackEx.java // public interface HttpCallbackEx extends HttpCallback { // // void onStart(); // // void onEnd(); // // //返回true 则不会回调 // boolean isDestroy(); // } // // Path: qshttp/src/main/java/org/song/http/framework/ability/IHttpProgress.java // public interface IHttpProgress { // //当前进度 文件大小 文件名/标记 // void onProgress(long rwLen, long allLen, String mark); // // } // Path: qshttp/src/main/java/org/song/http/framework/ThreadHandler.java import android.os.Handler; import android.os.Looper; import android.os.Message; import org.song.http.framework.ability.HttpCallback; import org.song.http.framework.ability.HttpCallbackEx; import org.song.http.framework.ability.IHttpProgress; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; package org.song.http.framework; /* * Created by song on 2016/9/18. * 子线程联网任务 回调主线程 类 */ public class ThreadHandler extends Handler { private int mThreadWhat = 19930411; private Map<Integer, HttpCallback> sparseArray = new ConcurrentHashMap<>(); // private SparseArray<HttpCallback> sparseArray = new SparseArray<>(); private ThreadHandler() { super(Looper.getMainLooper()); } private static ThreadHandler instance; private static ThreadHandler getInstance() { if (instance == null) instance = new ThreadHandler(); return instance; } public synchronized int addHttpDataCallback(final HttpCallback cb) { mThreadWhat++; sparseArray.put(mThreadWhat, cb);
if (cb instanceof HttpCallbackEx) {
tohodog/QSHttp
qshttp/src/main/java/org/song/http/framework/ThreadHandler.java
// Path: qshttp/src/main/java/org/song/http/framework/ability/HttpCallback.java // public interface HttpCallback { // // void onSuccess(ResponseParams response); // // void onFailure(HttpException e); // // } // // Path: qshttp/src/main/java/org/song/http/framework/ability/HttpCallbackEx.java // public interface HttpCallbackEx extends HttpCallback { // // void onStart(); // // void onEnd(); // // //返回true 则不会回调 // boolean isDestroy(); // } // // Path: qshttp/src/main/java/org/song/http/framework/ability/IHttpProgress.java // public interface IHttpProgress { // //当前进度 文件大小 文件名/标记 // void onProgress(long rwLen, long allLen, String mark); // // }
import android.os.Handler; import android.os.Looper; import android.os.Message; import org.song.http.framework.ability.HttpCallback; import org.song.http.framework.ability.HttpCallbackEx; import org.song.http.framework.ability.IHttpProgress; import java.util.Map; import java.util.concurrent.ConcurrentHashMap;
final int what = message.what; HttpCallback cb = sparseArray.get(what); if (cb == null) { sparseArray.remove(what); return; } switch (message.arg1) { case HttpEnum.HTTP_SUCCESS: sparseArray.remove(what); if (cb instanceof HttpCallbackEx && ((HttpCallbackEx) cb).isDestroy()) break; ResponseParams responseParams = (ResponseParams) message.obj; try { cb.onSuccess(responseParams); } catch (Exception e) { e.printStackTrace(); cb.onFailure(HttpException.Run(e).responseParams(responseParams)); } if (cb instanceof HttpCallbackEx) ((HttpCallbackEx) cb).onEnd(); break; case HttpEnum.HTTP_FAILURE: sparseArray.remove(what); if (cb instanceof HttpCallbackEx && ((HttpCallbackEx) cb).isDestroy()) break; cb.onFailure((HttpException) message.obj); if (cb instanceof HttpCallbackEx) ((HttpCallbackEx) cb).onEnd(); break; case HttpEnum.HTTP_PROGRESS:
// Path: qshttp/src/main/java/org/song/http/framework/ability/HttpCallback.java // public interface HttpCallback { // // void onSuccess(ResponseParams response); // // void onFailure(HttpException e); // // } // // Path: qshttp/src/main/java/org/song/http/framework/ability/HttpCallbackEx.java // public interface HttpCallbackEx extends HttpCallback { // // void onStart(); // // void onEnd(); // // //返回true 则不会回调 // boolean isDestroy(); // } // // Path: qshttp/src/main/java/org/song/http/framework/ability/IHttpProgress.java // public interface IHttpProgress { // //当前进度 文件大小 文件名/标记 // void onProgress(long rwLen, long allLen, String mark); // // } // Path: qshttp/src/main/java/org/song/http/framework/ThreadHandler.java import android.os.Handler; import android.os.Looper; import android.os.Message; import org.song.http.framework.ability.HttpCallback; import org.song.http.framework.ability.HttpCallbackEx; import org.song.http.framework.ability.IHttpProgress; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; final int what = message.what; HttpCallback cb = sparseArray.get(what); if (cb == null) { sparseArray.remove(what); return; } switch (message.arg1) { case HttpEnum.HTTP_SUCCESS: sparseArray.remove(what); if (cb instanceof HttpCallbackEx && ((HttpCallbackEx) cb).isDestroy()) break; ResponseParams responseParams = (ResponseParams) message.obj; try { cb.onSuccess(responseParams); } catch (Exception e) { e.printStackTrace(); cb.onFailure(HttpException.Run(e).responseParams(responseParams)); } if (cb instanceof HttpCallbackEx) ((HttpCallbackEx) cb).onEnd(); break; case HttpEnum.HTTP_FAILURE: sparseArray.remove(what); if (cb instanceof HttpCallbackEx && ((HttpCallbackEx) cb).isDestroy()) break; cb.onFailure((HttpException) message.obj); if (cb instanceof HttpCallbackEx) ((HttpCallbackEx) cb).onEnd(); break; case HttpEnum.HTTP_PROGRESS:
if (cb instanceof IHttpProgress) {
tohodog/QSHttp
qshttp/src/main/java/org/song/http/framework/QSHttpConfig.java
// Path: qshttp/src/main/java/org/song/http/framework/ability/Interceptor.java // public interface Interceptor { // ResponseParams intercept(Chain chain) throws HttpException; // // interface Chain { // RequestParams request();//请求参数 // // ResponseParams proceed(RequestParams request) throws HttpException;//流程继续 // } // }
import android.app.Application; import android.net.Network; import android.os.Build; import org.song.http.framework.ability.Interceptor; import java.util.ArrayList; import java.util.List; import javax.net.SocketFactory; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSocketFactory;
package org.song.http.framework; /** * Created by song on 2019/4/2. * http框架全局配置 */ public class QSHttpConfig { private boolean debug; private Application application; private HttpEnum.XX_Http xxHttp; private String cachePath; private String baseUrl;
// Path: qshttp/src/main/java/org/song/http/framework/ability/Interceptor.java // public interface Interceptor { // ResponseParams intercept(Chain chain) throws HttpException; // // interface Chain { // RequestParams request();//请求参数 // // ResponseParams proceed(RequestParams request) throws HttpException;//流程继续 // } // } // Path: qshttp/src/main/java/org/song/http/framework/QSHttpConfig.java import android.app.Application; import android.net.Network; import android.os.Build; import org.song.http.framework.ability.Interceptor; import java.util.ArrayList; import java.util.List; import javax.net.SocketFactory; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSocketFactory; package org.song.http.framework; /** * Created by song on 2019/4/2. * http框架全局配置 */ public class QSHttpConfig { private boolean debug; private Application application; private HttpEnum.XX_Http xxHttp; private String cachePath; private String baseUrl;
private List<Interceptor> interceptorList;
mucaho/jnetrobust
jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/control/SentMapControlTest.java
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/SystemClock.java // public interface SystemClock { // long getTimeNow(); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static <T> Object $(T param) { // return createArray(getClass(param), param); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static Object $S(int... params) { // Short[] out = new Short[params.length]; // for (int i = 0; i < out.length; ++i) { // out[i] = (short) params[i]; // } // return out; // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/util/TestUtils.java // public final static int binInt(String binaryString) { // return Integer.parseInt(binaryString, 2); // }
import com.github.mucaho.jnetrobust.util.SystemClock; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import mockit.Invocation; import mockit.Mock; import mockit.MockUp; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.HashSet; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$S; import static com.github.mucaho.jnetrobust.util.TestUtils.binInt; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue;
/* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; @RunWith(JUnitParamsRunner.class) public class SentMapControlTest extends AbstractMapControlTest { protected SentMapControl handler = new SentMapControl(null, config.getPacketQueueLimit(), config.getPacketOffsetLimit(), config.getPacketRetransmitLimit() + 1,
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/SystemClock.java // public interface SystemClock { // long getTimeNow(); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static <T> Object $(T param) { // return createArray(getClass(param), param); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static Object $S(int... params) { // Short[] out = new Short[params.length]; // for (int i = 0; i < out.length; ++i) { // out[i] = (short) params[i]; // } // return out; // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/util/TestUtils.java // public final static int binInt(String binaryString) { // return Integer.parseInt(binaryString, 2); // } // Path: jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/control/SentMapControlTest.java import com.github.mucaho.jnetrobust.util.SystemClock; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import mockit.Invocation; import mockit.Mock; import mockit.MockUp; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.HashSet; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$S; import static com.github.mucaho.jnetrobust.util.TestUtils.binInt; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; @RunWith(JUnitParamsRunner.class) public class SentMapControlTest extends AbstractMapControlTest { protected SentMapControl handler = new SentMapControl(null, config.getPacketQueueLimit(), config.getPacketOffsetLimit(), config.getPacketRetransmitLimit() + 1,
config.getPacketQueueTimeout(), new SystemClock() {
mucaho/jnetrobust
jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/control/SentMapControlTest.java
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/SystemClock.java // public interface SystemClock { // long getTimeNow(); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static <T> Object $(T param) { // return createArray(getClass(param), param); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static Object $S(int... params) { // Short[] out = new Short[params.length]; // for (int i = 0; i < out.length; ++i) { // out[i] = (short) params[i]; // } // return out; // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/util/TestUtils.java // public final static int binInt(String binaryString) { // return Integer.parseInt(binaryString, 2); // }
import com.github.mucaho.jnetrobust.util.SystemClock; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import mockit.Invocation; import mockit.Mock; import mockit.MockUp; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.HashSet; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$S; import static com.github.mucaho.jnetrobust.util.TestUtils.binInt; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue;
/* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; @RunWith(JUnitParamsRunner.class) public class SentMapControlTest extends AbstractMapControlTest { protected SentMapControl handler = new SentMapControl(null, config.getPacketQueueLimit(), config.getPacketOffsetLimit(), config.getPacketRetransmitLimit() + 1, config.getPacketQueueTimeout(), new SystemClock() { @Override public long getTimeNow() { return System.currentTimeMillis(); } }); public SentMapControlTest() { initDataMap(handler); } @Before public final void prepareTest() { dataMap.clear(); } public Object[][] parametersForTestRemoveFromPending() { // MultiRefObject: // * it is important what the first reference is (first short in each line) // * order of insertion must be equal to order of removal for testing purposes (order of lines) Object[][] out = (Object[][])
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/SystemClock.java // public interface SystemClock { // long getTimeNow(); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static <T> Object $(T param) { // return createArray(getClass(param), param); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static Object $S(int... params) { // Short[] out = new Short[params.length]; // for (int i = 0; i < out.length; ++i) { // out[i] = (short) params[i]; // } // return out; // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/util/TestUtils.java // public final static int binInt(String binaryString) { // return Integer.parseInt(binaryString, 2); // } // Path: jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/control/SentMapControlTest.java import com.github.mucaho.jnetrobust.util.SystemClock; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import mockit.Invocation; import mockit.Mock; import mockit.MockUp; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.HashSet; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$S; import static com.github.mucaho.jnetrobust.util.TestUtils.binInt; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; @RunWith(JUnitParamsRunner.class) public class SentMapControlTest extends AbstractMapControlTest { protected SentMapControl handler = new SentMapControl(null, config.getPacketQueueLimit(), config.getPacketOffsetLimit(), config.getPacketRetransmitLimit() + 1, config.getPacketQueueTimeout(), new SystemClock() { @Override public long getTimeNow() { return System.currentTimeMillis(); } }); public SentMapControlTest() { initDataMap(handler); } @Before public final void prepareTest() { dataMap.clear(); } public Object[][] parametersForTestRemoveFromPending() { // MultiRefObject: // * it is important what the first reference is (first short in each line) // * order of insertion must be equal to order of removal for testing purposes (order of lines) Object[][] out = (Object[][])
$($(
mucaho/jnetrobust
jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/control/SentMapControlTest.java
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/SystemClock.java // public interface SystemClock { // long getTimeNow(); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static <T> Object $(T param) { // return createArray(getClass(param), param); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static Object $S(int... params) { // Short[] out = new Short[params.length]; // for (int i = 0; i < out.length; ++i) { // out[i] = (short) params[i]; // } // return out; // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/util/TestUtils.java // public final static int binInt(String binaryString) { // return Integer.parseInt(binaryString, 2); // }
import com.github.mucaho.jnetrobust.util.SystemClock; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import mockit.Invocation; import mockit.Mock; import mockit.MockUp; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.HashSet; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$S; import static com.github.mucaho.jnetrobust.util.TestUtils.binInt; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue;
/* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; @RunWith(JUnitParamsRunner.class) public class SentMapControlTest extends AbstractMapControlTest { protected SentMapControl handler = new SentMapControl(null, config.getPacketQueueLimit(), config.getPacketOffsetLimit(), config.getPacketRetransmitLimit() + 1, config.getPacketQueueTimeout(), new SystemClock() { @Override public long getTimeNow() { return System.currentTimeMillis(); } }); public SentMapControlTest() { initDataMap(handler); } @Before public final void prepareTest() { dataMap.clear(); } public Object[][] parametersForTestRemoveFromPending() { // MultiRefObject: // * it is important what the first reference is (first short in each line) // * order of insertion must be equal to order of removal for testing purposes (order of lines) Object[][] out = (Object[][]) $($(
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/SystemClock.java // public interface SystemClock { // long getTimeNow(); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static <T> Object $(T param) { // return createArray(getClass(param), param); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static Object $S(int... params) { // Short[] out = new Short[params.length]; // for (int i = 0; i < out.length; ++i) { // out[i] = (short) params[i]; // } // return out; // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/util/TestUtils.java // public final static int binInt(String binaryString) { // return Integer.parseInt(binaryString, 2); // } // Path: jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/control/SentMapControlTest.java import com.github.mucaho.jnetrobust.util.SystemClock; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import mockit.Invocation; import mockit.Mock; import mockit.MockUp; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.HashSet; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$S; import static com.github.mucaho.jnetrobust.util.TestUtils.binInt; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; @RunWith(JUnitParamsRunner.class) public class SentMapControlTest extends AbstractMapControlTest { protected SentMapControl handler = new SentMapControl(null, config.getPacketQueueLimit(), config.getPacketOffsetLimit(), config.getPacketRetransmitLimit() + 1, config.getPacketQueueTimeout(), new SystemClock() { @Override public long getTimeNow() { return System.currentTimeMillis(); } }); public SentMapControlTest() { initDataMap(handler); } @Before public final void prepareTest() { dataMap.clear(); } public Object[][] parametersForTestRemoveFromPending() { // MultiRefObject: // * it is important what the first reference is (first short in each line) // * order of insertion must be equal to order of removal for testing purposes (order of lines) Object[][] out = (Object[][]) $($(
(short) 10, binInt("0"), $($S(10))
mucaho/jnetrobust
jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/control/SentMapControlTest.java
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/SystemClock.java // public interface SystemClock { // long getTimeNow(); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static <T> Object $(T param) { // return createArray(getClass(param), param); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static Object $S(int... params) { // Short[] out = new Short[params.length]; // for (int i = 0; i < out.length; ++i) { // out[i] = (short) params[i]; // } // return out; // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/util/TestUtils.java // public final static int binInt(String binaryString) { // return Integer.parseInt(binaryString, 2); // }
import com.github.mucaho.jnetrobust.util.SystemClock; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import mockit.Invocation; import mockit.Mock; import mockit.MockUp; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.HashSet; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$S; import static com.github.mucaho.jnetrobust.util.TestUtils.binInt; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue;
/* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; @RunWith(JUnitParamsRunner.class) public class SentMapControlTest extends AbstractMapControlTest { protected SentMapControl handler = new SentMapControl(null, config.getPacketQueueLimit(), config.getPacketOffsetLimit(), config.getPacketRetransmitLimit() + 1, config.getPacketQueueTimeout(), new SystemClock() { @Override public long getTimeNow() { return System.currentTimeMillis(); } }); public SentMapControlTest() { initDataMap(handler); } @Before public final void prepareTest() { dataMap.clear(); } public Object[][] parametersForTestRemoveFromPending() { // MultiRefObject: // * it is important what the first reference is (first short in each line) // * order of insertion must be equal to order of removal for testing purposes (order of lines) Object[][] out = (Object[][]) $($(
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/SystemClock.java // public interface SystemClock { // long getTimeNow(); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static <T> Object $(T param) { // return createArray(getClass(param), param); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static Object $S(int... params) { // Short[] out = new Short[params.length]; // for (int i = 0; i < out.length; ++i) { // out[i] = (short) params[i]; // } // return out; // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/util/TestUtils.java // public final static int binInt(String binaryString) { // return Integer.parseInt(binaryString, 2); // } // Path: jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/control/SentMapControlTest.java import com.github.mucaho.jnetrobust.util.SystemClock; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import mockit.Invocation; import mockit.Mock; import mockit.MockUp; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.HashSet; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$S; import static com.github.mucaho.jnetrobust.util.TestUtils.binInt; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; @RunWith(JUnitParamsRunner.class) public class SentMapControlTest extends AbstractMapControlTest { protected SentMapControl handler = new SentMapControl(null, config.getPacketQueueLimit(), config.getPacketOffsetLimit(), config.getPacketRetransmitLimit() + 1, config.getPacketQueueTimeout(), new SystemClock() { @Override public long getTimeNow() { return System.currentTimeMillis(); } }); public SentMapControlTest() { initDataMap(handler); } @Before public final void prepareTest() { dataMap.clear(); } public Object[][] parametersForTestRemoveFromPending() { // MultiRefObject: // * it is important what the first reference is (first short in each line) // * order of insertion must be equal to order of removal for testing purposes (order of lines) Object[][] out = (Object[][]) $($(
(short) 10, binInt("0"), $($S(10))
mucaho/jnetrobust
jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/ShiftableBitSet.java
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/BitConstants.java // public static final long LSB = 0x1L; // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/BitConstants.java // public static final int SIZE = Long.SIZE;
import static com.github.mucaho.jnetrobust.util.BitConstants.LSB; import static com.github.mucaho.jnetrobust.util.BitConstants.SIZE;
} public long get() { return this.bits; } public int getInt() { return (int) bits; } public void shift(int i) { if (i >= 0) { this.shiftLeft(i); } else { this.shiftRight(-i); } } public void shiftRight(int i) { bits >>>= i; } public void shiftLeft(int i) { bits <<= i; } private void setBit(int index, boolean set) { if (set) {
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/BitConstants.java // public static final long LSB = 0x1L; // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/BitConstants.java // public static final int SIZE = Long.SIZE; // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/ShiftableBitSet.java import static com.github.mucaho.jnetrobust.util.BitConstants.LSB; import static com.github.mucaho.jnetrobust.util.BitConstants.SIZE; } public long get() { return this.bits; } public int getInt() { return (int) bits; } public void shift(int i) { if (i >= 0) { this.shiftLeft(i); } else { this.shiftRight(-i); } } public void shiftRight(int i) { bits >>>= i; } public void shiftLeft(int i) { bits <<= i; } private void setBit(int index, boolean set) { if (set) {
bits |= LSB << index;
mucaho/jnetrobust
jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/ShiftableBitSet.java
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/BitConstants.java // public static final long LSB = 0x1L; // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/BitConstants.java // public static final int SIZE = Long.SIZE;
import static com.github.mucaho.jnetrobust.util.BitConstants.LSB; import static com.github.mucaho.jnetrobust.util.BitConstants.SIZE;
return (int) bits; } public void shift(int i) { if (i >= 0) { this.shiftLeft(i); } else { this.shiftRight(-i); } } public void shiftRight(int i) { bits >>>= i; } public void shiftLeft(int i) { bits <<= i; } private void setBit(int index, boolean set) { if (set) { bits |= LSB << index; } else { bits &= ~(LSB << index); } } public void setHighestBit(boolean set) {
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/BitConstants.java // public static final long LSB = 0x1L; // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/BitConstants.java // public static final int SIZE = Long.SIZE; // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/ShiftableBitSet.java import static com.github.mucaho.jnetrobust.util.BitConstants.LSB; import static com.github.mucaho.jnetrobust.util.BitConstants.SIZE; return (int) bits; } public void shift(int i) { if (i >= 0) { this.shiftLeft(i); } else { this.shiftRight(-i); } } public void shiftRight(int i) { bits >>>= i; } public void shiftLeft(int i) { bits <<= i; } private void setBit(int index, boolean set) { if (set) { bits |= LSB << index; } else { bits &= ~(LSB << index); } } public void setHighestBit(boolean set) {
this.setBit(SIZE - 1, set);
mucaho/jnetrobust
jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/control/SegmentTest.java
// Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static <T> Object $(T param) { // return createArray(getClass(param), param); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static Object $S(int... params) { // Short[] out = new Short[params.length]; // for (int i = 0; i < out.length; ++i) { // out[i] = (short) params[i]; // } // return out; // }
import junitparams.JUnitParamsRunner; import junitparams.Parameters; import mockit.Deencapsulation; import org.junit.Test; import org.junit.runner.RunWith; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.NavigableSet; import java.util.TreeSet; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$S; import static org.junit.Assert.*;
/* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; @RunWith(JUnitParamsRunner.class) public class SegmentTest { public Object[][] parametersForTestReferences() { Segment segment2 = new Segment(); segment2.addTransmissionId((short)2); Segment segment22 = new Segment(); segment22.addTransmissionId((short)2); segment22.addTransmissionId((short)2); Segment segment345 = new Segment(); segment345.addTransmissionId((short)3); segment345.addTransmissionId((short)4); segment345.addTransmissionId((short)5); Object[][] out = (Object[][])
// Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static <T> Object $(T param) { // return createArray(getClass(param), param); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static Object $S(int... params) { // Short[] out = new Short[params.length]; // for (int i = 0; i < out.length; ++i) { // out[i] = (short) params[i]; // } // return out; // } // Path: jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/control/SegmentTest.java import junitparams.JUnitParamsRunner; import junitparams.Parameters; import mockit.Deencapsulation; import org.junit.Test; import org.junit.runner.RunWith; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.NavigableSet; import java.util.TreeSet; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$S; import static org.junit.Assert.*; /* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; @RunWith(JUnitParamsRunner.class) public class SegmentTest { public Object[][] parametersForTestReferences() { Segment segment2 = new Segment(); segment2.addTransmissionId((short)2); Segment segment22 = new Segment(); segment22.addTransmissionId((short)2); segment22.addTransmissionId((short)2); Segment segment345 = new Segment(); segment345.addTransmissionId((short)3); segment345.addTransmissionId((short)4); segment345.addTransmissionId((short)5); Object[][] out = (Object[][])
$($(
mucaho/jnetrobust
jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/control/SegmentTest.java
// Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static <T> Object $(T param) { // return createArray(getClass(param), param); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static Object $S(int... params) { // Short[] out = new Short[params.length]; // for (int i = 0; i < out.length; ++i) { // out[i] = (short) params[i]; // } // return out; // }
import junitparams.JUnitParamsRunner; import junitparams.Parameters; import mockit.Deencapsulation; import org.junit.Test; import org.junit.runner.RunWith; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.NavigableSet; import java.util.TreeSet; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$S; import static org.junit.Assert.*;
/* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; @RunWith(JUnitParamsRunner.class) public class SegmentTest { public Object[][] parametersForTestReferences() { Segment segment2 = new Segment(); segment2.addTransmissionId((short)2); Segment segment22 = new Segment(); segment22.addTransmissionId((short)2); segment22.addTransmissionId((short)2); Segment segment345 = new Segment(); segment345.addTransmissionId((short)3); segment345.addTransmissionId((short)4); segment345.addTransmissionId((short)5); Object[][] out = (Object[][]) $($(
// Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static <T> Object $(T param) { // return createArray(getClass(param), param); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static Object $S(int... params) { // Short[] out = new Short[params.length]; // for (int i = 0; i < out.length; ++i) { // out[i] = (short) params[i]; // } // return out; // } // Path: jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/control/SegmentTest.java import junitparams.JUnitParamsRunner; import junitparams.Parameters; import mockit.Deencapsulation; import org.junit.Test; import org.junit.runner.RunWith; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.NavigableSet; import java.util.TreeSet; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$S; import static org.junit.Assert.*; /* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; @RunWith(JUnitParamsRunner.class) public class SegmentTest { public Object[][] parametersForTestReferences() { Segment segment2 = new Segment(); segment2.addTransmissionId((short)2); Segment segment22 = new Segment(); segment22.addTransmissionId((short)2); segment22.addTransmissionId((short)2); Segment segment345 = new Segment(); segment345.addTransmissionId((short)3); segment345.addTransmissionId((short)4); segment345.addTransmissionId((short)5); Object[][] out = (Object[][]) $($(
new Segment(), true, $S(2), $S(2)
mucaho/jnetrobust
jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/control/SentSegmentMapIterTest.java
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/EntryIterator.java // public interface EntryIterator<K, V> { // // /** // * Returns the next key higher than the current key. // * // * @param currentKey the current key to be used in the lookup of the higher key // * or null to retrieve the first key // * @return <K> the next key higher than the current key or the first key // * or null if there is no higher key // */ // K getHigherKey(K currentKey); // // /** // * Returns the next key lower than the current key. // * // * @param currentKey the current key to be used in the lookup of the lower key // * or null to retrieve the last key // * @return <K> the previous key lower than the current key or the last key // * or null if there is no lower key // */ // K getLowerKey(K currentKey); // // /** // * Returns the value at the current key. // * // * @param currentKey the current key that is mapped to the returned value // * @return <V> the value bound to the current key // */ // V getValue(K currentKey); // // /** // * Removes the mapping the current key. // * // * @param currentKey the current key that is to be removed // * @return <V> the value bound to the current key // */ // V removeValue(K currentKey); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static <T> Object $(T param) { // return createArray(getClass(param), param); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static Object $S(int... params) { // Short[] out = new Short[params.length]; // for (int i = 0; i < out.length; ++i) { // out[i] = (short) params[i]; // } // return out; // }
import junitparams.JUnitParamsRunner; import junitparams.Parameters; import com.github.mucaho.jnetrobust.util.EntryIterator; import org.junit.Test; import org.junit.runner.RunWith; import java.nio.ByteBuffer; import java.util.*; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$S; import static org.junit.Assert.assertEquals;
/* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; @RunWith(JUnitParamsRunner.class) public class SentSegmentMapIterTest { private static short dataId = Short.MIN_VALUE; protected static ByteBuffer serializeShorts(Short[] numbers) { ByteBuffer buffer = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE + numbers.length * Short.SIZE / Byte.SIZE); buffer.putInt(numbers.length); for (short number : numbers) buffer.putShort(number); buffer.flip(); return buffer; } protected static Short[] deserializeShorts(ByteBuffer data) { int size = data.getInt(); Short[] numbers = new Short[size]; for (int i = 0; i < size; ++i) { numbers[i] = data.getShort(); } return numbers; } public Object[][] parametersForTestIterator() { Object[][] out = (Object[][])
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/EntryIterator.java // public interface EntryIterator<K, V> { // // /** // * Returns the next key higher than the current key. // * // * @param currentKey the current key to be used in the lookup of the higher key // * or null to retrieve the first key // * @return <K> the next key higher than the current key or the first key // * or null if there is no higher key // */ // K getHigherKey(K currentKey); // // /** // * Returns the next key lower than the current key. // * // * @param currentKey the current key to be used in the lookup of the lower key // * or null to retrieve the last key // * @return <K> the previous key lower than the current key or the last key // * or null if there is no lower key // */ // K getLowerKey(K currentKey); // // /** // * Returns the value at the current key. // * // * @param currentKey the current key that is mapped to the returned value // * @return <V> the value bound to the current key // */ // V getValue(K currentKey); // // /** // * Removes the mapping the current key. // * // * @param currentKey the current key that is to be removed // * @return <V> the value bound to the current key // */ // V removeValue(K currentKey); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static <T> Object $(T param) { // return createArray(getClass(param), param); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static Object $S(int... params) { // Short[] out = new Short[params.length]; // for (int i = 0; i < out.length; ++i) { // out[i] = (short) params[i]; // } // return out; // } // Path: jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/control/SentSegmentMapIterTest.java import junitparams.JUnitParamsRunner; import junitparams.Parameters; import com.github.mucaho.jnetrobust.util.EntryIterator; import org.junit.Test; import org.junit.runner.RunWith; import java.nio.ByteBuffer; import java.util.*; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$S; import static org.junit.Assert.assertEquals; /* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; @RunWith(JUnitParamsRunner.class) public class SentSegmentMapIterTest { private static short dataId = Short.MIN_VALUE; protected static ByteBuffer serializeShorts(Short[] numbers) { ByteBuffer buffer = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE + numbers.length * Short.SIZE / Byte.SIZE); buffer.putInt(numbers.length); for (short number : numbers) buffer.putShort(number); buffer.flip(); return buffer; } protected static Short[] deserializeShorts(ByteBuffer data) { int size = data.getInt(); Short[] numbers = new Short[size]; for (int i = 0; i < size; ++i) { numbers[i] = data.getShort(); } return numbers; } public Object[][] parametersForTestIterator() { Object[][] out = (Object[][])
$($(
mucaho/jnetrobust
jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/control/SentSegmentMapIterTest.java
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/EntryIterator.java // public interface EntryIterator<K, V> { // // /** // * Returns the next key higher than the current key. // * // * @param currentKey the current key to be used in the lookup of the higher key // * or null to retrieve the first key // * @return <K> the next key higher than the current key or the first key // * or null if there is no higher key // */ // K getHigherKey(K currentKey); // // /** // * Returns the next key lower than the current key. // * // * @param currentKey the current key to be used in the lookup of the lower key // * or null to retrieve the last key // * @return <K> the previous key lower than the current key or the last key // * or null if there is no lower key // */ // K getLowerKey(K currentKey); // // /** // * Returns the value at the current key. // * // * @param currentKey the current key that is mapped to the returned value // * @return <V> the value bound to the current key // */ // V getValue(K currentKey); // // /** // * Removes the mapping the current key. // * // * @param currentKey the current key that is to be removed // * @return <V> the value bound to the current key // */ // V removeValue(K currentKey); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static <T> Object $(T param) { // return createArray(getClass(param), param); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static Object $S(int... params) { // Short[] out = new Short[params.length]; // for (int i = 0; i < out.length; ++i) { // out[i] = (short) params[i]; // } // return out; // }
import junitparams.JUnitParamsRunner; import junitparams.Parameters; import com.github.mucaho.jnetrobust.util.EntryIterator; import org.junit.Test; import org.junit.runner.RunWith; import java.nio.ByteBuffer; import java.util.*; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$S; import static org.junit.Assert.assertEquals;
/* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; @RunWith(JUnitParamsRunner.class) public class SentSegmentMapIterTest { private static short dataId = Short.MIN_VALUE; protected static ByteBuffer serializeShorts(Short[] numbers) { ByteBuffer buffer = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE + numbers.length * Short.SIZE / Byte.SIZE); buffer.putInt(numbers.length); for (short number : numbers) buffer.putShort(number); buffer.flip(); return buffer; } protected static Short[] deserializeShorts(ByteBuffer data) { int size = data.getInt(); Short[] numbers = new Short[size]; for (int i = 0; i < size; ++i) { numbers[i] = data.getShort(); } return numbers; } public Object[][] parametersForTestIterator() { Object[][] out = (Object[][]) $($(
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/EntryIterator.java // public interface EntryIterator<K, V> { // // /** // * Returns the next key higher than the current key. // * // * @param currentKey the current key to be used in the lookup of the higher key // * or null to retrieve the first key // * @return <K> the next key higher than the current key or the first key // * or null if there is no higher key // */ // K getHigherKey(K currentKey); // // /** // * Returns the next key lower than the current key. // * // * @param currentKey the current key to be used in the lookup of the lower key // * or null to retrieve the last key // * @return <K> the previous key lower than the current key or the last key // * or null if there is no lower key // */ // K getLowerKey(K currentKey); // // /** // * Returns the value at the current key. // * // * @param currentKey the current key that is mapped to the returned value // * @return <V> the value bound to the current key // */ // V getValue(K currentKey); // // /** // * Removes the mapping the current key. // * // * @param currentKey the current key that is to be removed // * @return <V> the value bound to the current key // */ // V removeValue(K currentKey); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static <T> Object $(T param) { // return createArray(getClass(param), param); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static Object $S(int... params) { // Short[] out = new Short[params.length]; // for (int i = 0; i < out.length; ++i) { // out[i] = (short) params[i]; // } // return out; // } // Path: jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/control/SentSegmentMapIterTest.java import junitparams.JUnitParamsRunner; import junitparams.Parameters; import com.github.mucaho.jnetrobust.util.EntryIterator; import org.junit.Test; import org.junit.runner.RunWith; import java.nio.ByteBuffer; import java.util.*; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$S; import static org.junit.Assert.assertEquals; /* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; @RunWith(JUnitParamsRunner.class) public class SentSegmentMapIterTest { private static short dataId = Short.MIN_VALUE; protected static ByteBuffer serializeShorts(Short[] numbers) { ByteBuffer buffer = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE + numbers.length * Short.SIZE / Byte.SIZE); buffer.putInt(numbers.length); for (short number : numbers) buffer.putShort(number); buffer.flip(); return buffer; } protected static Short[] deserializeShorts(ByteBuffer data) { int size = data.getInt(); Short[] numbers = new Short[size]; for (int i = 0; i < size; ++i) { numbers[i] = data.getShort(); } return numbers; } public Object[][] parametersForTestIterator() { Object[][] out = (Object[][]) $($(
$($S(1, 2, 3), $S(4, 5), $S(7, 9), $S(8, 10))
mucaho/jnetrobust
jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/control/SentSegmentMapIterTest.java
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/EntryIterator.java // public interface EntryIterator<K, V> { // // /** // * Returns the next key higher than the current key. // * // * @param currentKey the current key to be used in the lookup of the higher key // * or null to retrieve the first key // * @return <K> the next key higher than the current key or the first key // * or null if there is no higher key // */ // K getHigherKey(K currentKey); // // /** // * Returns the next key lower than the current key. // * // * @param currentKey the current key to be used in the lookup of the lower key // * or null to retrieve the last key // * @return <K> the previous key lower than the current key or the last key // * or null if there is no lower key // */ // K getLowerKey(K currentKey); // // /** // * Returns the value at the current key. // * // * @param currentKey the current key that is mapped to the returned value // * @return <V> the value bound to the current key // */ // V getValue(K currentKey); // // /** // * Removes the mapping the current key. // * // * @param currentKey the current key that is to be removed // * @return <V> the value bound to the current key // */ // V removeValue(K currentKey); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static <T> Object $(T param) { // return createArray(getClass(param), param); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static Object $S(int... params) { // Short[] out = new Short[params.length]; // for (int i = 0; i < out.length; ++i) { // out[i] = (short) params[i]; // } // return out; // }
import junitparams.JUnitParamsRunner; import junitparams.Parameters; import com.github.mucaho.jnetrobust.util.EntryIterator; import org.junit.Test; import org.junit.runner.RunWith; import java.nio.ByteBuffer; import java.util.*; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$S; import static org.junit.Assert.assertEquals;
/* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; @RunWith(JUnitParamsRunner.class) public class SentSegmentMapIterTest { private static short dataId = Short.MIN_VALUE; protected static ByteBuffer serializeShorts(Short[] numbers) { ByteBuffer buffer = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE + numbers.length * Short.SIZE / Byte.SIZE); buffer.putInt(numbers.length); for (short number : numbers) buffer.putShort(number); buffer.flip(); return buffer; } protected static Short[] deserializeShorts(ByteBuffer data) { int size = data.getInt(); Short[] numbers = new Short[size]; for (int i = 0; i < size; ++i) { numbers[i] = data.getShort(); } return numbers; } public Object[][] parametersForTestIterator() { Object[][] out = (Object[][]) $($( $($S(1, 2, 3), $S(4, 5), $S(7, 9), $S(8, 10)) )); return out; } @Test @Parameters public final void testIterator(Short[][] refGroups) { AbstractSegmentMap dataMap = new SentSegmentMap();
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/EntryIterator.java // public interface EntryIterator<K, V> { // // /** // * Returns the next key higher than the current key. // * // * @param currentKey the current key to be used in the lookup of the higher key // * or null to retrieve the first key // * @return <K> the next key higher than the current key or the first key // * or null if there is no higher key // */ // K getHigherKey(K currentKey); // // /** // * Returns the next key lower than the current key. // * // * @param currentKey the current key to be used in the lookup of the lower key // * or null to retrieve the last key // * @return <K> the previous key lower than the current key or the last key // * or null if there is no lower key // */ // K getLowerKey(K currentKey); // // /** // * Returns the value at the current key. // * // * @param currentKey the current key that is mapped to the returned value // * @return <V> the value bound to the current key // */ // V getValue(K currentKey); // // /** // * Removes the mapping the current key. // * // * @param currentKey the current key that is to be removed // * @return <V> the value bound to the current key // */ // V removeValue(K currentKey); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static <T> Object $(T param) { // return createArray(getClass(param), param); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static Object $S(int... params) { // Short[] out = new Short[params.length]; // for (int i = 0; i < out.length; ++i) { // out[i] = (short) params[i]; // } // return out; // } // Path: jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/control/SentSegmentMapIterTest.java import junitparams.JUnitParamsRunner; import junitparams.Parameters; import com.github.mucaho.jnetrobust.util.EntryIterator; import org.junit.Test; import org.junit.runner.RunWith; import java.nio.ByteBuffer; import java.util.*; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$S; import static org.junit.Assert.assertEquals; /* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; @RunWith(JUnitParamsRunner.class) public class SentSegmentMapIterTest { private static short dataId = Short.MIN_VALUE; protected static ByteBuffer serializeShorts(Short[] numbers) { ByteBuffer buffer = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE + numbers.length * Short.SIZE / Byte.SIZE); buffer.putInt(numbers.length); for (short number : numbers) buffer.putShort(number); buffer.flip(); return buffer; } protected static Short[] deserializeShorts(ByteBuffer data) { int size = data.getInt(); Short[] numbers = new Short[size]; for (int i = 0; i < size; ++i) { numbers[i] = data.getShort(); } return numbers; } public Object[][] parametersForTestIterator() { Object[][] out = (Object[][]) $($( $($S(1, 2, 3), $S(4, 5), $S(7, 9), $S(8, 10)) )); return out; } @Test @Parameters public final void testIterator(Short[][] refGroups) { AbstractSegmentMap dataMap = new SentSegmentMap();
EntryIterator<Short, Segment> iter = dataMap.getIterator();
mucaho/jnetrobust
jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/control/NewestReceivedControl.java
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/IdComparator.java // public final class IdComparator implements Comparator<Short> { // public static final IdComparator instance = new IdComparator(); // // public static final int MAX_SEQUENCE = Short.MAX_VALUE - Short.MIN_VALUE + 1; // // @Override // public final int compare(Short seq1, Short seq2) { // if (seq1 == null && seq2 == null) { // return 0; // } else if (seq1 == null) { // return -1; // } else if (seq2 == null) { // return 1; // } else { // return compare(seq1.shortValue(), seq2.shortValue()); // } // } // // public final int compare(Short seq1, short seq2) { // return compare(seq1.shortValue(), seq2); // } // // public final int compare(short seq1, Short seq2) { // return compare(seq1, seq2.shortValue()); // } // // public final int compare(short seq1, short seq2) { // return difference(seq1 - Short.MIN_VALUE, seq2 - Short.MIN_VALUE, MAX_SEQUENCE); // } // // public final boolean equals(Short seq1, Short seq2) { // return equals(seq1.shortValue(), seq2.shortValue()); // } // // public final boolean equals(Short seq1, short seq2) { // return equals(seq1.shortValue(), seq2); // } // // public final boolean equals(short seq1, Short seq2) { // return equals(seq1, seq2.shortValue()); // } // // public final boolean equals(short seq1, short seq2) { // return seq1 == seq2; // } // // /* // * Example: maxSequence = 100; maxSequence/2 = 50; // * seq1 = 10; // * seq2 = 30; // * diff = -20; // * abs(-20 ) <= 50 ==> return -20; // * // * seq1 = 30; // * seq2 = 10; // * diff = 20; // * abs(20) <= 50 ==> return 20; // * // * // * seq1 = 70; // * seq2 = 10; // * diff = 60; // * abs(60) !<= 50 ==> return (-1 * 100) + 60 = -40 // * // * seq1 = 10; // * seq2 = 70; // * diff = -60; // * abs(-60) !<= 50 ==> return (--1 * 100) - 60 = 40 // * // */ // private static final int difference(int seq1, int seq2, int maxSequence) { // int diff = seq1 - seq2; // if (Math.abs(diff) <= maxSequence / 2) // return diff; // else // return (-Integer.signum(diff) * maxSequence) + diff; // } // }
import com.github.mucaho.jnetrobust.util.IdComparator; import java.nio.ByteBuffer;
/* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; public class NewestReceivedControl { public interface NewestReceivedListener { void handleNewestData(short dataId, ByteBuffer data); } private final NewestReceivedListener listener; public NewestReceivedControl(NewestReceivedListener listener) { this.listener = listener; } private boolean newestReceivedChanged = false; private Segment newestReceivedSegment = null; public void refreshNewestReceived(Segment segment) {
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/IdComparator.java // public final class IdComparator implements Comparator<Short> { // public static final IdComparator instance = new IdComparator(); // // public static final int MAX_SEQUENCE = Short.MAX_VALUE - Short.MIN_VALUE + 1; // // @Override // public final int compare(Short seq1, Short seq2) { // if (seq1 == null && seq2 == null) { // return 0; // } else if (seq1 == null) { // return -1; // } else if (seq2 == null) { // return 1; // } else { // return compare(seq1.shortValue(), seq2.shortValue()); // } // } // // public final int compare(Short seq1, short seq2) { // return compare(seq1.shortValue(), seq2); // } // // public final int compare(short seq1, Short seq2) { // return compare(seq1, seq2.shortValue()); // } // // public final int compare(short seq1, short seq2) { // return difference(seq1 - Short.MIN_VALUE, seq2 - Short.MIN_VALUE, MAX_SEQUENCE); // } // // public final boolean equals(Short seq1, Short seq2) { // return equals(seq1.shortValue(), seq2.shortValue()); // } // // public final boolean equals(Short seq1, short seq2) { // return equals(seq1.shortValue(), seq2); // } // // public final boolean equals(short seq1, Short seq2) { // return equals(seq1, seq2.shortValue()); // } // // public final boolean equals(short seq1, short seq2) { // return seq1 == seq2; // } // // /* // * Example: maxSequence = 100; maxSequence/2 = 50; // * seq1 = 10; // * seq2 = 30; // * diff = -20; // * abs(-20 ) <= 50 ==> return -20; // * // * seq1 = 30; // * seq2 = 10; // * diff = 20; // * abs(20) <= 50 ==> return 20; // * // * // * seq1 = 70; // * seq2 = 10; // * diff = 60; // * abs(60) !<= 50 ==> return (-1 * 100) + 60 = -40 // * // * seq1 = 10; // * seq2 = 70; // * diff = -60; // * abs(-60) !<= 50 ==> return (--1 * 100) - 60 = 40 // * // */ // private static final int difference(int seq1, int seq2, int maxSequence) { // int diff = seq1 - seq2; // if (Math.abs(diff) <= maxSequence / 2) // return diff; // else // return (-Integer.signum(diff) * maxSequence) + diff; // } // } // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/control/NewestReceivedControl.java import com.github.mucaho.jnetrobust.util.IdComparator; import java.nio.ByteBuffer; /* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; public class NewestReceivedControl { public interface NewestReceivedListener { void handleNewestData(short dataId, ByteBuffer data); } private final NewestReceivedListener listener; public NewestReceivedControl(NewestReceivedListener listener) { this.listener = listener; } private boolean newestReceivedChanged = false; private Segment newestReceivedSegment = null; public void refreshNewestReceived(Segment segment) {
if (newestReceivedSegment == null || IdComparator.instance.compare(segment.getDataId(), newestReceivedSegment.getDataId()) > 0) {
mucaho/jnetrobust
jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/control/AckBitsControlTest.java
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/ShiftableBitSet.java // public final class ShiftableBitSet { // private long bits; // // // public ShiftableBitSet(long bits) { // super(); // this.bits = bits; // } // // public ShiftableBitSet() { // this.bits = 0; // } // // // public void and(long i) { // this.bits &= i; // } // // public void or(long i) { // this.bits |= i; // } // // public void xor(long i) { // this.bits ^= i; // } // // // public void minus(long i) { // this.bits -= i; // } // // public void plus(long i) { // this.bits += i; // } // // // public void set(long i) { // this.bits = i; // } // // public long get() { // return this.bits; // } // // public int getInt() { // return (int) bits; // } // // // public void shift(int i) { // if (i >= 0) { // this.shiftLeft(i); // } else { // this.shiftRight(-i); // } // } // // public void shiftRight(int i) { // bits >>>= i; // } // // public void shiftLeft(int i) { // bits <<= i; // } // // // private void setBit(int index, boolean set) { // if (set) { // bits |= LSB << index; // } else { // bits &= ~(LSB << index); // } // } // // public void setHighestBit(boolean set) { // this.setBit(SIZE - 1, set); // } // // public void setLowestBit(boolean set) { // this.setBit(0, set); // } // // public void set(int index, boolean set) { // if (index < 0) { // add negative index bit (shift bitset left and set bit) // this.shiftLeft(-index); // this.setLowestBit(set); // } else if (index < SIZE) { // set to positive 0 <= index < Size // this.setBit(index, set); // } else { // non-existing index, right shift the bitset then set the bit // this.shiftRight(index - SIZE + 1); // this.setHighestBit(set); // } // } // // @Override // public String toString() { // return String.format("%64s", Long.toBinaryString(bits)); // } // } // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/BitConstants.java // public final class BitConstants { // public static final int OFFSET = 1; // public static final int SIZE = Long.SIZE; // public static final long MSB = 0x8000000000000000L; // public static final long LSB = 0x1L; // private static final long INT_MASK = 0xFFFFFFFFL; // // private BitConstants() { // } // // public static final long convertBits(int bits) { // return ((long) bits) & INT_MASK; // } // // public static final int convertBits(long bits) { // return (int) bits; // } // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/util/TestUtils.java // public final static long binLong(String binaryString) { // return Long.parseLong(binaryString, 2); // }
import junitparams.JUnitParamsRunner; import junitparams.Parameters; import mockit.Deencapsulation; import com.github.mucaho.jnetrobust.util.ShiftableBitSet; import org.junit.Test; import org.junit.runner.RunWith; import java.util.ArrayList; import java.util.Collection; import java.util.Random; import static com.github.mucaho.jnetrobust.util.BitConstants.*; import static com.github.mucaho.jnetrobust.util.TestUtils.binLong; import static org.junit.Assert.assertEquals;
/* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; @RunWith(JUnitParamsRunner.class) public class AckBitsControlTest { @Test @Parameters public final void testAddToAckInt(long preBits, int inDiff, long postBits) {
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/ShiftableBitSet.java // public final class ShiftableBitSet { // private long bits; // // // public ShiftableBitSet(long bits) { // super(); // this.bits = bits; // } // // public ShiftableBitSet() { // this.bits = 0; // } // // // public void and(long i) { // this.bits &= i; // } // // public void or(long i) { // this.bits |= i; // } // // public void xor(long i) { // this.bits ^= i; // } // // // public void minus(long i) { // this.bits -= i; // } // // public void plus(long i) { // this.bits += i; // } // // // public void set(long i) { // this.bits = i; // } // // public long get() { // return this.bits; // } // // public int getInt() { // return (int) bits; // } // // // public void shift(int i) { // if (i >= 0) { // this.shiftLeft(i); // } else { // this.shiftRight(-i); // } // } // // public void shiftRight(int i) { // bits >>>= i; // } // // public void shiftLeft(int i) { // bits <<= i; // } // // // private void setBit(int index, boolean set) { // if (set) { // bits |= LSB << index; // } else { // bits &= ~(LSB << index); // } // } // // public void setHighestBit(boolean set) { // this.setBit(SIZE - 1, set); // } // // public void setLowestBit(boolean set) { // this.setBit(0, set); // } // // public void set(int index, boolean set) { // if (index < 0) { // add negative index bit (shift bitset left and set bit) // this.shiftLeft(-index); // this.setLowestBit(set); // } else if (index < SIZE) { // set to positive 0 <= index < Size // this.setBit(index, set); // } else { // non-existing index, right shift the bitset then set the bit // this.shiftRight(index - SIZE + 1); // this.setHighestBit(set); // } // } // // @Override // public String toString() { // return String.format("%64s", Long.toBinaryString(bits)); // } // } // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/BitConstants.java // public final class BitConstants { // public static final int OFFSET = 1; // public static final int SIZE = Long.SIZE; // public static final long MSB = 0x8000000000000000L; // public static final long LSB = 0x1L; // private static final long INT_MASK = 0xFFFFFFFFL; // // private BitConstants() { // } // // public static final long convertBits(int bits) { // return ((long) bits) & INT_MASK; // } // // public static final int convertBits(long bits) { // return (int) bits; // } // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/util/TestUtils.java // public final static long binLong(String binaryString) { // return Long.parseLong(binaryString, 2); // } // Path: jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/control/AckBitsControlTest.java import junitparams.JUnitParamsRunner; import junitparams.Parameters; import mockit.Deencapsulation; import com.github.mucaho.jnetrobust.util.ShiftableBitSet; import org.junit.Test; import org.junit.runner.RunWith; import java.util.ArrayList; import java.util.Collection; import java.util.Random; import static com.github.mucaho.jnetrobust.util.BitConstants.*; import static com.github.mucaho.jnetrobust.util.TestUtils.binLong; import static org.junit.Assert.assertEquals; /* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; @RunWith(JUnitParamsRunner.class) public class AckBitsControlTest { @Test @Parameters public final void testAddToAckInt(long preBits, int inDiff, long postBits) {
ShiftableBitSet actualBitSet = new ShiftableBitSet(preBits);
mucaho/jnetrobust
jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/control/AckBitsControlTest.java
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/ShiftableBitSet.java // public final class ShiftableBitSet { // private long bits; // // // public ShiftableBitSet(long bits) { // super(); // this.bits = bits; // } // // public ShiftableBitSet() { // this.bits = 0; // } // // // public void and(long i) { // this.bits &= i; // } // // public void or(long i) { // this.bits |= i; // } // // public void xor(long i) { // this.bits ^= i; // } // // // public void minus(long i) { // this.bits -= i; // } // // public void plus(long i) { // this.bits += i; // } // // // public void set(long i) { // this.bits = i; // } // // public long get() { // return this.bits; // } // // public int getInt() { // return (int) bits; // } // // // public void shift(int i) { // if (i >= 0) { // this.shiftLeft(i); // } else { // this.shiftRight(-i); // } // } // // public void shiftRight(int i) { // bits >>>= i; // } // // public void shiftLeft(int i) { // bits <<= i; // } // // // private void setBit(int index, boolean set) { // if (set) { // bits |= LSB << index; // } else { // bits &= ~(LSB << index); // } // } // // public void setHighestBit(boolean set) { // this.setBit(SIZE - 1, set); // } // // public void setLowestBit(boolean set) { // this.setBit(0, set); // } // // public void set(int index, boolean set) { // if (index < 0) { // add negative index bit (shift bitset left and set bit) // this.shiftLeft(-index); // this.setLowestBit(set); // } else if (index < SIZE) { // set to positive 0 <= index < Size // this.setBit(index, set); // } else { // non-existing index, right shift the bitset then set the bit // this.shiftRight(index - SIZE + 1); // this.setHighestBit(set); // } // } // // @Override // public String toString() { // return String.format("%64s", Long.toBinaryString(bits)); // } // } // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/BitConstants.java // public final class BitConstants { // public static final int OFFSET = 1; // public static final int SIZE = Long.SIZE; // public static final long MSB = 0x8000000000000000L; // public static final long LSB = 0x1L; // private static final long INT_MASK = 0xFFFFFFFFL; // // private BitConstants() { // } // // public static final long convertBits(int bits) { // return ((long) bits) & INT_MASK; // } // // public static final int convertBits(long bits) { // return (int) bits; // } // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/util/TestUtils.java // public final static long binLong(String binaryString) { // return Long.parseLong(binaryString, 2); // }
import junitparams.JUnitParamsRunner; import junitparams.Parameters; import mockit.Deencapsulation; import com.github.mucaho.jnetrobust.util.ShiftableBitSet; import org.junit.Test; import org.junit.runner.RunWith; import java.util.ArrayList; import java.util.Collection; import java.util.Random; import static com.github.mucaho.jnetrobust.util.BitConstants.*; import static com.github.mucaho.jnetrobust.util.TestUtils.binLong; import static org.junit.Assert.assertEquals;
/* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; @RunWith(JUnitParamsRunner.class) public class AckBitsControlTest { @Test @Parameters public final void testAddToAckInt(long preBits, int inDiff, long postBits) { ShiftableBitSet actualBitSet = new ShiftableBitSet(preBits); ShiftableBitSet expectedBitSet = new ShiftableBitSet(postBits); AckBitsControl handler = new AckBitsControl(); Deencapsulation.setField(handler, "ackRemoteBits", actualBitSet); String debug = ""; debug += actualBitSet; handler.addToAck(inDiff); debug += ".addToAck(" + inDiff + ")"; debug += " = " + actualBitSet; debug += " != " + expectedBitSet; assertEquals(debug, expectedBitSet.get(), actualBitSet.get()); } public Collection<Object[]> parametersForTestAddToAckInt() { ArrayList<Object[]> list = new ArrayList<Object[]>(); Random rng = new Random(); long preBits; long postBits; int index; list.add(new Object[]{0L, 0, 0L}); list.add(new Object[]{0L, OFFSET + SIZE, 0L});
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/ShiftableBitSet.java // public final class ShiftableBitSet { // private long bits; // // // public ShiftableBitSet(long bits) { // super(); // this.bits = bits; // } // // public ShiftableBitSet() { // this.bits = 0; // } // // // public void and(long i) { // this.bits &= i; // } // // public void or(long i) { // this.bits |= i; // } // // public void xor(long i) { // this.bits ^= i; // } // // // public void minus(long i) { // this.bits -= i; // } // // public void plus(long i) { // this.bits += i; // } // // // public void set(long i) { // this.bits = i; // } // // public long get() { // return this.bits; // } // // public int getInt() { // return (int) bits; // } // // // public void shift(int i) { // if (i >= 0) { // this.shiftLeft(i); // } else { // this.shiftRight(-i); // } // } // // public void shiftRight(int i) { // bits >>>= i; // } // // public void shiftLeft(int i) { // bits <<= i; // } // // // private void setBit(int index, boolean set) { // if (set) { // bits |= LSB << index; // } else { // bits &= ~(LSB << index); // } // } // // public void setHighestBit(boolean set) { // this.setBit(SIZE - 1, set); // } // // public void setLowestBit(boolean set) { // this.setBit(0, set); // } // // public void set(int index, boolean set) { // if (index < 0) { // add negative index bit (shift bitset left and set bit) // this.shiftLeft(-index); // this.setLowestBit(set); // } else if (index < SIZE) { // set to positive 0 <= index < Size // this.setBit(index, set); // } else { // non-existing index, right shift the bitset then set the bit // this.shiftRight(index - SIZE + 1); // this.setHighestBit(set); // } // } // // @Override // public String toString() { // return String.format("%64s", Long.toBinaryString(bits)); // } // } // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/BitConstants.java // public final class BitConstants { // public static final int OFFSET = 1; // public static final int SIZE = Long.SIZE; // public static final long MSB = 0x8000000000000000L; // public static final long LSB = 0x1L; // private static final long INT_MASK = 0xFFFFFFFFL; // // private BitConstants() { // } // // public static final long convertBits(int bits) { // return ((long) bits) & INT_MASK; // } // // public static final int convertBits(long bits) { // return (int) bits; // } // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/util/TestUtils.java // public final static long binLong(String binaryString) { // return Long.parseLong(binaryString, 2); // } // Path: jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/control/AckBitsControlTest.java import junitparams.JUnitParamsRunner; import junitparams.Parameters; import mockit.Deencapsulation; import com.github.mucaho.jnetrobust.util.ShiftableBitSet; import org.junit.Test; import org.junit.runner.RunWith; import java.util.ArrayList; import java.util.Collection; import java.util.Random; import static com.github.mucaho.jnetrobust.util.BitConstants.*; import static com.github.mucaho.jnetrobust.util.TestUtils.binLong; import static org.junit.Assert.assertEquals; /* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; @RunWith(JUnitParamsRunner.class) public class AckBitsControlTest { @Test @Parameters public final void testAddToAckInt(long preBits, int inDiff, long postBits) { ShiftableBitSet actualBitSet = new ShiftableBitSet(preBits); ShiftableBitSet expectedBitSet = new ShiftableBitSet(postBits); AckBitsControl handler = new AckBitsControl(); Deencapsulation.setField(handler, "ackRemoteBits", actualBitSet); String debug = ""; debug += actualBitSet; handler.addToAck(inDiff); debug += ".addToAck(" + inDiff + ")"; debug += " = " + actualBitSet; debug += " != " + expectedBitSet; assertEquals(debug, expectedBitSet.get(), actualBitSet.get()); } public Collection<Object[]> parametersForTestAddToAckInt() { ArrayList<Object[]> list = new ArrayList<Object[]>(); Random rng = new Random(); long preBits; long postBits; int index; list.add(new Object[]{0L, 0, 0L}); list.add(new Object[]{0L, OFFSET + SIZE, 0L});
list.add(new Object[]{binLong("0100"), OFFSET, binLong("0101")});
mucaho/jnetrobust
jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/control/ReceivedMapControlTest.java
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/SystemClock.java // public interface SystemClock { // long getTimeNow(); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static <T> Object $(T param) { // return createArray(getClass(param), param); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static Object $S(int... params) { // Short[] out = new Short[params.length]; // for (int i = 0; i < out.length; ++i) { // out[i] = (short) params[i]; // } // return out; // }
import com.github.mucaho.jnetrobust.util.SystemClock; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import mockit.Deencapsulation; import mockit.Mock; import mockit.MockUp; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import java.util.LinkedHashSet; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$S; import static org.junit.Assert.*;
/* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; @RunWith(JUnitParamsRunner.class) public class ReceivedMapControlTest extends AbstractMapControlTest { protected static ReceivedMapControl handler = new ReceivedMapControl((short) 0, null, config.getPacketQueueLimit(), config.getPacketOffsetLimit(), config.getPacketRetransmitLimit() + 1,
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/SystemClock.java // public interface SystemClock { // long getTimeNow(); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static <T> Object $(T param) { // return createArray(getClass(param), param); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static Object $S(int... params) { // Short[] out = new Short[params.length]; // for (int i = 0; i < out.length; ++i) { // out[i] = (short) params[i]; // } // return out; // } // Path: jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/control/ReceivedMapControlTest.java import com.github.mucaho.jnetrobust.util.SystemClock; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import mockit.Deencapsulation; import mockit.Mock; import mockit.MockUp; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import java.util.LinkedHashSet; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$S; import static org.junit.Assert.*; /* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; @RunWith(JUnitParamsRunner.class) public class ReceivedMapControlTest extends AbstractMapControlTest { protected static ReceivedMapControl handler = new ReceivedMapControl((short) 0, null, config.getPacketQueueLimit(), config.getPacketOffsetLimit(), config.getPacketRetransmitLimit() + 1,
config.getPacketQueueTimeout(), new SystemClock() {
mucaho/jnetrobust
jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/control/ReceivedMapControlTest.java
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/SystemClock.java // public interface SystemClock { // long getTimeNow(); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static <T> Object $(T param) { // return createArray(getClass(param), param); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static Object $S(int... params) { // Short[] out = new Short[params.length]; // for (int i = 0; i < out.length; ++i) { // out[i] = (short) params[i]; // } // return out; // }
import com.github.mucaho.jnetrobust.util.SystemClock; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import mockit.Deencapsulation; import mockit.Mock; import mockit.MockUp; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import java.util.LinkedHashSet; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$S; import static org.junit.Assert.*;
/* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; @RunWith(JUnitParamsRunner.class) public class ReceivedMapControlTest extends AbstractMapControlTest { protected static ReceivedMapControl handler = new ReceivedMapControl((short) 0, null, config.getPacketQueueLimit(), config.getPacketOffsetLimit(), config.getPacketRetransmitLimit() + 1, config.getPacketQueueTimeout(), new SystemClock() { @Override public long getTimeNow() { return System.currentTimeMillis(); } }); static { System.setProperty("jmockit-mockParameters", "annotated"); } @BeforeClass public static void initMap() { initDataMap(handler); dataId = 0; Deencapsulation.setField(handler, "nextDataId", (short) 1); dataMap.clear(); } public Object[][] parametersForTestRemoveTail() { Object[][] out = (Object[][])
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/SystemClock.java // public interface SystemClock { // long getTimeNow(); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static <T> Object $(T param) { // return createArray(getClass(param), param); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static Object $S(int... params) { // Short[] out = new Short[params.length]; // for (int i = 0; i < out.length; ++i) { // out[i] = (short) params[i]; // } // return out; // } // Path: jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/control/ReceivedMapControlTest.java import com.github.mucaho.jnetrobust.util.SystemClock; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import mockit.Deencapsulation; import mockit.Mock; import mockit.MockUp; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import java.util.LinkedHashSet; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$S; import static org.junit.Assert.*; /* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; @RunWith(JUnitParamsRunner.class) public class ReceivedMapControlTest extends AbstractMapControlTest { protected static ReceivedMapControl handler = new ReceivedMapControl((short) 0, null, config.getPacketQueueLimit(), config.getPacketOffsetLimit(), config.getPacketRetransmitLimit() + 1, config.getPacketQueueTimeout(), new SystemClock() { @Override public long getTimeNow() { return System.currentTimeMillis(); } }); static { System.setProperty("jmockit-mockParameters", "annotated"); } @BeforeClass public static void initMap() { initDataMap(handler); dataId = 0; Deencapsulation.setField(handler, "nextDataId", (short) 1); dataMap.clear(); } public Object[][] parametersForTestRemoveTail() { Object[][] out = (Object[][])
$($(
mucaho/jnetrobust
jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/control/ReceivedMapControlTest.java
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/SystemClock.java // public interface SystemClock { // long getTimeNow(); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static <T> Object $(T param) { // return createArray(getClass(param), param); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static Object $S(int... params) { // Short[] out = new Short[params.length]; // for (int i = 0; i < out.length; ++i) { // out[i] = (short) params[i]; // } // return out; // }
import com.github.mucaho.jnetrobust.util.SystemClock; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import mockit.Deencapsulation; import mockit.Mock; import mockit.MockUp; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import java.util.LinkedHashSet; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$S; import static org.junit.Assert.*;
/* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; @RunWith(JUnitParamsRunner.class) public class ReceivedMapControlTest extends AbstractMapControlTest { protected static ReceivedMapControl handler = new ReceivedMapControl((short) 0, null, config.getPacketQueueLimit(), config.getPacketOffsetLimit(), config.getPacketRetransmitLimit() + 1, config.getPacketQueueTimeout(), new SystemClock() { @Override public long getTimeNow() { return System.currentTimeMillis(); } }); static { System.setProperty("jmockit-mockParameters", "annotated"); } @BeforeClass public static void initMap() { initDataMap(handler); dataId = 0; Deencapsulation.setField(handler, "nextDataId", (short) 1); dataMap.clear(); } public Object[][] parametersForTestRemoveTail() { Object[][] out = (Object[][]) $($(
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/SystemClock.java // public interface SystemClock { // long getTimeNow(); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static <T> Object $(T param) { // return createArray(getClass(param), param); // } // // Path: jnetrobust-core/src/test/java/com/github/mucaho/jarrayliterals/ArrayShortcuts.java // public static Object $S(int... params) { // Short[] out = new Short[params.length]; // for (int i = 0; i < out.length; ++i) { // out[i] = (short) params[i]; // } // return out; // } // Path: jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/control/ReceivedMapControlTest.java import com.github.mucaho.jnetrobust.util.SystemClock; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import mockit.Deencapsulation; import mockit.Mock; import mockit.MockUp; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import java.util.LinkedHashSet; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$; import static com.github.mucaho.jarrayliterals.ArrayShortcuts.$S; import static org.junit.Assert.*; /* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; @RunWith(JUnitParamsRunner.class) public class ReceivedMapControlTest extends AbstractMapControlTest { protected static ReceivedMapControl handler = new ReceivedMapControl((short) 0, null, config.getPacketQueueLimit(), config.getPacketOffsetLimit(), config.getPacketRetransmitLimit() + 1, config.getPacketQueueTimeout(), new SystemClock() { @Override public long getTimeNow() { return System.currentTimeMillis(); } }); static { System.setProperty("jmockit-mockParameters", "annotated"); } @BeforeClass public static void initMap() { initDataMap(handler); dataId = 0; Deencapsulation.setField(handler, "nextDataId", (short) 1); dataMap.clear(); } public Object[][] parametersForTestRemoveTail() { Object[][] out = (Object[][]) $($(
(short) 3, $S, (short) 1
mucaho/jnetrobust
jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/control/ReceivedSegmentMap.java
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/IdComparator.java // public final class IdComparator implements Comparator<Short> { // public static final IdComparator instance = new IdComparator(); // // public static final int MAX_SEQUENCE = Short.MAX_VALUE - Short.MIN_VALUE + 1; // // @Override // public final int compare(Short seq1, Short seq2) { // if (seq1 == null && seq2 == null) { // return 0; // } else if (seq1 == null) { // return -1; // } else if (seq2 == null) { // return 1; // } else { // return compare(seq1.shortValue(), seq2.shortValue()); // } // } // // public final int compare(Short seq1, short seq2) { // return compare(seq1.shortValue(), seq2); // } // // public final int compare(short seq1, Short seq2) { // return compare(seq1, seq2.shortValue()); // } // // public final int compare(short seq1, short seq2) { // return difference(seq1 - Short.MIN_VALUE, seq2 - Short.MIN_VALUE, MAX_SEQUENCE); // } // // public final boolean equals(Short seq1, Short seq2) { // return equals(seq1.shortValue(), seq2.shortValue()); // } // // public final boolean equals(Short seq1, short seq2) { // return equals(seq1.shortValue(), seq2); // } // // public final boolean equals(short seq1, Short seq2) { // return equals(seq1, seq2.shortValue()); // } // // public final boolean equals(short seq1, short seq2) { // return seq1 == seq2; // } // // /* // * Example: maxSequence = 100; maxSequence/2 = 50; // * seq1 = 10; // * seq2 = 30; // * diff = -20; // * abs(-20 ) <= 50 ==> return -20; // * // * seq1 = 30; // * seq2 = 10; // * diff = 20; // * abs(20) <= 50 ==> return 20; // * // * // * seq1 = 70; // * seq2 = 10; // * diff = 60; // * abs(60) !<= 50 ==> return (-1 * 100) + 60 = -40 // * // * seq1 = 10; // * seq2 = 70; // * diff = -60; // * abs(-60) !<= 50 ==> return (--1 * 100) - 60 = 40 // * // */ // private static final int difference(int seq1, int seq2, int maxSequence) { // int diff = seq1 - seq2; // if (Math.abs(diff) <= maxSequence / 2) // return diff; // else // return (-Integer.signum(diff) * maxSequence) + diff; // } // } // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/SegmentDataIdComparator.java // public final class SegmentDataIdComparator implements Comparator<Segment> { // public static final SegmentDataIdComparator instance = new SegmentDataIdComparator(); // // @Override // public int compare(Segment o1, Segment o2) { // return IdComparator.instance.compare(o1.getDataId(), o2.getDataId()); // } // }
import com.github.mucaho.jnetrobust.util.IdComparator; import com.github.mucaho.jnetrobust.util.SegmentDataIdComparator; import java.util.NavigableSet;
/* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; public class ReceivedSegmentMap extends AbstractSegmentMap { public ReceivedSegmentMap() {
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/IdComparator.java // public final class IdComparator implements Comparator<Short> { // public static final IdComparator instance = new IdComparator(); // // public static final int MAX_SEQUENCE = Short.MAX_VALUE - Short.MIN_VALUE + 1; // // @Override // public final int compare(Short seq1, Short seq2) { // if (seq1 == null && seq2 == null) { // return 0; // } else if (seq1 == null) { // return -1; // } else if (seq2 == null) { // return 1; // } else { // return compare(seq1.shortValue(), seq2.shortValue()); // } // } // // public final int compare(Short seq1, short seq2) { // return compare(seq1.shortValue(), seq2); // } // // public final int compare(short seq1, Short seq2) { // return compare(seq1, seq2.shortValue()); // } // // public final int compare(short seq1, short seq2) { // return difference(seq1 - Short.MIN_VALUE, seq2 - Short.MIN_VALUE, MAX_SEQUENCE); // } // // public final boolean equals(Short seq1, Short seq2) { // return equals(seq1.shortValue(), seq2.shortValue()); // } // // public final boolean equals(Short seq1, short seq2) { // return equals(seq1.shortValue(), seq2); // } // // public final boolean equals(short seq1, Short seq2) { // return equals(seq1, seq2.shortValue()); // } // // public final boolean equals(short seq1, short seq2) { // return seq1 == seq2; // } // // /* // * Example: maxSequence = 100; maxSequence/2 = 50; // * seq1 = 10; // * seq2 = 30; // * diff = -20; // * abs(-20 ) <= 50 ==> return -20; // * // * seq1 = 30; // * seq2 = 10; // * diff = 20; // * abs(20) <= 50 ==> return 20; // * // * // * seq1 = 70; // * seq2 = 10; // * diff = 60; // * abs(60) !<= 50 ==> return (-1 * 100) + 60 = -40 // * // * seq1 = 10; // * seq2 = 70; // * diff = -60; // * abs(-60) !<= 50 ==> return (--1 * 100) - 60 = 40 // * // */ // private static final int difference(int seq1, int seq2, int maxSequence) { // int diff = seq1 - seq2; // if (Math.abs(diff) <= maxSequence / 2) // return diff; // else // return (-Integer.signum(diff) * maxSequence) + diff; // } // } // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/SegmentDataIdComparator.java // public final class SegmentDataIdComparator implements Comparator<Segment> { // public static final SegmentDataIdComparator instance = new SegmentDataIdComparator(); // // @Override // public int compare(Segment o1, Segment o2) { // return IdComparator.instance.compare(o1.getDataId(), o2.getDataId()); // } // } // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/control/ReceivedSegmentMap.java import com.github.mucaho.jnetrobust.util.IdComparator; import com.github.mucaho.jnetrobust.util.SegmentDataIdComparator; import java.util.NavigableSet; /* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; public class ReceivedSegmentMap extends AbstractSegmentMap { public ReceivedSegmentMap() {
super(IdComparator.instance, SegmentDataIdComparator.instance);
mucaho/jnetrobust
jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/control/ReceivedSegmentMap.java
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/IdComparator.java // public final class IdComparator implements Comparator<Short> { // public static final IdComparator instance = new IdComparator(); // // public static final int MAX_SEQUENCE = Short.MAX_VALUE - Short.MIN_VALUE + 1; // // @Override // public final int compare(Short seq1, Short seq2) { // if (seq1 == null && seq2 == null) { // return 0; // } else if (seq1 == null) { // return -1; // } else if (seq2 == null) { // return 1; // } else { // return compare(seq1.shortValue(), seq2.shortValue()); // } // } // // public final int compare(Short seq1, short seq2) { // return compare(seq1.shortValue(), seq2); // } // // public final int compare(short seq1, Short seq2) { // return compare(seq1, seq2.shortValue()); // } // // public final int compare(short seq1, short seq2) { // return difference(seq1 - Short.MIN_VALUE, seq2 - Short.MIN_VALUE, MAX_SEQUENCE); // } // // public final boolean equals(Short seq1, Short seq2) { // return equals(seq1.shortValue(), seq2.shortValue()); // } // // public final boolean equals(Short seq1, short seq2) { // return equals(seq1.shortValue(), seq2); // } // // public final boolean equals(short seq1, Short seq2) { // return equals(seq1, seq2.shortValue()); // } // // public final boolean equals(short seq1, short seq2) { // return seq1 == seq2; // } // // /* // * Example: maxSequence = 100; maxSequence/2 = 50; // * seq1 = 10; // * seq2 = 30; // * diff = -20; // * abs(-20 ) <= 50 ==> return -20; // * // * seq1 = 30; // * seq2 = 10; // * diff = 20; // * abs(20) <= 50 ==> return 20; // * // * // * seq1 = 70; // * seq2 = 10; // * diff = 60; // * abs(60) !<= 50 ==> return (-1 * 100) + 60 = -40 // * // * seq1 = 10; // * seq2 = 70; // * diff = -60; // * abs(-60) !<= 50 ==> return (--1 * 100) - 60 = 40 // * // */ // private static final int difference(int seq1, int seq2, int maxSequence) { // int diff = seq1 - seq2; // if (Math.abs(diff) <= maxSequence / 2) // return diff; // else // return (-Integer.signum(diff) * maxSequence) + diff; // } // } // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/SegmentDataIdComparator.java // public final class SegmentDataIdComparator implements Comparator<Segment> { // public static final SegmentDataIdComparator instance = new SegmentDataIdComparator(); // // @Override // public int compare(Segment o1, Segment o2) { // return IdComparator.instance.compare(o1.getDataId(), o2.getDataId()); // } // }
import com.github.mucaho.jnetrobust.util.IdComparator; import com.github.mucaho.jnetrobust.util.SegmentDataIdComparator; import java.util.NavigableSet;
/* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; public class ReceivedSegmentMap extends AbstractSegmentMap { public ReceivedSegmentMap() {
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/IdComparator.java // public final class IdComparator implements Comparator<Short> { // public static final IdComparator instance = new IdComparator(); // // public static final int MAX_SEQUENCE = Short.MAX_VALUE - Short.MIN_VALUE + 1; // // @Override // public final int compare(Short seq1, Short seq2) { // if (seq1 == null && seq2 == null) { // return 0; // } else if (seq1 == null) { // return -1; // } else if (seq2 == null) { // return 1; // } else { // return compare(seq1.shortValue(), seq2.shortValue()); // } // } // // public final int compare(Short seq1, short seq2) { // return compare(seq1.shortValue(), seq2); // } // // public final int compare(short seq1, Short seq2) { // return compare(seq1, seq2.shortValue()); // } // // public final int compare(short seq1, short seq2) { // return difference(seq1 - Short.MIN_VALUE, seq2 - Short.MIN_VALUE, MAX_SEQUENCE); // } // // public final boolean equals(Short seq1, Short seq2) { // return equals(seq1.shortValue(), seq2.shortValue()); // } // // public final boolean equals(Short seq1, short seq2) { // return equals(seq1.shortValue(), seq2); // } // // public final boolean equals(short seq1, Short seq2) { // return equals(seq1, seq2.shortValue()); // } // // public final boolean equals(short seq1, short seq2) { // return seq1 == seq2; // } // // /* // * Example: maxSequence = 100; maxSequence/2 = 50; // * seq1 = 10; // * seq2 = 30; // * diff = -20; // * abs(-20 ) <= 50 ==> return -20; // * // * seq1 = 30; // * seq2 = 10; // * diff = 20; // * abs(20) <= 50 ==> return 20; // * // * // * seq1 = 70; // * seq2 = 10; // * diff = 60; // * abs(60) !<= 50 ==> return (-1 * 100) + 60 = -40 // * // * seq1 = 10; // * seq2 = 70; // * diff = -60; // * abs(-60) !<= 50 ==> return (--1 * 100) - 60 = 40 // * // */ // private static final int difference(int seq1, int seq2, int maxSequence) { // int diff = seq1 - seq2; // if (Math.abs(diff) <= maxSequence / 2) // return diff; // else // return (-Integer.signum(diff) * maxSequence) + diff; // } // } // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/SegmentDataIdComparator.java // public final class SegmentDataIdComparator implements Comparator<Segment> { // public static final SegmentDataIdComparator instance = new SegmentDataIdComparator(); // // @Override // public int compare(Segment o1, Segment o2) { // return IdComparator.instance.compare(o1.getDataId(), o2.getDataId()); // } // } // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/control/ReceivedSegmentMap.java import com.github.mucaho.jnetrobust.util.IdComparator; import com.github.mucaho.jnetrobust.util.SegmentDataIdComparator; import java.util.NavigableSet; /* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; public class ReceivedSegmentMap extends AbstractSegmentMap { public ReceivedSegmentMap() {
super(IdComparator.instance, SegmentDataIdComparator.instance);
mucaho/jnetrobust
jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/control/SentMapControl.java
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/FastLog.java // public final class FastLog { // /* // * See http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog // */ // private final static long b[] = {0x2, 0xC, 0xF0, 0xFF00, 0xFFFF0000, 0xFFFFFFFF00000000L}; // private final static int S[] = {1, 2, 4, 8, 16, 32}; // // public final static int log2(long v) { // int r = 0; // result of log2(v) will go here // for (int i = 5; i >= 0; i--) { // if ((v & b[i]) != 0) { // v >>= S[i]; // r |= S[i]; // } // } // return r; // } // // public final static int log2(int v) { // int r = 0; // result of log2(v) will go here // for (int i = 4; i >= 0; i--) { // if ((v & b[i]) != 0) { // v >>= S[i]; // r |= S[i]; // } // } // return r; // } // } // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/SystemClock.java // public interface SystemClock { // long getTimeNow(); // } // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/BitConstants.java // public static final long LSB = 0x1L; // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/BitConstants.java // public static final int OFFSET = 1;
import com.github.mucaho.jnetrobust.util.FastLog; import com.github.mucaho.jnetrobust.util.SystemClock; import java.nio.ByteBuffer; import static com.github.mucaho.jnetrobust.util.BitConstants.LSB; import static com.github.mucaho.jnetrobust.util.BitConstants.OFFSET;
/* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; public class SentMapControl extends AbstractMapControl { public interface TransmissionSuccessListener { void handleAckedData(short dataId, ByteBuffer ackedData); void handleUnackedData(short dataId, ByteBuffer unackedData); } private TransmissionSuccessListener listener; public SentMapControl(TransmissionSuccessListener listener, int maxEntries, int maxEntryOffset,
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/FastLog.java // public final class FastLog { // /* // * See http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog // */ // private final static long b[] = {0x2, 0xC, 0xF0, 0xFF00, 0xFFFF0000, 0xFFFFFFFF00000000L}; // private final static int S[] = {1, 2, 4, 8, 16, 32}; // // public final static int log2(long v) { // int r = 0; // result of log2(v) will go here // for (int i = 5; i >= 0; i--) { // if ((v & b[i]) != 0) { // v >>= S[i]; // r |= S[i]; // } // } // return r; // } // // public final static int log2(int v) { // int r = 0; // result of log2(v) will go here // for (int i = 4; i >= 0; i--) { // if ((v & b[i]) != 0) { // v >>= S[i]; // r |= S[i]; // } // } // return r; // } // } // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/SystemClock.java // public interface SystemClock { // long getTimeNow(); // } // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/BitConstants.java // public static final long LSB = 0x1L; // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/BitConstants.java // public static final int OFFSET = 1; // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/control/SentMapControl.java import com.github.mucaho.jnetrobust.util.FastLog; import com.github.mucaho.jnetrobust.util.SystemClock; import java.nio.ByteBuffer; import static com.github.mucaho.jnetrobust.util.BitConstants.LSB; import static com.github.mucaho.jnetrobust.util.BitConstants.OFFSET; /* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; public class SentMapControl extends AbstractMapControl { public interface TransmissionSuccessListener { void handleAckedData(short dataId, ByteBuffer ackedData); void handleUnackedData(short dataId, ByteBuffer unackedData); } private TransmissionSuccessListener listener; public SentMapControl(TransmissionSuccessListener listener, int maxEntries, int maxEntryOffset,
int maxEntryOccurrences, long maxEntryTimeout, SystemClock systemClock) {
mucaho/jnetrobust
jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/control/SentMapControl.java
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/FastLog.java // public final class FastLog { // /* // * See http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog // */ // private final static long b[] = {0x2, 0xC, 0xF0, 0xFF00, 0xFFFF0000, 0xFFFFFFFF00000000L}; // private final static int S[] = {1, 2, 4, 8, 16, 32}; // // public final static int log2(long v) { // int r = 0; // result of log2(v) will go here // for (int i = 5; i >= 0; i--) { // if ((v & b[i]) != 0) { // v >>= S[i]; // r |= S[i]; // } // } // return r; // } // // public final static int log2(int v) { // int r = 0; // result of log2(v) will go here // for (int i = 4; i >= 0; i--) { // if ((v & b[i]) != 0) { // v >>= S[i]; // r |= S[i]; // } // } // return r; // } // } // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/SystemClock.java // public interface SystemClock { // long getTimeNow(); // } // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/BitConstants.java // public static final long LSB = 0x1L; // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/BitConstants.java // public static final int OFFSET = 1;
import com.github.mucaho.jnetrobust.util.FastLog; import com.github.mucaho.jnetrobust.util.SystemClock; import java.nio.ByteBuffer; import static com.github.mucaho.jnetrobust.util.BitConstants.LSB; import static com.github.mucaho.jnetrobust.util.BitConstants.OFFSET;
/* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; public class SentMapControl extends AbstractMapControl { public interface TransmissionSuccessListener { void handleAckedData(short dataId, ByteBuffer ackedData); void handleUnackedData(short dataId, ByteBuffer unackedData); } private TransmissionSuccessListener listener; public SentMapControl(TransmissionSuccessListener listener, int maxEntries, int maxEntryOffset, int maxEntryOccurrences, long maxEntryTimeout, SystemClock systemClock) { super(maxEntries, maxEntryOffset, maxEntryOccurrences, maxEntryTimeout, systemClock); this.listener = listener; } @Override protected AbstractSegmentMap createMap() { return new SentSegmentMap(); } public void addToSent(Short transmissionId, Segment segment) { // add to pending map dataMap.put(transmissionId, segment); } public void removeFromSent(Short transmissionId, long precedingTransmissionIds) { // remove multiple (oldest until newest) from pending map removeFromSentOnBits(transmissionId, precedingTransmissionIds); // remove newest from pending map notifyAcked(transmissionId, dataMap.removeAll(transmissionId), true); } private void removeFromSentOnBits(Short transmissionId, long precedingTransmissionIds) { Short precedingTransmissionId; int msbIndex; while (precedingTransmissionIds != 0) {
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/FastLog.java // public final class FastLog { // /* // * See http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog // */ // private final static long b[] = {0x2, 0xC, 0xF0, 0xFF00, 0xFFFF0000, 0xFFFFFFFF00000000L}; // private final static int S[] = {1, 2, 4, 8, 16, 32}; // // public final static int log2(long v) { // int r = 0; // result of log2(v) will go here // for (int i = 5; i >= 0; i--) { // if ((v & b[i]) != 0) { // v >>= S[i]; // r |= S[i]; // } // } // return r; // } // // public final static int log2(int v) { // int r = 0; // result of log2(v) will go here // for (int i = 4; i >= 0; i--) { // if ((v & b[i]) != 0) { // v >>= S[i]; // r |= S[i]; // } // } // return r; // } // } // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/SystemClock.java // public interface SystemClock { // long getTimeNow(); // } // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/BitConstants.java // public static final long LSB = 0x1L; // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/BitConstants.java // public static final int OFFSET = 1; // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/control/SentMapControl.java import com.github.mucaho.jnetrobust.util.FastLog; import com.github.mucaho.jnetrobust.util.SystemClock; import java.nio.ByteBuffer; import static com.github.mucaho.jnetrobust.util.BitConstants.LSB; import static com.github.mucaho.jnetrobust.util.BitConstants.OFFSET; /* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; public class SentMapControl extends AbstractMapControl { public interface TransmissionSuccessListener { void handleAckedData(short dataId, ByteBuffer ackedData); void handleUnackedData(short dataId, ByteBuffer unackedData); } private TransmissionSuccessListener listener; public SentMapControl(TransmissionSuccessListener listener, int maxEntries, int maxEntryOffset, int maxEntryOccurrences, long maxEntryTimeout, SystemClock systemClock) { super(maxEntries, maxEntryOffset, maxEntryOccurrences, maxEntryTimeout, systemClock); this.listener = listener; } @Override protected AbstractSegmentMap createMap() { return new SentSegmentMap(); } public void addToSent(Short transmissionId, Segment segment) { // add to pending map dataMap.put(transmissionId, segment); } public void removeFromSent(Short transmissionId, long precedingTransmissionIds) { // remove multiple (oldest until newest) from pending map removeFromSentOnBits(transmissionId, precedingTransmissionIds); // remove newest from pending map notifyAcked(transmissionId, dataMap.removeAll(transmissionId), true); } private void removeFromSentOnBits(Short transmissionId, long precedingTransmissionIds) { Short precedingTransmissionId; int msbIndex; while (precedingTransmissionIds != 0) {
msbIndex = FastLog.log2(precedingTransmissionIds);
mucaho/jnetrobust
jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/control/SentMapControl.java
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/FastLog.java // public final class FastLog { // /* // * See http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog // */ // private final static long b[] = {0x2, 0xC, 0xF0, 0xFF00, 0xFFFF0000, 0xFFFFFFFF00000000L}; // private final static int S[] = {1, 2, 4, 8, 16, 32}; // // public final static int log2(long v) { // int r = 0; // result of log2(v) will go here // for (int i = 5; i >= 0; i--) { // if ((v & b[i]) != 0) { // v >>= S[i]; // r |= S[i]; // } // } // return r; // } // // public final static int log2(int v) { // int r = 0; // result of log2(v) will go here // for (int i = 4; i >= 0; i--) { // if ((v & b[i]) != 0) { // v >>= S[i]; // r |= S[i]; // } // } // return r; // } // } // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/SystemClock.java // public interface SystemClock { // long getTimeNow(); // } // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/BitConstants.java // public static final long LSB = 0x1L; // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/BitConstants.java // public static final int OFFSET = 1;
import com.github.mucaho.jnetrobust.util.FastLog; import com.github.mucaho.jnetrobust.util.SystemClock; import java.nio.ByteBuffer; import static com.github.mucaho.jnetrobust.util.BitConstants.LSB; import static com.github.mucaho.jnetrobust.util.BitConstants.OFFSET;
/* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; public class SentMapControl extends AbstractMapControl { public interface TransmissionSuccessListener { void handleAckedData(short dataId, ByteBuffer ackedData); void handleUnackedData(short dataId, ByteBuffer unackedData); } private TransmissionSuccessListener listener; public SentMapControl(TransmissionSuccessListener listener, int maxEntries, int maxEntryOffset, int maxEntryOccurrences, long maxEntryTimeout, SystemClock systemClock) { super(maxEntries, maxEntryOffset, maxEntryOccurrences, maxEntryTimeout, systemClock); this.listener = listener; } @Override protected AbstractSegmentMap createMap() { return new SentSegmentMap(); } public void addToSent(Short transmissionId, Segment segment) { // add to pending map dataMap.put(transmissionId, segment); } public void removeFromSent(Short transmissionId, long precedingTransmissionIds) { // remove multiple (oldest until newest) from pending map removeFromSentOnBits(transmissionId, precedingTransmissionIds); // remove newest from pending map notifyAcked(transmissionId, dataMap.removeAll(transmissionId), true); } private void removeFromSentOnBits(Short transmissionId, long precedingTransmissionIds) { Short precedingTransmissionId; int msbIndex; while (precedingTransmissionIds != 0) { msbIndex = FastLog.log2(precedingTransmissionIds);
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/FastLog.java // public final class FastLog { // /* // * See http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog // */ // private final static long b[] = {0x2, 0xC, 0xF0, 0xFF00, 0xFFFF0000, 0xFFFFFFFF00000000L}; // private final static int S[] = {1, 2, 4, 8, 16, 32}; // // public final static int log2(long v) { // int r = 0; // result of log2(v) will go here // for (int i = 5; i >= 0; i--) { // if ((v & b[i]) != 0) { // v >>= S[i]; // r |= S[i]; // } // } // return r; // } // // public final static int log2(int v) { // int r = 0; // result of log2(v) will go here // for (int i = 4; i >= 0; i--) { // if ((v & b[i]) != 0) { // v >>= S[i]; // r |= S[i]; // } // } // return r; // } // } // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/SystemClock.java // public interface SystemClock { // long getTimeNow(); // } // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/BitConstants.java // public static final long LSB = 0x1L; // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/BitConstants.java // public static final int OFFSET = 1; // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/control/SentMapControl.java import com.github.mucaho.jnetrobust.util.FastLog; import com.github.mucaho.jnetrobust.util.SystemClock; import java.nio.ByteBuffer; import static com.github.mucaho.jnetrobust.util.BitConstants.LSB; import static com.github.mucaho.jnetrobust.util.BitConstants.OFFSET; /* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; public class SentMapControl extends AbstractMapControl { public interface TransmissionSuccessListener { void handleAckedData(short dataId, ByteBuffer ackedData); void handleUnackedData(short dataId, ByteBuffer unackedData); } private TransmissionSuccessListener listener; public SentMapControl(TransmissionSuccessListener listener, int maxEntries, int maxEntryOffset, int maxEntryOccurrences, long maxEntryTimeout, SystemClock systemClock) { super(maxEntries, maxEntryOffset, maxEntryOccurrences, maxEntryTimeout, systemClock); this.listener = listener; } @Override protected AbstractSegmentMap createMap() { return new SentSegmentMap(); } public void addToSent(Short transmissionId, Segment segment) { // add to pending map dataMap.put(transmissionId, segment); } public void removeFromSent(Short transmissionId, long precedingTransmissionIds) { // remove multiple (oldest until newest) from pending map removeFromSentOnBits(transmissionId, precedingTransmissionIds); // remove newest from pending map notifyAcked(transmissionId, dataMap.removeAll(transmissionId), true); } private void removeFromSentOnBits(Short transmissionId, long precedingTransmissionIds) { Short precedingTransmissionId; int msbIndex; while (precedingTransmissionIds != 0) { msbIndex = FastLog.log2(precedingTransmissionIds);
precedingTransmissionId = (short) (transmissionId - msbIndex - OFFSET);
mucaho/jnetrobust
jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/control/SentMapControl.java
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/FastLog.java // public final class FastLog { // /* // * See http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog // */ // private final static long b[] = {0x2, 0xC, 0xF0, 0xFF00, 0xFFFF0000, 0xFFFFFFFF00000000L}; // private final static int S[] = {1, 2, 4, 8, 16, 32}; // // public final static int log2(long v) { // int r = 0; // result of log2(v) will go here // for (int i = 5; i >= 0; i--) { // if ((v & b[i]) != 0) { // v >>= S[i]; // r |= S[i]; // } // } // return r; // } // // public final static int log2(int v) { // int r = 0; // result of log2(v) will go here // for (int i = 4; i >= 0; i--) { // if ((v & b[i]) != 0) { // v >>= S[i]; // r |= S[i]; // } // } // return r; // } // } // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/SystemClock.java // public interface SystemClock { // long getTimeNow(); // } // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/BitConstants.java // public static final long LSB = 0x1L; // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/BitConstants.java // public static final int OFFSET = 1;
import com.github.mucaho.jnetrobust.util.FastLog; import com.github.mucaho.jnetrobust.util.SystemClock; import java.nio.ByteBuffer; import static com.github.mucaho.jnetrobust.util.BitConstants.LSB; import static com.github.mucaho.jnetrobust.util.BitConstants.OFFSET;
/* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; public class SentMapControl extends AbstractMapControl { public interface TransmissionSuccessListener { void handleAckedData(short dataId, ByteBuffer ackedData); void handleUnackedData(short dataId, ByteBuffer unackedData); } private TransmissionSuccessListener listener; public SentMapControl(TransmissionSuccessListener listener, int maxEntries, int maxEntryOffset, int maxEntryOccurrences, long maxEntryTimeout, SystemClock systemClock) { super(maxEntries, maxEntryOffset, maxEntryOccurrences, maxEntryTimeout, systemClock); this.listener = listener; } @Override protected AbstractSegmentMap createMap() { return new SentSegmentMap(); } public void addToSent(Short transmissionId, Segment segment) { // add to pending map dataMap.put(transmissionId, segment); } public void removeFromSent(Short transmissionId, long precedingTransmissionIds) { // remove multiple (oldest until newest) from pending map removeFromSentOnBits(transmissionId, precedingTransmissionIds); // remove newest from pending map notifyAcked(transmissionId, dataMap.removeAll(transmissionId), true); } private void removeFromSentOnBits(Short transmissionId, long precedingTransmissionIds) { Short precedingTransmissionId; int msbIndex; while (precedingTransmissionIds != 0) { msbIndex = FastLog.log2(precedingTransmissionIds); precedingTransmissionId = (short) (transmissionId - msbIndex - OFFSET); notifyAcked(precedingTransmissionId, dataMap.removeAll(precedingTransmissionId), false);
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/FastLog.java // public final class FastLog { // /* // * See http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog // */ // private final static long b[] = {0x2, 0xC, 0xF0, 0xFF00, 0xFFFF0000, 0xFFFFFFFF00000000L}; // private final static int S[] = {1, 2, 4, 8, 16, 32}; // // public final static int log2(long v) { // int r = 0; // result of log2(v) will go here // for (int i = 5; i >= 0; i--) { // if ((v & b[i]) != 0) { // v >>= S[i]; // r |= S[i]; // } // } // return r; // } // // public final static int log2(int v) { // int r = 0; // result of log2(v) will go here // for (int i = 4; i >= 0; i--) { // if ((v & b[i]) != 0) { // v >>= S[i]; // r |= S[i]; // } // } // return r; // } // } // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/SystemClock.java // public interface SystemClock { // long getTimeNow(); // } // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/BitConstants.java // public static final long LSB = 0x1L; // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/BitConstants.java // public static final int OFFSET = 1; // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/control/SentMapControl.java import com.github.mucaho.jnetrobust.util.FastLog; import com.github.mucaho.jnetrobust.util.SystemClock; import java.nio.ByteBuffer; import static com.github.mucaho.jnetrobust.util.BitConstants.LSB; import static com.github.mucaho.jnetrobust.util.BitConstants.OFFSET; /* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; public class SentMapControl extends AbstractMapControl { public interface TransmissionSuccessListener { void handleAckedData(short dataId, ByteBuffer ackedData); void handleUnackedData(short dataId, ByteBuffer unackedData); } private TransmissionSuccessListener listener; public SentMapControl(TransmissionSuccessListener listener, int maxEntries, int maxEntryOffset, int maxEntryOccurrences, long maxEntryTimeout, SystemClock systemClock) { super(maxEntries, maxEntryOffset, maxEntryOccurrences, maxEntryTimeout, systemClock); this.listener = listener; } @Override protected AbstractSegmentMap createMap() { return new SentSegmentMap(); } public void addToSent(Short transmissionId, Segment segment) { // add to pending map dataMap.put(transmissionId, segment); } public void removeFromSent(Short transmissionId, long precedingTransmissionIds) { // remove multiple (oldest until newest) from pending map removeFromSentOnBits(transmissionId, precedingTransmissionIds); // remove newest from pending map notifyAcked(transmissionId, dataMap.removeAll(transmissionId), true); } private void removeFromSentOnBits(Short transmissionId, long precedingTransmissionIds) { Short precedingTransmissionId; int msbIndex; while (precedingTransmissionIds != 0) { msbIndex = FastLog.log2(precedingTransmissionIds); precedingTransmissionId = (short) (transmissionId - msbIndex - OFFSET); notifyAcked(precedingTransmissionId, dataMap.removeAll(precedingTransmissionId), false);
precedingTransmissionIds &= ~(LSB << msbIndex);
mucaho/jnetrobust
jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/control/SentSegmentMap.java
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/IdComparator.java // public final class IdComparator implements Comparator<Short> { // public static final IdComparator instance = new IdComparator(); // // public static final int MAX_SEQUENCE = Short.MAX_VALUE - Short.MIN_VALUE + 1; // // @Override // public final int compare(Short seq1, Short seq2) { // if (seq1 == null && seq2 == null) { // return 0; // } else if (seq1 == null) { // return -1; // } else if (seq2 == null) { // return 1; // } else { // return compare(seq1.shortValue(), seq2.shortValue()); // } // } // // public final int compare(Short seq1, short seq2) { // return compare(seq1.shortValue(), seq2); // } // // public final int compare(short seq1, Short seq2) { // return compare(seq1, seq2.shortValue()); // } // // public final int compare(short seq1, short seq2) { // return difference(seq1 - Short.MIN_VALUE, seq2 - Short.MIN_VALUE, MAX_SEQUENCE); // } // // public final boolean equals(Short seq1, Short seq2) { // return equals(seq1.shortValue(), seq2.shortValue()); // } // // public final boolean equals(Short seq1, short seq2) { // return equals(seq1.shortValue(), seq2); // } // // public final boolean equals(short seq1, Short seq2) { // return equals(seq1, seq2.shortValue()); // } // // public final boolean equals(short seq1, short seq2) { // return seq1 == seq2; // } // // /* // * Example: maxSequence = 100; maxSequence/2 = 50; // * seq1 = 10; // * seq2 = 30; // * diff = -20; // * abs(-20 ) <= 50 ==> return -20; // * // * seq1 = 30; // * seq2 = 10; // * diff = 20; // * abs(20) <= 50 ==> return 20; // * // * // * seq1 = 70; // * seq2 = 10; // * diff = 60; // * abs(60) !<= 50 ==> return (-1 * 100) + 60 = -40 // * // * seq1 = 10; // * seq2 = 70; // * diff = -60; // * abs(-60) !<= 50 ==> return (--1 * 100) - 60 = 40 // * // */ // private static final int difference(int seq1, int seq2, int maxSequence) { // int diff = seq1 - seq2; // if (Math.abs(diff) <= maxSequence / 2) // return diff; // else // return (-Integer.signum(diff) * maxSequence) + diff; // } // } // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/SegmentLastTransmissionIdComparator.java // public final class SegmentLastTransmissionIdComparator implements Comparator<Segment> { // public static final SegmentLastTransmissionIdComparator instance = new SegmentLastTransmissionIdComparator(); // // @Override // public int compare(Segment o1, Segment o2) { // Short lastTransmissionId1 = o1.getLastTransmissionId(); // Short lastTransmissionId2 = o2.getLastTransmissionId(); // // int lastTransmissionIdComparison; // if (lastTransmissionId1 == null && lastTransmissionId2 == null) { // lastTransmissionIdComparison = 0; // } else if (lastTransmissionId1 == null) { // lastTransmissionIdComparison = -1; // } else if (lastTransmissionId2 == null) { // lastTransmissionIdComparison = 1; // } else { // lastTransmissionIdComparison = IdComparator.instance.compare(lastTransmissionId1, lastTransmissionId2); // } // // // must be equal-consistent, 0 return value only allowed iff dataIds same! // int dataIdComparison = IdComparator.instance.compare(o1.getDataId(), o2.getDataId()); // return dataIdComparison == 0 || lastTransmissionIdComparison == 0 // ? dataIdComparison // : lastTransmissionIdComparison; // } // }
import com.github.mucaho.jnetrobust.util.IdComparator; import com.github.mucaho.jnetrobust.util.SegmentLastTransmissionIdComparator; import java.util.NavigableSet;
/* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; public class SentSegmentMap extends AbstractSegmentMap { public SentSegmentMap() {
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/IdComparator.java // public final class IdComparator implements Comparator<Short> { // public static final IdComparator instance = new IdComparator(); // // public static final int MAX_SEQUENCE = Short.MAX_VALUE - Short.MIN_VALUE + 1; // // @Override // public final int compare(Short seq1, Short seq2) { // if (seq1 == null && seq2 == null) { // return 0; // } else if (seq1 == null) { // return -1; // } else if (seq2 == null) { // return 1; // } else { // return compare(seq1.shortValue(), seq2.shortValue()); // } // } // // public final int compare(Short seq1, short seq2) { // return compare(seq1.shortValue(), seq2); // } // // public final int compare(short seq1, Short seq2) { // return compare(seq1, seq2.shortValue()); // } // // public final int compare(short seq1, short seq2) { // return difference(seq1 - Short.MIN_VALUE, seq2 - Short.MIN_VALUE, MAX_SEQUENCE); // } // // public final boolean equals(Short seq1, Short seq2) { // return equals(seq1.shortValue(), seq2.shortValue()); // } // // public final boolean equals(Short seq1, short seq2) { // return equals(seq1.shortValue(), seq2); // } // // public final boolean equals(short seq1, Short seq2) { // return equals(seq1, seq2.shortValue()); // } // // public final boolean equals(short seq1, short seq2) { // return seq1 == seq2; // } // // /* // * Example: maxSequence = 100; maxSequence/2 = 50; // * seq1 = 10; // * seq2 = 30; // * diff = -20; // * abs(-20 ) <= 50 ==> return -20; // * // * seq1 = 30; // * seq2 = 10; // * diff = 20; // * abs(20) <= 50 ==> return 20; // * // * // * seq1 = 70; // * seq2 = 10; // * diff = 60; // * abs(60) !<= 50 ==> return (-1 * 100) + 60 = -40 // * // * seq1 = 10; // * seq2 = 70; // * diff = -60; // * abs(-60) !<= 50 ==> return (--1 * 100) - 60 = 40 // * // */ // private static final int difference(int seq1, int seq2, int maxSequence) { // int diff = seq1 - seq2; // if (Math.abs(diff) <= maxSequence / 2) // return diff; // else // return (-Integer.signum(diff) * maxSequence) + diff; // } // } // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/SegmentLastTransmissionIdComparator.java // public final class SegmentLastTransmissionIdComparator implements Comparator<Segment> { // public static final SegmentLastTransmissionIdComparator instance = new SegmentLastTransmissionIdComparator(); // // @Override // public int compare(Segment o1, Segment o2) { // Short lastTransmissionId1 = o1.getLastTransmissionId(); // Short lastTransmissionId2 = o2.getLastTransmissionId(); // // int lastTransmissionIdComparison; // if (lastTransmissionId1 == null && lastTransmissionId2 == null) { // lastTransmissionIdComparison = 0; // } else if (lastTransmissionId1 == null) { // lastTransmissionIdComparison = -1; // } else if (lastTransmissionId2 == null) { // lastTransmissionIdComparison = 1; // } else { // lastTransmissionIdComparison = IdComparator.instance.compare(lastTransmissionId1, lastTransmissionId2); // } // // // must be equal-consistent, 0 return value only allowed iff dataIds same! // int dataIdComparison = IdComparator.instance.compare(o1.getDataId(), o2.getDataId()); // return dataIdComparison == 0 || lastTransmissionIdComparison == 0 // ? dataIdComparison // : lastTransmissionIdComparison; // } // } // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/control/SentSegmentMap.java import com.github.mucaho.jnetrobust.util.IdComparator; import com.github.mucaho.jnetrobust.util.SegmentLastTransmissionIdComparator; import java.util.NavigableSet; /* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; public class SentSegmentMap extends AbstractSegmentMap { public SentSegmentMap() {
super(IdComparator.instance, SegmentLastTransmissionIdComparator.instance);
mucaho/jnetrobust
jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/control/SentSegmentMap.java
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/IdComparator.java // public final class IdComparator implements Comparator<Short> { // public static final IdComparator instance = new IdComparator(); // // public static final int MAX_SEQUENCE = Short.MAX_VALUE - Short.MIN_VALUE + 1; // // @Override // public final int compare(Short seq1, Short seq2) { // if (seq1 == null && seq2 == null) { // return 0; // } else if (seq1 == null) { // return -1; // } else if (seq2 == null) { // return 1; // } else { // return compare(seq1.shortValue(), seq2.shortValue()); // } // } // // public final int compare(Short seq1, short seq2) { // return compare(seq1.shortValue(), seq2); // } // // public final int compare(short seq1, Short seq2) { // return compare(seq1, seq2.shortValue()); // } // // public final int compare(short seq1, short seq2) { // return difference(seq1 - Short.MIN_VALUE, seq2 - Short.MIN_VALUE, MAX_SEQUENCE); // } // // public final boolean equals(Short seq1, Short seq2) { // return equals(seq1.shortValue(), seq2.shortValue()); // } // // public final boolean equals(Short seq1, short seq2) { // return equals(seq1.shortValue(), seq2); // } // // public final boolean equals(short seq1, Short seq2) { // return equals(seq1, seq2.shortValue()); // } // // public final boolean equals(short seq1, short seq2) { // return seq1 == seq2; // } // // /* // * Example: maxSequence = 100; maxSequence/2 = 50; // * seq1 = 10; // * seq2 = 30; // * diff = -20; // * abs(-20 ) <= 50 ==> return -20; // * // * seq1 = 30; // * seq2 = 10; // * diff = 20; // * abs(20) <= 50 ==> return 20; // * // * // * seq1 = 70; // * seq2 = 10; // * diff = 60; // * abs(60) !<= 50 ==> return (-1 * 100) + 60 = -40 // * // * seq1 = 10; // * seq2 = 70; // * diff = -60; // * abs(-60) !<= 50 ==> return (--1 * 100) - 60 = 40 // * // */ // private static final int difference(int seq1, int seq2, int maxSequence) { // int diff = seq1 - seq2; // if (Math.abs(diff) <= maxSequence / 2) // return diff; // else // return (-Integer.signum(diff) * maxSequence) + diff; // } // } // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/SegmentLastTransmissionIdComparator.java // public final class SegmentLastTransmissionIdComparator implements Comparator<Segment> { // public static final SegmentLastTransmissionIdComparator instance = new SegmentLastTransmissionIdComparator(); // // @Override // public int compare(Segment o1, Segment o2) { // Short lastTransmissionId1 = o1.getLastTransmissionId(); // Short lastTransmissionId2 = o2.getLastTransmissionId(); // // int lastTransmissionIdComparison; // if (lastTransmissionId1 == null && lastTransmissionId2 == null) { // lastTransmissionIdComparison = 0; // } else if (lastTransmissionId1 == null) { // lastTransmissionIdComparison = -1; // } else if (lastTransmissionId2 == null) { // lastTransmissionIdComparison = 1; // } else { // lastTransmissionIdComparison = IdComparator.instance.compare(lastTransmissionId1, lastTransmissionId2); // } // // // must be equal-consistent, 0 return value only allowed iff dataIds same! // int dataIdComparison = IdComparator.instance.compare(o1.getDataId(), o2.getDataId()); // return dataIdComparison == 0 || lastTransmissionIdComparison == 0 // ? dataIdComparison // : lastTransmissionIdComparison; // } // }
import com.github.mucaho.jnetrobust.util.IdComparator; import com.github.mucaho.jnetrobust.util.SegmentLastTransmissionIdComparator; import java.util.NavigableSet;
/* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; public class SentSegmentMap extends AbstractSegmentMap { public SentSegmentMap() {
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/IdComparator.java // public final class IdComparator implements Comparator<Short> { // public static final IdComparator instance = new IdComparator(); // // public static final int MAX_SEQUENCE = Short.MAX_VALUE - Short.MIN_VALUE + 1; // // @Override // public final int compare(Short seq1, Short seq2) { // if (seq1 == null && seq2 == null) { // return 0; // } else if (seq1 == null) { // return -1; // } else if (seq2 == null) { // return 1; // } else { // return compare(seq1.shortValue(), seq2.shortValue()); // } // } // // public final int compare(Short seq1, short seq2) { // return compare(seq1.shortValue(), seq2); // } // // public final int compare(short seq1, Short seq2) { // return compare(seq1, seq2.shortValue()); // } // // public final int compare(short seq1, short seq2) { // return difference(seq1 - Short.MIN_VALUE, seq2 - Short.MIN_VALUE, MAX_SEQUENCE); // } // // public final boolean equals(Short seq1, Short seq2) { // return equals(seq1.shortValue(), seq2.shortValue()); // } // // public final boolean equals(Short seq1, short seq2) { // return equals(seq1.shortValue(), seq2); // } // // public final boolean equals(short seq1, Short seq2) { // return equals(seq1, seq2.shortValue()); // } // // public final boolean equals(short seq1, short seq2) { // return seq1 == seq2; // } // // /* // * Example: maxSequence = 100; maxSequence/2 = 50; // * seq1 = 10; // * seq2 = 30; // * diff = -20; // * abs(-20 ) <= 50 ==> return -20; // * // * seq1 = 30; // * seq2 = 10; // * diff = 20; // * abs(20) <= 50 ==> return 20; // * // * // * seq1 = 70; // * seq2 = 10; // * diff = 60; // * abs(60) !<= 50 ==> return (-1 * 100) + 60 = -40 // * // * seq1 = 10; // * seq2 = 70; // * diff = -60; // * abs(-60) !<= 50 ==> return (--1 * 100) - 60 = 40 // * // */ // private static final int difference(int seq1, int seq2, int maxSequence) { // int diff = seq1 - seq2; // if (Math.abs(diff) <= maxSequence / 2) // return diff; // else // return (-Integer.signum(diff) * maxSequence) + diff; // } // } // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/SegmentLastTransmissionIdComparator.java // public final class SegmentLastTransmissionIdComparator implements Comparator<Segment> { // public static final SegmentLastTransmissionIdComparator instance = new SegmentLastTransmissionIdComparator(); // // @Override // public int compare(Segment o1, Segment o2) { // Short lastTransmissionId1 = o1.getLastTransmissionId(); // Short lastTransmissionId2 = o2.getLastTransmissionId(); // // int lastTransmissionIdComparison; // if (lastTransmissionId1 == null && lastTransmissionId2 == null) { // lastTransmissionIdComparison = 0; // } else if (lastTransmissionId1 == null) { // lastTransmissionIdComparison = -1; // } else if (lastTransmissionId2 == null) { // lastTransmissionIdComparison = 1; // } else { // lastTransmissionIdComparison = IdComparator.instance.compare(lastTransmissionId1, lastTransmissionId2); // } // // // must be equal-consistent, 0 return value only allowed iff dataIds same! // int dataIdComparison = IdComparator.instance.compare(o1.getDataId(), o2.getDataId()); // return dataIdComparison == 0 || lastTransmissionIdComparison == 0 // ? dataIdComparison // : lastTransmissionIdComparison; // } // } // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/control/SentSegmentMap.java import com.github.mucaho.jnetrobust.util.IdComparator; import com.github.mucaho.jnetrobust.util.SegmentLastTransmissionIdComparator; import java.util.NavigableSet; /* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; public class SentSegmentMap extends AbstractSegmentMap { public SentSegmentMap() {
super(IdComparator.instance, SegmentLastTransmissionIdComparator.instance);
mucaho/jnetrobust
jnetrobust-samples/src/main/java/com/github/mucaho/jnetrobust/example/ProtocolHandleListener.java
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/Logger.java // public abstract class Logger { // /** // * Enum representing all possible <code>logging event descriptions</code>. // */ // public static enum LoggingEvent { // SEND("Data sent"), // RECEIVE("Data received"), // NEWEST("Newest data received"), // SEND_RETRANSMISSION("Data retransmitted"), // RETRANSMISSION("Data needs to be retransmitted"), // ORDERED("Data received ordered"), // UNORDERED("Data received not ordered"), // ACKED("Data was received at other end"), // NOTACKED("Data was probably not received at other end"); // // private final String description; // private LoggingEvent(String description) { // this.description = description; // } // // @Override // public String toString() { // return description; // } // } // // /** // * Log changes in the protocol's state. // * @param description the description of the log event, matches one of the {@link Logger.LoggingEvent logging events} // * @param params zero or more features that are logged // */ // public abstract void log(String description, Object... params); // // /** // * Abstract simple logger which logs events to the {@link java.lang.System#out System.out} stream.<br /> // * Implementors should extend this class providing a suitable implementation for {@link #deserialize(ByteBuffer)}. // */ // public abstract static class AbstractConsoleLogger extends Logger { // // private final String name; // // public AbstractConsoleLogger(String name) { // this.name = name; // } // // @Override // public void log(String description, Object... params) { // StringBuffer sb = new StringBuffer(); // sb.append("[" + name + "]: " + description + "\t"); // for (int i = 0, l = params.length; i < l; ++i) { // if (params[i] instanceof ByteBuffer) { // ByteBuffer dataBuffer = (ByteBuffer) params[i]; // dataBuffer.rewind(); // sb.append(deserialize(dataBuffer) + "\t"); // dataBuffer.rewind(); // } else { // sb.append(params[i] + "\t"); // } // } // sb.append("@loggerId=").append(hashCode()).append("\t@T=").append(System.currentTimeMillis()); // System.out.println(sb.toString()); // } // // protected abstract String deserialize(ByteBuffer dataBuffer); // } // }
import com.github.mucaho.jnetrobust.Logger; import java.io.Serializable;
/* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.example; public interface ProtocolHandleListener<T extends Serializable> { class ProtocolException extends RuntimeException {
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/Logger.java // public abstract class Logger { // /** // * Enum representing all possible <code>logging event descriptions</code>. // */ // public static enum LoggingEvent { // SEND("Data sent"), // RECEIVE("Data received"), // NEWEST("Newest data received"), // SEND_RETRANSMISSION("Data retransmitted"), // RETRANSMISSION("Data needs to be retransmitted"), // ORDERED("Data received ordered"), // UNORDERED("Data received not ordered"), // ACKED("Data was received at other end"), // NOTACKED("Data was probably not received at other end"); // // private final String description; // private LoggingEvent(String description) { // this.description = description; // } // // @Override // public String toString() { // return description; // } // } // // /** // * Log changes in the protocol's state. // * @param description the description of the log event, matches one of the {@link Logger.LoggingEvent logging events} // * @param params zero or more features that are logged // */ // public abstract void log(String description, Object... params); // // /** // * Abstract simple logger which logs events to the {@link java.lang.System#out System.out} stream.<br /> // * Implementors should extend this class providing a suitable implementation for {@link #deserialize(ByteBuffer)}. // */ // public abstract static class AbstractConsoleLogger extends Logger { // // private final String name; // // public AbstractConsoleLogger(String name) { // this.name = name; // } // // @Override // public void log(String description, Object... params) { // StringBuffer sb = new StringBuffer(); // sb.append("[" + name + "]: " + description + "\t"); // for (int i = 0, l = params.length; i < l; ++i) { // if (params[i] instanceof ByteBuffer) { // ByteBuffer dataBuffer = (ByteBuffer) params[i]; // dataBuffer.rewind(); // sb.append(deserialize(dataBuffer) + "\t"); // dataBuffer.rewind(); // } else { // sb.append(params[i] + "\t"); // } // } // sb.append("@loggerId=").append(hashCode()).append("\t@T=").append(System.currentTimeMillis()); // System.out.println(sb.toString()); // } // // protected abstract String deserialize(ByteBuffer dataBuffer); // } // } // Path: jnetrobust-samples/src/main/java/com/github/mucaho/jnetrobust/example/ProtocolHandleListener.java import com.github.mucaho.jnetrobust.Logger; import java.io.Serializable; /* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.example; public interface ProtocolHandleListener<T extends Serializable> { class ProtocolException extends RuntimeException {
private final Logger.LoggingEvent loggingEvent;
mucaho/jnetrobust
jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/util/ShiftableBitSetTest.java
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/ShiftableBitSet.java // public final class ShiftableBitSet { // private long bits; // // // public ShiftableBitSet(long bits) { // super(); // this.bits = bits; // } // // public ShiftableBitSet() { // this.bits = 0; // } // // // public void and(long i) { // this.bits &= i; // } // // public void or(long i) { // this.bits |= i; // } // // public void xor(long i) { // this.bits ^= i; // } // // // public void minus(long i) { // this.bits -= i; // } // // public void plus(long i) { // this.bits += i; // } // // // public void set(long i) { // this.bits = i; // } // // public long get() { // return this.bits; // } // // public int getInt() { // return (int) bits; // } // // // public void shift(int i) { // if (i >= 0) { // this.shiftLeft(i); // } else { // this.shiftRight(-i); // } // } // // public void shiftRight(int i) { // bits >>>= i; // } // // public void shiftLeft(int i) { // bits <<= i; // } // // // private void setBit(int index, boolean set) { // if (set) { // bits |= LSB << index; // } else { // bits &= ~(LSB << index); // } // } // // public void setHighestBit(boolean set) { // this.setBit(SIZE - 1, set); // } // // public void setLowestBit(boolean set) { // this.setBit(0, set); // } // // public void set(int index, boolean set) { // if (index < 0) { // add negative index bit (shift bitset left and set bit) // this.shiftLeft(-index); // this.setLowestBit(set); // } else if (index < SIZE) { // set to positive 0 <= index < Size // this.setBit(index, set); // } else { // non-existing index, right shift the bitset then set the bit // this.shiftRight(index - SIZE + 1); // this.setHighestBit(set); // } // } // // @Override // public String toString() { // return String.format("%64s", Long.toBinaryString(bits)); // } // } // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/BitConstants.java // public final class BitConstants { // public static final int OFFSET = 1; // public static final int SIZE = Long.SIZE; // public static final long MSB = 0x8000000000000000L; // public static final long LSB = 0x1L; // private static final long INT_MASK = 0xFFFFFFFFL; // // private BitConstants() { // } // // public static final long convertBits(int bits) { // return ((long) bits) & INT_MASK; // } // // public static final int convertBits(long bits) { // return (int) bits; // } // }
import com.github.mucaho.jnetrobust.util.ShiftableBitSet; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.util.ArrayList; import java.util.Collection; import java.util.Random; import static com.github.mucaho.jnetrobust.util.BitConstants.*; import static org.junit.Assert.assertEquals;
isSet = rng.nextBoolean(); index = rng.nextInt(SIZE); newBitSet = isSet ? (bitSet | LSB << index) : (bitSet & ~(LSB << index)); list.add(new Object[]{bitSet, index, isSet, newBitSet}); bitSet = newBitSet; index = rng.nextInt(SIZE - 1) + 1; newBitSet = bitSet << index; newBitSet = isSet ? (newBitSet | LSB) : (newBitSet & ~LSB); list.add(new Object[]{bitSet, -index, isSet, newBitSet}); bitSet = newBitSet; index += SIZE; newBitSet = bitSet >>> (index - SIZE + 1); newBitSet = isSet ? (newBitSet | MSB) : (newBitSet & ~MSB); list.add(new Object[]{bitSet, index, isSet, newBitSet}); bitSet = newBitSet; } return list; } private int index; private long expectedBitSet; private boolean set;
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/ShiftableBitSet.java // public final class ShiftableBitSet { // private long bits; // // // public ShiftableBitSet(long bits) { // super(); // this.bits = bits; // } // // public ShiftableBitSet() { // this.bits = 0; // } // // // public void and(long i) { // this.bits &= i; // } // // public void or(long i) { // this.bits |= i; // } // // public void xor(long i) { // this.bits ^= i; // } // // // public void minus(long i) { // this.bits -= i; // } // // public void plus(long i) { // this.bits += i; // } // // // public void set(long i) { // this.bits = i; // } // // public long get() { // return this.bits; // } // // public int getInt() { // return (int) bits; // } // // // public void shift(int i) { // if (i >= 0) { // this.shiftLeft(i); // } else { // this.shiftRight(-i); // } // } // // public void shiftRight(int i) { // bits >>>= i; // } // // public void shiftLeft(int i) { // bits <<= i; // } // // // private void setBit(int index, boolean set) { // if (set) { // bits |= LSB << index; // } else { // bits &= ~(LSB << index); // } // } // // public void setHighestBit(boolean set) { // this.setBit(SIZE - 1, set); // } // // public void setLowestBit(boolean set) { // this.setBit(0, set); // } // // public void set(int index, boolean set) { // if (index < 0) { // add negative index bit (shift bitset left and set bit) // this.shiftLeft(-index); // this.setLowestBit(set); // } else if (index < SIZE) { // set to positive 0 <= index < Size // this.setBit(index, set); // } else { // non-existing index, right shift the bitset then set the bit // this.shiftRight(index - SIZE + 1); // this.setHighestBit(set); // } // } // // @Override // public String toString() { // return String.format("%64s", Long.toBinaryString(bits)); // } // } // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/BitConstants.java // public final class BitConstants { // public static final int OFFSET = 1; // public static final int SIZE = Long.SIZE; // public static final long MSB = 0x8000000000000000L; // public static final long LSB = 0x1L; // private static final long INT_MASK = 0xFFFFFFFFL; // // private BitConstants() { // } // // public static final long convertBits(int bits) { // return ((long) bits) & INT_MASK; // } // // public static final int convertBits(long bits) { // return (int) bits; // } // } // Path: jnetrobust-core/src/test/java/com/github/mucaho/jnetrobust/util/ShiftableBitSetTest.java import com.github.mucaho.jnetrobust.util.ShiftableBitSet; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.util.ArrayList; import java.util.Collection; import java.util.Random; import static com.github.mucaho.jnetrobust.util.BitConstants.*; import static org.junit.Assert.assertEquals; isSet = rng.nextBoolean(); index = rng.nextInt(SIZE); newBitSet = isSet ? (bitSet | LSB << index) : (bitSet & ~(LSB << index)); list.add(new Object[]{bitSet, index, isSet, newBitSet}); bitSet = newBitSet; index = rng.nextInt(SIZE - 1) + 1; newBitSet = bitSet << index; newBitSet = isSet ? (newBitSet | LSB) : (newBitSet & ~LSB); list.add(new Object[]{bitSet, -index, isSet, newBitSet}); bitSet = newBitSet; index += SIZE; newBitSet = bitSet >>> (index - SIZE + 1); newBitSet = isSet ? (newBitSet | MSB) : (newBitSet & ~MSB); list.add(new Object[]{bitSet, index, isSet, newBitSet}); bitSet = newBitSet; } return list; } private int index; private long expectedBitSet; private boolean set;
private ShiftableBitSet bitSet;
mucaho/jnetrobust
jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/control/ReceivedMapControl.java
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/IdComparator.java // public final class IdComparator implements Comparator<Short> { // public static final IdComparator instance = new IdComparator(); // // public static final int MAX_SEQUENCE = Short.MAX_VALUE - Short.MIN_VALUE + 1; // // @Override // public final int compare(Short seq1, Short seq2) { // if (seq1 == null && seq2 == null) { // return 0; // } else if (seq1 == null) { // return -1; // } else if (seq2 == null) { // return 1; // } else { // return compare(seq1.shortValue(), seq2.shortValue()); // } // } // // public final int compare(Short seq1, short seq2) { // return compare(seq1.shortValue(), seq2); // } // // public final int compare(short seq1, Short seq2) { // return compare(seq1, seq2.shortValue()); // } // // public final int compare(short seq1, short seq2) { // return difference(seq1 - Short.MIN_VALUE, seq2 - Short.MIN_VALUE, MAX_SEQUENCE); // } // // public final boolean equals(Short seq1, Short seq2) { // return equals(seq1.shortValue(), seq2.shortValue()); // } // // public final boolean equals(Short seq1, short seq2) { // return equals(seq1.shortValue(), seq2); // } // // public final boolean equals(short seq1, Short seq2) { // return equals(seq1, seq2.shortValue()); // } // // public final boolean equals(short seq1, short seq2) { // return seq1 == seq2; // } // // /* // * Example: maxSequence = 100; maxSequence/2 = 50; // * seq1 = 10; // * seq2 = 30; // * diff = -20; // * abs(-20 ) <= 50 ==> return -20; // * // * seq1 = 30; // * seq2 = 10; // * diff = 20; // * abs(20) <= 50 ==> return 20; // * // * // * seq1 = 70; // * seq2 = 10; // * diff = 60; // * abs(60) !<= 50 ==> return (-1 * 100) + 60 = -40 // * // * seq1 = 10; // * seq2 = 70; // * diff = -60; // * abs(-60) !<= 50 ==> return (--1 * 100) - 60 = 40 // * // */ // private static final int difference(int seq1, int seq2, int maxSequence) { // int diff = seq1 - seq2; // if (Math.abs(diff) <= maxSequence / 2) // return diff; // else // return (-Integer.signum(diff) * maxSequence) + diff; // } // } // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/SystemClock.java // public interface SystemClock { // long getTimeNow(); // }
import com.github.mucaho.jnetrobust.util.IdComparator; import com.github.mucaho.jnetrobust.util.SystemClock; import java.nio.ByteBuffer;
/* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; public class ReceivedMapControl extends AbstractMapControl { public interface TransmissionOrderListener { void handleOrderedData(short dataId, ByteBuffer orderedData); void handleUnorderedData(short dataId, ByteBuffer unorderedData); } private final TransmissionOrderListener listener; private short nextDataId; public ReceivedMapControl(short initialDataId, TransmissionOrderListener listener, int maxEntries, int maxEntryOffset,
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/IdComparator.java // public final class IdComparator implements Comparator<Short> { // public static final IdComparator instance = new IdComparator(); // // public static final int MAX_SEQUENCE = Short.MAX_VALUE - Short.MIN_VALUE + 1; // // @Override // public final int compare(Short seq1, Short seq2) { // if (seq1 == null && seq2 == null) { // return 0; // } else if (seq1 == null) { // return -1; // } else if (seq2 == null) { // return 1; // } else { // return compare(seq1.shortValue(), seq2.shortValue()); // } // } // // public final int compare(Short seq1, short seq2) { // return compare(seq1.shortValue(), seq2); // } // // public final int compare(short seq1, Short seq2) { // return compare(seq1, seq2.shortValue()); // } // // public final int compare(short seq1, short seq2) { // return difference(seq1 - Short.MIN_VALUE, seq2 - Short.MIN_VALUE, MAX_SEQUENCE); // } // // public final boolean equals(Short seq1, Short seq2) { // return equals(seq1.shortValue(), seq2.shortValue()); // } // // public final boolean equals(Short seq1, short seq2) { // return equals(seq1.shortValue(), seq2); // } // // public final boolean equals(short seq1, Short seq2) { // return equals(seq1, seq2.shortValue()); // } // // public final boolean equals(short seq1, short seq2) { // return seq1 == seq2; // } // // /* // * Example: maxSequence = 100; maxSequence/2 = 50; // * seq1 = 10; // * seq2 = 30; // * diff = -20; // * abs(-20 ) <= 50 ==> return -20; // * // * seq1 = 30; // * seq2 = 10; // * diff = 20; // * abs(20) <= 50 ==> return 20; // * // * // * seq1 = 70; // * seq2 = 10; // * diff = 60; // * abs(60) !<= 50 ==> return (-1 * 100) + 60 = -40 // * // * seq1 = 10; // * seq2 = 70; // * diff = -60; // * abs(-60) !<= 50 ==> return (--1 * 100) - 60 = 40 // * // */ // private static final int difference(int seq1, int seq2, int maxSequence) { // int diff = seq1 - seq2; // if (Math.abs(diff) <= maxSequence / 2) // return diff; // else // return (-Integer.signum(diff) * maxSequence) + diff; // } // } // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/SystemClock.java // public interface SystemClock { // long getTimeNow(); // } // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/control/ReceivedMapControl.java import com.github.mucaho.jnetrobust.util.IdComparator; import com.github.mucaho.jnetrobust.util.SystemClock; import java.nio.ByteBuffer; /* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; public class ReceivedMapControl extends AbstractMapControl { public interface TransmissionOrderListener { void handleOrderedData(short dataId, ByteBuffer orderedData); void handleUnorderedData(short dataId, ByteBuffer unorderedData); } private final TransmissionOrderListener listener; private short nextDataId; public ReceivedMapControl(short initialDataId, TransmissionOrderListener listener, int maxEntries, int maxEntryOffset,
int maxEntryOccurrences, long maxEntryTimeout, SystemClock systemClock) {
mucaho/jnetrobust
jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/control/ReceivedMapControl.java
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/IdComparator.java // public final class IdComparator implements Comparator<Short> { // public static final IdComparator instance = new IdComparator(); // // public static final int MAX_SEQUENCE = Short.MAX_VALUE - Short.MIN_VALUE + 1; // // @Override // public final int compare(Short seq1, Short seq2) { // if (seq1 == null && seq2 == null) { // return 0; // } else if (seq1 == null) { // return -1; // } else if (seq2 == null) { // return 1; // } else { // return compare(seq1.shortValue(), seq2.shortValue()); // } // } // // public final int compare(Short seq1, short seq2) { // return compare(seq1.shortValue(), seq2); // } // // public final int compare(short seq1, Short seq2) { // return compare(seq1, seq2.shortValue()); // } // // public final int compare(short seq1, short seq2) { // return difference(seq1 - Short.MIN_VALUE, seq2 - Short.MIN_VALUE, MAX_SEQUENCE); // } // // public final boolean equals(Short seq1, Short seq2) { // return equals(seq1.shortValue(), seq2.shortValue()); // } // // public final boolean equals(Short seq1, short seq2) { // return equals(seq1.shortValue(), seq2); // } // // public final boolean equals(short seq1, Short seq2) { // return equals(seq1, seq2.shortValue()); // } // // public final boolean equals(short seq1, short seq2) { // return seq1 == seq2; // } // // /* // * Example: maxSequence = 100; maxSequence/2 = 50; // * seq1 = 10; // * seq2 = 30; // * diff = -20; // * abs(-20 ) <= 50 ==> return -20; // * // * seq1 = 30; // * seq2 = 10; // * diff = 20; // * abs(20) <= 50 ==> return 20; // * // * // * seq1 = 70; // * seq2 = 10; // * diff = 60; // * abs(60) !<= 50 ==> return (-1 * 100) + 60 = -40 // * // * seq1 = 10; // * seq2 = 70; // * diff = -60; // * abs(-60) !<= 50 ==> return (--1 * 100) - 60 = 40 // * // */ // private static final int difference(int seq1, int seq2, int maxSequence) { // int diff = seq1 - seq2; // if (Math.abs(diff) <= maxSequence / 2) // return diff; // else // return (-Integer.signum(diff) * maxSequence) + diff; // } // } // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/SystemClock.java // public interface SystemClock { // long getTimeNow(); // }
import com.github.mucaho.jnetrobust.util.IdComparator; import com.github.mucaho.jnetrobust.util.SystemClock; import java.nio.ByteBuffer;
/* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; public class ReceivedMapControl extends AbstractMapControl { public interface TransmissionOrderListener { void handleOrderedData(short dataId, ByteBuffer orderedData); void handleUnorderedData(short dataId, ByteBuffer unorderedData); } private final TransmissionOrderListener listener; private short nextDataId; public ReceivedMapControl(short initialDataId, TransmissionOrderListener listener, int maxEntries, int maxEntryOffset, int maxEntryOccurrences, long maxEntryTimeout, SystemClock systemClock) { super(maxEntries, maxEntryOffset, maxEntryOccurrences, maxEntryTimeout, systemClock); this.listener = listener; this.nextDataId = (short) (initialDataId + 1); } @Override protected AbstractSegmentMap createMap() { return new ReceivedSegmentMap() { Segment put(Segment segment) {
// Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/IdComparator.java // public final class IdComparator implements Comparator<Short> { // public static final IdComparator instance = new IdComparator(); // // public static final int MAX_SEQUENCE = Short.MAX_VALUE - Short.MIN_VALUE + 1; // // @Override // public final int compare(Short seq1, Short seq2) { // if (seq1 == null && seq2 == null) { // return 0; // } else if (seq1 == null) { // return -1; // } else if (seq2 == null) { // return 1; // } else { // return compare(seq1.shortValue(), seq2.shortValue()); // } // } // // public final int compare(Short seq1, short seq2) { // return compare(seq1.shortValue(), seq2); // } // // public final int compare(short seq1, Short seq2) { // return compare(seq1, seq2.shortValue()); // } // // public final int compare(short seq1, short seq2) { // return difference(seq1 - Short.MIN_VALUE, seq2 - Short.MIN_VALUE, MAX_SEQUENCE); // } // // public final boolean equals(Short seq1, Short seq2) { // return equals(seq1.shortValue(), seq2.shortValue()); // } // // public final boolean equals(Short seq1, short seq2) { // return equals(seq1.shortValue(), seq2); // } // // public final boolean equals(short seq1, Short seq2) { // return equals(seq1, seq2.shortValue()); // } // // public final boolean equals(short seq1, short seq2) { // return seq1 == seq2; // } // // /* // * Example: maxSequence = 100; maxSequence/2 = 50; // * seq1 = 10; // * seq2 = 30; // * diff = -20; // * abs(-20 ) <= 50 ==> return -20; // * // * seq1 = 30; // * seq2 = 10; // * diff = 20; // * abs(20) <= 50 ==> return 20; // * // * // * seq1 = 70; // * seq2 = 10; // * diff = 60; // * abs(60) !<= 50 ==> return (-1 * 100) + 60 = -40 // * // * seq1 = 10; // * seq2 = 70; // * diff = -60; // * abs(-60) !<= 50 ==> return (--1 * 100) - 60 = 40 // * // */ // private static final int difference(int seq1, int seq2, int maxSequence) { // int diff = seq1 - seq2; // if (Math.abs(diff) <= maxSequence / 2) // return diff; // else // return (-Integer.signum(diff) * maxSequence) + diff; // } // } // // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/util/SystemClock.java // public interface SystemClock { // long getTimeNow(); // } // Path: jnetrobust-core/src/main/java/com/github/mucaho/jnetrobust/control/ReceivedMapControl.java import com.github.mucaho.jnetrobust.util.IdComparator; import com.github.mucaho.jnetrobust.util.SystemClock; import java.nio.ByteBuffer; /* * Copyright (c) 2014 mucaho (https://github.com/mucaho). * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.github.mucaho.jnetrobust.control; public class ReceivedMapControl extends AbstractMapControl { public interface TransmissionOrderListener { void handleOrderedData(short dataId, ByteBuffer orderedData); void handleUnorderedData(short dataId, ByteBuffer unorderedData); } private final TransmissionOrderListener listener; private short nextDataId; public ReceivedMapControl(short initialDataId, TransmissionOrderListener listener, int maxEntries, int maxEntryOffset, int maxEntryOccurrences, long maxEntryTimeout, SystemClock systemClock) { super(maxEntries, maxEntryOffset, maxEntryOccurrences, maxEntryTimeout, systemClock); this.listener = listener; this.nextDataId = (short) (initialDataId + 1); } @Override protected AbstractSegmentMap createMap() { return new ReceivedSegmentMap() { Segment put(Segment segment) {
if (IdComparator.instance.compare(segment.getDataId(), nextDataId) >= 0) {
dengxiayehu/fqrtmpplayer
player-android/src/org/videolan/libvlc/Media.java
// Path: player-android/src/org/videolan/libvlc/Media.java // public static abstract class Track { // public static class Type { // public static final int Unknown = -1; // public static final int Audio = 0; // public static final int Video = 1; // public static final int Text = 2; // } // // public final int type; // public final String codec; // public final String originalCodec; // public final int id; // public final int profile; // public final int level; // public final int bitrate; // public final String language; // public final String description; // // private Track(int type, String codec, String originalCodec, int id, int profile, // int level, int bitrate, String language, String description) { // this.type = type; // this.codec = codec; // this.originalCodec = originalCodec; // this.id = id; // this.profile = profile; // this.level = level; // this.bitrate = bitrate; // this.language = language; // this.description = description; // } // } // // Path: player-android/src/org/videolan/libvlc/util/AndroidUtil.java // public class AndroidUtil { // public static boolean isFroyoOrLater() { // return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO; // } // // public static boolean isGingerbreadOrLater() { // return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD; // } // // public static boolean isHoneycombOrLater() { // return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB; // } // // public static boolean isHoneycombMr1OrLater() { // return android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1; // } // // public static boolean isICSOrLater() { // return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH; // } // // public static boolean isJellyBeanOrLater() { // return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN; // } // // public static boolean isJellyBeanMR1OrLater() { // return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1; // } // // public static boolean isJellyBeanMR2OrLater() { // return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2; // } // // public static File UriToFile(Uri uri) { // return new File(uri.getPath().replaceFirst("file://", "")); // } // // /** // * Quickly converts path to URIs, which are mandatory in libVLC. // * // * @param path The path to be converted. // * @return A URI representation of path // */ // public static Uri PathToUri(String path) { // return Uri.fromFile(new File(path)); // } // // public static Uri LocationToUri(String location) { // Uri uri = Uri.parse(location); // if (uri.getScheme() == null) // throw new IllegalArgumentException("location has no scheme"); // return uri; // } // // public static Uri FileToUri(File file) { // return Uri.fromFile(file); // } // }
import java.io.FileDescriptor; import org.videolan.libvlc.Media.Track; import org.videolan.libvlc.util.AndroidUtil; import org.videolan.libvlc.util.HWDecoderUtil; import android.net.Uri;
} /** * see libvlc_state_t */ public static class State { public static final int NothingSpecial = 0; public static final int Opening = 1; public static final int Buffering = 2; public static final int Playing = 3; public static final int Paused = 4; public static final int Stopped = 5; public static final int Ended = 6; public static final int Error = 7; public static final int MAX = 8; } /** * see libvlc_media_parse_flag_t */ public static class Parse { public static final int ParseLocal = 0; public static final int ParseNetwork = 0x01; public static final int FetchLocal = 0x02; public static final int FetchNetwork = 0x04; } /** * see libvlc_media_track_t */
// Path: player-android/src/org/videolan/libvlc/Media.java // public static abstract class Track { // public static class Type { // public static final int Unknown = -1; // public static final int Audio = 0; // public static final int Video = 1; // public static final int Text = 2; // } // // public final int type; // public final String codec; // public final String originalCodec; // public final int id; // public final int profile; // public final int level; // public final int bitrate; // public final String language; // public final String description; // // private Track(int type, String codec, String originalCodec, int id, int profile, // int level, int bitrate, String language, String description) { // this.type = type; // this.codec = codec; // this.originalCodec = originalCodec; // this.id = id; // this.profile = profile; // this.level = level; // this.bitrate = bitrate; // this.language = language; // this.description = description; // } // } // // Path: player-android/src/org/videolan/libvlc/util/AndroidUtil.java // public class AndroidUtil { // public static boolean isFroyoOrLater() { // return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO; // } // // public static boolean isGingerbreadOrLater() { // return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD; // } // // public static boolean isHoneycombOrLater() { // return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB; // } // // public static boolean isHoneycombMr1OrLater() { // return android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1; // } // // public static boolean isICSOrLater() { // return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH; // } // // public static boolean isJellyBeanOrLater() { // return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN; // } // // public static boolean isJellyBeanMR1OrLater() { // return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1; // } // // public static boolean isJellyBeanMR2OrLater() { // return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2; // } // // public static File UriToFile(Uri uri) { // return new File(uri.getPath().replaceFirst("file://", "")); // } // // /** // * Quickly converts path to URIs, which are mandatory in libVLC. // * // * @param path The path to be converted. // * @return A URI representation of path // */ // public static Uri PathToUri(String path) { // return Uri.fromFile(new File(path)); // } // // public static Uri LocationToUri(String location) { // Uri uri = Uri.parse(location); // if (uri.getScheme() == null) // throw new IllegalArgumentException("location has no scheme"); // return uri; // } // // public static Uri FileToUri(File file) { // return Uri.fromFile(file); // } // } // Path: player-android/src/org/videolan/libvlc/Media.java import java.io.FileDescriptor; import org.videolan.libvlc.Media.Track; import org.videolan.libvlc.util.AndroidUtil; import org.videolan.libvlc.util.HWDecoderUtil; import android.net.Uri; } /** * see libvlc_state_t */ public static class State { public static final int NothingSpecial = 0; public static final int Opening = 1; public static final int Buffering = 2; public static final int Playing = 3; public static final int Paused = 4; public static final int Stopped = 5; public static final int Ended = 6; public static final int Error = 7; public static final int MAX = 8; } /** * see libvlc_media_parse_flag_t */ public static class Parse { public static final int ParseLocal = 0; public static final int ParseNetwork = 0x01; public static final int FetchLocal = 0x02; public static final int FetchNetwork = 0x04; } /** * see libvlc_media_track_t */
public static abstract class Track {
dengxiayehu/fqrtmpplayer
player-android/src/org/videolan/libvlc/AWindow.java
// Path: player-android/src/org/videolan/libvlc/util/AndroidUtil.java // public class AndroidUtil { // public static boolean isFroyoOrLater() { // return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO; // } // // public static boolean isGingerbreadOrLater() { // return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD; // } // // public static boolean isHoneycombOrLater() { // return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB; // } // // public static boolean isHoneycombMr1OrLater() { // return android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1; // } // // public static boolean isICSOrLater() { // return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH; // } // // public static boolean isJellyBeanOrLater() { // return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN; // } // // public static boolean isJellyBeanMR1OrLater() { // return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1; // } // // public static boolean isJellyBeanMR2OrLater() { // return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2; // } // // public static File UriToFile(Uri uri) { // return new File(uri.getPath().replaceFirst("file://", "")); // } // // /** // * Quickly converts path to URIs, which are mandatory in libVLC. // * // * @param path The path to be converted. // * @return A URI representation of path // */ // public static Uri PathToUri(String path) { // return Uri.fromFile(new File(path)); // } // // public static Uri LocationToUri(String location) { // Uri uri = Uri.parse(location); // if (uri.getScheme() == null) // throw new IllegalArgumentException("location has no scheme"); // return uri; // } // // public static Uri FileToUri(File file) { // return Uri.fromFile(file); // } // }
import android.util.Log; import android.view.Surface; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.TextureView; import java.util.ArrayList; import java.util.concurrent.atomic.AtomicInteger; import org.videolan.libvlc.util.AndroidUtil; import android.annotation.TargetApi; import android.graphics.SurfaceTexture; import android.os.Build; import android.os.Handler; import android.os.Looper;
onSurfaceDestroyed(); } }; @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private TextureView.SurfaceTextureListener createSurfaceTextureListener() { return new TextureView.SurfaceTextureListener() { @Override public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) { setSurface(new Surface(surfaceTexture)); } @Override public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) { } @Override public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) { onSurfaceDestroyed(); return true; } @Override public void onSurfaceTextureUpdated(SurfaceTexture surface) { } }; } private final TextureView.SurfaceTextureListener mSurfaceTextureListener =
// Path: player-android/src/org/videolan/libvlc/util/AndroidUtil.java // public class AndroidUtil { // public static boolean isFroyoOrLater() { // return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO; // } // // public static boolean isGingerbreadOrLater() { // return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD; // } // // public static boolean isHoneycombOrLater() { // return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB; // } // // public static boolean isHoneycombMr1OrLater() { // return android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1; // } // // public static boolean isICSOrLater() { // return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH; // } // // public static boolean isJellyBeanOrLater() { // return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN; // } // // public static boolean isJellyBeanMR1OrLater() { // return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1; // } // // public static boolean isJellyBeanMR2OrLater() { // return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2; // } // // public static File UriToFile(Uri uri) { // return new File(uri.getPath().replaceFirst("file://", "")); // } // // /** // * Quickly converts path to URIs, which are mandatory in libVLC. // * // * @param path The path to be converted. // * @return A URI representation of path // */ // public static Uri PathToUri(String path) { // return Uri.fromFile(new File(path)); // } // // public static Uri LocationToUri(String location) { // Uri uri = Uri.parse(location); // if (uri.getScheme() == null) // throw new IllegalArgumentException("location has no scheme"); // return uri; // } // // public static Uri FileToUri(File file) { // return Uri.fromFile(file); // } // } // Path: player-android/src/org/videolan/libvlc/AWindow.java import android.util.Log; import android.view.Surface; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.TextureView; import java.util.ArrayList; import java.util.concurrent.atomic.AtomicInteger; import org.videolan.libvlc.util.AndroidUtil; import android.annotation.TargetApi; import android.graphics.SurfaceTexture; import android.os.Build; import android.os.Handler; import android.os.Looper; onSurfaceDestroyed(); } }; @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private TextureView.SurfaceTextureListener createSurfaceTextureListener() { return new TextureView.SurfaceTextureListener() { @Override public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) { setSurface(new Surface(surfaceTexture)); } @Override public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) { } @Override public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) { onSurfaceDestroyed(); return true; } @Override public void onSurfaceTextureUpdated(SurfaceTexture surface) { } }; } private final TextureView.SurfaceTextureListener mSurfaceTextureListener =
AndroidUtil.isICSOrLater() ? createSurfaceTextureListener() : null;
dengxiayehu/fqrtmpplayer
player-android/src/com/dxyh/fqrtmpplayer/camera/CameraHolder.java
// Path: player-android/src/com/dxyh/fqrtmpplayer/util/Util.java // public static void Assert(boolean cond) { // if (!cond) { // throw new AssertionError(); // } // }
import static com.dxyh.fqrtmpplayer.util.Util.Assert; import java.io.IOException; import android.hardware.Camera; import android.hardware.Camera.CameraInfo; import android.hardware.Camera.Parameters; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; import android.util.Log;
if (CameraHolder.this.mUsers == 0) releaseCamera(); } break; } } } private CameraHolder() { HandlerThread ht = new HandlerThread("CameraHolder"); ht.start(); mHandler = new MyHandler(ht.getLooper()); mNumberOfCameras = android.hardware.Camera.getNumberOfCameras(); mInfo = new CameraInfo[mNumberOfCameras]; for (int i = 0; i < mNumberOfCameras; ++i) { mInfo[i] = new CameraInfo(); android.hardware.Camera.getCameraInfo(i, mInfo[i]); } } public int getNumberOfCameras() { return mNumberOfCameras; } public CameraInfo[] getCameraInfo() { return mInfo; } public synchronized android.hardware.Camera open(int cameraId) throws CameraHardwareException {
// Path: player-android/src/com/dxyh/fqrtmpplayer/util/Util.java // public static void Assert(boolean cond) { // if (!cond) { // throw new AssertionError(); // } // } // Path: player-android/src/com/dxyh/fqrtmpplayer/camera/CameraHolder.java import static com.dxyh.fqrtmpplayer.util.Util.Assert; import java.io.IOException; import android.hardware.Camera; import android.hardware.Camera.CameraInfo; import android.hardware.Camera.Parameters; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; import android.util.Log; if (CameraHolder.this.mUsers == 0) releaseCamera(); } break; } } } private CameraHolder() { HandlerThread ht = new HandlerThread("CameraHolder"); ht.start(); mHandler = new MyHandler(ht.getLooper()); mNumberOfCameras = android.hardware.Camera.getNumberOfCameras(); mInfo = new CameraInfo[mNumberOfCameras]; for (int i = 0; i < mNumberOfCameras; ++i) { mInfo[i] = new CameraInfo(); android.hardware.Camera.getCameraInfo(i, mInfo[i]); } } public int getNumberOfCameras() { return mNumberOfCameras; } public CameraInfo[] getCameraInfo() { return mInfo; } public synchronized android.hardware.Camera open(int cameraId) throws CameraHardwareException {
Assert(mUsers == 0);
dengxiayehu/fqrtmpplayer
player-android/src/com/dxyh/fqrtmpplayer/FQRtmpPlayer.java
// Path: player-android/src/com/dxyh/fqrtmpplayer/gui/UiTools.java // public class UiTools { // @SuppressWarnings("unused") // private static final String TAG = "UiTools"; // // public interface OnInputDialogClickListener { // public void onClick(DialogInterface dialog, final String input); // } // public static void inputDialog(Activity activity, final String title, // final String hint, // final OnInputDialogClickListener positive_listener, // final OnInputDialogClickListener negative_listener) { // final EditText edit = new EditText(MyApplication.getAppContext()); // edit.setFocusable(true); // if (!TextUtils.isEmpty(hint)) { // edit.setHint(hint); // } else { // edit.setHint(R.string.edit_hint); // } // edit.setSingleLine(true); // edit.setSelection(edit.getText().toString().length()); // // AlertDialog.Builder builder = // new AlertDialog.Builder(activity); // builder.setTitle(title) // .setIcon(android.R.drawable.ic_dialog_info) // .setView(edit) // .setCancelable(false) // .setPositiveButton(R.string.dialog_positive_btn_label,new Dialog.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // if (positive_listener != null) // positive_listener.onClick(dialog, edit.getText().toString()); // }}) // .setNegativeButton(R.string.dialog_negative_btn_label, new Dialog.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // if (negative_listener != null) // negative_listener.onClick(dialog, edit.getText().toString()); // }}); // builder.show(); // } // // public static final int SHORT_TOAST = Toast.LENGTH_SHORT; // public static final int LONG_TOAST = Toast.LENGTH_LONG; // // public static void toast(final Activity activity, final String text, final int duration) { // activity.runOnUiThread(new Runnable() { // @Override // public void run() { // Toast.makeText(activity, text, duration).show(); // } // }); // } // // public static void adjust_brightness(final Activity activity, final float brightness) { // activity.runOnUiThread(new Runnable() { // @Override // public void run() { // Window win = activity.getWindow(); // // int mode = Settings.System.getInt( // activity.getContentResolver(), // Settings.System.SCREEN_BRIGHTNESS_MODE, // Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL); // if (mode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) { // WindowManager.LayoutParams winParams = win.getAttributes(); // winParams.screenBrightness = brightness; // win.setAttributes(winParams); // } // } // }); // } // }
import com.dxyh.fqrtmpplayer.aidl.IClientCallback; import com.dxyh.fqrtmpplayer.aidl.IPlayer; import com.dxyh.fqrtmpplayer.gui.UiTools; import android.annotation.SuppressLint; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.RemoteException; import android.text.TextUtils; import android.util.Log; import android.view.SurfaceView;
public void onPrepared(IPlayer player) throws RemoteException { Log.i(TAG, "onPrepared"); mHandler.sendEmptyMessage(ON_PREPARED); } @Override public void onCompletion(IPlayer player) throws RemoteException { Log.i(TAG, "onCompletion"); mHandler.sendEmptyMessage(ON_COMPLETION); } @Override public void onBufferingUpdateListener(IPlayer player, int percent) throws RemoteException { Log.i(TAG, "onBufferingUpdateListener"); Message msg = mHandler.obtainMessage(ON_BUFFERING, percent, 0); mHandler.sendMessage(msg); } @Override public boolean onError(IPlayer player, int what, int extra) throws RemoteException { Log.i(TAG, "onError"); Message msg = mHandler.obtainMessage(ON_ERROR, what, extra); mHandler.sendMessage(msg); return true; } }; @Override public void process(final String url) { if (TextUtils.isEmpty(url)) {
// Path: player-android/src/com/dxyh/fqrtmpplayer/gui/UiTools.java // public class UiTools { // @SuppressWarnings("unused") // private static final String TAG = "UiTools"; // // public interface OnInputDialogClickListener { // public void onClick(DialogInterface dialog, final String input); // } // public static void inputDialog(Activity activity, final String title, // final String hint, // final OnInputDialogClickListener positive_listener, // final OnInputDialogClickListener negative_listener) { // final EditText edit = new EditText(MyApplication.getAppContext()); // edit.setFocusable(true); // if (!TextUtils.isEmpty(hint)) { // edit.setHint(hint); // } else { // edit.setHint(R.string.edit_hint); // } // edit.setSingleLine(true); // edit.setSelection(edit.getText().toString().length()); // // AlertDialog.Builder builder = // new AlertDialog.Builder(activity); // builder.setTitle(title) // .setIcon(android.R.drawable.ic_dialog_info) // .setView(edit) // .setCancelable(false) // .setPositiveButton(R.string.dialog_positive_btn_label,new Dialog.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // if (positive_listener != null) // positive_listener.onClick(dialog, edit.getText().toString()); // }}) // .setNegativeButton(R.string.dialog_negative_btn_label, new Dialog.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // if (negative_listener != null) // negative_listener.onClick(dialog, edit.getText().toString()); // }}); // builder.show(); // } // // public static final int SHORT_TOAST = Toast.LENGTH_SHORT; // public static final int LONG_TOAST = Toast.LENGTH_LONG; // // public static void toast(final Activity activity, final String text, final int duration) { // activity.runOnUiThread(new Runnable() { // @Override // public void run() { // Toast.makeText(activity, text, duration).show(); // } // }); // } // // public static void adjust_brightness(final Activity activity, final float brightness) { // activity.runOnUiThread(new Runnable() { // @Override // public void run() { // Window win = activity.getWindow(); // // int mode = Settings.System.getInt( // activity.getContentResolver(), // Settings.System.SCREEN_BRIGHTNESS_MODE, // Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL); // if (mode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) { // WindowManager.LayoutParams winParams = win.getAttributes(); // winParams.screenBrightness = brightness; // win.setAttributes(winParams); // } // } // }); // } // } // Path: player-android/src/com/dxyh/fqrtmpplayer/FQRtmpPlayer.java import com.dxyh.fqrtmpplayer.aidl.IClientCallback; import com.dxyh.fqrtmpplayer.aidl.IPlayer; import com.dxyh.fqrtmpplayer.gui.UiTools; import android.annotation.SuppressLint; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.RemoteException; import android.text.TextUtils; import android.util.Log; import android.view.SurfaceView; public void onPrepared(IPlayer player) throws RemoteException { Log.i(TAG, "onPrepared"); mHandler.sendEmptyMessage(ON_PREPARED); } @Override public void onCompletion(IPlayer player) throws RemoteException { Log.i(TAG, "onCompletion"); mHandler.sendEmptyMessage(ON_COMPLETION); } @Override public void onBufferingUpdateListener(IPlayer player, int percent) throws RemoteException { Log.i(TAG, "onBufferingUpdateListener"); Message msg = mHandler.obtainMessage(ON_BUFFERING, percent, 0); mHandler.sendMessage(msg); } @Override public boolean onError(IPlayer player, int what, int extra) throws RemoteException { Log.i(TAG, "onError"); Message msg = mHandler.obtainMessage(ON_ERROR, what, extra); mHandler.sendMessage(msg); return true; } }; @Override public void process(final String url) { if (TextUtils.isEmpty(url)) {
UiTools.toast(mActivity, "Invalid play url", UiTools.SHORT_TOAST);
dengxiayehu/fqrtmpplayer
player-android/src/com/dxyh/fqrtmpplayer/gui/UiTools.java
// Path: player-android/src/com/dxyh/fqrtmpplayer/MyApplication.java // public class MyApplication extends Application implements LibFQRtmp.OnNativeCrashListener { // private final static String TAG = "MyApplication"; // private static MyApplication instance; // // private ThreadPoolExecutor mThreadPool = new ThreadPoolExecutor(0, 3, 2, TimeUnit.SECONDS, // new LinkedBlockingQueue<Runnable>()); // // @Override // public void onCreate() { // super.onCreate(); // // instance = this; // // LibFQRtmp.setOnNativeCrashListener(this); // } // // @Override // public void onNativeCrash() { // Log.e(TAG, "FQRtmpPlayer crashed"); // } // // @Override // public void onLowMemory() { // super.onLowMemory(); // Log.w(TAG, "System is running low on memory"); // } // // public static MyApplication getInstance() { // return instance; // } // // public static Context getAppContext() { // return instance; // } // // public static Resources getAppResources() { // return instance.getResources(); // } // // public static void runBackground(Runnable runnable) { // instance.mThreadPool.execute(runnable); // } // }
import com.dxyh.fqrtmpplayer.MyApplication; import com.dxyh.fqrtmpplayer.R; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.provider.Settings; import android.text.TextUtils; import android.view.Window; import android.view.WindowManager; import android.widget.EditText; import android.widget.Toast;
package com.dxyh.fqrtmpplayer.gui; public class UiTools { @SuppressWarnings("unused") private static final String TAG = "UiTools"; public interface OnInputDialogClickListener { public void onClick(DialogInterface dialog, final String input); } public static void inputDialog(Activity activity, final String title, final String hint, final OnInputDialogClickListener positive_listener, final OnInputDialogClickListener negative_listener) {
// Path: player-android/src/com/dxyh/fqrtmpplayer/MyApplication.java // public class MyApplication extends Application implements LibFQRtmp.OnNativeCrashListener { // private final static String TAG = "MyApplication"; // private static MyApplication instance; // // private ThreadPoolExecutor mThreadPool = new ThreadPoolExecutor(0, 3, 2, TimeUnit.SECONDS, // new LinkedBlockingQueue<Runnable>()); // // @Override // public void onCreate() { // super.onCreate(); // // instance = this; // // LibFQRtmp.setOnNativeCrashListener(this); // } // // @Override // public void onNativeCrash() { // Log.e(TAG, "FQRtmpPlayer crashed"); // } // // @Override // public void onLowMemory() { // super.onLowMemory(); // Log.w(TAG, "System is running low on memory"); // } // // public static MyApplication getInstance() { // return instance; // } // // public static Context getAppContext() { // return instance; // } // // public static Resources getAppResources() { // return instance.getResources(); // } // // public static void runBackground(Runnable runnable) { // instance.mThreadPool.execute(runnable); // } // } // Path: player-android/src/com/dxyh/fqrtmpplayer/gui/UiTools.java import com.dxyh.fqrtmpplayer.MyApplication; import com.dxyh.fqrtmpplayer.R; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.provider.Settings; import android.text.TextUtils; import android.view.Window; import android.view.WindowManager; import android.widget.EditText; import android.widget.Toast; package com.dxyh.fqrtmpplayer.gui; public class UiTools { @SuppressWarnings("unused") private static final String TAG = "UiTools"; public interface OnInputDialogClickListener { public void onClick(DialogInterface dialog, final String input); } public static void inputDialog(Activity activity, final String title, final String hint, final OnInputDialogClickListener positive_listener, final OnInputDialogClickListener negative_listener) {
final EditText edit = new EditText(MyApplication.getAppContext());
lukaspili/Volley-Ball
samples/src/main/java/com/siu/android/volleyball/samples/volley/request/SampleNetworkRequest.java
// Path: library/src/main/java/com/siu/android/volleyball/BallResponse.java // public class BallResponse<T> { // // public static enum ResponseSource { // LOCAL, CACHE, NETWORK // } // // protected Response<T> mResponse; // protected ResponseSource mResponseSource; // protected boolean mIdentical = false; // // /** // * Returns whether this response is considered successful. // */ // public boolean isSuccess() { // return mResponse.isSuccess(); // } // // public static <T> BallResponse<T> identical(ResponseSource responseSource) { // return new BallResponse<T>(Response.<T>success(null, null), responseSource, true); // } // // public static <T> BallResponse<T> success(T result) { // return new BallResponse<T>(Response.success(result, null)); // } // // public static <T> BallResponse<T> success(T result, Cache.Entry cacheEntry) { // return new BallResponse<T>(Response.success(result, cacheEntry)); // } // // public static <T> BallResponse<T> error(VolleyError error) { // return new BallResponse<T>(Response.<T>error(error), ResponseSource.NETWORK); // error cames always from network // } // // protected BallResponse(Response<T> response) { // this(response, null, false); // } // // protected BallResponse(Response<T> response, ResponseSource responseSource) { // this(response, responseSource, false); // } // // public BallResponse(Response<T> response, ResponseSource responseSource, boolean identical) { // mResponse = response; // mResponseSource = responseSource; // mIdentical = identical; // } // // public ResponseSource getResponseSource() { // return mResponseSource; // } // // public void setResponseSource(ResponseSource responseSource) { // this.mResponseSource = responseSource; // } // // public boolean isIntermediate() { // return mResponse.intermediate; // } // // public void setIntermediate(boolean intermediate) { // mResponse.intermediate = intermediate; // } // // public T getResult() { // return mResponse.result; // } // // public Cache.Entry getCacheEntry() { // return mResponse.cacheEntry; // } // // public VolleyError getError() { // return mResponse.error; // } // // public boolean isIdentical() { // return mIdentical; // } // // public void setIdentical(boolean identical) { // mIdentical = identical; // } // } // // Path: library/src/main/java/com/siu/android/volleyball/request/NetworkRequest.java // public abstract class NetworkRequest<T> extends BallRequest<T> { // // protected NetworkRequest(int method, String url, Response.ErrorListener errorListener) { // super(method, url, errorListener); // } // // public NetworkRequest(int method, String url, SingleResponseListener<T> responseListener, Response.ErrorListener errorListener) { // super(method, url, responseListener, errorListener); // } // // @Override // public boolean shouldProcessNetwork() { // return true; // } // // @Override // protected NetworkRequestProcessor createNetworkRequestProcessor() { // return new NetworkRequestProcessor() { // @Override // public BallResponse<T> parseNetworkResponse(NetworkResponse networkResponse) { // return parseBallNetworkResponse(networkResponse); // } // }; // } // // protected abstract BallResponse<T> parseBallNetworkResponse(NetworkResponse response); // } // // Path: library/src/main/java/com/siu/android/volleyball/response/SingleResponseListener.java // public abstract class SingleResponseListener<T> implements ResponseListener<T> { // // /** // * Can happen when the response is soft cached // * // * @param response // * @param responseSource // */ // @Override // public final void onIntermediateResponse(T response, BallResponse.ResponseSource responseSource) { // onResponse(response); // } // // @Override // public final void onFinalResponse(T response, BallResponse.ResponseSource responseSource) { // onResponse(response); // } // // /** // * Can happen when the response is soft cached. Maybe ? // * // * @param responseSource // */ // @Override // public final void onFinalResponseIdenticalToIntermediate(BallResponse.ResponseSource responseSource) { // // } // // //TODO: add response source because it can still be soft cached response // public abstract void onResponse(T response); // }
import com.android.volley.NetworkResponse; import com.android.volley.Response; import com.android.volley.toolbox.HttpHeaderParser; import com.siu.android.volleyball.BallResponse; import com.siu.android.volleyball.request.NetworkRequest; import com.siu.android.volleyball.response.SingleResponseListener;
package com.siu.android.volleyball.samples.volley.request; /** * Created by lukas on 9/17/13. */ public class SampleNetworkRequest extends NetworkRequest<String> { public SampleNetworkRequest(int method, String url, SingleResponseListener<String> responseListener, Response.ErrorListener errorListener) { super(method, url, responseListener, errorListener); } @Override
// Path: library/src/main/java/com/siu/android/volleyball/BallResponse.java // public class BallResponse<T> { // // public static enum ResponseSource { // LOCAL, CACHE, NETWORK // } // // protected Response<T> mResponse; // protected ResponseSource mResponseSource; // protected boolean mIdentical = false; // // /** // * Returns whether this response is considered successful. // */ // public boolean isSuccess() { // return mResponse.isSuccess(); // } // // public static <T> BallResponse<T> identical(ResponseSource responseSource) { // return new BallResponse<T>(Response.<T>success(null, null), responseSource, true); // } // // public static <T> BallResponse<T> success(T result) { // return new BallResponse<T>(Response.success(result, null)); // } // // public static <T> BallResponse<T> success(T result, Cache.Entry cacheEntry) { // return new BallResponse<T>(Response.success(result, cacheEntry)); // } // // public static <T> BallResponse<T> error(VolleyError error) { // return new BallResponse<T>(Response.<T>error(error), ResponseSource.NETWORK); // error cames always from network // } // // protected BallResponse(Response<T> response) { // this(response, null, false); // } // // protected BallResponse(Response<T> response, ResponseSource responseSource) { // this(response, responseSource, false); // } // // public BallResponse(Response<T> response, ResponseSource responseSource, boolean identical) { // mResponse = response; // mResponseSource = responseSource; // mIdentical = identical; // } // // public ResponseSource getResponseSource() { // return mResponseSource; // } // // public void setResponseSource(ResponseSource responseSource) { // this.mResponseSource = responseSource; // } // // public boolean isIntermediate() { // return mResponse.intermediate; // } // // public void setIntermediate(boolean intermediate) { // mResponse.intermediate = intermediate; // } // // public T getResult() { // return mResponse.result; // } // // public Cache.Entry getCacheEntry() { // return mResponse.cacheEntry; // } // // public VolleyError getError() { // return mResponse.error; // } // // public boolean isIdentical() { // return mIdentical; // } // // public void setIdentical(boolean identical) { // mIdentical = identical; // } // } // // Path: library/src/main/java/com/siu/android/volleyball/request/NetworkRequest.java // public abstract class NetworkRequest<T> extends BallRequest<T> { // // protected NetworkRequest(int method, String url, Response.ErrorListener errorListener) { // super(method, url, errorListener); // } // // public NetworkRequest(int method, String url, SingleResponseListener<T> responseListener, Response.ErrorListener errorListener) { // super(method, url, responseListener, errorListener); // } // // @Override // public boolean shouldProcessNetwork() { // return true; // } // // @Override // protected NetworkRequestProcessor createNetworkRequestProcessor() { // return new NetworkRequestProcessor() { // @Override // public BallResponse<T> parseNetworkResponse(NetworkResponse networkResponse) { // return parseBallNetworkResponse(networkResponse); // } // }; // } // // protected abstract BallResponse<T> parseBallNetworkResponse(NetworkResponse response); // } // // Path: library/src/main/java/com/siu/android/volleyball/response/SingleResponseListener.java // public abstract class SingleResponseListener<T> implements ResponseListener<T> { // // /** // * Can happen when the response is soft cached // * // * @param response // * @param responseSource // */ // @Override // public final void onIntermediateResponse(T response, BallResponse.ResponseSource responseSource) { // onResponse(response); // } // // @Override // public final void onFinalResponse(T response, BallResponse.ResponseSource responseSource) { // onResponse(response); // } // // /** // * Can happen when the response is soft cached. Maybe ? // * // * @param responseSource // */ // @Override // public final void onFinalResponseIdenticalToIntermediate(BallResponse.ResponseSource responseSource) { // // } // // //TODO: add response source because it can still be soft cached response // public abstract void onResponse(T response); // } // Path: samples/src/main/java/com/siu/android/volleyball/samples/volley/request/SampleNetworkRequest.java import com.android.volley.NetworkResponse; import com.android.volley.Response; import com.android.volley.toolbox.HttpHeaderParser; import com.siu.android.volleyball.BallResponse; import com.siu.android.volleyball.request.NetworkRequest; import com.siu.android.volleyball.response.SingleResponseListener; package com.siu.android.volleyball.samples.volley.request; /** * Created by lukas on 9/17/13. */ public class SampleNetworkRequest extends NetworkRequest<String> { public SampleNetworkRequest(int method, String url, SingleResponseListener<String> responseListener, Response.ErrorListener errorListener) { super(method, url, responseListener, errorListener); } @Override
protected BallResponse<String> parseBallNetworkResponse(NetworkResponse response) {
lukaspili/Volley-Ball
samples/src/main/java/com/siu/android/volleyball/samples/volley/request/SampleLocalRequest.java
// Path: library/src/main/java/com/siu/android/volleyball/request/LocalRequest.java // public abstract class LocalRequest<T> extends BallRequest<T> { // // protected LocalRequest() { // super(-1, null, null); // } // // protected LocalRequest(SingleResponseListener<T> responseListener) { // super(-1, null, responseListener, null); // } // // @Override // public boolean shouldProcessLocal() { // return true; // } // // @Override // protected LocalRequestProcessor<T> createLocalRequestProcessor() { // return new LocalRequestProcessor<T>() { // @Override // public T getLocalResponse() { // return performLocal(); // } // // @Override // public void saveLocalResponse(T response) { // // } // }; // } // // public abstract T performLocal(); // } // // Path: library/src/main/java/com/siu/android/volleyball/response/ResponseListener.java // public interface ResponseListener<T> { // // public void onIntermediateResponse(T response, BallResponse.ResponseSource responseSource); // // public void onFinalResponse(T response, BallResponse.ResponseSource responseSource); // // public void onFinalResponseIdenticalToIntermediate(BallResponse.ResponseSource responseSource); // } // // Path: library/src/main/java/com/siu/android/volleyball/response/SingleResponseListener.java // public abstract class SingleResponseListener<T> implements ResponseListener<T> { // // /** // * Can happen when the response is soft cached // * // * @param response // * @param responseSource // */ // @Override // public final void onIntermediateResponse(T response, BallResponse.ResponseSource responseSource) { // onResponse(response); // } // // @Override // public final void onFinalResponse(T response, BallResponse.ResponseSource responseSource) { // onResponse(response); // } // // /** // * Can happen when the response is soft cached. Maybe ? // * // * @param responseSource // */ // @Override // public final void onFinalResponseIdenticalToIntermediate(BallResponse.ResponseSource responseSource) { // // } // // //TODO: add response source because it can still be soft cached response // public abstract void onResponse(T response); // } // // Path: samples/src/main/java/com/siu/android/volleyball/samples/util/ScenarioUtils.java // public class ScenarioUtils { // // public static final void waitSeveralSeconds(int seconds) { // try { // Thread.sleep(seconds * 1000); // } catch (InterruptedException e) { // throw new RuntimeException(e); // } // } // }
import com.android.volley.Response; import com.siu.android.volleyball.request.LocalRequest; import com.siu.android.volleyball.response.ResponseListener; import com.siu.android.volleyball.response.SingleResponseListener; import com.siu.android.volleyball.samples.util.ScenarioUtils;
package com.siu.android.volleyball.samples.volley.request; /** * Sample local request * The request here returns a String object result of the async operation, but you can also use the Void type */ public class SampleLocalRequest extends LocalRequest<String> { public SampleLocalRequest(SingleResponseListener<String> responseListener) { super(responseListener); } @Override public String performLocal() { // perform your task outside of UI thread here
// Path: library/src/main/java/com/siu/android/volleyball/request/LocalRequest.java // public abstract class LocalRequest<T> extends BallRequest<T> { // // protected LocalRequest() { // super(-1, null, null); // } // // protected LocalRequest(SingleResponseListener<T> responseListener) { // super(-1, null, responseListener, null); // } // // @Override // public boolean shouldProcessLocal() { // return true; // } // // @Override // protected LocalRequestProcessor<T> createLocalRequestProcessor() { // return new LocalRequestProcessor<T>() { // @Override // public T getLocalResponse() { // return performLocal(); // } // // @Override // public void saveLocalResponse(T response) { // // } // }; // } // // public abstract T performLocal(); // } // // Path: library/src/main/java/com/siu/android/volleyball/response/ResponseListener.java // public interface ResponseListener<T> { // // public void onIntermediateResponse(T response, BallResponse.ResponseSource responseSource); // // public void onFinalResponse(T response, BallResponse.ResponseSource responseSource); // // public void onFinalResponseIdenticalToIntermediate(BallResponse.ResponseSource responseSource); // } // // Path: library/src/main/java/com/siu/android/volleyball/response/SingleResponseListener.java // public abstract class SingleResponseListener<T> implements ResponseListener<T> { // // /** // * Can happen when the response is soft cached // * // * @param response // * @param responseSource // */ // @Override // public final void onIntermediateResponse(T response, BallResponse.ResponseSource responseSource) { // onResponse(response); // } // // @Override // public final void onFinalResponse(T response, BallResponse.ResponseSource responseSource) { // onResponse(response); // } // // /** // * Can happen when the response is soft cached. Maybe ? // * // * @param responseSource // */ // @Override // public final void onFinalResponseIdenticalToIntermediate(BallResponse.ResponseSource responseSource) { // // } // // //TODO: add response source because it can still be soft cached response // public abstract void onResponse(T response); // } // // Path: samples/src/main/java/com/siu/android/volleyball/samples/util/ScenarioUtils.java // public class ScenarioUtils { // // public static final void waitSeveralSeconds(int seconds) { // try { // Thread.sleep(seconds * 1000); // } catch (InterruptedException e) { // throw new RuntimeException(e); // } // } // } // Path: samples/src/main/java/com/siu/android/volleyball/samples/volley/request/SampleLocalRequest.java import com.android.volley.Response; import com.siu.android.volleyball.request.LocalRequest; import com.siu.android.volleyball.response.ResponseListener; import com.siu.android.volleyball.response.SingleResponseListener; import com.siu.android.volleyball.samples.util.ScenarioUtils; package com.siu.android.volleyball.samples.volley.request; /** * Sample local request * The request here returns a String object result of the async operation, but you can also use the Void type */ public class SampleLocalRequest extends LocalRequest<String> { public SampleLocalRequest(SingleResponseListener<String> responseListener) { super(responseListener); } @Override public String performLocal() { // perform your task outside of UI thread here
ScenarioUtils.waitSeveralSeconds(2);
lukaspili/Volley-Ball
library/src/main/java/com/siu/android/volleyball/mock/FileMockNetwork.java
// Path: library/src/main/java/com/siu/android/volleyball/exception/BallException.java // public class BallException extends RuntimeException { // // public BallException() { // } // // public BallException(String detailMessage) { // super(detailMessage); // } // // public BallException(String detailMessage, Object... args) { // super(String.format(detailMessage, args)); // } // // // // public BallException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public BallException(Throwable throwable) { // super(throwable); // } // } // // Path: library/src/main/java/com/siu/android/volleyball/util/BallLogger.java // public class BallLogger { // // // D // public static void d(String string) { // Log.d(BallLogger.class.getName(), string); // } // // public static void d(String string, Throwable tr) { // Log.d(BallLogger.class.getName(), string, tr); // } // // public static void d(String string, Object... args) { // d(String.format(string, args)); // } // // public static void d(String string, Throwable tr, Object... args) { // d(String.format(string, args), tr); // } // // // // E // public static void e(String string) { // Log.e(BallLogger.class.getName(), string); // } // // public static void e(String string, Throwable tr) { // Log.e(BallLogger.class.getName(), string, tr); // } // // public static void e(String string, Object... args) { // e(String.format(string, args)); // } // // public static void e(String string, Throwable tr, Object... args) { // e(String.format(string, args), tr); // } // } // // Path: library/src/main/java/com/siu/android/volleyball/util/ConfigUtils.java // public class ConfigUtils { // // public static final HttpStack getDefaultHttpStack(Context context) { // String userAgent = "volley/0"; // try { // String packageName = context.getPackageName(); // PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0); // userAgent = packageName + "/" + info.versionCode; // } catch (PackageManager.NameNotFoundException e) { // } // // HttpStack stack; // if (Build.VERSION.SDK_INT >= 9) { // stack = new HurlStack(); // } else { // // Prior to Gingerbread, HttpUrlConnection was unreliable. // // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html // stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent)); // } // // return stack; // } // // public static Network getDefaultNetwork(HttpStack httpStack) { // return new BasicNetwork(httpStack); // } // // public static Network getDefaultNetworkWithDefaultHttpStack(Context context) { // return new BasicNetwork(getDefaultHttpStack(context)); // } // } // // Path: library/src/main/java/com/siu/android/volleyball/util/RequestUtils.java // public class RequestUtils { // // /** // * Get the equivalent string of the int request http method // * // * @param method the method as int constant // * @return the method as string // * @throws IllegalArgumentException if no match is found between the int constant and the equivalent string // */ // public static final String methodToString(int method) throws IllegalArgumentException { // switch (method) { // case Request.Method.GET: // return "GET"; // case Request.Method.POST: // return "POST"; // case Request.Method.PUT: // return "PUT"; // case Request.Method.DELETE: // return "DELETE"; // } // // throw new IllegalArgumentException("Unkown method for int constant " + method); // } // }
import android.content.Context; import com.android.volley.Network; import com.android.volley.NetworkResponse; import com.android.volley.NoConnectionError; import com.android.volley.Request; import com.android.volley.VolleyError; import com.android.volley.toolbox.HttpStack; import com.siu.android.volleyball.exception.BallException; import com.siu.android.volleyball.util.BallLogger; import com.siu.android.volleyball.util.ConfigUtils; import com.siu.android.volleyball.util.RequestUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map;
package com.siu.android.volleyball.mock; /** * Created by lukas on 8/29/13. */ public class FileMockNetwork implements Network { private Context mContext; private Config mConfig; public FileMockNetwork(Context context) { this(context, new Config()); } public FileMockNetwork(Context context, Config config) { mContext = context; mConfig = config; // configure the real network for non mocked requests if (config.mRealNetwork == null) {
// Path: library/src/main/java/com/siu/android/volleyball/exception/BallException.java // public class BallException extends RuntimeException { // // public BallException() { // } // // public BallException(String detailMessage) { // super(detailMessage); // } // // public BallException(String detailMessage, Object... args) { // super(String.format(detailMessage, args)); // } // // // // public BallException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public BallException(Throwable throwable) { // super(throwable); // } // } // // Path: library/src/main/java/com/siu/android/volleyball/util/BallLogger.java // public class BallLogger { // // // D // public static void d(String string) { // Log.d(BallLogger.class.getName(), string); // } // // public static void d(String string, Throwable tr) { // Log.d(BallLogger.class.getName(), string, tr); // } // // public static void d(String string, Object... args) { // d(String.format(string, args)); // } // // public static void d(String string, Throwable tr, Object... args) { // d(String.format(string, args), tr); // } // // // // E // public static void e(String string) { // Log.e(BallLogger.class.getName(), string); // } // // public static void e(String string, Throwable tr) { // Log.e(BallLogger.class.getName(), string, tr); // } // // public static void e(String string, Object... args) { // e(String.format(string, args)); // } // // public static void e(String string, Throwable tr, Object... args) { // e(String.format(string, args), tr); // } // } // // Path: library/src/main/java/com/siu/android/volleyball/util/ConfigUtils.java // public class ConfigUtils { // // public static final HttpStack getDefaultHttpStack(Context context) { // String userAgent = "volley/0"; // try { // String packageName = context.getPackageName(); // PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0); // userAgent = packageName + "/" + info.versionCode; // } catch (PackageManager.NameNotFoundException e) { // } // // HttpStack stack; // if (Build.VERSION.SDK_INT >= 9) { // stack = new HurlStack(); // } else { // // Prior to Gingerbread, HttpUrlConnection was unreliable. // // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html // stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent)); // } // // return stack; // } // // public static Network getDefaultNetwork(HttpStack httpStack) { // return new BasicNetwork(httpStack); // } // // public static Network getDefaultNetworkWithDefaultHttpStack(Context context) { // return new BasicNetwork(getDefaultHttpStack(context)); // } // } // // Path: library/src/main/java/com/siu/android/volleyball/util/RequestUtils.java // public class RequestUtils { // // /** // * Get the equivalent string of the int request http method // * // * @param method the method as int constant // * @return the method as string // * @throws IllegalArgumentException if no match is found between the int constant and the equivalent string // */ // public static final String methodToString(int method) throws IllegalArgumentException { // switch (method) { // case Request.Method.GET: // return "GET"; // case Request.Method.POST: // return "POST"; // case Request.Method.PUT: // return "PUT"; // case Request.Method.DELETE: // return "DELETE"; // } // // throw new IllegalArgumentException("Unkown method for int constant " + method); // } // } // Path: library/src/main/java/com/siu/android/volleyball/mock/FileMockNetwork.java import android.content.Context; import com.android.volley.Network; import com.android.volley.NetworkResponse; import com.android.volley.NoConnectionError; import com.android.volley.Request; import com.android.volley.VolleyError; import com.android.volley.toolbox.HttpStack; import com.siu.android.volleyball.exception.BallException; import com.siu.android.volleyball.util.BallLogger; import com.siu.android.volleyball.util.ConfigUtils; import com.siu.android.volleyball.util.RequestUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; package com.siu.android.volleyball.mock; /** * Created by lukas on 8/29/13. */ public class FileMockNetwork implements Network { private Context mContext; private Config mConfig; public FileMockNetwork(Context context) { this(context, new Config()); } public FileMockNetwork(Context context, Config config) { mContext = context; mConfig = config; // configure the real network for non mocked requests if (config.mRealNetwork == null) {
HttpStack httpStack = (config.mRealNetworkHttpStack == null) ? ConfigUtils.getDefaultHttpStack(mContext) : config.mRealNetworkHttpStack;
lukaspili/Volley-Ball
library/src/main/java/com/siu/android/volleyball/mock/FileMockNetwork.java
// Path: library/src/main/java/com/siu/android/volleyball/exception/BallException.java // public class BallException extends RuntimeException { // // public BallException() { // } // // public BallException(String detailMessage) { // super(detailMessage); // } // // public BallException(String detailMessage, Object... args) { // super(String.format(detailMessage, args)); // } // // // // public BallException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public BallException(Throwable throwable) { // super(throwable); // } // } // // Path: library/src/main/java/com/siu/android/volleyball/util/BallLogger.java // public class BallLogger { // // // D // public static void d(String string) { // Log.d(BallLogger.class.getName(), string); // } // // public static void d(String string, Throwable tr) { // Log.d(BallLogger.class.getName(), string, tr); // } // // public static void d(String string, Object... args) { // d(String.format(string, args)); // } // // public static void d(String string, Throwable tr, Object... args) { // d(String.format(string, args), tr); // } // // // // E // public static void e(String string) { // Log.e(BallLogger.class.getName(), string); // } // // public static void e(String string, Throwable tr) { // Log.e(BallLogger.class.getName(), string, tr); // } // // public static void e(String string, Object... args) { // e(String.format(string, args)); // } // // public static void e(String string, Throwable tr, Object... args) { // e(String.format(string, args), tr); // } // } // // Path: library/src/main/java/com/siu/android/volleyball/util/ConfigUtils.java // public class ConfigUtils { // // public static final HttpStack getDefaultHttpStack(Context context) { // String userAgent = "volley/0"; // try { // String packageName = context.getPackageName(); // PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0); // userAgent = packageName + "/" + info.versionCode; // } catch (PackageManager.NameNotFoundException e) { // } // // HttpStack stack; // if (Build.VERSION.SDK_INT >= 9) { // stack = new HurlStack(); // } else { // // Prior to Gingerbread, HttpUrlConnection was unreliable. // // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html // stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent)); // } // // return stack; // } // // public static Network getDefaultNetwork(HttpStack httpStack) { // return new BasicNetwork(httpStack); // } // // public static Network getDefaultNetworkWithDefaultHttpStack(Context context) { // return new BasicNetwork(getDefaultHttpStack(context)); // } // } // // Path: library/src/main/java/com/siu/android/volleyball/util/RequestUtils.java // public class RequestUtils { // // /** // * Get the equivalent string of the int request http method // * // * @param method the method as int constant // * @return the method as string // * @throws IllegalArgumentException if no match is found between the int constant and the equivalent string // */ // public static final String methodToString(int method) throws IllegalArgumentException { // switch (method) { // case Request.Method.GET: // return "GET"; // case Request.Method.POST: // return "POST"; // case Request.Method.PUT: // return "PUT"; // case Request.Method.DELETE: // return "DELETE"; // } // // throw new IllegalArgumentException("Unkown method for int constant " + method); // } // }
import android.content.Context; import com.android.volley.Network; import com.android.volley.NetworkResponse; import com.android.volley.NoConnectionError; import com.android.volley.Request; import com.android.volley.VolleyError; import com.android.volley.toolbox.HttpStack; import com.siu.android.volleyball.exception.BallException; import com.siu.android.volleyball.util.BallLogger; import com.siu.android.volleyball.util.ConfigUtils; import com.siu.android.volleyball.util.RequestUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map;
package com.siu.android.volleyball.mock; /** * Created by lukas on 8/29/13. */ public class FileMockNetwork implements Network { private Context mContext; private Config mConfig; public FileMockNetwork(Context context) { this(context, new Config()); } public FileMockNetwork(Context context, Config config) { mContext = context; mConfig = config; // configure the real network for non mocked requests if (config.mRealNetwork == null) { HttpStack httpStack = (config.mRealNetworkHttpStack == null) ? ConfigUtils.getDefaultHttpStack(mContext) : config.mRealNetworkHttpStack; config.mRealNetwork = ConfigUtils.getDefaultNetwork(httpStack); } if (!mConfig.mBasePath.equals("") && !mConfig.mBasePath.endsWith("/")) { mConfig.mBasePath += "/"; } } @Override public NetworkResponse performRequest(Request<?> request) throws VolleyError { if (!shouldMock(request)) { return mConfig.mRealNetwork.performRequest(request); } Mock mock = getMock(request); String filePath = mConfig.mBasePath + mock.mFilename;
// Path: library/src/main/java/com/siu/android/volleyball/exception/BallException.java // public class BallException extends RuntimeException { // // public BallException() { // } // // public BallException(String detailMessage) { // super(detailMessage); // } // // public BallException(String detailMessage, Object... args) { // super(String.format(detailMessage, args)); // } // // // // public BallException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public BallException(Throwable throwable) { // super(throwable); // } // } // // Path: library/src/main/java/com/siu/android/volleyball/util/BallLogger.java // public class BallLogger { // // // D // public static void d(String string) { // Log.d(BallLogger.class.getName(), string); // } // // public static void d(String string, Throwable tr) { // Log.d(BallLogger.class.getName(), string, tr); // } // // public static void d(String string, Object... args) { // d(String.format(string, args)); // } // // public static void d(String string, Throwable tr, Object... args) { // d(String.format(string, args), tr); // } // // // // E // public static void e(String string) { // Log.e(BallLogger.class.getName(), string); // } // // public static void e(String string, Throwable tr) { // Log.e(BallLogger.class.getName(), string, tr); // } // // public static void e(String string, Object... args) { // e(String.format(string, args)); // } // // public static void e(String string, Throwable tr, Object... args) { // e(String.format(string, args), tr); // } // } // // Path: library/src/main/java/com/siu/android/volleyball/util/ConfigUtils.java // public class ConfigUtils { // // public static final HttpStack getDefaultHttpStack(Context context) { // String userAgent = "volley/0"; // try { // String packageName = context.getPackageName(); // PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0); // userAgent = packageName + "/" + info.versionCode; // } catch (PackageManager.NameNotFoundException e) { // } // // HttpStack stack; // if (Build.VERSION.SDK_INT >= 9) { // stack = new HurlStack(); // } else { // // Prior to Gingerbread, HttpUrlConnection was unreliable. // // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html // stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent)); // } // // return stack; // } // // public static Network getDefaultNetwork(HttpStack httpStack) { // return new BasicNetwork(httpStack); // } // // public static Network getDefaultNetworkWithDefaultHttpStack(Context context) { // return new BasicNetwork(getDefaultHttpStack(context)); // } // } // // Path: library/src/main/java/com/siu/android/volleyball/util/RequestUtils.java // public class RequestUtils { // // /** // * Get the equivalent string of the int request http method // * // * @param method the method as int constant // * @return the method as string // * @throws IllegalArgumentException if no match is found between the int constant and the equivalent string // */ // public static final String methodToString(int method) throws IllegalArgumentException { // switch (method) { // case Request.Method.GET: // return "GET"; // case Request.Method.POST: // return "POST"; // case Request.Method.PUT: // return "PUT"; // case Request.Method.DELETE: // return "DELETE"; // } // // throw new IllegalArgumentException("Unkown method for int constant " + method); // } // } // Path: library/src/main/java/com/siu/android/volleyball/mock/FileMockNetwork.java import android.content.Context; import com.android.volley.Network; import com.android.volley.NetworkResponse; import com.android.volley.NoConnectionError; import com.android.volley.Request; import com.android.volley.VolleyError; import com.android.volley.toolbox.HttpStack; import com.siu.android.volleyball.exception.BallException; import com.siu.android.volleyball.util.BallLogger; import com.siu.android.volleyball.util.ConfigUtils; import com.siu.android.volleyball.util.RequestUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; package com.siu.android.volleyball.mock; /** * Created by lukas on 8/29/13. */ public class FileMockNetwork implements Network { private Context mContext; private Config mConfig; public FileMockNetwork(Context context) { this(context, new Config()); } public FileMockNetwork(Context context, Config config) { mContext = context; mConfig = config; // configure the real network for non mocked requests if (config.mRealNetwork == null) { HttpStack httpStack = (config.mRealNetworkHttpStack == null) ? ConfigUtils.getDefaultHttpStack(mContext) : config.mRealNetworkHttpStack; config.mRealNetwork = ConfigUtils.getDefaultNetwork(httpStack); } if (!mConfig.mBasePath.equals("") && !mConfig.mBasePath.endsWith("/")) { mConfig.mBasePath += "/"; } } @Override public NetworkResponse performRequest(Request<?> request) throws VolleyError { if (!shouldMock(request)) { return mConfig.mRealNetwork.performRequest(request); } Mock mock = getMock(request); String filePath = mConfig.mBasePath + mock.mFilename;
BallLogger.d("Mock file path = %s", filePath);
lukaspili/Volley-Ball
library/src/main/java/com/siu/android/volleyball/mock/FileMockNetwork.java
// Path: library/src/main/java/com/siu/android/volleyball/exception/BallException.java // public class BallException extends RuntimeException { // // public BallException() { // } // // public BallException(String detailMessage) { // super(detailMessage); // } // // public BallException(String detailMessage, Object... args) { // super(String.format(detailMessage, args)); // } // // // // public BallException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public BallException(Throwable throwable) { // super(throwable); // } // } // // Path: library/src/main/java/com/siu/android/volleyball/util/BallLogger.java // public class BallLogger { // // // D // public static void d(String string) { // Log.d(BallLogger.class.getName(), string); // } // // public static void d(String string, Throwable tr) { // Log.d(BallLogger.class.getName(), string, tr); // } // // public static void d(String string, Object... args) { // d(String.format(string, args)); // } // // public static void d(String string, Throwable tr, Object... args) { // d(String.format(string, args), tr); // } // // // // E // public static void e(String string) { // Log.e(BallLogger.class.getName(), string); // } // // public static void e(String string, Throwable tr) { // Log.e(BallLogger.class.getName(), string, tr); // } // // public static void e(String string, Object... args) { // e(String.format(string, args)); // } // // public static void e(String string, Throwable tr, Object... args) { // e(String.format(string, args), tr); // } // } // // Path: library/src/main/java/com/siu/android/volleyball/util/ConfigUtils.java // public class ConfigUtils { // // public static final HttpStack getDefaultHttpStack(Context context) { // String userAgent = "volley/0"; // try { // String packageName = context.getPackageName(); // PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0); // userAgent = packageName + "/" + info.versionCode; // } catch (PackageManager.NameNotFoundException e) { // } // // HttpStack stack; // if (Build.VERSION.SDK_INT >= 9) { // stack = new HurlStack(); // } else { // // Prior to Gingerbread, HttpUrlConnection was unreliable. // // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html // stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent)); // } // // return stack; // } // // public static Network getDefaultNetwork(HttpStack httpStack) { // return new BasicNetwork(httpStack); // } // // public static Network getDefaultNetworkWithDefaultHttpStack(Context context) { // return new BasicNetwork(getDefaultHttpStack(context)); // } // } // // Path: library/src/main/java/com/siu/android/volleyball/util/RequestUtils.java // public class RequestUtils { // // /** // * Get the equivalent string of the int request http method // * // * @param method the method as int constant // * @return the method as string // * @throws IllegalArgumentException if no match is found between the int constant and the equivalent string // */ // public static final String methodToString(int method) throws IllegalArgumentException { // switch (method) { // case Request.Method.GET: // return "GET"; // case Request.Method.POST: // return "POST"; // case Request.Method.PUT: // return "PUT"; // case Request.Method.DELETE: // return "DELETE"; // } // // throw new IllegalArgumentException("Unkown method for int constant " + method); // } // }
import android.content.Context; import com.android.volley.Network; import com.android.volley.NetworkResponse; import com.android.volley.NoConnectionError; import com.android.volley.Request; import com.android.volley.VolleyError; import com.android.volley.toolbox.HttpStack; import com.siu.android.volleyball.exception.BallException; import com.siu.android.volleyball.util.BallLogger; import com.siu.android.volleyball.util.ConfigUtils; import com.siu.android.volleyball.util.RequestUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map;
Map<String, String> headers = new HashMap<String, String>(); headers.put("Content-Type", mock.mContentType); return new NetworkResponse(200, data, headers, false); } /** * Default implementation mocks every request * * @param request the request that can be mocked * @return if the request should be mocked */ protected boolean shouldMock(Request request) { return true; } /** * Default implementation respond with file named by the request url last path with ".json" suffix * and a content type set to "content/json". * <p/> * Examples: * - GET http://some.url.com/entries -> get_entries.json * - GET http://some.url.com/entries?bla=foobar -> get_entries.json * - POST http://some.url.com/entries -> post_entries.json * * @param request the request that will be mocked * @return the mock associated to the request */ protected Mock getMock(Request request) { if (!request.getUrl().contains("/") || request.getUrl().equals("/")) {
// Path: library/src/main/java/com/siu/android/volleyball/exception/BallException.java // public class BallException extends RuntimeException { // // public BallException() { // } // // public BallException(String detailMessage) { // super(detailMessage); // } // // public BallException(String detailMessage, Object... args) { // super(String.format(detailMessage, args)); // } // // // // public BallException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public BallException(Throwable throwable) { // super(throwable); // } // } // // Path: library/src/main/java/com/siu/android/volleyball/util/BallLogger.java // public class BallLogger { // // // D // public static void d(String string) { // Log.d(BallLogger.class.getName(), string); // } // // public static void d(String string, Throwable tr) { // Log.d(BallLogger.class.getName(), string, tr); // } // // public static void d(String string, Object... args) { // d(String.format(string, args)); // } // // public static void d(String string, Throwable tr, Object... args) { // d(String.format(string, args), tr); // } // // // // E // public static void e(String string) { // Log.e(BallLogger.class.getName(), string); // } // // public static void e(String string, Throwable tr) { // Log.e(BallLogger.class.getName(), string, tr); // } // // public static void e(String string, Object... args) { // e(String.format(string, args)); // } // // public static void e(String string, Throwable tr, Object... args) { // e(String.format(string, args), tr); // } // } // // Path: library/src/main/java/com/siu/android/volleyball/util/ConfigUtils.java // public class ConfigUtils { // // public static final HttpStack getDefaultHttpStack(Context context) { // String userAgent = "volley/0"; // try { // String packageName = context.getPackageName(); // PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0); // userAgent = packageName + "/" + info.versionCode; // } catch (PackageManager.NameNotFoundException e) { // } // // HttpStack stack; // if (Build.VERSION.SDK_INT >= 9) { // stack = new HurlStack(); // } else { // // Prior to Gingerbread, HttpUrlConnection was unreliable. // // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html // stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent)); // } // // return stack; // } // // public static Network getDefaultNetwork(HttpStack httpStack) { // return new BasicNetwork(httpStack); // } // // public static Network getDefaultNetworkWithDefaultHttpStack(Context context) { // return new BasicNetwork(getDefaultHttpStack(context)); // } // } // // Path: library/src/main/java/com/siu/android/volleyball/util/RequestUtils.java // public class RequestUtils { // // /** // * Get the equivalent string of the int request http method // * // * @param method the method as int constant // * @return the method as string // * @throws IllegalArgumentException if no match is found between the int constant and the equivalent string // */ // public static final String methodToString(int method) throws IllegalArgumentException { // switch (method) { // case Request.Method.GET: // return "GET"; // case Request.Method.POST: // return "POST"; // case Request.Method.PUT: // return "PUT"; // case Request.Method.DELETE: // return "DELETE"; // } // // throw new IllegalArgumentException("Unkown method for int constant " + method); // } // } // Path: library/src/main/java/com/siu/android/volleyball/mock/FileMockNetwork.java import android.content.Context; import com.android.volley.Network; import com.android.volley.NetworkResponse; import com.android.volley.NoConnectionError; import com.android.volley.Request; import com.android.volley.VolleyError; import com.android.volley.toolbox.HttpStack; import com.siu.android.volleyball.exception.BallException; import com.siu.android.volleyball.util.BallLogger; import com.siu.android.volleyball.util.ConfigUtils; import com.siu.android.volleyball.util.RequestUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; Map<String, String> headers = new HashMap<String, String>(); headers.put("Content-Type", mock.mContentType); return new NetworkResponse(200, data, headers, false); } /** * Default implementation mocks every request * * @param request the request that can be mocked * @return if the request should be mocked */ protected boolean shouldMock(Request request) { return true; } /** * Default implementation respond with file named by the request url last path with ".json" suffix * and a content type set to "content/json". * <p/> * Examples: * - GET http://some.url.com/entries -> get_entries.json * - GET http://some.url.com/entries?bla=foobar -> get_entries.json * - POST http://some.url.com/entries -> post_entries.json * * @param request the request that will be mocked * @return the mock associated to the request */ protected Mock getMock(Request request) { if (!request.getUrl().contains("/") || request.getUrl().equals("/")) {
throw new BallException("Invalid request url for mock, can't determine what is the last path to get the associated mock file : %s", request.getUrl());
lukaspili/Volley-Ball
library/src/main/java/com/siu/android/volleyball/mock/FileMockNetwork.java
// Path: library/src/main/java/com/siu/android/volleyball/exception/BallException.java // public class BallException extends RuntimeException { // // public BallException() { // } // // public BallException(String detailMessage) { // super(detailMessage); // } // // public BallException(String detailMessage, Object... args) { // super(String.format(detailMessage, args)); // } // // // // public BallException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public BallException(Throwable throwable) { // super(throwable); // } // } // // Path: library/src/main/java/com/siu/android/volleyball/util/BallLogger.java // public class BallLogger { // // // D // public static void d(String string) { // Log.d(BallLogger.class.getName(), string); // } // // public static void d(String string, Throwable tr) { // Log.d(BallLogger.class.getName(), string, tr); // } // // public static void d(String string, Object... args) { // d(String.format(string, args)); // } // // public static void d(String string, Throwable tr, Object... args) { // d(String.format(string, args), tr); // } // // // // E // public static void e(String string) { // Log.e(BallLogger.class.getName(), string); // } // // public static void e(String string, Throwable tr) { // Log.e(BallLogger.class.getName(), string, tr); // } // // public static void e(String string, Object... args) { // e(String.format(string, args)); // } // // public static void e(String string, Throwable tr, Object... args) { // e(String.format(string, args), tr); // } // } // // Path: library/src/main/java/com/siu/android/volleyball/util/ConfigUtils.java // public class ConfigUtils { // // public static final HttpStack getDefaultHttpStack(Context context) { // String userAgent = "volley/0"; // try { // String packageName = context.getPackageName(); // PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0); // userAgent = packageName + "/" + info.versionCode; // } catch (PackageManager.NameNotFoundException e) { // } // // HttpStack stack; // if (Build.VERSION.SDK_INT >= 9) { // stack = new HurlStack(); // } else { // // Prior to Gingerbread, HttpUrlConnection was unreliable. // // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html // stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent)); // } // // return stack; // } // // public static Network getDefaultNetwork(HttpStack httpStack) { // return new BasicNetwork(httpStack); // } // // public static Network getDefaultNetworkWithDefaultHttpStack(Context context) { // return new BasicNetwork(getDefaultHttpStack(context)); // } // } // // Path: library/src/main/java/com/siu/android/volleyball/util/RequestUtils.java // public class RequestUtils { // // /** // * Get the equivalent string of the int request http method // * // * @param method the method as int constant // * @return the method as string // * @throws IllegalArgumentException if no match is found between the int constant and the equivalent string // */ // public static final String methodToString(int method) throws IllegalArgumentException { // switch (method) { // case Request.Method.GET: // return "GET"; // case Request.Method.POST: // return "POST"; // case Request.Method.PUT: // return "PUT"; // case Request.Method.DELETE: // return "DELETE"; // } // // throw new IllegalArgumentException("Unkown method for int constant " + method); // } // }
import android.content.Context; import com.android.volley.Network; import com.android.volley.NetworkResponse; import com.android.volley.NoConnectionError; import com.android.volley.Request; import com.android.volley.VolleyError; import com.android.volley.toolbox.HttpStack; import com.siu.android.volleyball.exception.BallException; import com.siu.android.volleyball.util.BallLogger; import com.siu.android.volleyball.util.ConfigUtils; import com.siu.android.volleyball.util.RequestUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map;
/** * Default implementation respond with file named by the request url last path with ".json" suffix * and a content type set to "content/json". * <p/> * Examples: * - GET http://some.url.com/entries -> get_entries.json * - GET http://some.url.com/entries?bla=foobar -> get_entries.json * - POST http://some.url.com/entries -> post_entries.json * * @param request the request that will be mocked * @return the mock associated to the request */ protected Mock getMock(Request request) { if (!request.getUrl().contains("/") || request.getUrl().equals("/")) { throw new BallException("Invalid request url for mock, can't determine what is the last path to get the associated mock file : %s", request.getUrl()); } String path = request.getUrl(); if (path.lastIndexOf("/") == path.length() - 1) { path = path.substring(0, path.length() - 2); } path = FilenameUtils.getBaseName(path); if (path.contains("?")) { path = path.substring(0, path.indexOf("?")); }
// Path: library/src/main/java/com/siu/android/volleyball/exception/BallException.java // public class BallException extends RuntimeException { // // public BallException() { // } // // public BallException(String detailMessage) { // super(detailMessage); // } // // public BallException(String detailMessage, Object... args) { // super(String.format(detailMessage, args)); // } // // // // public BallException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public BallException(Throwable throwable) { // super(throwable); // } // } // // Path: library/src/main/java/com/siu/android/volleyball/util/BallLogger.java // public class BallLogger { // // // D // public static void d(String string) { // Log.d(BallLogger.class.getName(), string); // } // // public static void d(String string, Throwable tr) { // Log.d(BallLogger.class.getName(), string, tr); // } // // public static void d(String string, Object... args) { // d(String.format(string, args)); // } // // public static void d(String string, Throwable tr, Object... args) { // d(String.format(string, args), tr); // } // // // // E // public static void e(String string) { // Log.e(BallLogger.class.getName(), string); // } // // public static void e(String string, Throwable tr) { // Log.e(BallLogger.class.getName(), string, tr); // } // // public static void e(String string, Object... args) { // e(String.format(string, args)); // } // // public static void e(String string, Throwable tr, Object... args) { // e(String.format(string, args), tr); // } // } // // Path: library/src/main/java/com/siu/android/volleyball/util/ConfigUtils.java // public class ConfigUtils { // // public static final HttpStack getDefaultHttpStack(Context context) { // String userAgent = "volley/0"; // try { // String packageName = context.getPackageName(); // PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0); // userAgent = packageName + "/" + info.versionCode; // } catch (PackageManager.NameNotFoundException e) { // } // // HttpStack stack; // if (Build.VERSION.SDK_INT >= 9) { // stack = new HurlStack(); // } else { // // Prior to Gingerbread, HttpUrlConnection was unreliable. // // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html // stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent)); // } // // return stack; // } // // public static Network getDefaultNetwork(HttpStack httpStack) { // return new BasicNetwork(httpStack); // } // // public static Network getDefaultNetworkWithDefaultHttpStack(Context context) { // return new BasicNetwork(getDefaultHttpStack(context)); // } // } // // Path: library/src/main/java/com/siu/android/volleyball/util/RequestUtils.java // public class RequestUtils { // // /** // * Get the equivalent string of the int request http method // * // * @param method the method as int constant // * @return the method as string // * @throws IllegalArgumentException if no match is found between the int constant and the equivalent string // */ // public static final String methodToString(int method) throws IllegalArgumentException { // switch (method) { // case Request.Method.GET: // return "GET"; // case Request.Method.POST: // return "POST"; // case Request.Method.PUT: // return "PUT"; // case Request.Method.DELETE: // return "DELETE"; // } // // throw new IllegalArgumentException("Unkown method for int constant " + method); // } // } // Path: library/src/main/java/com/siu/android/volleyball/mock/FileMockNetwork.java import android.content.Context; import com.android.volley.Network; import com.android.volley.NetworkResponse; import com.android.volley.NoConnectionError; import com.android.volley.Request; import com.android.volley.VolleyError; import com.android.volley.toolbox.HttpStack; import com.siu.android.volleyball.exception.BallException; import com.siu.android.volleyball.util.BallLogger; import com.siu.android.volleyball.util.ConfigUtils; import com.siu.android.volleyball.util.RequestUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; /** * Default implementation respond with file named by the request url last path with ".json" suffix * and a content type set to "content/json". * <p/> * Examples: * - GET http://some.url.com/entries -> get_entries.json * - GET http://some.url.com/entries?bla=foobar -> get_entries.json * - POST http://some.url.com/entries -> post_entries.json * * @param request the request that will be mocked * @return the mock associated to the request */ protected Mock getMock(Request request) { if (!request.getUrl().contains("/") || request.getUrl().equals("/")) { throw new BallException("Invalid request url for mock, can't determine what is the last path to get the associated mock file : %s", request.getUrl()); } String path = request.getUrl(); if (path.lastIndexOf("/") == path.length() - 1) { path = path.substring(0, path.length() - 2); } path = FilenameUtils.getBaseName(path); if (path.contains("?")) { path = path.substring(0, path.indexOf("?")); }
path = RequestUtils.methodToString(request.getMethod()) + "_" + path + ".json";
lukaspili/Volley-Ball
library/src/main/java/com/siu/android/volleyball/toolbox/BallImageRequest.java
// Path: library/src/main/java/com/siu/android/volleyball/BallResponse.java // public class BallResponse<T> { // // public static enum ResponseSource { // LOCAL, CACHE, NETWORK // } // // protected Response<T> mResponse; // protected ResponseSource mResponseSource; // protected boolean mIdentical = false; // // /** // * Returns whether this response is considered successful. // */ // public boolean isSuccess() { // return mResponse.isSuccess(); // } // // public static <T> BallResponse<T> identical(ResponseSource responseSource) { // return new BallResponse<T>(Response.<T>success(null, null), responseSource, true); // } // // public static <T> BallResponse<T> success(T result) { // return new BallResponse<T>(Response.success(result, null)); // } // // public static <T> BallResponse<T> success(T result, Cache.Entry cacheEntry) { // return new BallResponse<T>(Response.success(result, cacheEntry)); // } // // public static <T> BallResponse<T> error(VolleyError error) { // return new BallResponse<T>(Response.<T>error(error), ResponseSource.NETWORK); // error cames always from network // } // // protected BallResponse(Response<T> response) { // this(response, null, false); // } // // protected BallResponse(Response<T> response, ResponseSource responseSource) { // this(response, responseSource, false); // } // // public BallResponse(Response<T> response, ResponseSource responseSource, boolean identical) { // mResponse = response; // mResponseSource = responseSource; // mIdentical = identical; // } // // public ResponseSource getResponseSource() { // return mResponseSource; // } // // public void setResponseSource(ResponseSource responseSource) { // this.mResponseSource = responseSource; // } // // public boolean isIntermediate() { // return mResponse.intermediate; // } // // public void setIntermediate(boolean intermediate) { // mResponse.intermediate = intermediate; // } // // public T getResult() { // return mResponse.result; // } // // public Cache.Entry getCacheEntry() { // return mResponse.cacheEntry; // } // // public VolleyError getError() { // return mResponse.error; // } // // public boolean isIdentical() { // return mIdentical; // } // // public void setIdentical(boolean identical) { // mIdentical = identical; // } // } // // Path: library/src/main/java/com/siu/android/volleyball/request/NetworkRequest.java // public abstract class NetworkRequest<T> extends BallRequest<T> { // // protected NetworkRequest(int method, String url, Response.ErrorListener errorListener) { // super(method, url, errorListener); // } // // public NetworkRequest(int method, String url, SingleResponseListener<T> responseListener, Response.ErrorListener errorListener) { // super(method, url, responseListener, errorListener); // } // // @Override // public boolean shouldProcessNetwork() { // return true; // } // // @Override // protected NetworkRequestProcessor createNetworkRequestProcessor() { // return new NetworkRequestProcessor() { // @Override // public BallResponse<T> parseNetworkResponse(NetworkResponse networkResponse) { // return parseBallNetworkResponse(networkResponse); // } // }; // } // // protected abstract BallResponse<T> parseBallNetworkResponse(NetworkResponse response); // } // // Path: library/src/main/java/com/siu/android/volleyball/response/SingleResponseListener.java // public abstract class SingleResponseListener<T> implements ResponseListener<T> { // // /** // * Can happen when the response is soft cached // * // * @param response // * @param responseSource // */ // @Override // public final void onIntermediateResponse(T response, BallResponse.ResponseSource responseSource) { // onResponse(response); // } // // @Override // public final void onFinalResponse(T response, BallResponse.ResponseSource responseSource) { // onResponse(response); // } // // /** // * Can happen when the response is soft cached. Maybe ? // * // * @param responseSource // */ // @Override // public final void onFinalResponseIdenticalToIntermediate(BallResponse.ResponseSource responseSource) { // // } // // //TODO: add response source because it can still be soft cached response // public abstract void onResponse(T response); // }
import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; import com.android.volley.DefaultRetryPolicy; import com.android.volley.NetworkResponse; import com.android.volley.ParseError; import com.android.volley.Response; import com.android.volley.VolleyLog; import com.android.volley.toolbox.HttpHeaderParser; import com.siu.android.volleyball.BallResponse; import com.siu.android.volleyball.request.NetworkRequest; import com.siu.android.volleyball.response.SingleResponseListener;
* @param actualSecondary Actual size of the secondary dimension */ private static int getResizedDimension(int maxPrimary, int maxSecondary, int actualPrimary, int actualSecondary) { // If no dominant value at all, just return the actual. if (maxPrimary == 0 && maxSecondary == 0) { return actualPrimary; } // If primary is unspecified, scale primary to match secondary's scaling ratio. if (maxPrimary == 0) { double ratio = (double) maxSecondary / (double) actualSecondary; return (int) (actualPrimary * ratio); } if (maxSecondary == 0) { return maxPrimary; } double ratio = (double) actualSecondary / (double) actualPrimary; int resized = maxPrimary; if (resized * ratio > maxSecondary) { resized = (int) (maxSecondary / ratio); } return resized; } /** * The real guts of parseNetworkResponse. Broken out for readability. */
// Path: library/src/main/java/com/siu/android/volleyball/BallResponse.java // public class BallResponse<T> { // // public static enum ResponseSource { // LOCAL, CACHE, NETWORK // } // // protected Response<T> mResponse; // protected ResponseSource mResponseSource; // protected boolean mIdentical = false; // // /** // * Returns whether this response is considered successful. // */ // public boolean isSuccess() { // return mResponse.isSuccess(); // } // // public static <T> BallResponse<T> identical(ResponseSource responseSource) { // return new BallResponse<T>(Response.<T>success(null, null), responseSource, true); // } // // public static <T> BallResponse<T> success(T result) { // return new BallResponse<T>(Response.success(result, null)); // } // // public static <T> BallResponse<T> success(T result, Cache.Entry cacheEntry) { // return new BallResponse<T>(Response.success(result, cacheEntry)); // } // // public static <T> BallResponse<T> error(VolleyError error) { // return new BallResponse<T>(Response.<T>error(error), ResponseSource.NETWORK); // error cames always from network // } // // protected BallResponse(Response<T> response) { // this(response, null, false); // } // // protected BallResponse(Response<T> response, ResponseSource responseSource) { // this(response, responseSource, false); // } // // public BallResponse(Response<T> response, ResponseSource responseSource, boolean identical) { // mResponse = response; // mResponseSource = responseSource; // mIdentical = identical; // } // // public ResponseSource getResponseSource() { // return mResponseSource; // } // // public void setResponseSource(ResponseSource responseSource) { // this.mResponseSource = responseSource; // } // // public boolean isIntermediate() { // return mResponse.intermediate; // } // // public void setIntermediate(boolean intermediate) { // mResponse.intermediate = intermediate; // } // // public T getResult() { // return mResponse.result; // } // // public Cache.Entry getCacheEntry() { // return mResponse.cacheEntry; // } // // public VolleyError getError() { // return mResponse.error; // } // // public boolean isIdentical() { // return mIdentical; // } // // public void setIdentical(boolean identical) { // mIdentical = identical; // } // } // // Path: library/src/main/java/com/siu/android/volleyball/request/NetworkRequest.java // public abstract class NetworkRequest<T> extends BallRequest<T> { // // protected NetworkRequest(int method, String url, Response.ErrorListener errorListener) { // super(method, url, errorListener); // } // // public NetworkRequest(int method, String url, SingleResponseListener<T> responseListener, Response.ErrorListener errorListener) { // super(method, url, responseListener, errorListener); // } // // @Override // public boolean shouldProcessNetwork() { // return true; // } // // @Override // protected NetworkRequestProcessor createNetworkRequestProcessor() { // return new NetworkRequestProcessor() { // @Override // public BallResponse<T> parseNetworkResponse(NetworkResponse networkResponse) { // return parseBallNetworkResponse(networkResponse); // } // }; // } // // protected abstract BallResponse<T> parseBallNetworkResponse(NetworkResponse response); // } // // Path: library/src/main/java/com/siu/android/volleyball/response/SingleResponseListener.java // public abstract class SingleResponseListener<T> implements ResponseListener<T> { // // /** // * Can happen when the response is soft cached // * // * @param response // * @param responseSource // */ // @Override // public final void onIntermediateResponse(T response, BallResponse.ResponseSource responseSource) { // onResponse(response); // } // // @Override // public final void onFinalResponse(T response, BallResponse.ResponseSource responseSource) { // onResponse(response); // } // // /** // * Can happen when the response is soft cached. Maybe ? // * // * @param responseSource // */ // @Override // public final void onFinalResponseIdenticalToIntermediate(BallResponse.ResponseSource responseSource) { // // } // // //TODO: add response source because it can still be soft cached response // public abstract void onResponse(T response); // } // Path: library/src/main/java/com/siu/android/volleyball/toolbox/BallImageRequest.java import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; import com.android.volley.DefaultRetryPolicy; import com.android.volley.NetworkResponse; import com.android.volley.ParseError; import com.android.volley.Response; import com.android.volley.VolleyLog; import com.android.volley.toolbox.HttpHeaderParser; import com.siu.android.volleyball.BallResponse; import com.siu.android.volleyball.request.NetworkRequest; import com.siu.android.volleyball.response.SingleResponseListener; * @param actualSecondary Actual size of the secondary dimension */ private static int getResizedDimension(int maxPrimary, int maxSecondary, int actualPrimary, int actualSecondary) { // If no dominant value at all, just return the actual. if (maxPrimary == 0 && maxSecondary == 0) { return actualPrimary; } // If primary is unspecified, scale primary to match secondary's scaling ratio. if (maxPrimary == 0) { double ratio = (double) maxSecondary / (double) actualSecondary; return (int) (actualPrimary * ratio); } if (maxSecondary == 0) { return maxPrimary; } double ratio = (double) actualSecondary / (double) actualPrimary; int resized = maxPrimary; if (resized * ratio > maxSecondary) { resized = (int) (maxSecondary / ratio); } return resized; } /** * The real guts of parseNetworkResponse. Broken out for readability. */
private BallResponse<Bitmap> doParse(NetworkResponse response) {
lukaspili/Volley-Ball
samples/src/main/java/com/siu/android/volleyball/samples/database/EntryDao.java
// Path: samples/src/main/java/com/siu/android/volleyball/samples/Application.java // public class Application extends android.app.Application { // // private static Context sContext; // private static BallRequestQueue sRequestQueue; // private static BallRequestQueue sScenarioRequestQueue; // private static DatabaseHelper sDatabaseHelper; // private static SQLiteDatabase sSQLiteDatabase; // // @Override // public void onCreate() { // super.onCreate(); // // sContext = getApplicationContext(); // // if (Constants.DEBUG) { // deleteDatabase(DatabaseHelper.NAME); // } // // // init volley ball // VolleyBallConfig.Builder configBuilder = new VolleyBallConfig.Builder(sContext); // // // mock // if (Constants.MOCK_WEBSERVICE) { // FileMockNetwork network = new FileMockNetwork(sContext, new FileMockNetwork.Config() // .basePath("fakeapi") // .requestDuration(1) // .realNetworkHttpStack(new OkHttpStack())); // configBuilder.network(network); // } else { // configBuilder.httpStack(new OkHttpStack()); // } // // sRequestQueue = VolleyBall.newRequestQueue(configBuilder.build()); // // sScenarioRequestQueue = VolleyBall.newRequestQueue(new VolleyBallConfig.Builder(sContext) // .network(new FakeNetwork()) // .build()); // // // init database helper // sDatabaseHelper = new DatabaseHelper(sContext); // sSQLiteDatabase = sDatabaseHelper.getWritableDatabase(); // } // // public static Context getContext() { // return sContext; // } // // public static BallRequestQueue getRequestQueue() { // return sRequestQueue; // } // // public static BallRequestQueue getScenarioRequestQueue() { // return sScenarioRequestQueue; // } // // public static DatabaseHelper getDatabaseHelper() { // return sDatabaseHelper; // } // // public static SQLiteDatabase getSQLiteDatabase() { // return sSQLiteDatabase; // } // } // // Path: samples/src/main/java/com/siu/android/volleyball/samples/model/Entry.java // public class Entry implements EntryMapping { // // private long id; // private String title; // // public Entry() { // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: samples/src/main/java/com/siu/android/volleyball/samples/util/SimpleLogger.java // public class SimpleLogger { // // // D // public static void d(String string) { // Log.d(SimpleLogger.class.getName(), string); // } // // public static void d(String string, Throwable tr) { // Log.d(SimpleLogger.class.getName(), string, tr); // } // // public static void d(String string, Object... args) { // d(String.format(string, args)); // } // // public static void d(String string, Throwable tr, Object... args) { // d(String.format(string, args), tr); // } // // // // E // public static void e(String string) { // Log.e(SimpleLogger.class.getName(), string); // } // // public static void e(String string, Throwable tr) { // Log.e(SimpleLogger.class.getName(), string, tr); // } // // public static void e(String string, Object... args) { // e(String.format(string, args)); // } // // public static void e(String string, Throwable tr, Object... args) { // e(String.format(string, args), tr); // } // }
import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.siu.android.volleyball.samples.Application; import com.siu.android.volleyball.samples.model.Entry; import com.siu.android.volleyball.samples.util.SimpleLogger; import java.util.ArrayList; import java.util.List;
package com.siu.android.volleyball.samples.database; /** * Created by lukas on 8/30/13. */ public class EntryDao { public static final List<Entry> getEntries() {
// Path: samples/src/main/java/com/siu/android/volleyball/samples/Application.java // public class Application extends android.app.Application { // // private static Context sContext; // private static BallRequestQueue sRequestQueue; // private static BallRequestQueue sScenarioRequestQueue; // private static DatabaseHelper sDatabaseHelper; // private static SQLiteDatabase sSQLiteDatabase; // // @Override // public void onCreate() { // super.onCreate(); // // sContext = getApplicationContext(); // // if (Constants.DEBUG) { // deleteDatabase(DatabaseHelper.NAME); // } // // // init volley ball // VolleyBallConfig.Builder configBuilder = new VolleyBallConfig.Builder(sContext); // // // mock // if (Constants.MOCK_WEBSERVICE) { // FileMockNetwork network = new FileMockNetwork(sContext, new FileMockNetwork.Config() // .basePath("fakeapi") // .requestDuration(1) // .realNetworkHttpStack(new OkHttpStack())); // configBuilder.network(network); // } else { // configBuilder.httpStack(new OkHttpStack()); // } // // sRequestQueue = VolleyBall.newRequestQueue(configBuilder.build()); // // sScenarioRequestQueue = VolleyBall.newRequestQueue(new VolleyBallConfig.Builder(sContext) // .network(new FakeNetwork()) // .build()); // // // init database helper // sDatabaseHelper = new DatabaseHelper(sContext); // sSQLiteDatabase = sDatabaseHelper.getWritableDatabase(); // } // // public static Context getContext() { // return sContext; // } // // public static BallRequestQueue getRequestQueue() { // return sRequestQueue; // } // // public static BallRequestQueue getScenarioRequestQueue() { // return sScenarioRequestQueue; // } // // public static DatabaseHelper getDatabaseHelper() { // return sDatabaseHelper; // } // // public static SQLiteDatabase getSQLiteDatabase() { // return sSQLiteDatabase; // } // } // // Path: samples/src/main/java/com/siu/android/volleyball/samples/model/Entry.java // public class Entry implements EntryMapping { // // private long id; // private String title; // // public Entry() { // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: samples/src/main/java/com/siu/android/volleyball/samples/util/SimpleLogger.java // public class SimpleLogger { // // // D // public static void d(String string) { // Log.d(SimpleLogger.class.getName(), string); // } // // public static void d(String string, Throwable tr) { // Log.d(SimpleLogger.class.getName(), string, tr); // } // // public static void d(String string, Object... args) { // d(String.format(string, args)); // } // // public static void d(String string, Throwable tr, Object... args) { // d(String.format(string, args), tr); // } // // // // E // public static void e(String string) { // Log.e(SimpleLogger.class.getName(), string); // } // // public static void e(String string, Throwable tr) { // Log.e(SimpleLogger.class.getName(), string, tr); // } // // public static void e(String string, Object... args) { // e(String.format(string, args)); // } // // public static void e(String string, Throwable tr, Object... args) { // e(String.format(string, args), tr); // } // } // Path: samples/src/main/java/com/siu/android/volleyball/samples/database/EntryDao.java import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.siu.android.volleyball.samples.Application; import com.siu.android.volleyball.samples.model.Entry; import com.siu.android.volleyball.samples.util.SimpleLogger; import java.util.ArrayList; import java.util.List; package com.siu.android.volleyball.samples.database; /** * Created by lukas on 8/30/13. */ public class EntryDao { public static final List<Entry> getEntries() {
Cursor cursor = Application.getSQLiteDatabase().query(Entry.TABLE, Entry.COLUMNS, null, null, null, null, null);
lukaspili/Volley-Ball
samples/src/main/java/com/siu/android/volleyball/samples/database/EntryDao.java
// Path: samples/src/main/java/com/siu/android/volleyball/samples/Application.java // public class Application extends android.app.Application { // // private static Context sContext; // private static BallRequestQueue sRequestQueue; // private static BallRequestQueue sScenarioRequestQueue; // private static DatabaseHelper sDatabaseHelper; // private static SQLiteDatabase sSQLiteDatabase; // // @Override // public void onCreate() { // super.onCreate(); // // sContext = getApplicationContext(); // // if (Constants.DEBUG) { // deleteDatabase(DatabaseHelper.NAME); // } // // // init volley ball // VolleyBallConfig.Builder configBuilder = new VolleyBallConfig.Builder(sContext); // // // mock // if (Constants.MOCK_WEBSERVICE) { // FileMockNetwork network = new FileMockNetwork(sContext, new FileMockNetwork.Config() // .basePath("fakeapi") // .requestDuration(1) // .realNetworkHttpStack(new OkHttpStack())); // configBuilder.network(network); // } else { // configBuilder.httpStack(new OkHttpStack()); // } // // sRequestQueue = VolleyBall.newRequestQueue(configBuilder.build()); // // sScenarioRequestQueue = VolleyBall.newRequestQueue(new VolleyBallConfig.Builder(sContext) // .network(new FakeNetwork()) // .build()); // // // init database helper // sDatabaseHelper = new DatabaseHelper(sContext); // sSQLiteDatabase = sDatabaseHelper.getWritableDatabase(); // } // // public static Context getContext() { // return sContext; // } // // public static BallRequestQueue getRequestQueue() { // return sRequestQueue; // } // // public static BallRequestQueue getScenarioRequestQueue() { // return sScenarioRequestQueue; // } // // public static DatabaseHelper getDatabaseHelper() { // return sDatabaseHelper; // } // // public static SQLiteDatabase getSQLiteDatabase() { // return sSQLiteDatabase; // } // } // // Path: samples/src/main/java/com/siu/android/volleyball/samples/model/Entry.java // public class Entry implements EntryMapping { // // private long id; // private String title; // // public Entry() { // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: samples/src/main/java/com/siu/android/volleyball/samples/util/SimpleLogger.java // public class SimpleLogger { // // // D // public static void d(String string) { // Log.d(SimpleLogger.class.getName(), string); // } // // public static void d(String string, Throwable tr) { // Log.d(SimpleLogger.class.getName(), string, tr); // } // // public static void d(String string, Object... args) { // d(String.format(string, args)); // } // // public static void d(String string, Throwable tr, Object... args) { // d(String.format(string, args), tr); // } // // // // E // public static void e(String string) { // Log.e(SimpleLogger.class.getName(), string); // } // // public static void e(String string, Throwable tr) { // Log.e(SimpleLogger.class.getName(), string, tr); // } // // public static void e(String string, Object... args) { // e(String.format(string, args)); // } // // public static void e(String string, Throwable tr, Object... args) { // e(String.format(string, args), tr); // } // }
import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.siu.android.volleyball.samples.Application; import com.siu.android.volleyball.samples.model.Entry; import com.siu.android.volleyball.samples.util.SimpleLogger; import java.util.ArrayList; import java.util.List;
@Override public void run(SQLiteDatabase db) { db.delete(Entry.TABLE, null, null); ContentValues contentValues; for (Entry entry : entries) { contentValues = new ContentValues(); contentValues.put(Entry.TITLE, entry.getTitle()); db.insert(Entry.TABLE, null, contentValues); } } }); } public static final void save(Entry entry) { ContentValues contentValues = new ContentValues(); contentValues.put(Entry.ID, entry.getId()); contentValues.put(Entry.TITLE, entry.getTitle()); Application.getSQLiteDatabase().insert(Entry.TABLE, null, contentValues); } public static void runInTransaction(DatabaseTransaction databaseTransaction) { SQLiteDatabase db = Application.getSQLiteDatabase(); db.beginTransaction(); try { databaseTransaction.run(db); db.setTransactionSuccessful(); } catch (Exception e) {
// Path: samples/src/main/java/com/siu/android/volleyball/samples/Application.java // public class Application extends android.app.Application { // // private static Context sContext; // private static BallRequestQueue sRequestQueue; // private static BallRequestQueue sScenarioRequestQueue; // private static DatabaseHelper sDatabaseHelper; // private static SQLiteDatabase sSQLiteDatabase; // // @Override // public void onCreate() { // super.onCreate(); // // sContext = getApplicationContext(); // // if (Constants.DEBUG) { // deleteDatabase(DatabaseHelper.NAME); // } // // // init volley ball // VolleyBallConfig.Builder configBuilder = new VolleyBallConfig.Builder(sContext); // // // mock // if (Constants.MOCK_WEBSERVICE) { // FileMockNetwork network = new FileMockNetwork(sContext, new FileMockNetwork.Config() // .basePath("fakeapi") // .requestDuration(1) // .realNetworkHttpStack(new OkHttpStack())); // configBuilder.network(network); // } else { // configBuilder.httpStack(new OkHttpStack()); // } // // sRequestQueue = VolleyBall.newRequestQueue(configBuilder.build()); // // sScenarioRequestQueue = VolleyBall.newRequestQueue(new VolleyBallConfig.Builder(sContext) // .network(new FakeNetwork()) // .build()); // // // init database helper // sDatabaseHelper = new DatabaseHelper(sContext); // sSQLiteDatabase = sDatabaseHelper.getWritableDatabase(); // } // // public static Context getContext() { // return sContext; // } // // public static BallRequestQueue getRequestQueue() { // return sRequestQueue; // } // // public static BallRequestQueue getScenarioRequestQueue() { // return sScenarioRequestQueue; // } // // public static DatabaseHelper getDatabaseHelper() { // return sDatabaseHelper; // } // // public static SQLiteDatabase getSQLiteDatabase() { // return sSQLiteDatabase; // } // } // // Path: samples/src/main/java/com/siu/android/volleyball/samples/model/Entry.java // public class Entry implements EntryMapping { // // private long id; // private String title; // // public Entry() { // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // } // // Path: samples/src/main/java/com/siu/android/volleyball/samples/util/SimpleLogger.java // public class SimpleLogger { // // // D // public static void d(String string) { // Log.d(SimpleLogger.class.getName(), string); // } // // public static void d(String string, Throwable tr) { // Log.d(SimpleLogger.class.getName(), string, tr); // } // // public static void d(String string, Object... args) { // d(String.format(string, args)); // } // // public static void d(String string, Throwable tr, Object... args) { // d(String.format(string, args), tr); // } // // // // E // public static void e(String string) { // Log.e(SimpleLogger.class.getName(), string); // } // // public static void e(String string, Throwable tr) { // Log.e(SimpleLogger.class.getName(), string, tr); // } // // public static void e(String string, Object... args) { // e(String.format(string, args)); // } // // public static void e(String string, Throwable tr, Object... args) { // e(String.format(string, args), tr); // } // } // Path: samples/src/main/java/com/siu/android/volleyball/samples/database/EntryDao.java import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.siu.android.volleyball.samples.Application; import com.siu.android.volleyball.samples.model.Entry; import com.siu.android.volleyball.samples.util.SimpleLogger; import java.util.ArrayList; import java.util.List; @Override public void run(SQLiteDatabase db) { db.delete(Entry.TABLE, null, null); ContentValues contentValues; for (Entry entry : entries) { contentValues = new ContentValues(); contentValues.put(Entry.TITLE, entry.getTitle()); db.insert(Entry.TABLE, null, contentValues); } } }); } public static final void save(Entry entry) { ContentValues contentValues = new ContentValues(); contentValues.put(Entry.ID, entry.getId()); contentValues.put(Entry.TITLE, entry.getTitle()); Application.getSQLiteDatabase().insert(Entry.TABLE, null, contentValues); } public static void runInTransaction(DatabaseTransaction databaseTransaction) { SQLiteDatabase db = Application.getSQLiteDatabase(); db.beginTransaction(); try { databaseTransaction.run(db); db.setTransactionSuccessful(); } catch (Exception e) {
SimpleLogger.e("run in transaction error", e);
lukaspili/Volley-Ball
samples/src/main/java/com/siu/android/volleyball/samples/volley/request/SampleErrorNetworkRequest.java
// Path: library/src/main/java/com/siu/android/volleyball/BallResponse.java // public class BallResponse<T> { // // public static enum ResponseSource { // LOCAL, CACHE, NETWORK // } // // protected Response<T> mResponse; // protected ResponseSource mResponseSource; // protected boolean mIdentical = false; // // /** // * Returns whether this response is considered successful. // */ // public boolean isSuccess() { // return mResponse.isSuccess(); // } // // public static <T> BallResponse<T> identical(ResponseSource responseSource) { // return new BallResponse<T>(Response.<T>success(null, null), responseSource, true); // } // // public static <T> BallResponse<T> success(T result) { // return new BallResponse<T>(Response.success(result, null)); // } // // public static <T> BallResponse<T> success(T result, Cache.Entry cacheEntry) { // return new BallResponse<T>(Response.success(result, cacheEntry)); // } // // public static <T> BallResponse<T> error(VolleyError error) { // return new BallResponse<T>(Response.<T>error(error), ResponseSource.NETWORK); // error cames always from network // } // // protected BallResponse(Response<T> response) { // this(response, null, false); // } // // protected BallResponse(Response<T> response, ResponseSource responseSource) { // this(response, responseSource, false); // } // // public BallResponse(Response<T> response, ResponseSource responseSource, boolean identical) { // mResponse = response; // mResponseSource = responseSource; // mIdentical = identical; // } // // public ResponseSource getResponseSource() { // return mResponseSource; // } // // public void setResponseSource(ResponseSource responseSource) { // this.mResponseSource = responseSource; // } // // public boolean isIntermediate() { // return mResponse.intermediate; // } // // public void setIntermediate(boolean intermediate) { // mResponse.intermediate = intermediate; // } // // public T getResult() { // return mResponse.result; // } // // public Cache.Entry getCacheEntry() { // return mResponse.cacheEntry; // } // // public VolleyError getError() { // return mResponse.error; // } // // public boolean isIdentical() { // return mIdentical; // } // // public void setIdentical(boolean identical) { // mIdentical = identical; // } // } // // Path: library/src/main/java/com/siu/android/volleyball/request/NetworkRequest.java // public abstract class NetworkRequest<T> extends BallRequest<T> { // // protected NetworkRequest(int method, String url, Response.ErrorListener errorListener) { // super(method, url, errorListener); // } // // public NetworkRequest(int method, String url, SingleResponseListener<T> responseListener, Response.ErrorListener errorListener) { // super(method, url, responseListener, errorListener); // } // // @Override // public boolean shouldProcessNetwork() { // return true; // } // // @Override // protected NetworkRequestProcessor createNetworkRequestProcessor() { // return new NetworkRequestProcessor() { // @Override // public BallResponse<T> parseNetworkResponse(NetworkResponse networkResponse) { // return parseBallNetworkResponse(networkResponse); // } // }; // } // // protected abstract BallResponse<T> parseBallNetworkResponse(NetworkResponse response); // } // // Path: library/src/main/java/com/siu/android/volleyball/response/SingleResponseListener.java // public abstract class SingleResponseListener<T> implements ResponseListener<T> { // // /** // * Can happen when the response is soft cached // * // * @param response // * @param responseSource // */ // @Override // public final void onIntermediateResponse(T response, BallResponse.ResponseSource responseSource) { // onResponse(response); // } // // @Override // public final void onFinalResponse(T response, BallResponse.ResponseSource responseSource) { // onResponse(response); // } // // /** // * Can happen when the response is soft cached. Maybe ? // * // * @param responseSource // */ // @Override // public final void onFinalResponseIdenticalToIntermediate(BallResponse.ResponseSource responseSource) { // // } // // //TODO: add response source because it can still be soft cached response // public abstract void onResponse(T response); // }
import com.android.volley.NetworkResponse; import com.android.volley.Response; import com.android.volley.VolleyError; import com.siu.android.volleyball.BallResponse; import com.siu.android.volleyball.request.NetworkRequest; import com.siu.android.volleyball.response.SingleResponseListener;
package com.siu.android.volleyball.samples.volley.request; /** * Created by lukas on 9/17/13. */ public class SampleErrorNetworkRequest extends NetworkRequest<String> { public SampleErrorNetworkRequest(int method, String url, SingleResponseListener<String> responseListener, Response.ErrorListener errorListener) { super(method, url, responseListener, errorListener); } @Override
// Path: library/src/main/java/com/siu/android/volleyball/BallResponse.java // public class BallResponse<T> { // // public static enum ResponseSource { // LOCAL, CACHE, NETWORK // } // // protected Response<T> mResponse; // protected ResponseSource mResponseSource; // protected boolean mIdentical = false; // // /** // * Returns whether this response is considered successful. // */ // public boolean isSuccess() { // return mResponse.isSuccess(); // } // // public static <T> BallResponse<T> identical(ResponseSource responseSource) { // return new BallResponse<T>(Response.<T>success(null, null), responseSource, true); // } // // public static <T> BallResponse<T> success(T result) { // return new BallResponse<T>(Response.success(result, null)); // } // // public static <T> BallResponse<T> success(T result, Cache.Entry cacheEntry) { // return new BallResponse<T>(Response.success(result, cacheEntry)); // } // // public static <T> BallResponse<T> error(VolleyError error) { // return new BallResponse<T>(Response.<T>error(error), ResponseSource.NETWORK); // error cames always from network // } // // protected BallResponse(Response<T> response) { // this(response, null, false); // } // // protected BallResponse(Response<T> response, ResponseSource responseSource) { // this(response, responseSource, false); // } // // public BallResponse(Response<T> response, ResponseSource responseSource, boolean identical) { // mResponse = response; // mResponseSource = responseSource; // mIdentical = identical; // } // // public ResponseSource getResponseSource() { // return mResponseSource; // } // // public void setResponseSource(ResponseSource responseSource) { // this.mResponseSource = responseSource; // } // // public boolean isIntermediate() { // return mResponse.intermediate; // } // // public void setIntermediate(boolean intermediate) { // mResponse.intermediate = intermediate; // } // // public T getResult() { // return mResponse.result; // } // // public Cache.Entry getCacheEntry() { // return mResponse.cacheEntry; // } // // public VolleyError getError() { // return mResponse.error; // } // // public boolean isIdentical() { // return mIdentical; // } // // public void setIdentical(boolean identical) { // mIdentical = identical; // } // } // // Path: library/src/main/java/com/siu/android/volleyball/request/NetworkRequest.java // public abstract class NetworkRequest<T> extends BallRequest<T> { // // protected NetworkRequest(int method, String url, Response.ErrorListener errorListener) { // super(method, url, errorListener); // } // // public NetworkRequest(int method, String url, SingleResponseListener<T> responseListener, Response.ErrorListener errorListener) { // super(method, url, responseListener, errorListener); // } // // @Override // public boolean shouldProcessNetwork() { // return true; // } // // @Override // protected NetworkRequestProcessor createNetworkRequestProcessor() { // return new NetworkRequestProcessor() { // @Override // public BallResponse<T> parseNetworkResponse(NetworkResponse networkResponse) { // return parseBallNetworkResponse(networkResponse); // } // }; // } // // protected abstract BallResponse<T> parseBallNetworkResponse(NetworkResponse response); // } // // Path: library/src/main/java/com/siu/android/volleyball/response/SingleResponseListener.java // public abstract class SingleResponseListener<T> implements ResponseListener<T> { // // /** // * Can happen when the response is soft cached // * // * @param response // * @param responseSource // */ // @Override // public final void onIntermediateResponse(T response, BallResponse.ResponseSource responseSource) { // onResponse(response); // } // // @Override // public final void onFinalResponse(T response, BallResponse.ResponseSource responseSource) { // onResponse(response); // } // // /** // * Can happen when the response is soft cached. Maybe ? // * // * @param responseSource // */ // @Override // public final void onFinalResponseIdenticalToIntermediate(BallResponse.ResponseSource responseSource) { // // } // // //TODO: add response source because it can still be soft cached response // public abstract void onResponse(T response); // } // Path: samples/src/main/java/com/siu/android/volleyball/samples/volley/request/SampleErrorNetworkRequest.java import com.android.volley.NetworkResponse; import com.android.volley.Response; import com.android.volley.VolleyError; import com.siu.android.volleyball.BallResponse; import com.siu.android.volleyball.request.NetworkRequest; import com.siu.android.volleyball.response.SingleResponseListener; package com.siu.android.volleyball.samples.volley.request; /** * Created by lukas on 9/17/13. */ public class SampleErrorNetworkRequest extends NetworkRequest<String> { public SampleErrorNetworkRequest(int method, String url, SingleResponseListener<String> responseListener, Response.ErrorListener errorListener) { super(method, url, responseListener, errorListener); } @Override
protected BallResponse<String> parseBallNetworkResponse(NetworkResponse response) {
lukaspili/Volley-Ball
library/src/main/java/com/siu/android/volleyball/toolbox/VolleyBallConfig.java
// Path: library/src/main/java/com/siu/android/volleyball/util/ConfigUtils.java // public class ConfigUtils { // // public static final HttpStack getDefaultHttpStack(Context context) { // String userAgent = "volley/0"; // try { // String packageName = context.getPackageName(); // PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0); // userAgent = packageName + "/" + info.versionCode; // } catch (PackageManager.NameNotFoundException e) { // } // // HttpStack stack; // if (Build.VERSION.SDK_INT >= 9) { // stack = new HurlStack(); // } else { // // Prior to Gingerbread, HttpUrlConnection was unreliable. // // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html // stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent)); // } // // return stack; // } // // public static Network getDefaultNetwork(HttpStack httpStack) { // return new BasicNetwork(httpStack); // } // // public static Network getDefaultNetworkWithDefaultHttpStack(Context context) { // return new BasicNetwork(getDefaultHttpStack(context)); // } // }
import android.content.Context; import com.android.volley.Cache; import com.android.volley.Network; import com.android.volley.toolbox.DiskBasedCache; import com.android.volley.toolbox.HttpStack; import com.siu.android.volleyball.util.ConfigUtils; import java.io.File;
package com.siu.android.volleyball.toolbox; /** * Created by lukas on 8/29/13. */ public class VolleyBallConfig { private static final String DEFAULT_CACHE_DIR = "volley"; private Context mContext; private HttpStack mHttpStack; private Network mNetwork; private Cache mCache; private VolleyBallConfig() { } public static class Builder { private VolleyBallConfig mInstance; public Builder(Context context) { mInstance = new VolleyBallConfig(); mInstance.mContext = context; } public Builder httpStack(HttpStack httpStack) { mInstance.mHttpStack = httpStack; return this; } public Builder network(Network network) { mInstance.mNetwork = network; return this; } public Builder cache(Cache cache) { mInstance.mCache = cache; return this; } public VolleyBallConfig build() { if (mInstance.mHttpStack == null) {
// Path: library/src/main/java/com/siu/android/volleyball/util/ConfigUtils.java // public class ConfigUtils { // // public static final HttpStack getDefaultHttpStack(Context context) { // String userAgent = "volley/0"; // try { // String packageName = context.getPackageName(); // PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0); // userAgent = packageName + "/" + info.versionCode; // } catch (PackageManager.NameNotFoundException e) { // } // // HttpStack stack; // if (Build.VERSION.SDK_INT >= 9) { // stack = new HurlStack(); // } else { // // Prior to Gingerbread, HttpUrlConnection was unreliable. // // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html // stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent)); // } // // return stack; // } // // public static Network getDefaultNetwork(HttpStack httpStack) { // return new BasicNetwork(httpStack); // } // // public static Network getDefaultNetworkWithDefaultHttpStack(Context context) { // return new BasicNetwork(getDefaultHttpStack(context)); // } // } // Path: library/src/main/java/com/siu/android/volleyball/toolbox/VolleyBallConfig.java import android.content.Context; import com.android.volley.Cache; import com.android.volley.Network; import com.android.volley.toolbox.DiskBasedCache; import com.android.volley.toolbox.HttpStack; import com.siu.android.volleyball.util.ConfigUtils; import java.io.File; package com.siu.android.volleyball.toolbox; /** * Created by lukas on 8/29/13. */ public class VolleyBallConfig { private static final String DEFAULT_CACHE_DIR = "volley"; private Context mContext; private HttpStack mHttpStack; private Network mNetwork; private Cache mCache; private VolleyBallConfig() { } public static class Builder { private VolleyBallConfig mInstance; public Builder(Context context) { mInstance = new VolleyBallConfig(); mInstance.mContext = context; } public Builder httpStack(HttpStack httpStack) { mInstance.mHttpStack = httpStack; return this; } public Builder network(Network network) { mInstance.mNetwork = network; return this; } public Builder cache(Cache cache) { mInstance.mCache = cache; return this; } public VolleyBallConfig build() { if (mInstance.mHttpStack == null) {
mInstance.mHttpStack = ConfigUtils.getDefaultHttpStack(mInstance.mContext);
lukaspili/Volley-Ball
library/src/main/java/com/siu/android/volleyball/toolbox/BallNetworkImageView.java
// Path: library/src/main/java/com/siu/android/volleyball/toolbox/BallImageLoader.java // public class ImageContainer { // /** // * The most relevant bitmap for the container. If the image was in cache, the // * Holder to use for the final bitmap (the one that pairs to the requested URL). // */ // private Bitmap mBitmap; // // private final ImageListener mListener; // // /** The cache key that was associated with the request */ // private final String mCacheKey; // // /** The request URL that was specified */ // private final String mRequestUrl; // // /** // * Constructs a BitmapContainer object. // * @param bitmap The final bitmap (if it exists). // * @param requestUrl The requested URL for this container. // * @param cacheKey The cache key that identifies the requested URL for this container. // */ // public ImageContainer(Bitmap bitmap, String requestUrl, // String cacheKey, ImageListener listener) { // mBitmap = bitmap; // mRequestUrl = requestUrl; // mCacheKey = cacheKey; // mListener = listener; // } // // /** // * Releases interest in the in-flight request (and cancels it if no one else is listening). // */ // public void cancelRequest() { // if (mListener == null) { // return; // } // // BatchedImageRequest request = mInFlightRequests.get(mCacheKey); // if (request != null) { // boolean canceled = request.removeContainerAndCancelIfNecessary(this); // if (canceled) { // mInFlightRequests.remove(mCacheKey); // } // } else { // // check to see if it is already batched for delivery. // request = mBatchedResponses.get(mCacheKey); // if (request != null) { // request.removeContainerAndCancelIfNecessary(this); // if (request.mContainers.size() == 0) { // mBatchedResponses.remove(mCacheKey); // } // } // } // } // // /** // * Returns the bitmap associated with the request URL if it has been loaded, null otherwise. // */ // public Bitmap getBitmap() { // return mBitmap; // } // // /** // * Returns the requested URL for this container. // */ // public String getRequestUrl() { // return mRequestUrl; // } // } // // Path: library/src/main/java/com/siu/android/volleyball/toolbox/BallImageLoader.java // public interface ImageListener extends ErrorListener { // /** // * Listens for non-error changes to the loading of the image request. // * // * @param response Holds all information pertaining to the request, as well // * as the bitmap (if it is loaded). // * @param isImmediate True if this was called during ImageLoader.get() variants. // * This can be used to differentiate between a cached image loading and a network // * image loading in order to, for example, run an animation to fade in network loaded // * images. // */ // public void onResponse(ImageContainer response, boolean isImmediate); // }
import android.content.Context; import android.text.TextUtils; import android.util.AttributeSet; import android.view.ViewGroup.LayoutParams; import android.widget.ImageView; import com.android.volley.VolleyError; import com.siu.android.volleyball.toolbox.BallImageLoader.ImageContainer; import com.siu.android.volleyball.toolbox.BallImageLoader.ImageListener;
/** * Copyright (C) 2013 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 com.siu.android.volleyball.toolbox; /** * Handles fetching an image from a URL as well as the life-cycle of the * associated request. */ public class BallNetworkImageView extends ImageView { /** The URL of the network image to load */ private String mUrl; /** * Resource ID of the image to be used as a placeholder until the network image is loaded. */ private int mDefaultImageId; /** * Resource ID of the image to be used if the network response fails. */ private int mErrorImageId; /** Local copy of the ImageLoader. */ private BallImageLoader mImageLoader; /** Current ImageContainer. (either in-flight or finished) */
// Path: library/src/main/java/com/siu/android/volleyball/toolbox/BallImageLoader.java // public class ImageContainer { // /** // * The most relevant bitmap for the container. If the image was in cache, the // * Holder to use for the final bitmap (the one that pairs to the requested URL). // */ // private Bitmap mBitmap; // // private final ImageListener mListener; // // /** The cache key that was associated with the request */ // private final String mCacheKey; // // /** The request URL that was specified */ // private final String mRequestUrl; // // /** // * Constructs a BitmapContainer object. // * @param bitmap The final bitmap (if it exists). // * @param requestUrl The requested URL for this container. // * @param cacheKey The cache key that identifies the requested URL for this container. // */ // public ImageContainer(Bitmap bitmap, String requestUrl, // String cacheKey, ImageListener listener) { // mBitmap = bitmap; // mRequestUrl = requestUrl; // mCacheKey = cacheKey; // mListener = listener; // } // // /** // * Releases interest in the in-flight request (and cancels it if no one else is listening). // */ // public void cancelRequest() { // if (mListener == null) { // return; // } // // BatchedImageRequest request = mInFlightRequests.get(mCacheKey); // if (request != null) { // boolean canceled = request.removeContainerAndCancelIfNecessary(this); // if (canceled) { // mInFlightRequests.remove(mCacheKey); // } // } else { // // check to see if it is already batched for delivery. // request = mBatchedResponses.get(mCacheKey); // if (request != null) { // request.removeContainerAndCancelIfNecessary(this); // if (request.mContainers.size() == 0) { // mBatchedResponses.remove(mCacheKey); // } // } // } // } // // /** // * Returns the bitmap associated with the request URL if it has been loaded, null otherwise. // */ // public Bitmap getBitmap() { // return mBitmap; // } // // /** // * Returns the requested URL for this container. // */ // public String getRequestUrl() { // return mRequestUrl; // } // } // // Path: library/src/main/java/com/siu/android/volleyball/toolbox/BallImageLoader.java // public interface ImageListener extends ErrorListener { // /** // * Listens for non-error changes to the loading of the image request. // * // * @param response Holds all information pertaining to the request, as well // * as the bitmap (if it is loaded). // * @param isImmediate True if this was called during ImageLoader.get() variants. // * This can be used to differentiate between a cached image loading and a network // * image loading in order to, for example, run an animation to fade in network loaded // * images. // */ // public void onResponse(ImageContainer response, boolean isImmediate); // } // Path: library/src/main/java/com/siu/android/volleyball/toolbox/BallNetworkImageView.java import android.content.Context; import android.text.TextUtils; import android.util.AttributeSet; import android.view.ViewGroup.LayoutParams; import android.widget.ImageView; import com.android.volley.VolleyError; import com.siu.android.volleyball.toolbox.BallImageLoader.ImageContainer; import com.siu.android.volleyball.toolbox.BallImageLoader.ImageListener; /** * Copyright (C) 2013 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 com.siu.android.volleyball.toolbox; /** * Handles fetching an image from a URL as well as the life-cycle of the * associated request. */ public class BallNetworkImageView extends ImageView { /** The URL of the network image to load */ private String mUrl; /** * Resource ID of the image to be used as a placeholder until the network image is loaded. */ private int mDefaultImageId; /** * Resource ID of the image to be used if the network response fails. */ private int mErrorImageId; /** Local copy of the ImageLoader. */ private BallImageLoader mImageLoader; /** Current ImageContainer. (either in-flight or finished) */
private ImageContainer mImageContainer;
lukaspili/Volley-Ball
library/src/main/java/com/siu/android/volleyball/toolbox/BallNetworkImageView.java
// Path: library/src/main/java/com/siu/android/volleyball/toolbox/BallImageLoader.java // public class ImageContainer { // /** // * The most relevant bitmap for the container. If the image was in cache, the // * Holder to use for the final bitmap (the one that pairs to the requested URL). // */ // private Bitmap mBitmap; // // private final ImageListener mListener; // // /** The cache key that was associated with the request */ // private final String mCacheKey; // // /** The request URL that was specified */ // private final String mRequestUrl; // // /** // * Constructs a BitmapContainer object. // * @param bitmap The final bitmap (if it exists). // * @param requestUrl The requested URL for this container. // * @param cacheKey The cache key that identifies the requested URL for this container. // */ // public ImageContainer(Bitmap bitmap, String requestUrl, // String cacheKey, ImageListener listener) { // mBitmap = bitmap; // mRequestUrl = requestUrl; // mCacheKey = cacheKey; // mListener = listener; // } // // /** // * Releases interest in the in-flight request (and cancels it if no one else is listening). // */ // public void cancelRequest() { // if (mListener == null) { // return; // } // // BatchedImageRequest request = mInFlightRequests.get(mCacheKey); // if (request != null) { // boolean canceled = request.removeContainerAndCancelIfNecessary(this); // if (canceled) { // mInFlightRequests.remove(mCacheKey); // } // } else { // // check to see if it is already batched for delivery. // request = mBatchedResponses.get(mCacheKey); // if (request != null) { // request.removeContainerAndCancelIfNecessary(this); // if (request.mContainers.size() == 0) { // mBatchedResponses.remove(mCacheKey); // } // } // } // } // // /** // * Returns the bitmap associated with the request URL if it has been loaded, null otherwise. // */ // public Bitmap getBitmap() { // return mBitmap; // } // // /** // * Returns the requested URL for this container. // */ // public String getRequestUrl() { // return mRequestUrl; // } // } // // Path: library/src/main/java/com/siu/android/volleyball/toolbox/BallImageLoader.java // public interface ImageListener extends ErrorListener { // /** // * Listens for non-error changes to the loading of the image request. // * // * @param response Holds all information pertaining to the request, as well // * as the bitmap (if it is loaded). // * @param isImmediate True if this was called during ImageLoader.get() variants. // * This can be used to differentiate between a cached image loading and a network // * image loading in order to, for example, run an animation to fade in network loaded // * images. // */ // public void onResponse(ImageContainer response, boolean isImmediate); // }
import android.content.Context; import android.text.TextUtils; import android.util.AttributeSet; import android.view.ViewGroup.LayoutParams; import android.widget.ImageView; import com.android.volley.VolleyError; import com.siu.android.volleyball.toolbox.BallImageLoader.ImageContainer; import com.siu.android.volleyball.toolbox.BallImageLoader.ImageListener;
if (width == 0 && height == 0 && !isFullyWrapContent) { return; } // if the URL to be loaded in this view is empty, cancel any old requests and clear the // currently loaded image. if (TextUtils.isEmpty(mUrl)) { if (mImageContainer != null) { mImageContainer.cancelRequest(); mImageContainer = null; } setImageBitmap(null); return; } // if there was an old request in this view, check if it needs to be canceled. if (mImageContainer != null && mImageContainer.getRequestUrl() != null) { if (mImageContainer.getRequestUrl().equals(mUrl)) { // if the request is from the same URL, return. return; } else { // if there is a pre-existing request, cancel it if it's fetching a different URL. mImageContainer.cancelRequest(); setImageBitmap(null); } } // The pre-existing content of this view didn't match the current URL. Load the new image // from the network. ImageContainer newContainer = mImageLoader.get(mUrl,
// Path: library/src/main/java/com/siu/android/volleyball/toolbox/BallImageLoader.java // public class ImageContainer { // /** // * The most relevant bitmap for the container. If the image was in cache, the // * Holder to use for the final bitmap (the one that pairs to the requested URL). // */ // private Bitmap mBitmap; // // private final ImageListener mListener; // // /** The cache key that was associated with the request */ // private final String mCacheKey; // // /** The request URL that was specified */ // private final String mRequestUrl; // // /** // * Constructs a BitmapContainer object. // * @param bitmap The final bitmap (if it exists). // * @param requestUrl The requested URL for this container. // * @param cacheKey The cache key that identifies the requested URL for this container. // */ // public ImageContainer(Bitmap bitmap, String requestUrl, // String cacheKey, ImageListener listener) { // mBitmap = bitmap; // mRequestUrl = requestUrl; // mCacheKey = cacheKey; // mListener = listener; // } // // /** // * Releases interest in the in-flight request (and cancels it if no one else is listening). // */ // public void cancelRequest() { // if (mListener == null) { // return; // } // // BatchedImageRequest request = mInFlightRequests.get(mCacheKey); // if (request != null) { // boolean canceled = request.removeContainerAndCancelIfNecessary(this); // if (canceled) { // mInFlightRequests.remove(mCacheKey); // } // } else { // // check to see if it is already batched for delivery. // request = mBatchedResponses.get(mCacheKey); // if (request != null) { // request.removeContainerAndCancelIfNecessary(this); // if (request.mContainers.size() == 0) { // mBatchedResponses.remove(mCacheKey); // } // } // } // } // // /** // * Returns the bitmap associated with the request URL if it has been loaded, null otherwise. // */ // public Bitmap getBitmap() { // return mBitmap; // } // // /** // * Returns the requested URL for this container. // */ // public String getRequestUrl() { // return mRequestUrl; // } // } // // Path: library/src/main/java/com/siu/android/volleyball/toolbox/BallImageLoader.java // public interface ImageListener extends ErrorListener { // /** // * Listens for non-error changes to the loading of the image request. // * // * @param response Holds all information pertaining to the request, as well // * as the bitmap (if it is loaded). // * @param isImmediate True if this was called during ImageLoader.get() variants. // * This can be used to differentiate between a cached image loading and a network // * image loading in order to, for example, run an animation to fade in network loaded // * images. // */ // public void onResponse(ImageContainer response, boolean isImmediate); // } // Path: library/src/main/java/com/siu/android/volleyball/toolbox/BallNetworkImageView.java import android.content.Context; import android.text.TextUtils; import android.util.AttributeSet; import android.view.ViewGroup.LayoutParams; import android.widget.ImageView; import com.android.volley.VolleyError; import com.siu.android.volleyball.toolbox.BallImageLoader.ImageContainer; import com.siu.android.volleyball.toolbox.BallImageLoader.ImageListener; if (width == 0 && height == 0 && !isFullyWrapContent) { return; } // if the URL to be loaded in this view is empty, cancel any old requests and clear the // currently loaded image. if (TextUtils.isEmpty(mUrl)) { if (mImageContainer != null) { mImageContainer.cancelRequest(); mImageContainer = null; } setImageBitmap(null); return; } // if there was an old request in this view, check if it needs to be canceled. if (mImageContainer != null && mImageContainer.getRequestUrl() != null) { if (mImageContainer.getRequestUrl().equals(mUrl)) { // if the request is from the same URL, return. return; } else { // if there is a pre-existing request, cancel it if it's fetching a different URL. mImageContainer.cancelRequest(); setImageBitmap(null); } } // The pre-existing content of this view didn't match the current URL. Load the new image // from the network. ImageContainer newContainer = mImageLoader.get(mUrl,
new ImageListener() {
lukaspili/Volley-Ball
samples/src/main/java/com/siu/android/volleyball/samples/volley/fake/FakeNetwork.java
// Path: samples/src/main/java/com/siu/android/volleyball/samples/util/ScenarioUtils.java // public class ScenarioUtils { // // public static final void waitSeveralSeconds(int seconds) { // try { // Thread.sleep(seconds * 1000); // } catch (InterruptedException e) { // throw new RuntimeException(e); // } // } // }
import com.android.volley.Network; import com.android.volley.NetworkResponse; import com.android.volley.Request; import com.android.volley.VolleyError; import com.siu.android.volleyball.samples.util.ScenarioUtils; import java.util.HashMap;
package com.siu.android.volleyball.samples.volley.fake; /** * Created by lukas on 9/9/13. */ public class FakeNetwork implements Network { private boolean mSuccess = true; private boolean mNotModified = false; private int mWaitSeconds = 0; public FakeNetwork() { } public FakeNetwork(boolean success, boolean notModified, int waitSeconds) { mSuccess = success; mNotModified = notModified; mWaitSeconds = waitSeconds; } @Override public NetworkResponse performRequest(Request<?> request) throws VolleyError {
// Path: samples/src/main/java/com/siu/android/volleyball/samples/util/ScenarioUtils.java // public class ScenarioUtils { // // public static final void waitSeveralSeconds(int seconds) { // try { // Thread.sleep(seconds * 1000); // } catch (InterruptedException e) { // throw new RuntimeException(e); // } // } // } // Path: samples/src/main/java/com/siu/android/volleyball/samples/volley/fake/FakeNetwork.java import com.android.volley.Network; import com.android.volley.NetworkResponse; import com.android.volley.Request; import com.android.volley.VolleyError; import com.siu.android.volleyball.samples.util.ScenarioUtils; import java.util.HashMap; package com.siu.android.volleyball.samples.volley.fake; /** * Created by lukas on 9/9/13. */ public class FakeNetwork implements Network { private boolean mSuccess = true; private boolean mNotModified = false; private int mWaitSeconds = 0; public FakeNetwork() { } public FakeNetwork(boolean success, boolean notModified, int waitSeconds) { mSuccess = success; mNotModified = notModified; mWaitSeconds = waitSeconds; } @Override public NetworkResponse performRequest(Request<?> request) throws VolleyError {
ScenarioUtils.waitSeveralSeconds(mWaitSeconds);
lukaspili/Volley-Ball
samples/src/main/java/com/siu/android/volleyball/samples/volley/request/SampleRequest.java
// Path: library/src/main/java/com/siu/android/volleyball/BallResponse.java // public class BallResponse<T> { // // public static enum ResponseSource { // LOCAL, CACHE, NETWORK // } // // protected Response<T> mResponse; // protected ResponseSource mResponseSource; // protected boolean mIdentical = false; // // /** // * Returns whether this response is considered successful. // */ // public boolean isSuccess() { // return mResponse.isSuccess(); // } // // public static <T> BallResponse<T> identical(ResponseSource responseSource) { // return new BallResponse<T>(Response.<T>success(null, null), responseSource, true); // } // // public static <T> BallResponse<T> success(T result) { // return new BallResponse<T>(Response.success(result, null)); // } // // public static <T> BallResponse<T> success(T result, Cache.Entry cacheEntry) { // return new BallResponse<T>(Response.success(result, cacheEntry)); // } // // public static <T> BallResponse<T> error(VolleyError error) { // return new BallResponse<T>(Response.<T>error(error), ResponseSource.NETWORK); // error cames always from network // } // // protected BallResponse(Response<T> response) { // this(response, null, false); // } // // protected BallResponse(Response<T> response, ResponseSource responseSource) { // this(response, responseSource, false); // } // // public BallResponse(Response<T> response, ResponseSource responseSource, boolean identical) { // mResponse = response; // mResponseSource = responseSource; // mIdentical = identical; // } // // public ResponseSource getResponseSource() { // return mResponseSource; // } // // public void setResponseSource(ResponseSource responseSource) { // this.mResponseSource = responseSource; // } // // public boolean isIntermediate() { // return mResponse.intermediate; // } // // public void setIntermediate(boolean intermediate) { // mResponse.intermediate = intermediate; // } // // public T getResult() { // return mResponse.result; // } // // public Cache.Entry getCacheEntry() { // return mResponse.cacheEntry; // } // // public VolleyError getError() { // return mResponse.error; // } // // public boolean isIdentical() { // return mIdentical; // } // // public void setIdentical(boolean identical) { // mIdentical = identical; // } // } // // Path: library/src/main/java/com/siu/android/volleyball/request/CompleteRequest.java // public abstract class CompleteRequest<T> extends BallRequest<T> { // // public CompleteRequest(int method, String url, Response.ErrorListener errorListener) { // super(method, url, errorListener); // } // // protected CompleteRequest(int method, String url, ResponseListener<T> responseListener, Response.ErrorListener errorListener) { // super(method, url, responseListener, errorListener); // } // // // /* LOCAL */ // // @Override // public boolean shouldProcessLocal() { // return true; // } // // @Override // protected LocalRequestProcessor<T> createLocalRequestProcessor() { // return new LocalRequestProcessor<T>() { // @Override // public T getLocalResponse() { // return CompleteRequest.this.getLocalResponse(); // } // // @Override // public void saveLocalResponse(T response) { // CompleteRequest.this.saveNetworkResponseToLocal(response); // } // }; // } // // protected abstract T getLocalResponse(); // // public abstract void saveNetworkResponseToLocal(T response); // // // /* NETWORK */ // // @Override // public boolean shouldProcessNetwork() { // return true; // } // // @Override // protected NetworkRequestProcessor createNetworkRequestProcessor() { // return new NetworkRequestProcessor() { // @Override // public BallResponse<T> parseNetworkResponse(NetworkResponse networkResponse) { // return parseBallNetworkResponse(networkResponse); // } // }; // } // // protected abstract BallResponse<T> parseBallNetworkResponse(NetworkResponse response); // } // // Path: library/src/main/java/com/siu/android/volleyball/response/ResponseListener.java // public interface ResponseListener<T> { // // public void onIntermediateResponse(T response, BallResponse.ResponseSource responseSource); // // public void onFinalResponse(T response, BallResponse.ResponseSource responseSource); // // public void onFinalResponseIdenticalToIntermediate(BallResponse.ResponseSource responseSource); // }
import com.android.volley.NetworkResponse; import com.android.volley.Response; import com.siu.android.volleyball.BallResponse; import com.siu.android.volleyball.request.CompleteRequest; import com.siu.android.volleyball.response.ResponseListener;
package com.siu.android.volleyball.samples.volley.request; /** * Created by lukas on 9/13/13. */ public class SampleRequest extends CompleteRequest<Object> { public SampleRequest(int method, String url, ResponseListener<Object> responseListener, Response.ErrorListener errorListener) { super(method, url, responseListener, errorListener); } @Override protected Object getLocalResponse() { // query your local database for example // return the result or null if there is no result from database return new Object(); } @Override public void saveNetworkResponseToLocal(Object response) { // save the network response to the local database // next time the request is performed the local response will return the result faster than the network request } @Override
// Path: library/src/main/java/com/siu/android/volleyball/BallResponse.java // public class BallResponse<T> { // // public static enum ResponseSource { // LOCAL, CACHE, NETWORK // } // // protected Response<T> mResponse; // protected ResponseSource mResponseSource; // protected boolean mIdentical = false; // // /** // * Returns whether this response is considered successful. // */ // public boolean isSuccess() { // return mResponse.isSuccess(); // } // // public static <T> BallResponse<T> identical(ResponseSource responseSource) { // return new BallResponse<T>(Response.<T>success(null, null), responseSource, true); // } // // public static <T> BallResponse<T> success(T result) { // return new BallResponse<T>(Response.success(result, null)); // } // // public static <T> BallResponse<T> success(T result, Cache.Entry cacheEntry) { // return new BallResponse<T>(Response.success(result, cacheEntry)); // } // // public static <T> BallResponse<T> error(VolleyError error) { // return new BallResponse<T>(Response.<T>error(error), ResponseSource.NETWORK); // error cames always from network // } // // protected BallResponse(Response<T> response) { // this(response, null, false); // } // // protected BallResponse(Response<T> response, ResponseSource responseSource) { // this(response, responseSource, false); // } // // public BallResponse(Response<T> response, ResponseSource responseSource, boolean identical) { // mResponse = response; // mResponseSource = responseSource; // mIdentical = identical; // } // // public ResponseSource getResponseSource() { // return mResponseSource; // } // // public void setResponseSource(ResponseSource responseSource) { // this.mResponseSource = responseSource; // } // // public boolean isIntermediate() { // return mResponse.intermediate; // } // // public void setIntermediate(boolean intermediate) { // mResponse.intermediate = intermediate; // } // // public T getResult() { // return mResponse.result; // } // // public Cache.Entry getCacheEntry() { // return mResponse.cacheEntry; // } // // public VolleyError getError() { // return mResponse.error; // } // // public boolean isIdentical() { // return mIdentical; // } // // public void setIdentical(boolean identical) { // mIdentical = identical; // } // } // // Path: library/src/main/java/com/siu/android/volleyball/request/CompleteRequest.java // public abstract class CompleteRequest<T> extends BallRequest<T> { // // public CompleteRequest(int method, String url, Response.ErrorListener errorListener) { // super(method, url, errorListener); // } // // protected CompleteRequest(int method, String url, ResponseListener<T> responseListener, Response.ErrorListener errorListener) { // super(method, url, responseListener, errorListener); // } // // // /* LOCAL */ // // @Override // public boolean shouldProcessLocal() { // return true; // } // // @Override // protected LocalRequestProcessor<T> createLocalRequestProcessor() { // return new LocalRequestProcessor<T>() { // @Override // public T getLocalResponse() { // return CompleteRequest.this.getLocalResponse(); // } // // @Override // public void saveLocalResponse(T response) { // CompleteRequest.this.saveNetworkResponseToLocal(response); // } // }; // } // // protected abstract T getLocalResponse(); // // public abstract void saveNetworkResponseToLocal(T response); // // // /* NETWORK */ // // @Override // public boolean shouldProcessNetwork() { // return true; // } // // @Override // protected NetworkRequestProcessor createNetworkRequestProcessor() { // return new NetworkRequestProcessor() { // @Override // public BallResponse<T> parseNetworkResponse(NetworkResponse networkResponse) { // return parseBallNetworkResponse(networkResponse); // } // }; // } // // protected abstract BallResponse<T> parseBallNetworkResponse(NetworkResponse response); // } // // Path: library/src/main/java/com/siu/android/volleyball/response/ResponseListener.java // public interface ResponseListener<T> { // // public void onIntermediateResponse(T response, BallResponse.ResponseSource responseSource); // // public void onFinalResponse(T response, BallResponse.ResponseSource responseSource); // // public void onFinalResponseIdenticalToIntermediate(BallResponse.ResponseSource responseSource); // } // Path: samples/src/main/java/com/siu/android/volleyball/samples/volley/request/SampleRequest.java import com.android.volley.NetworkResponse; import com.android.volley.Response; import com.siu.android.volleyball.BallResponse; import com.siu.android.volleyball.request.CompleteRequest; import com.siu.android.volleyball.response.ResponseListener; package com.siu.android.volleyball.samples.volley.request; /** * Created by lukas on 9/13/13. */ public class SampleRequest extends CompleteRequest<Object> { public SampleRequest(int method, String url, ResponseListener<Object> responseListener, Response.ErrorListener errorListener) { super(method, url, responseListener, errorListener); } @Override protected Object getLocalResponse() { // query your local database for example // return the result or null if there is no result from database return new Object(); } @Override public void saveNetworkResponseToLocal(Object response) { // save the network response to the local database // next time the request is performed the local response will return the result faster than the network request } @Override
protected BallResponse<Object> parseBallNetworkResponse(NetworkResponse response) {
lukaspili/Volley-Ball
samples/src/main/java/com/siu/android/volleyball/samples/volley/ScenarioListener.java
// Path: library/src/main/java/com/siu/android/volleyball/BallResponse.java // public class BallResponse<T> { // // public static enum ResponseSource { // LOCAL, CACHE, NETWORK // } // // protected Response<T> mResponse; // protected ResponseSource mResponseSource; // protected boolean mIdentical = false; // // /** // * Returns whether this response is considered successful. // */ // public boolean isSuccess() { // return mResponse.isSuccess(); // } // // public static <T> BallResponse<T> identical(ResponseSource responseSource) { // return new BallResponse<T>(Response.<T>success(null, null), responseSource, true); // } // // public static <T> BallResponse<T> success(T result) { // return new BallResponse<T>(Response.success(result, null)); // } // // public static <T> BallResponse<T> success(T result, Cache.Entry cacheEntry) { // return new BallResponse<T>(Response.success(result, cacheEntry)); // } // // public static <T> BallResponse<T> error(VolleyError error) { // return new BallResponse<T>(Response.<T>error(error), ResponseSource.NETWORK); // error cames always from network // } // // protected BallResponse(Response<T> response) { // this(response, null, false); // } // // protected BallResponse(Response<T> response, ResponseSource responseSource) { // this(response, responseSource, false); // } // // public BallResponse(Response<T> response, ResponseSource responseSource, boolean identical) { // mResponse = response; // mResponseSource = responseSource; // mIdentical = identical; // } // // public ResponseSource getResponseSource() { // return mResponseSource; // } // // public void setResponseSource(ResponseSource responseSource) { // this.mResponseSource = responseSource; // } // // public boolean isIntermediate() { // return mResponse.intermediate; // } // // public void setIntermediate(boolean intermediate) { // mResponse.intermediate = intermediate; // } // // public T getResult() { // return mResponse.result; // } // // public Cache.Entry getCacheEntry() { // return mResponse.cacheEntry; // } // // public VolleyError getError() { // return mResponse.error; // } // // public boolean isIdentical() { // return mIdentical; // } // // public void setIdentical(boolean identical) { // mIdentical = identical; // } // } // // Path: library/src/main/java/com/siu/android/volleyball/response/ResponseListener.java // public interface ResponseListener<T> { // // public void onIntermediateResponse(T response, BallResponse.ResponseSource responseSource); // // public void onFinalResponse(T response, BallResponse.ResponseSource responseSource); // // public void onFinalResponseIdenticalToIntermediate(BallResponse.ResponseSource responseSource); // } // // Path: samples/src/main/java/com/siu/android/volleyball/samples/adapter/LogsAdapter.java // public class LogsAdapter extends BindableAdapter<Log> { // // private List<Log> mList; // // public LogsAdapter(Context context, List<Log> list) { // super(context); // mList = list; // } // // @Override // public Log getItem(int position) { // return mList.get(position); // } // // @Override // public View newView(LayoutInflater inflater, int position, ViewGroup container) { // return inflater.inflate(R.layout.log_row, null); // } // // @Override // public void bindView(Log item, int position, View view) { // TextView contentTextView = (TextView) view.findViewById(R.id.content); // contentTextView.setText(item.getContent()); // // TextView millisTextView = (TextView) view.findViewById(R.id.millis); // millisTextView.setText(String.valueOf(item.getMillis())); // } // // @Override // public int getCount() { // return mList.size(); // } // // @Override // public long getItemId(int i) { // return i; // } // }
import com.siu.android.volleyball.BallResponse; import com.siu.android.volleyball.response.ResponseListener; import com.siu.android.volleyball.samples.adapter.LogsAdapter; import java.util.List;
package com.siu.android.volleyball.samples.volley; /** * Created by lukas on 9/3/13. */ public class ScenarioListener implements ResponseListener<String> { private List<String> mList;
// Path: library/src/main/java/com/siu/android/volleyball/BallResponse.java // public class BallResponse<T> { // // public static enum ResponseSource { // LOCAL, CACHE, NETWORK // } // // protected Response<T> mResponse; // protected ResponseSource mResponseSource; // protected boolean mIdentical = false; // // /** // * Returns whether this response is considered successful. // */ // public boolean isSuccess() { // return mResponse.isSuccess(); // } // // public static <T> BallResponse<T> identical(ResponseSource responseSource) { // return new BallResponse<T>(Response.<T>success(null, null), responseSource, true); // } // // public static <T> BallResponse<T> success(T result) { // return new BallResponse<T>(Response.success(result, null)); // } // // public static <T> BallResponse<T> success(T result, Cache.Entry cacheEntry) { // return new BallResponse<T>(Response.success(result, cacheEntry)); // } // // public static <T> BallResponse<T> error(VolleyError error) { // return new BallResponse<T>(Response.<T>error(error), ResponseSource.NETWORK); // error cames always from network // } // // protected BallResponse(Response<T> response) { // this(response, null, false); // } // // protected BallResponse(Response<T> response, ResponseSource responseSource) { // this(response, responseSource, false); // } // // public BallResponse(Response<T> response, ResponseSource responseSource, boolean identical) { // mResponse = response; // mResponseSource = responseSource; // mIdentical = identical; // } // // public ResponseSource getResponseSource() { // return mResponseSource; // } // // public void setResponseSource(ResponseSource responseSource) { // this.mResponseSource = responseSource; // } // // public boolean isIntermediate() { // return mResponse.intermediate; // } // // public void setIntermediate(boolean intermediate) { // mResponse.intermediate = intermediate; // } // // public T getResult() { // return mResponse.result; // } // // public Cache.Entry getCacheEntry() { // return mResponse.cacheEntry; // } // // public VolleyError getError() { // return mResponse.error; // } // // public boolean isIdentical() { // return mIdentical; // } // // public void setIdentical(boolean identical) { // mIdentical = identical; // } // } // // Path: library/src/main/java/com/siu/android/volleyball/response/ResponseListener.java // public interface ResponseListener<T> { // // public void onIntermediateResponse(T response, BallResponse.ResponseSource responseSource); // // public void onFinalResponse(T response, BallResponse.ResponseSource responseSource); // // public void onFinalResponseIdenticalToIntermediate(BallResponse.ResponseSource responseSource); // } // // Path: samples/src/main/java/com/siu/android/volleyball/samples/adapter/LogsAdapter.java // public class LogsAdapter extends BindableAdapter<Log> { // // private List<Log> mList; // // public LogsAdapter(Context context, List<Log> list) { // super(context); // mList = list; // } // // @Override // public Log getItem(int position) { // return mList.get(position); // } // // @Override // public View newView(LayoutInflater inflater, int position, ViewGroup container) { // return inflater.inflate(R.layout.log_row, null); // } // // @Override // public void bindView(Log item, int position, View view) { // TextView contentTextView = (TextView) view.findViewById(R.id.content); // contentTextView.setText(item.getContent()); // // TextView millisTextView = (TextView) view.findViewById(R.id.millis); // millisTextView.setText(String.valueOf(item.getMillis())); // } // // @Override // public int getCount() { // return mList.size(); // } // // @Override // public long getItemId(int i) { // return i; // } // } // Path: samples/src/main/java/com/siu/android/volleyball/samples/volley/ScenarioListener.java import com.siu.android.volleyball.BallResponse; import com.siu.android.volleyball.response.ResponseListener; import com.siu.android.volleyball.samples.adapter.LogsAdapter; import java.util.List; package com.siu.android.volleyball.samples.volley; /** * Created by lukas on 9/3/13. */ public class ScenarioListener implements ResponseListener<String> { private List<String> mList;
private LogsAdapter mAdapter;
lukaspili/Volley-Ball
samples/src/main/java/com/siu/android/volleyball/samples/volley/ScenarioListener.java
// Path: library/src/main/java/com/siu/android/volleyball/BallResponse.java // public class BallResponse<T> { // // public static enum ResponseSource { // LOCAL, CACHE, NETWORK // } // // protected Response<T> mResponse; // protected ResponseSource mResponseSource; // protected boolean mIdentical = false; // // /** // * Returns whether this response is considered successful. // */ // public boolean isSuccess() { // return mResponse.isSuccess(); // } // // public static <T> BallResponse<T> identical(ResponseSource responseSource) { // return new BallResponse<T>(Response.<T>success(null, null), responseSource, true); // } // // public static <T> BallResponse<T> success(T result) { // return new BallResponse<T>(Response.success(result, null)); // } // // public static <T> BallResponse<T> success(T result, Cache.Entry cacheEntry) { // return new BallResponse<T>(Response.success(result, cacheEntry)); // } // // public static <T> BallResponse<T> error(VolleyError error) { // return new BallResponse<T>(Response.<T>error(error), ResponseSource.NETWORK); // error cames always from network // } // // protected BallResponse(Response<T> response) { // this(response, null, false); // } // // protected BallResponse(Response<T> response, ResponseSource responseSource) { // this(response, responseSource, false); // } // // public BallResponse(Response<T> response, ResponseSource responseSource, boolean identical) { // mResponse = response; // mResponseSource = responseSource; // mIdentical = identical; // } // // public ResponseSource getResponseSource() { // return mResponseSource; // } // // public void setResponseSource(ResponseSource responseSource) { // this.mResponseSource = responseSource; // } // // public boolean isIntermediate() { // return mResponse.intermediate; // } // // public void setIntermediate(boolean intermediate) { // mResponse.intermediate = intermediate; // } // // public T getResult() { // return mResponse.result; // } // // public Cache.Entry getCacheEntry() { // return mResponse.cacheEntry; // } // // public VolleyError getError() { // return mResponse.error; // } // // public boolean isIdentical() { // return mIdentical; // } // // public void setIdentical(boolean identical) { // mIdentical = identical; // } // } // // Path: library/src/main/java/com/siu/android/volleyball/response/ResponseListener.java // public interface ResponseListener<T> { // // public void onIntermediateResponse(T response, BallResponse.ResponseSource responseSource); // // public void onFinalResponse(T response, BallResponse.ResponseSource responseSource); // // public void onFinalResponseIdenticalToIntermediate(BallResponse.ResponseSource responseSource); // } // // Path: samples/src/main/java/com/siu/android/volleyball/samples/adapter/LogsAdapter.java // public class LogsAdapter extends BindableAdapter<Log> { // // private List<Log> mList; // // public LogsAdapter(Context context, List<Log> list) { // super(context); // mList = list; // } // // @Override // public Log getItem(int position) { // return mList.get(position); // } // // @Override // public View newView(LayoutInflater inflater, int position, ViewGroup container) { // return inflater.inflate(R.layout.log_row, null); // } // // @Override // public void bindView(Log item, int position, View view) { // TextView contentTextView = (TextView) view.findViewById(R.id.content); // contentTextView.setText(item.getContent()); // // TextView millisTextView = (TextView) view.findViewById(R.id.millis); // millisTextView.setText(String.valueOf(item.getMillis())); // } // // @Override // public int getCount() { // return mList.size(); // } // // @Override // public long getItemId(int i) { // return i; // } // }
import com.siu.android.volleyball.BallResponse; import com.siu.android.volleyball.response.ResponseListener; import com.siu.android.volleyball.samples.adapter.LogsAdapter; import java.util.List;
package com.siu.android.volleyball.samples.volley; /** * Created by lukas on 9/3/13. */ public class ScenarioListener implements ResponseListener<String> { private List<String> mList; private LogsAdapter mAdapter; public ScenarioListener(List<String> list, LogsAdapter adapter) { mList = list; mAdapter = adapter; } @Override
// Path: library/src/main/java/com/siu/android/volleyball/BallResponse.java // public class BallResponse<T> { // // public static enum ResponseSource { // LOCAL, CACHE, NETWORK // } // // protected Response<T> mResponse; // protected ResponseSource mResponseSource; // protected boolean mIdentical = false; // // /** // * Returns whether this response is considered successful. // */ // public boolean isSuccess() { // return mResponse.isSuccess(); // } // // public static <T> BallResponse<T> identical(ResponseSource responseSource) { // return new BallResponse<T>(Response.<T>success(null, null), responseSource, true); // } // // public static <T> BallResponse<T> success(T result) { // return new BallResponse<T>(Response.success(result, null)); // } // // public static <T> BallResponse<T> success(T result, Cache.Entry cacheEntry) { // return new BallResponse<T>(Response.success(result, cacheEntry)); // } // // public static <T> BallResponse<T> error(VolleyError error) { // return new BallResponse<T>(Response.<T>error(error), ResponseSource.NETWORK); // error cames always from network // } // // protected BallResponse(Response<T> response) { // this(response, null, false); // } // // protected BallResponse(Response<T> response, ResponseSource responseSource) { // this(response, responseSource, false); // } // // public BallResponse(Response<T> response, ResponseSource responseSource, boolean identical) { // mResponse = response; // mResponseSource = responseSource; // mIdentical = identical; // } // // public ResponseSource getResponseSource() { // return mResponseSource; // } // // public void setResponseSource(ResponseSource responseSource) { // this.mResponseSource = responseSource; // } // // public boolean isIntermediate() { // return mResponse.intermediate; // } // // public void setIntermediate(boolean intermediate) { // mResponse.intermediate = intermediate; // } // // public T getResult() { // return mResponse.result; // } // // public Cache.Entry getCacheEntry() { // return mResponse.cacheEntry; // } // // public VolleyError getError() { // return mResponse.error; // } // // public boolean isIdentical() { // return mIdentical; // } // // public void setIdentical(boolean identical) { // mIdentical = identical; // } // } // // Path: library/src/main/java/com/siu/android/volleyball/response/ResponseListener.java // public interface ResponseListener<T> { // // public void onIntermediateResponse(T response, BallResponse.ResponseSource responseSource); // // public void onFinalResponse(T response, BallResponse.ResponseSource responseSource); // // public void onFinalResponseIdenticalToIntermediate(BallResponse.ResponseSource responseSource); // } // // Path: samples/src/main/java/com/siu/android/volleyball/samples/adapter/LogsAdapter.java // public class LogsAdapter extends BindableAdapter<Log> { // // private List<Log> mList; // // public LogsAdapter(Context context, List<Log> list) { // super(context); // mList = list; // } // // @Override // public Log getItem(int position) { // return mList.get(position); // } // // @Override // public View newView(LayoutInflater inflater, int position, ViewGroup container) { // return inflater.inflate(R.layout.log_row, null); // } // // @Override // public void bindView(Log item, int position, View view) { // TextView contentTextView = (TextView) view.findViewById(R.id.content); // contentTextView.setText(item.getContent()); // // TextView millisTextView = (TextView) view.findViewById(R.id.millis); // millisTextView.setText(String.valueOf(item.getMillis())); // } // // @Override // public int getCount() { // return mList.size(); // } // // @Override // public long getItemId(int i) { // return i; // } // } // Path: samples/src/main/java/com/siu/android/volleyball/samples/volley/ScenarioListener.java import com.siu.android.volleyball.BallResponse; import com.siu.android.volleyball.response.ResponseListener; import com.siu.android.volleyball.samples.adapter.LogsAdapter; import java.util.List; package com.siu.android.volleyball.samples.volley; /** * Created by lukas on 9/3/13. */ public class ScenarioListener implements ResponseListener<String> { private List<String> mList; private LogsAdapter mAdapter; public ScenarioListener(List<String> list, LogsAdapter adapter) { mList = list; mAdapter = adapter; } @Override
public void onIntermediateResponse(String response, BallResponse.ResponseSource responseSource) {
lukaspili/Volley-Ball
library/src/main/java/com/siu/android/volleyball/response/SingleResponseListener.java
// Path: library/src/main/java/com/siu/android/volleyball/BallResponse.java // public class BallResponse<T> { // // public static enum ResponseSource { // LOCAL, CACHE, NETWORK // } // // protected Response<T> mResponse; // protected ResponseSource mResponseSource; // protected boolean mIdentical = false; // // /** // * Returns whether this response is considered successful. // */ // public boolean isSuccess() { // return mResponse.isSuccess(); // } // // public static <T> BallResponse<T> identical(ResponseSource responseSource) { // return new BallResponse<T>(Response.<T>success(null, null), responseSource, true); // } // // public static <T> BallResponse<T> success(T result) { // return new BallResponse<T>(Response.success(result, null)); // } // // public static <T> BallResponse<T> success(T result, Cache.Entry cacheEntry) { // return new BallResponse<T>(Response.success(result, cacheEntry)); // } // // public static <T> BallResponse<T> error(VolleyError error) { // return new BallResponse<T>(Response.<T>error(error), ResponseSource.NETWORK); // error cames always from network // } // // protected BallResponse(Response<T> response) { // this(response, null, false); // } // // protected BallResponse(Response<T> response, ResponseSource responseSource) { // this(response, responseSource, false); // } // // public BallResponse(Response<T> response, ResponseSource responseSource, boolean identical) { // mResponse = response; // mResponseSource = responseSource; // mIdentical = identical; // } // // public ResponseSource getResponseSource() { // return mResponseSource; // } // // public void setResponseSource(ResponseSource responseSource) { // this.mResponseSource = responseSource; // } // // public boolean isIntermediate() { // return mResponse.intermediate; // } // // public void setIntermediate(boolean intermediate) { // mResponse.intermediate = intermediate; // } // // public T getResult() { // return mResponse.result; // } // // public Cache.Entry getCacheEntry() { // return mResponse.cacheEntry; // } // // public VolleyError getError() { // return mResponse.error; // } // // public boolean isIdentical() { // return mIdentical; // } // // public void setIdentical(boolean identical) { // mIdentical = identical; // } // } // // Path: library/src/main/java/com/siu/android/volleyball/exception/BallException.java // public class BallException extends RuntimeException { // // public BallException() { // } // // public BallException(String detailMessage) { // super(detailMessage); // } // // public BallException(String detailMessage, Object... args) { // super(String.format(detailMessage, args)); // } // // // // public BallException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public BallException(Throwable throwable) { // super(throwable); // } // }
import com.siu.android.volleyball.BallResponse; import com.siu.android.volleyball.exception.BallException;
package com.siu.android.volleyball.response; /** * Created by lukas on 8/31/13. */ public abstract class SingleResponseListener<T> implements ResponseListener<T> { /** * Can happen when the response is soft cached * * @param response * @param responseSource */ @Override
// Path: library/src/main/java/com/siu/android/volleyball/BallResponse.java // public class BallResponse<T> { // // public static enum ResponseSource { // LOCAL, CACHE, NETWORK // } // // protected Response<T> mResponse; // protected ResponseSource mResponseSource; // protected boolean mIdentical = false; // // /** // * Returns whether this response is considered successful. // */ // public boolean isSuccess() { // return mResponse.isSuccess(); // } // // public static <T> BallResponse<T> identical(ResponseSource responseSource) { // return new BallResponse<T>(Response.<T>success(null, null), responseSource, true); // } // // public static <T> BallResponse<T> success(T result) { // return new BallResponse<T>(Response.success(result, null)); // } // // public static <T> BallResponse<T> success(T result, Cache.Entry cacheEntry) { // return new BallResponse<T>(Response.success(result, cacheEntry)); // } // // public static <T> BallResponse<T> error(VolleyError error) { // return new BallResponse<T>(Response.<T>error(error), ResponseSource.NETWORK); // error cames always from network // } // // protected BallResponse(Response<T> response) { // this(response, null, false); // } // // protected BallResponse(Response<T> response, ResponseSource responseSource) { // this(response, responseSource, false); // } // // public BallResponse(Response<T> response, ResponseSource responseSource, boolean identical) { // mResponse = response; // mResponseSource = responseSource; // mIdentical = identical; // } // // public ResponseSource getResponseSource() { // return mResponseSource; // } // // public void setResponseSource(ResponseSource responseSource) { // this.mResponseSource = responseSource; // } // // public boolean isIntermediate() { // return mResponse.intermediate; // } // // public void setIntermediate(boolean intermediate) { // mResponse.intermediate = intermediate; // } // // public T getResult() { // return mResponse.result; // } // // public Cache.Entry getCacheEntry() { // return mResponse.cacheEntry; // } // // public VolleyError getError() { // return mResponse.error; // } // // public boolean isIdentical() { // return mIdentical; // } // // public void setIdentical(boolean identical) { // mIdentical = identical; // } // } // // Path: library/src/main/java/com/siu/android/volleyball/exception/BallException.java // public class BallException extends RuntimeException { // // public BallException() { // } // // public BallException(String detailMessage) { // super(detailMessage); // } // // public BallException(String detailMessage, Object... args) { // super(String.format(detailMessage, args)); // } // // // // public BallException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public BallException(Throwable throwable) { // super(throwable); // } // } // Path: library/src/main/java/com/siu/android/volleyball/response/SingleResponseListener.java import com.siu.android.volleyball.BallResponse; import com.siu.android.volleyball.exception.BallException; package com.siu.android.volleyball.response; /** * Created by lukas on 8/31/13. */ public abstract class SingleResponseListener<T> implements ResponseListener<T> { /** * Can happen when the response is soft cached * * @param response * @param responseSource */ @Override
public final void onIntermediateResponse(T response, BallResponse.ResponseSource responseSource) {
lukaspili/Volley-Ball
library/src/main/java/com/android/volley/CompatRequest.java
// Path: library/src/main/java/com/siu/android/volleyball/BallResponse.java // public class BallResponse<T> { // // public static enum ResponseSource { // LOCAL, CACHE, NETWORK // } // // protected Response<T> mResponse; // protected ResponseSource mResponseSource; // protected boolean mIdentical = false; // // /** // * Returns whether this response is considered successful. // */ // public boolean isSuccess() { // return mResponse.isSuccess(); // } // // public static <T> BallResponse<T> identical(ResponseSource responseSource) { // return new BallResponse<T>(Response.<T>success(null, null), responseSource, true); // } // // public static <T> BallResponse<T> success(T result) { // return new BallResponse<T>(Response.success(result, null)); // } // // public static <T> BallResponse<T> success(T result, Cache.Entry cacheEntry) { // return new BallResponse<T>(Response.success(result, cacheEntry)); // } // // public static <T> BallResponse<T> error(VolleyError error) { // return new BallResponse<T>(Response.<T>error(error), ResponseSource.NETWORK); // error cames always from network // } // // protected BallResponse(Response<T> response) { // this(response, null, false); // } // // protected BallResponse(Response<T> response, ResponseSource responseSource) { // this(response, responseSource, false); // } // // public BallResponse(Response<T> response, ResponseSource responseSource, boolean identical) { // mResponse = response; // mResponseSource = responseSource; // mIdentical = identical; // } // // public ResponseSource getResponseSource() { // return mResponseSource; // } // // public void setResponseSource(ResponseSource responseSource) { // this.mResponseSource = responseSource; // } // // public boolean isIntermediate() { // return mResponse.intermediate; // } // // public void setIntermediate(boolean intermediate) { // mResponse.intermediate = intermediate; // } // // public T getResult() { // return mResponse.result; // } // // public Cache.Entry getCacheEntry() { // return mResponse.cacheEntry; // } // // public VolleyError getError() { // return mResponse.error; // } // // public boolean isIdentical() { // return mIdentical; // } // // public void setIdentical(boolean identical) { // mIdentical = identical; // } // } // // Path: library/src/main/java/com/siu/android/volleyball/request/NetworkRequest.java // public abstract class NetworkRequest<T> extends BallRequest<T> { // // protected NetworkRequest(int method, String url, Response.ErrorListener errorListener) { // super(method, url, errorListener); // } // // public NetworkRequest(int method, String url, SingleResponseListener<T> responseListener, Response.ErrorListener errorListener) { // super(method, url, responseListener, errorListener); // } // // @Override // public boolean shouldProcessNetwork() { // return true; // } // // @Override // protected NetworkRequestProcessor createNetworkRequestProcessor() { // return new NetworkRequestProcessor() { // @Override // public BallResponse<T> parseNetworkResponse(NetworkResponse networkResponse) { // return parseBallNetworkResponse(networkResponse); // } // }; // } // // protected abstract BallResponse<T> parseBallNetworkResponse(NetworkResponse response); // }
import com.siu.android.volleyball.BallResponse; import com.siu.android.volleyball.request.NetworkRequest;
package com.android.volley; /** * Not finished */ public class CompatRequest<T> extends NetworkRequest<T> { private Request<T> mRequest; public CompatRequest(Request request) { super(request.getMethod(), request.getUrl(), null); } @Override
// Path: library/src/main/java/com/siu/android/volleyball/BallResponse.java // public class BallResponse<T> { // // public static enum ResponseSource { // LOCAL, CACHE, NETWORK // } // // protected Response<T> mResponse; // protected ResponseSource mResponseSource; // protected boolean mIdentical = false; // // /** // * Returns whether this response is considered successful. // */ // public boolean isSuccess() { // return mResponse.isSuccess(); // } // // public static <T> BallResponse<T> identical(ResponseSource responseSource) { // return new BallResponse<T>(Response.<T>success(null, null), responseSource, true); // } // // public static <T> BallResponse<T> success(T result) { // return new BallResponse<T>(Response.success(result, null)); // } // // public static <T> BallResponse<T> success(T result, Cache.Entry cacheEntry) { // return new BallResponse<T>(Response.success(result, cacheEntry)); // } // // public static <T> BallResponse<T> error(VolleyError error) { // return new BallResponse<T>(Response.<T>error(error), ResponseSource.NETWORK); // error cames always from network // } // // protected BallResponse(Response<T> response) { // this(response, null, false); // } // // protected BallResponse(Response<T> response, ResponseSource responseSource) { // this(response, responseSource, false); // } // // public BallResponse(Response<T> response, ResponseSource responseSource, boolean identical) { // mResponse = response; // mResponseSource = responseSource; // mIdentical = identical; // } // // public ResponseSource getResponseSource() { // return mResponseSource; // } // // public void setResponseSource(ResponseSource responseSource) { // this.mResponseSource = responseSource; // } // // public boolean isIntermediate() { // return mResponse.intermediate; // } // // public void setIntermediate(boolean intermediate) { // mResponse.intermediate = intermediate; // } // // public T getResult() { // return mResponse.result; // } // // public Cache.Entry getCacheEntry() { // return mResponse.cacheEntry; // } // // public VolleyError getError() { // return mResponse.error; // } // // public boolean isIdentical() { // return mIdentical; // } // // public void setIdentical(boolean identical) { // mIdentical = identical; // } // } // // Path: library/src/main/java/com/siu/android/volleyball/request/NetworkRequest.java // public abstract class NetworkRequest<T> extends BallRequest<T> { // // protected NetworkRequest(int method, String url, Response.ErrorListener errorListener) { // super(method, url, errorListener); // } // // public NetworkRequest(int method, String url, SingleResponseListener<T> responseListener, Response.ErrorListener errorListener) { // super(method, url, responseListener, errorListener); // } // // @Override // public boolean shouldProcessNetwork() { // return true; // } // // @Override // protected NetworkRequestProcessor createNetworkRequestProcessor() { // return new NetworkRequestProcessor() { // @Override // public BallResponse<T> parseNetworkResponse(NetworkResponse networkResponse) { // return parseBallNetworkResponse(networkResponse); // } // }; // } // // protected abstract BallResponse<T> parseBallNetworkResponse(NetworkResponse response); // } // Path: library/src/main/java/com/android/volley/CompatRequest.java import com.siu.android.volleyball.BallResponse; import com.siu.android.volleyball.request.NetworkRequest; package com.android.volley; /** * Not finished */ public class CompatRequest<T> extends NetworkRequest<T> { private Request<T> mRequest; public CompatRequest(Request request) { super(request.getMethod(), request.getUrl(), null); } @Override
protected BallResponse<T> parseBallNetworkResponse(NetworkResponse networkResponse) {