method2testcases stringlengths 118 3.08k |
|---|
### Question:
SchemaUtils { public static String getGcsFileAsString(String filePath) { MatchResult result; try { result = FileSystems.match(filePath); checkArgument( result.status() == MatchResult.Status.OK && !result.metadata().isEmpty(), "Failed to match any files with the pattern: " + filePath); List<ResourceId> rId = result.metadata().stream() .map(MatchResult.Metadata::resourceId) .collect(Collectors.toList()); checkArgument(rId.size() == 1, "Expected exactly 1 file, but got " + rId.size() + " files."); Reader reader = Channels.newReader(FileSystems.open(rId.get(0)), StandardCharsets.UTF_8.name()); return CharStreams.toString(reader); } catch (IOException ioe) { LOG.error("File system i/o error: " + ioe.getMessage()); throw new RuntimeException(ioe); } } static String getGcsFileAsString(String filePath); static Schema getAvroSchema(String schemaLocation); static final String DEADLETTER_SCHEMA; }### Answer:
@Test public void testGetGcsFileAsString() { String expectedContent = "{\n" + " \"type\" : \"record\",\n" + " \"name\" : \"test_file\",\n" + " \"namespace\" : \"com.test\",\n" + " \"fields\" : [\n" + " {\n" + " \"name\": \"id\",\n" + " \"type\": \"string\"\n" + " },\n" + " {\n" + " \"name\": \"price\",\n" + " \"type\": \"double\"\n" + " }\n" + " ]\n" + "}\n"; String actualContent = SchemaUtils.getGcsFileAsString(AVRO_SCHEMA_FILE_PATH); assertEquals(expectedContent, actualContent); } |
### Question:
SchemaUtils { public static Schema getAvroSchema(String schemaLocation) { String schemaFile = getGcsFileAsString(schemaLocation); return new Schema.Parser().parse(schemaFile); } static String getGcsFileAsString(String filePath); static Schema getAvroSchema(String schemaLocation); static final String DEADLETTER_SCHEMA; }### Answer:
@Test public void testGetAvroSchema() { String avroSchema = "{\n" + " \"type\" : \"record\",\n" + " \"name\" : \"test_file\",\n" + " \"namespace\" : \"com.test\",\n" + " \"fields\" : [\n" + " {\n" + " \"name\": \"id\",\n" + " \"type\": \"string\"\n" + " },\n" + " {\n" + " \"name\": \"price\",\n" + " \"type\": \"double\"\n" + " }\n" + " ]\n" + "}"; Schema expectedSchema = new Schema.Parser().parse(avroSchema); Schema actualSchema = SchemaUtils.getAvroSchema(AVRO_SCHEMA_FILE_PATH); assertEquals(expectedSchema, actualSchema); } |
### Question:
FailsafeElement { @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } final FailsafeElement other = (FailsafeElement) obj; return Objects.deepEquals(this.originalPayload, other.getOriginalPayload()) && Objects.deepEquals(this.payload, other.getPayload()) && Objects.deepEquals(this.errorMessage, other.getErrorMessage()) && Objects.deepEquals(this.stacktrace, other.getStacktrace()); } private FailsafeElement(OriginalT originalPayload, CurrentT payload); static FailsafeElement<OriginalT, CurrentT> of(
OriginalT originalPayload, CurrentT currentPayload); static FailsafeElement<OriginalT, CurrentT> of(
FailsafeElement<OriginalT, CurrentT> other); OriginalT getOriginalPayload(); CurrentT getPayload(); String getErrorMessage(); FailsafeElement<OriginalT, CurrentT> setErrorMessage(String errorMessage); String getStacktrace(); FailsafeElement<OriginalT, CurrentT> setStacktrace(String stacktrace); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testEquals() { FailsafeElement<String, Integer> element = FailsafeElement.of("answer", 42) .setErrorMessage("failed!") .setStacktrace("com.google..."); assertThat( element, is( equalTo( FailsafeElement.of("answer", 42) .setErrorMessage("failed!") .setStacktrace("com.google...")))); assertThat( element, is( not( equalTo( FailsafeElement.of("answer", 1) .setErrorMessage("failed!") .setStacktrace("com.google..."))))); assertThat(element, is(equalTo(FailsafeElement.of(element)))); } |
### Question:
BigQueryStatementIssuingFn extends DoFn<KV<String, BigQueryAction>, Void> { static String makeJobId(String jobIdPrefix, String statement) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ssz") .withZone(ZoneId.of("UTC")); String randomId = UUID.randomUUID().toString(); return String.format("%s_%d_%s_%s", jobIdPrefix, Math.abs(statement.hashCode()), formatter.format(Instant.now()), randomId); } BigQueryStatementIssuingFn(String jobIdPrefix); @Setup void setUp(); @ProcessElement void process(ProcessContext c); }### Answer:
@Test void testMakeJobId() { String jobId = BigQueryStatementIssuingFn.makeJobId( "my_prefix", "SELECT my, bq, statement FROM pipeline"); assertThat(jobId, matchesPattern("my_prefix_[0-9]+_2[0-9_]+UTC_[0-9a-f-]+")); } |
### Question:
BigQuerySchemaUtils { public static Schema beamSchemaToBigQueryClientSchema( org.apache.beam.sdk.schemas.Schema tableSchema) { ArrayList<Field> bqFields = new ArrayList<>(tableSchema.getFieldCount()); for (org.apache.beam.sdk.schemas.Schema.Field f : tableSchema.getFields()) { bqFields.add(beamFieldToBigQueryClientField(f)); } return Schema.of(bqFields); } static Schema beamSchemaToBigQueryClientSchema(
org.apache.beam.sdk.schemas.Schema tableSchema); }### Answer:
@Test public void testComplexSchemaToBQSchema() { assertThat(BigQuerySchemaUtils.beamSchemaToBigQueryClientSchema(ALL_BEAM_SCHEMA), is(ALL_BQ_SCHEMA)); }
@Test public void testUnsupportedTypes() { UNSUPPORTED_TYPE_SCHEMAS.forEach(schema -> { assertThrows( IllegalArgumentException.class, () -> BigQuerySchemaUtils.beamSchemaToBigQueryClientSchema(schema), "Expected an exception with unsupported type conversion, but didn't see one"); }); } |
### Question:
ChangelogTableDynamicDestinations extends DynamicDestinations<TableRow, String> { public static String getBigQueryTableName(String sourceTable, Boolean isChangelogTable) { String[] tableNameComponents = sourceTable.split("\\."); LOG.debug("Source table: {}. After split: {}", sourceTable, tableNameComponents); if (isChangelogTable) { return String.format("%s_changelog", tableNameComponents[2]); } else { return tableNameComponents[2]; } } ChangelogTableDynamicDestinations(
String changeLogDataset,
String gcpProjectId,
PCollectionView<Map<String, KV<Schema, Schema>>> schemaMapView); static String getBigQueryTableName(String sourceTable, Boolean isChangelogTable); @Override String getDestination(ValueInSingleWindow<TableRow> rowInfo); @Override TableDestination getTable(String targetTable); @Override TableSchema getSchema(String targetTable); @Override List<PCollectionView<?>> getSideInputs(); }### Answer:
@Test void testTableNameFormatting() { String sourceTable = "mainstance.cdcForDataflow.team_metadata"; assertThat( ChangelogTableDynamicDestinations.getBigQueryTableName(sourceTable, false), equalTo("team_metadata")); assertThat( ChangelogTableDynamicDestinations.getBigQueryTableName(sourceTable, true), equalTo("team_metadata_changelog")); } |
### Question:
App { public String greet(String name) { return Util.join("Hello ", name); } static void main(String[] args); String greet(String name); }### Answer:
@Test public void testGreet() { App app = new App(); assertEquals(app.greet("world"), "Hello world"); } |
### Question:
Util { public static String join(String... elements) { return StringUtils.join(elements); } static String join(String... elements); }### Answer:
@Test public void testJoin() { assertEquals(Util.join("x", "y"), "xy"); } |
### Question:
ConfigService { public String getConfig(final String key) { return configs.getString(key); } ConfigService(); String getConfig(final String key); }### Answer:
@Test public void testGetConfig() { ConfigService cs = new ConfigService(); assertEquals(cs.getConfig("datastore"), "app"); } |
### Question:
App { public String greet(String name) { return Util.join("Hello ", name); } String greet(String name); boolean store(String name); }### Answer:
@Test public void testGreet() { App app = new App(); assertEquals(app.greet("world"), "Hello world"); } |
### Question:
App { public boolean store(String name) { ConfigService cs = new ConfigService(); cs.getConfig("datastore"); return true; } String greet(String name); boolean store(String name); }### Answer:
@Test public void testStore() { App app = new App(); assertTrue(app.store("x")); } |
### Question:
CalendarUtil { public static List<Date> getMonthDates(int year, int month) { LocalDate localDate = new LocalDate(year, month, 1); List<Date> dates = new ArrayList<>(); while (localDate.getMonthOfYear() <= month && localDate.getYear() == year) { dates.addAll(getWeekDates(localDate.getYear(), localDate.getMonthOfYear(), localDate.getDayOfMonth())); localDate = localDate.plusWeeks(1).withDayOfWeek(1); } return dates; } static Date getDate(LocalDate localDate, int type); static List<List<Date>> getMonthOfWeekDates(int year, int month); static List<Date> getMonthDates(int year, int month); static List<Date> getWeekDates(int year, int month, int day); static int getDayForWeek(int y, int m, int d); static int[] positionToDate(int position, int startY, int startM); static int getMonthPosition(int year1, int month1, int year2, int month2); static int getWeekPosition(int startYear, int startMonth, int startDay, int year, int month, int day); static List<Date> getWeekDaysForPosition(int startYear, int startMonth, int startDay, int positionWeek); static LocalDate getCurrentDate(); static int getMaxDayByYearMonth(int year,int month); }### Answer:
@Test public void getMonthDates() throws Exception { List<Date> dates = CalendarUtil.getMonthDates(2018, 7); assertEquals(42, dates.size()); } |
### Question:
CalendarUtil { public static int getWeekPosition(int startYear, int startMonth, int startDay, int year, int month, int day) { LocalDate start = new LocalDate(startYear, startMonth, startDay).withDayOfWeek(1); LocalDate end = new LocalDate(year, month, day).withDayOfWeek(1); return Weeks.weeksBetween(start, end).getWeeks(); } static Date getDate(LocalDate localDate, int type); static List<List<Date>> getMonthOfWeekDates(int year, int month); static List<Date> getMonthDates(int year, int month); static List<Date> getWeekDates(int year, int month, int day); static int getDayForWeek(int y, int m, int d); static int[] positionToDate(int position, int startY, int startM); static int getMonthPosition(int year1, int month1, int year2, int month2); static int getWeekPosition(int startYear, int startMonth, int startDay, int year, int month, int day); static List<Date> getWeekDaysForPosition(int startYear, int startMonth, int startDay, int positionWeek); static LocalDate getCurrentDate(); static int getMaxDayByYearMonth(int year,int month); }### Answer:
@Test public void getWeekPosition() throws Exception { int weekPosition = CalendarUtil.getWeekPosition(2017, 7, 14, 2017, 8, 16); assertEquals(5, weekPosition); weekPosition = CalendarUtil.getWeekPosition(1980, 1, 1, 2018, 2, 25); assertEquals(1990, weekPosition); } |
### Question:
CalendarUtil { public static List<Date> getWeekDaysForPosition(int startYear, int startMonth, int startDay, int positionWeek) { ArrayList<Date> dates = new ArrayList<>(); LocalDate localDate = new LocalDate(startYear, startMonth, startDay).plusWeeks(positionWeek); for (int i = 1; i <= 7; i++) { dates.add(getDate(localDate.withDayOfWeek(i), Date.TYPE_THIS_MONTH)); } return dates; } static Date getDate(LocalDate localDate, int type); static List<List<Date>> getMonthOfWeekDates(int year, int month); static List<Date> getMonthDates(int year, int month); static List<Date> getWeekDates(int year, int month, int day); static int getDayForWeek(int y, int m, int d); static int[] positionToDate(int position, int startY, int startM); static int getMonthPosition(int year1, int month1, int year2, int month2); static int getWeekPosition(int startYear, int startMonth, int startDay, int year, int month, int day); static List<Date> getWeekDaysForPosition(int startYear, int startMonth, int startDay, int positionWeek); static LocalDate getCurrentDate(); static int getMaxDayByYearMonth(int year,int month); }### Answer:
@Test public void getWeekDaysForPosition() throws Exception { int weekPosition = CalendarUtil.getWeekPosition(1980, 1, 1, 2018, 2, 25); List<Date> dates = CalendarUtil.getWeekDaysForPosition(1980, 1, 1, weekPosition); assertEquals(dates.get(6).toString(), "2018-02-25"); } |
### Question:
CalendarUtil { public static List<List<Date>> getMonthOfWeekDates(int year, int month) { LocalDate localDate = new LocalDate(year, month, 1); List<List<Date>> weeks = new ArrayList<>(); while (localDate.getMonthOfYear() <= month && localDate.getYear() == year) { weeks.add(getWeekDates(localDate.getYear(), localDate.getMonthOfYear(), localDate.getDayOfMonth())); localDate = localDate.plusWeeks(1).withDayOfWeek(1); } return weeks; } static Date getDate(LocalDate localDate, int type); static List<List<Date>> getMonthOfWeekDates(int year, int month); static List<Date> getMonthDates(int year, int month); static List<Date> getWeekDates(int year, int month, int day); static int getDayForWeek(int y, int m, int d); static int[] positionToDate(int position, int startY, int startM); static int getMonthPosition(int year1, int month1, int year2, int month2); static int getWeekPosition(int startYear, int startMonth, int startDay, int year, int month, int day); static List<Date> getWeekDaysForPosition(int startYear, int startMonth, int startDay, int positionWeek); static LocalDate getCurrentDate(); static int getMaxDayByYearMonth(int year,int month); }### Answer:
@Test public void getMonthOfWeekDate() throws Exception { List<List<Date>> lists = CalendarUtil.getMonthOfWeekDates(2018, 2); assertEquals(5, lists.size()); List<List<Date>> lists2 = CalendarUtil.getMonthOfWeekDates(2017, 12); assertEquals(5, lists2.size()); List<List<Date>> lists3 = CalendarUtil.getMonthOfWeekDates(2018, 1); assertEquals(5, lists3.size()); } |
### Question:
SchemaBuilder { public static Schema renameFields(Schema original, Map<String,String> renames) { List<Field> fields = new ArrayList<>(); for (Field f : original) { if (renames.containsKey(f.name())) { f = new Field(renames.get(f.name()), f.type, f.crs, f.props); } fields.add(f); } return new Schema(original.name(), fields); } SchemaBuilder(String name); SchemaBuilder uri(String uri); SchemaBuilder crs(CoordinateReferenceSystem crs); SchemaBuilder crs(String srs); SchemaBuilder field(String name, Class<?> type); SchemaBuilder field(String name, Class<? extends Geometry> type, String crs); SchemaBuilder field(String name, Class<? extends Geometry> type, CoordinateReferenceSystem crs); SchemaBuilder field(Field fld); SchemaBuilder fields(Iterable<Field> flds); SchemaBuilder fields(String spec); SchemaBuilder fields(Feature f); SchemaBuilder property(String key, Object value); Schema schema(); static Schema select(Schema original, Iterable<String> fields); static Schema crs(Schema original, CoordinateReferenceSystem crs); static Schema rename(Schema original, String name); static Schema renameFields(Schema original, Map<String,String> renames); }### Answer:
@Test public void testRenameFields() { Schema schema = new SchemaBuilder("widgets") .fields("sp:String,ip:Integer,pp:Point:srid=4326").schema(); Map<String,String> renames = new HashMap<>(); renames.put("sp", "ps"); renames.put("ip", "pi"); schema = SchemaBuilder.renameFields(schema, renames); assertNotNull(schema.field("ps")); assertNotNull(schema.field("pi")); assertNotNull(schema.field("pp")); assertNull(schema.field("sp")); assertNull(schema.field("ip")); } |
### Question:
GeoJSONWriter extends JSONEncoder { public GeoJSONWriter point(Point p) throws IOException { if (p == null) { return (GeoJSONWriter) nul(); } object() .key("type").value("Point") .key("coordinates").array() .value(p.getX()) .value(p.getY()); if (!Double.isNaN(p.getCoordinate().z)) { value(p.getCoordinate().z); } endArray().endObject(); return this; } GeoJSONWriter(Writer out); GeoJSONWriter(Writer out, int indentSize); static String toString(Geometry g); static String toString(Feature f); static String toString(Cursor<Feature> features); GeoJSONWriter bbox(Envelope b); GeoJSONWriter crs(CoordinateReferenceSystem crs); GeoJSONWriter geometry(Geometry g); GeoJSONWriter point(Point p); GeoJSONWriter lineString(LineString l); GeoJSONWriter polygon(Polygon p); GeoJSONWriter multiPoint(MultiPoint mp); GeoJSONWriter multiLineString(MultiLineString ml); GeoJSONWriter multiPolygon(MultiPolygon mp); GeoJSONWriter geometryCollection(GeometryCollection gc); GeoJSONWriter feature(Feature f); GeoJSONWriter featureCollection(Cursor<Feature> features); GeoJSONWriter featureCollection(); GeoJSONWriter endFeatureCollection(); @Override GeoJSONWriter object(); @Override GeoJSONWriter array(); @Override GeoJSONWriter key(String key); @Override GeoJSONWriter value(Number value); @Override GeoJSONWriter value(double value); @Override GeoJSONWriter value(long value); @Override GeoJSONWriter value(Object value); @Override GeoJSONWriter nul(); @Override GeoJSONWriter value(String value); @Override GeoJSONWriter endObject(); @Override GeoJSONWriter endArray(); @Override GeoJSONWriter flush(); }### Answer:
@Test public void testSingleObject() throws IOException { w.point(Geom.point(1, 2)); JSONObject obj = (JSONObject) JSONValue.parse(string()); assertEquals("Point", obj.get("type")); } |
### Question:
GeoJSONWriter extends JSONEncoder { @Override public GeoJSONWriter array() throws IOException { return (GeoJSONWriter) super.array(); } GeoJSONWriter(Writer out); GeoJSONWriter(Writer out, int indentSize); static String toString(Geometry g); static String toString(Feature f); static String toString(Cursor<Feature> features); GeoJSONWriter bbox(Envelope b); GeoJSONWriter crs(CoordinateReferenceSystem crs); GeoJSONWriter geometry(Geometry g); GeoJSONWriter point(Point p); GeoJSONWriter lineString(LineString l); GeoJSONWriter polygon(Polygon p); GeoJSONWriter multiPoint(MultiPoint mp); GeoJSONWriter multiLineString(MultiLineString ml); GeoJSONWriter multiPolygon(MultiPolygon mp); GeoJSONWriter geometryCollection(GeometryCollection gc); GeoJSONWriter feature(Feature f); GeoJSONWriter featureCollection(Cursor<Feature> features); GeoJSONWriter featureCollection(); GeoJSONWriter endFeatureCollection(); @Override GeoJSONWriter object(); @Override GeoJSONWriter array(); @Override GeoJSONWriter key(String key); @Override GeoJSONWriter value(Number value); @Override GeoJSONWriter value(double value); @Override GeoJSONWriter value(long value); @Override GeoJSONWriter value(Object value); @Override GeoJSONWriter nul(); @Override GeoJSONWriter value(String value); @Override GeoJSONWriter endObject(); @Override GeoJSONWriter endArray(); @Override GeoJSONWriter flush(); }### Answer:
@Test public void testArray() throws Exception { w.object(); w.key("foo").array() .point(Geom.point(1, 2)).point(Geom.point(3, 4)) .endArray(); w.endObject(); JSONObject obj = (JSONObject) JSONValue.parse(string()); assertTrue(obj.get("foo") instanceof JSONArray); } |
### Question:
TilePyramid { public TileCover cover(Bounds e, int width, int height) { Pair<Double,Double> res = res(e, width, height); return cover(e, res.first, res.second); } static TilePyramidBuilder build(); List<TileGrid> grids(); Bounds bounds(); TilePyramid bounds(Bounds bounds); CoordinateReferenceSystem crs(); TilePyramid crs(CoordinateReferenceSystem crs); Origin origin(); TilePyramid origin(Origin origin); Integer tileWidth(); TilePyramid tileWidth(Integer tileWidth); Integer tileHeight(); TilePyramid tileHeight(Integer tileHeight); TileGrid grid(int z); Bounds bounds(Tile t); Tile realign(Tile t, Origin o); TileCover cover(Bounds e, int width, int height); TileCover cover(Bounds e, double resx, double resy); TileCover cover(Bounds e, int z); TileCover cover(Bounds e, TileGrid grid); }### Answer:
@Test public void testCover() { Bounds b = tp.bounds(); TileCover cov = tp.cover(b, 1); assertEquals(4, cov.width()); assertEquals(2, cov.height()); assertEquals(0, cov.x0()); assertEquals(0, cov.y0()); assertEquals(3, cov.x1()); assertEquals(1, cov.y1()); cov = tp.cover(Bounds.translate(b, -b.getWidth() / 2f, -b.getHeight() / 2f), 1); assertEquals(4, cov.width()); assertEquals(2, cov.height()); assertEquals(-2, cov.x0()); assertEquals(-1, cov.y0()); assertEquals(1, cov.x1()); assertEquals(0, cov.y1()); cov = tp.cover(Bounds.scale(b, 0.1), 1); assertEquals(2, cov.width()); assertEquals(2, cov.height()); assertEquals(1, cov.x0()); assertEquals(0, cov.y0()); assertEquals(2, cov.x1()); assertEquals(1, cov.y1()); } |
### Question:
Bounds extends Envelope { public static String toString(Envelope e) { return toString(e, ",", true); } Bounds(); Bounds(Envelope env); Bounds(double west, double east, double south, double north); static Bounds scale(Envelope env, double scale); static Bounds scale(Envelope env, double scale, Coordinate focus); static Bounds expand(Envelope env, double x, double y); static Bounds square(Envelope env); static List<Coordinate> corners(Envelope env); static Iterable<T> tile(final T env, double resx, double resy, final T reuse); static Bounds translate(Envelope env, double dx, double dy); static Polygon toPolygon(Envelope e); static boolean isNull(Envelope e); static String toString(Envelope e); static String toString(Envelope e, String delim, boolean alt); static Bounds parse(String str); static Bounds parse(String str, boolean alt); static Bounds parse(String str, boolean alt, String delim); static Envelope flip(Envelope e); static Envelope random(Envelope bbox, float res); static List<Envelope> randoms(Envelope bbox, float minRes, float maxRes, int n); double west(); double south(); double east(); double north(); double width(); double height(); Bounds scale(double factor); Bounds expand(double amt); Bounds expand(double x, double y); Bounds square(); Bounds shift(double dx, double dy); List<Coordinate> corners(); Iterable<Bounds> tile(double resx, double resy); Polygon polygon(); @Override Bounds intersection(Envelope env); @Override String toString(); static final Bounds WORLD_BOUNDS_4326; }### Answer:
@Test public void testToString() { Envelope e = new Envelope(1,2,3,4); assertTrue(Bounds.toString(e).matches("1\\.0+,3\\.0+,2\\.0+,4\\.0+")); assertTrue(Bounds.toString(e, " ", false).matches("1\\.0+ 2\\.0+ 3\\.0+ 4\\.0+")); } |
### Question:
MBTileSet implements TileDataset, FileData { @Override public Driver<?> driver() { return new MBTiles(); } MBTileSet(Backend backend, MBTilesOpts opts); MBTileSet(File file); String getTileFormat(); @Override File file(); @Override Driver<?> driver(); @Override Map<Key<?>, Object> driverOptions(); @Override String name(); String title(); String description(); @Override CoordinateReferenceSystem crs(); @Override Bounds bounds(); @Override TilePyramid pyramid(); @Override Tile read(long z, long x, long y); @Override Cursor<Tile> read(long z1, long z2, long x1, long x2, long y1, long y2); @Override void close(); }### Answer:
@Test public void driver() { assertEquals(MBTiles.class, tileset.driver().getClass()); } |
### Question:
Geom { public static <T extends Geometry> T narrow(GeometryCollection gc) { if (gc.getNumGeometries() == 0) { return (T) gc; } List<Geometry> objects = new ArrayList<>(gc.getNumGeometries()); for (Geometry g : iterate(gc)) { objects.add(g); } return (T) gc.getFactory().buildGeometry(objects); } static GeomBuilder build(); static Point point(double x, double y); static LineString lineString(double... ord); static Polygon polygon(double... ord); static Iterable<Point> iterate(MultiPoint mp); static Iterable<LineString> iterate(MultiLineString ml); static Iterable<Polygon> iterate(MultiPolygon mp); static Iterable<Geometry> iterate(GeometryCollection gc); static Iterable<LineString> holes(final Polygon p); static Point first(MultiPoint mp); static LineString first(MultiLineString ml); static Polygon first(MultiPolygon mp); static T[] array(GeometryCollection gc, T[] array); static T narrow(GeometryCollection gc); static List<T> flatten(GeometryCollection gc); static List<T> flatten(List<Geometry> gl); static Geometry singlify(Geometry geom); static String json(Geometry g); static PreparedGeometry prepare(Geometry g); static GeometryCollection multi(Geometry g); static void visit(Geometry g, GeometryVisitor v); static Geometry parse(String str); final static GeometryFactory factory; }### Answer:
@Test public void testNarrow() { GeometryCollection gcol = Geom.build() .point(1, 1).point() .point(2, 2).point() .point(3, 3).point() .toCollection(); assertTrue(Geom.narrow(gcol) instanceof MultiPoint); } |
### Question:
Geom { public static <T extends Geometry> List<T> flatten(GeometryCollection gc) { return flatten(Collections.singletonList((Geometry)gc)); } static GeomBuilder build(); static Point point(double x, double y); static LineString lineString(double... ord); static Polygon polygon(double... ord); static Iterable<Point> iterate(MultiPoint mp); static Iterable<LineString> iterate(MultiLineString ml); static Iterable<Polygon> iterate(MultiPolygon mp); static Iterable<Geometry> iterate(GeometryCollection gc); static Iterable<LineString> holes(final Polygon p); static Point first(MultiPoint mp); static LineString first(MultiLineString ml); static Polygon first(MultiPolygon mp); static T[] array(GeometryCollection gc, T[] array); static T narrow(GeometryCollection gc); static List<T> flatten(GeometryCollection gc); static List<T> flatten(List<Geometry> gl); static Geometry singlify(Geometry geom); static String json(Geometry g); static PreparedGeometry prepare(Geometry g); static GeometryCollection multi(Geometry g); static void visit(Geometry g, GeometryVisitor v); static Geometry parse(String str); final static GeometryFactory factory; }### Answer:
@Test public void testFlatten() { GeometryCollection gcol = Geom.build() .point(1,1).point() .point(2,3).point(4,5).multiPoint() .toCollection(); List<Point> flat = Geom.flatten(gcol); assertEquals(3, flat.size()); assertEquals(1d, flat.get(0).getX(), 0.1); assertEquals(2d, flat.get(1).getX(), 0.1); assertEquals(4d, flat.get(2).getX(), 0.1); } |
### Question:
Geom { public static Geometry parse(String str) { for (GeomParser p : PARSERS) { try { Geometry g = p.parse(str); if (g != null) { return g; } } catch(Exception e) { } } return null; } static GeomBuilder build(); static Point point(double x, double y); static LineString lineString(double... ord); static Polygon polygon(double... ord); static Iterable<Point> iterate(MultiPoint mp); static Iterable<LineString> iterate(MultiLineString ml); static Iterable<Polygon> iterate(MultiPolygon mp); static Iterable<Geometry> iterate(GeometryCollection gc); static Iterable<LineString> holes(final Polygon p); static Point first(MultiPoint mp); static LineString first(MultiLineString ml); static Polygon first(MultiPolygon mp); static T[] array(GeometryCollection gc, T[] array); static T narrow(GeometryCollection gc); static List<T> flatten(GeometryCollection gc); static List<T> flatten(List<Geometry> gl); static Geometry singlify(Geometry geom); static String json(Geometry g); static PreparedGeometry prepare(Geometry g); static GeometryCollection multi(Geometry g); static void visit(Geometry g, GeometryVisitor v); static Geometry parse(String str); final static GeometryFactory factory; }### Answer:
@Test public void testParse() { assertNotNull(Geom.parse("POINT(1 2)")); assertNotNull(Geom.parse("{\"type\": \"Point\", \"coordinates\": [1,2]}")); assertNull(Geom.parse("foo")); } |
### Question:
MBTileSet implements TileDataset, FileData { @Override public Map<Key<?>, Object> driverOptions() { return (Map) Collections.singletonMap(MBTiles.FILE, file()); } MBTileSet(Backend backend, MBTilesOpts opts); MBTileSet(File file); String getTileFormat(); @Override File file(); @Override Driver<?> driver(); @Override Map<Key<?>, Object> driverOptions(); @Override String name(); String title(); String description(); @Override CoordinateReferenceSystem crs(); @Override Bounds bounds(); @Override TilePyramid pyramid(); @Override Tile read(long z, long x, long y); @Override Cursor<Tile> read(long z1, long z2, long x1, long x2, long y1, long y2); @Override void close(); }### Answer:
@Test public void driverOptions() { Map<Key<?>, Object> options = tileset.driverOptions(); assertTrue(options.containsKey(MBTiles.FILE)); assertEquals("test.mbtiles", ((File)options.get(MBTiles.FILE)).getName()); } |
### Question:
GeomBuilder { public GeomBuilder point(double x, double y) { cstack.push(new Coordinate(x, y)); return this; } GeomBuilder(); GeomBuilder(GeometryFactory factory); GeomBuilder(int srid); GeomBuilder point(double x, double y); GeomBuilder pointz(double x, double y, double z); GeomBuilder points(double ...ord); GeomBuilder pointsz(double ...ord); GeomBuilder point(); GeomBuilder lineString(); GeomBuilder ring(); GeomBuilder polygon(); GeomBuilder multiPoint(); GeomBuilder multiLineString(); GeomBuilder multiPolygon(); GeomBuilder collection(); GeomBuilder buffer(double amt); Geometry get(); Point toPoint(); LineString toLineString(); LinearRing toLinearRing(); Polygon toPolygon(); MultiPoint toMultiPoint(); MultiLineString toMultiLineString(); MultiPolygon toMultiPolygon(); GeometryCollection toCollection(); }### Answer:
@Test public void testPoint() { Point p = gb.point(1,2).toPoint(); assertPoint(p, 1, 2); } |
### Question:
GeomBuilder { public GeomBuilder pointz(double x, double y, double z) { cstack.push(new Coordinate(x,y,z)); return this; } GeomBuilder(); GeomBuilder(GeometryFactory factory); GeomBuilder(int srid); GeomBuilder point(double x, double y); GeomBuilder pointz(double x, double y, double z); GeomBuilder points(double ...ord); GeomBuilder pointsz(double ...ord); GeomBuilder point(); GeomBuilder lineString(); GeomBuilder ring(); GeomBuilder polygon(); GeomBuilder multiPoint(); GeomBuilder multiLineString(); GeomBuilder multiPolygon(); GeomBuilder collection(); GeomBuilder buffer(double amt); Geometry get(); Point toPoint(); LineString toLineString(); LinearRing toLinearRing(); Polygon toPolygon(); MultiPoint toMultiPoint(); MultiLineString toMultiLineString(); MultiPolygon toMultiPolygon(); GeometryCollection toCollection(); }### Answer:
@Test public void testPointZ() { Point p = gb.pointz(1,2,3).toPoint(); assertPointZ(p, 1,2,3); } |
### Question:
GeomBuilder { public GeomBuilder lineString() { gstack.push(factory.createLineString(cpopAll())); return this; } GeomBuilder(); GeomBuilder(GeometryFactory factory); GeomBuilder(int srid); GeomBuilder point(double x, double y); GeomBuilder pointz(double x, double y, double z); GeomBuilder points(double ...ord); GeomBuilder pointsz(double ...ord); GeomBuilder point(); GeomBuilder lineString(); GeomBuilder ring(); GeomBuilder polygon(); GeomBuilder multiPoint(); GeomBuilder multiLineString(); GeomBuilder multiPolygon(); GeomBuilder collection(); GeomBuilder buffer(double amt); Geometry get(); Point toPoint(); LineString toLineString(); LinearRing toLinearRing(); Polygon toPolygon(); MultiPoint toMultiPoint(); MultiLineString toMultiLineString(); MultiPolygon toMultiPolygon(); GeometryCollection toCollection(); }### Answer:
@Test public void testLineString() { LineString l = gb.point(1,2).point(3,4).toLineString(); assertEquals(2, l.getNumPoints()); assertPoint(l.getPointN(0), 1,2); assertPoint(l.getPointN(1), 3,4); } |
### Question:
GeomBuilder { public GeomBuilder polygon() { if (gstack.isEmpty() || !(gstack.peek() instanceof LinearRing)) { ring(); } LinearRing[] rings = gpopAll(LinearRing.class); LinearRing outer = rings[0]; LinearRing[] inner = null; if (rings.length > 1) { inner = Arrays.copyOfRange(rings, 1, rings.length); } gstack.push(factory.createPolygon(outer, inner)); return this; } GeomBuilder(); GeomBuilder(GeometryFactory factory); GeomBuilder(int srid); GeomBuilder point(double x, double y); GeomBuilder pointz(double x, double y, double z); GeomBuilder points(double ...ord); GeomBuilder pointsz(double ...ord); GeomBuilder point(); GeomBuilder lineString(); GeomBuilder ring(); GeomBuilder polygon(); GeomBuilder multiPoint(); GeomBuilder multiLineString(); GeomBuilder multiPolygon(); GeomBuilder collection(); GeomBuilder buffer(double amt); Geometry get(); Point toPoint(); LineString toLineString(); LinearRing toLinearRing(); Polygon toPolygon(); MultiPoint toMultiPoint(); MultiLineString toMultiLineString(); MultiPolygon toMultiPolygon(); GeometryCollection toCollection(); }### Answer:
@Test public void testPolygon() { Polygon p = gb.points(1,2,3,4,5,6,1,2).ring().toPolygon(); LineString outer = p.getExteriorRing(); assertEquals(4, outer.getNumPoints()); assertPoint(outer.getPointN(0), 1,2); assertPoint(outer.getPointN(1), 3,4); assertPoint(outer.getPointN(2), 5,6); assertPoint(outer.getPointN(3), 1,2); } |
### Question:
GeomBuilder { public GeomBuilder multiPoint() { if (!cstack.isEmpty()) { gstack.push(factory.createMultiPoint(cpopAll())); } else { gstack.push(factory.createMultiPoint(gpopAll(Point.class))); } return this; } GeomBuilder(); GeomBuilder(GeometryFactory factory); GeomBuilder(int srid); GeomBuilder point(double x, double y); GeomBuilder pointz(double x, double y, double z); GeomBuilder points(double ...ord); GeomBuilder pointsz(double ...ord); GeomBuilder point(); GeomBuilder lineString(); GeomBuilder ring(); GeomBuilder polygon(); GeomBuilder multiPoint(); GeomBuilder multiLineString(); GeomBuilder multiPolygon(); GeomBuilder collection(); GeomBuilder buffer(double amt); Geometry get(); Point toPoint(); LineString toLineString(); LinearRing toLinearRing(); Polygon toPolygon(); MultiPoint toMultiPoint(); MultiLineString toMultiLineString(); MultiPolygon toMultiPolygon(); GeometryCollection toCollection(); }### Answer:
@Test public void testMultiPoint() { MultiPoint mp = gb.points(0,1,2,3).toMultiPoint(); assertEquals(2, mp.getNumGeometries()); assertPoint((Point) mp.getGeometryN(0), 0,1); assertPoint((Point) mp.getGeometryN(1), 2,3); } |
### Question:
GeomBuilder { public GeomBuilder multiLineString() { gstack.push(factory.createMultiLineString(gpopAll(LineString.class))); return this; } GeomBuilder(); GeomBuilder(GeometryFactory factory); GeomBuilder(int srid); GeomBuilder point(double x, double y); GeomBuilder pointz(double x, double y, double z); GeomBuilder points(double ...ord); GeomBuilder pointsz(double ...ord); GeomBuilder point(); GeomBuilder lineString(); GeomBuilder ring(); GeomBuilder polygon(); GeomBuilder multiPoint(); GeomBuilder multiLineString(); GeomBuilder multiPolygon(); GeomBuilder collection(); GeomBuilder buffer(double amt); Geometry get(); Point toPoint(); LineString toLineString(); LinearRing toLinearRing(); Polygon toPolygon(); MultiPoint toMultiPoint(); MultiLineString toMultiLineString(); MultiPolygon toMultiPolygon(); GeometryCollection toCollection(); }### Answer:
@Test public void testMultiLineString() { MultiLineString ml = gb.points(0,1,2,3).lineString().points(4,5,6,7).lineString().toMultiLineString(); assertEquals(2, ml.getNumGeometries()); LineString l1 = (LineString) ml.getGeometryN(0); assertEquals(2, l1.getNumPoints()); assertPoint(l1.getPointN(0), 0,1); assertPoint(l1.getPointN(1), 2,3); LineString l2 = (LineString) ml.getGeometryN(1); assertEquals(2, l2.getNumPoints()); assertPoint(l2.getPointN(0), 4,5); assertPoint(l2.getPointN(1), 6,7); } |
### Question:
GeomBuilder { public GeomBuilder multiPolygon() { gstack.push(factory.createMultiPolygon(gpopAll(Polygon.class))); return this; } GeomBuilder(); GeomBuilder(GeometryFactory factory); GeomBuilder(int srid); GeomBuilder point(double x, double y); GeomBuilder pointz(double x, double y, double z); GeomBuilder points(double ...ord); GeomBuilder pointsz(double ...ord); GeomBuilder point(); GeomBuilder lineString(); GeomBuilder ring(); GeomBuilder polygon(); GeomBuilder multiPoint(); GeomBuilder multiLineString(); GeomBuilder multiPolygon(); GeomBuilder collection(); GeomBuilder buffer(double amt); Geometry get(); Point toPoint(); LineString toLineString(); LinearRing toLinearRing(); Polygon toPolygon(); MultiPoint toMultiPoint(); MultiLineString toMultiLineString(); MultiPolygon toMultiPolygon(); GeometryCollection toCollection(); }### Answer:
@Test public void testMultiPolygon() { MultiPolygon mp = gb.points(1,2,3,4,5,6,1,2).ring().polygon() .points(7,8,9,10,11,12,7,8).ring().polygon().toMultiPolygon(); assertEquals(2, mp.getNumGeometries()); } |
### Question:
MBTileSet implements TileDataset, FileData { @Override public String name() { return Util.base(file().getName()); } MBTileSet(Backend backend, MBTilesOpts opts); MBTileSet(File file); String getTileFormat(); @Override File file(); @Override Driver<?> driver(); @Override Map<Key<?>, Object> driverOptions(); @Override String name(); String title(); String description(); @Override CoordinateReferenceSystem crs(); @Override Bounds bounds(); @Override TilePyramid pyramid(); @Override Tile read(long z, long x, long y); @Override Cursor<Tile> read(long z1, long z2, long x1, long x2, long y1, long y2); @Override void close(); }### Answer:
@Test public void name() { assertEquals("test", tileset.name()); } |
### Question:
MBTileSet implements TileDataset, FileData { public String title() { try { String sql = String.format(Locale.ROOT,"SELECT value FROM %s WHERE name = ?", METADATA); Backend.Results results = backend.queryPrepared(sql, "name"); try { if (results.next()) { return results.getString(0); } } finally { results.close(); } } catch(IOException e) { LOG.error("Error querying for tile name!", e); } return null; } MBTileSet(Backend backend, MBTilesOpts opts); MBTileSet(File file); String getTileFormat(); @Override File file(); @Override Driver<?> driver(); @Override Map<Key<?>, Object> driverOptions(); @Override String name(); String title(); String description(); @Override CoordinateReferenceSystem crs(); @Override Bounds bounds(); @Override TilePyramid pyramid(); @Override Tile read(long z, long x, long y); @Override Cursor<Tile> read(long z1, long z2, long x1, long x2, long y1, long y2); @Override void close(); }### Answer:
@Test public void title() { assertEquals("random", tileset.title()); } |
### Question:
MBTileSet implements TileDataset, FileData { public String description() { try { String sql = String.format(Locale.ROOT,"SELECT value FROM %s WHERE name = ?", METADATA); Backend.Results results = backend.queryPrepared(sql, "description"); try { if (results.next()) { return results.getString(0); } } finally { results.close(); } } catch(IOException e) { LOG.error("Error querying for tile description!", e); } return null; } MBTileSet(Backend backend, MBTilesOpts opts); MBTileSet(File file); String getTileFormat(); @Override File file(); @Override Driver<?> driver(); @Override Map<Key<?>, Object> driverOptions(); @Override String name(); String title(); String description(); @Override CoordinateReferenceSystem crs(); @Override Bounds bounds(); @Override TilePyramid pyramid(); @Override Tile read(long z, long x, long y); @Override Cursor<Tile> read(long z1, long z2, long x1, long x2, long y1, long y2); @Override void close(); }### Answer:
@Test public void description() { assertEquals("Random color tiles", tileset.description()); } |
### Question:
MBTileSet implements TileDataset, FileData { @Override public CoordinateReferenceSystem crs() throws IOException { return Proj.EPSG_900913; } MBTileSet(Backend backend, MBTilesOpts opts); MBTileSet(File file); String getTileFormat(); @Override File file(); @Override Driver<?> driver(); @Override Map<Key<?>, Object> driverOptions(); @Override String name(); String title(); String description(); @Override CoordinateReferenceSystem crs(); @Override Bounds bounds(); @Override TilePyramid pyramid(); @Override Tile read(long z, long x, long y); @Override Cursor<Tile> read(long z1, long z2, long x1, long x2, long y1, long y2); @Override void close(); }### Answer:
@Test public void crs() throws IOException { assertEquals(Proj.EPSG_900913, tileset.crs()); } |
### Question:
MBTileSet implements TileDataset, FileData { @Override public Bounds bounds() throws IOException { try { String sql = String.format(Locale.ROOT,"SELECT value FROM %s WHERE name = ?", METADATA); Backend.Results results = backend.queryPrepared(sql, "bounds"); try { if (results.next()) { Bounds b = Bounds.parse(results.getString(0), true); return b; } } finally { results.close(); } } catch(IOException e) { LOG.error("Error querying for tile bounds!", e); } return Proj.bounds(crs()); } MBTileSet(Backend backend, MBTilesOpts opts); MBTileSet(File file); String getTileFormat(); @Override File file(); @Override Driver<?> driver(); @Override Map<Key<?>, Object> driverOptions(); @Override String name(); String title(); String description(); @Override CoordinateReferenceSystem crs(); @Override Bounds bounds(); @Override TilePyramid pyramid(); @Override Tile read(long z, long x, long y); @Override Cursor<Tile> read(long z1, long z2, long x1, long x2, long y1, long y2); @Override void close(); }### Answer:
@Test public void bounds() throws IOException { assertEquals(new Envelope(-180,180, -85, 85), tileset.bounds()); } |
### Question:
MBTileSet implements TileDataset, FileData { @Override public Tile read(long z, long x, long y) throws IOException { String sql = String.format(Locale.ROOT,"SELECT tile_data FROM %s WHERE zoom_level = %d " + "AND tile_column = %d AND tile_row = %d", TILES, z, x, y); try { Backend.Results results = backend.queryPrepared(sql); try { if (results.next()) { return new Tile((int)z, (int)x, (int)y, results.getBytes(0), tileFormat); } } finally { results.close(); } } catch(IOException e) { LOG.error(String.format(Locale.ROOT,"Error reading tile %s/%s/%s!", z, x, y), e); } return null; } MBTileSet(Backend backend, MBTilesOpts opts); MBTileSet(File file); String getTileFormat(); @Override File file(); @Override Driver<?> driver(); @Override Map<Key<?>, Object> driverOptions(); @Override String name(); String title(); String description(); @Override CoordinateReferenceSystem crs(); @Override Bounds bounds(); @Override TilePyramid pyramid(); @Override Tile read(long z, long x, long y); @Override Cursor<Tile> read(long z1, long z2, long x1, long x2, long y1, long y2); @Override void close(); }### Answer:
@Test public void readTile() throws IOException { Tile tile = tileset.read(1, 1, 0); assertTrue(tile.data().length > 0); assertEquals(new Integer(1), tile.z()); assertEquals(new Integer(1), tile.x()); assertEquals(new Integer(0), tile.y()); assertEquals("image/png", tile.mimeType()); } |
### Question:
GDAL extends FileDriver<GDALDataset> implements RasterDriver<GDALDataset> { public static GDALDataset open(File file) throws IOException { return new GDAL().open(file, null); } GDAL(); static void init(); static GDALDataset open(File file); @Override boolean isEnabled(Messages messages); String getGDALDriverName(); @Override String name(); @Override List<String> aliases(); @Override Class<GDALDataset> type(); @Override String family(); @Override boolean canOpen(Map<?, Object> opts, Messages msgs); @Override Set<Capability> capabilities(); }### Answer:
@Test public void testOpen() throws Exception { GDAL drv = new GDAL(); assertTrue(drv.canOpen(data, null, null)); GDALDataset ds = drv.open(data, null); assertNotNull(ds); }
@Test public void testReadRaster() throws Exception { ByteBuffer buf = ByteBuffer.allocateDirect(10000); buf.order(ByteOrder.nativeOrder()); Dataset ds = gdal.Open(data.getAbsolutePath()); ds.ReadRaster_Direct(0, 0, 1, 1, 1, 1, gdalconst.GDT_Float32, buf, null); }
@Test public void testQuerySmallerRaster() throws Exception { GDALDataset ds = GDAL.open(data); Raster wholeimage = ds.read(new RasterQuery()); int count = wholeimage.data().size(); assertEquals(count, (ds.size().width()*ds.size().height())); Bounds smaller = ds.bounds().scale(0.5); assertTrue(ds.bounds().getArea()> smaller.getArea()); ds.bounds().contains(smaller); RasterQuery q1 = new RasterQuery() .datatype(DataType.DOUBLE) .bounds(smaller); Raster halfsize = ds.read(q1); assertEquals("should be half", (Integer)new Double(wholeimage.size().width()*.5).intValue(), (Integer)halfsize.size().width()); } |
### Question:
OGR extends FileVectorDriver<OGRWorkspace> implements Disposable { public static OGRWorkspace open(Path path) throws IOException { return new OGR().open(path.toFile(), null); } OGR(); OGR(org.gdal.ogr.Driver ogrDrv); static void init(); static OGRWorkspace open(Path path); @Override boolean isEnabled(Messages messages); @Override void close(); @Override String name(); @Override Class<OGRWorkspace> type(); @Override List<Key<?>> keys(); @Override String family(); @Override boolean canOpen(Map<?, Object> opts, Messages msgs); @Override Set<Capability> capabilities(); static final Key<String> DRIVER; }### Answer:
@Test public void testDriverOpen() throws Exception { assertTrue(OGRDataset.class.isInstance(Drivers.open(data))); }
@Test public void testCursor() throws Exception { int count = 0; OGRDataset dataset = Shapefile.open(data.toPath()); FeatureCursor cursor = dataset.read(new VectorQuery()); while(cursor.hasNext()) { cursor.next(); cursor.hasNext(); count++; } assertEquals(49, count); assertNull(cursor.next()); assertFalse(cursor.hasNext()); cursor = dataset.read(new VectorQuery()); for(int i=0; i<count; i++) { Feature f = cursor.next(); assertNotNull(f); } assertNull(cursor.next()); } |
### Question:
PostGIS implements VectorDriver<PostGISWorkspace> { @Override public Class<PostGISWorkspace> type() { return PostGISWorkspace.class; } static PostGISWorkspace open(PostGISOpts opts); @Override boolean isEnabled(Messages messages); @Override String name(); @Override List<String> aliases(); @Override Class<PostGISWorkspace> type(); @Override List<Key<? extends Object>> keys(); @Override String family(); @Override boolean canOpen(Map<?, Object> opts, Messages msgs); @Override PostGISWorkspace open(Map<?, Object> opts); @Override boolean canCreate(Map<?, Object> opts, Messages msgs); @Override PostGISWorkspace create(Map<?, Object> opts, Schema schema); @Override Set<Capability> capabilities(); static final Key<String> DB; static final Key<String> SCHEMA; static final Key<String> HOST; static final Key<Integer> PORT; static final Key<String> USER; static final Key<Password> PASSWD; }### Answer:
@Test public void testSchema() throws Exception { VectorDataset states = pg.get("states"); assertNotNull(states); Schema schema = states.schema(); assertNotNull(schema.field("STATE_NAME")); assertNotNull(schema.geometry()); assertEquals(MultiPolygon.class, schema.geometry().type()); assertNotNull(schema.crs()); assertEquals("EPSG:4326", schema.crs().getName()); } |
### Question:
PostGIS implements VectorDriver<PostGISWorkspace> { @Override public String name() { return "PostGIS"; } static PostGISWorkspace open(PostGISOpts opts); @Override boolean isEnabled(Messages messages); @Override String name(); @Override List<String> aliases(); @Override Class<PostGISWorkspace> type(); @Override List<Key<? extends Object>> keys(); @Override String family(); @Override boolean canOpen(Map<?, Object> opts, Messages msgs); @Override PostGISWorkspace open(Map<?, Object> opts); @Override boolean canCreate(Map<?, Object> opts, Messages msgs); @Override PostGISWorkspace create(Map<?, Object> opts, Schema schema); @Override Set<Capability> capabilities(); static final Key<String> DB; static final Key<String> SCHEMA; static final Key<String> HOST; static final Key<Integer> PORT; static final Key<String> USER; static final Key<Password> PASSWD; }### Answer:
@Test public void testCursorInsert() throws Exception { VectorDataset states = pg.get("states"); Schema schema = states.schema(); FeatureWriteCursor c = states.append(new VectorQuery()); Feature f = c.next(); GeomBuilder gb = new GeomBuilder(); Geometry g = gb.point(0,0).point().buffer(1).toMultiPolygon(); f.put(schema.geometry().name(), g); f.put("STATE_NAME", "JEOLAND"); c.write(); c.close(); assertEquals(50, states.count(new VectorQuery())); FeatureCursor d = states.read(new VectorQuery().bounds(g.getEnvelopeInternal())); assertTrue(d.hasNext()); assertEquals("JEOLAND", d.next().get("STATE_NAME")); d.close(); } |
### Question:
StyleHandler extends Handler { @Override public boolean canHandle(Request request, NanoServer server) { return match(request, STYLE_URI_RE); } @Override boolean canHandle(Request request, NanoServer server); @Override Response handle(Request request, NanoServer server); }### Answer:
@Test public void testCanHandle() { handler.canHandle(new Request("/styles", "GET"), mock.server); handler.canHandle(new Request("/styles/foo", "GET"), mock.server); } |
### Question:
AppsHandler extends Handler { @Override public boolean canHandle(Request request, NanoServer server) { String uri = request.getUri(); return uri.startsWith("/apps") || uri.startsWith("/ol"); } AppsHandler(); AppsHandler(File appsDir); @Override void init(NanoServer server); @Override boolean canHandle(Request request, NanoServer server); @Override Response handle(Request request, NanoServer server); }### Answer:
@Test public void testCanHandle() { handler.canHandle(new Request("/apps", null), null); handler.canHandle(new Request("/apps/foobar", null), null); } |
### Question:
SVGRenderer extends BaseRenderer implements Labeller { @Override public void render(Label label) { if (debugLabels()) { Envelope box = label.bounds(); xml.emptyElement("rect", "fill", "none", "stroke", "black", "x", box.getMinX(), "y", box.getMinY() - box.getHeight(), "width", box.getWidth(), "height", box.getHeight()); } Coordinate a = label.anchor(); Text text = label.get(Text.class, Text.class); Font font = text.font; xml.element("text", label.getText(), "x", a.x, "y", a.y, "font-family", font.family, "font-size", font.size, "text-anchor", text.anchor, "direction", text.direction); } SVGRenderer(); SVGRenderer indent(int size); @Override boolean layout(Label label, LabelIndex labels); @Override void render(Label label); @Override void close(); }### Answer:
@Test public void lines() throws IOException { Style s = Style.build().select("*") .set(LINE_DASHARRAY, "5 3 2 5 3 2") .set(LINE_WIDTH, 2) .style(); View v = Map.build().layer(TestData.line()).style(s).view(); r.init(v, null); r.render(output); }
@Test public void polygons() throws IOException { Style s = Style.build().select("*") .set(POLYGON_FILL, RGB.gray) .style(); View v = Map.build().layer(TestData.states()).style(s).view(); r.init(v, null); r.render(output); } |
### Question:
GeoGit extends FileVectorDriver<GeoGitWorkspace> { @Override public String name() { return "GeoGIT"; } static GeoGitWorkspace open(GeoGitOpts opts); @Override String name(); @Override List<Key<?>> keys(); @Override Class<GeoGitWorkspace> type(); @Override GeoGitWorkspace open(File file, Map<?, Object> opts); @Override boolean supports(VectorDriver.Capability cap); static final Key<String> USER; static final Key<String> EMAIL; }### Answer:
@Test public void testLayers() throws IOException { assertEquals(4, Iterables.size(ws.list())); Iterables.find(ws.list(), new Predicate<Handle<Dataset>>() { @Override public boolean apply(Handle<Dataset> input) { return input.name().equals("states"); } }); Iterables.find(ws.list(), new Predicate<Handle<Dataset>>() { @Override public boolean apply(Handle<Dataset> input) { return input.name().equals("point"); } }); } |
### Question:
RuleList extends ArrayList<Rule> { public RuleList select(RuleVisitor visitor) { RuleList match = new RuleList(); for (Rule r : this) { if (visitor.visit(r)) { match.add(r); } } return match; } RuleList(); RuleList(List<Rule> rules); Rule first(); Rule collapse(); RuleList select(RuleVisitor visitor); RuleList select(SelectorVisitor visitor); RuleList selectById(final String id, final boolean wildcard); RuleList selectByName(final String name, final boolean wildcard, final boolean matchCase); RuleList match(Feature feature); RuleList flatten(); List<RuleList> zgroup(); Set<String> fields(); }### Answer:
@Test public void testSelect() { Style style = new StyleBuilder() .rule().select("Map").set("background-color", "white").endRule() .rule().select("#widgets").filter("cost > 10").set("line-color", "#123").endRule() .style(); RuleList rules = style.getRules(); assertEquals(2, rules.size()); assertEquals(1, rules.selectByName("Map", false, true).size()); assertEquals(1, rules.selectByName("Map", false, false).size()); assertEquals(0, rules.selectByName("map", false, true).size()); assertEquals(1, rules.selectByName("map", false, false).size()); assertEquals(1, rules.selectById("widgets", false).size()); } |
### Question:
GT { public static Feature feature(SimpleFeature feature) { return new GTFeature(feature); } static void initLonLatAxisOrder(); static void initLaxComparisonTolerance(); static Feature feature(SimpleFeature feature); static SimpleFeature feature(Feature feature); static SimpleFeature feature(Feature feature, SimpleFeatureType featureType); static Schema schema(SimpleFeatureType featureType); static SimpleFeatureType featureType(Schema schema); static Iterator<SimpleFeature> iterator(final Cursor<Feature> cursor); static Expression expr(final io.jeo.filter.Expression expr); static Filter filter(final io.jeo.filter.Filter filter, SimpleFeatureType featureType); static CoordinateReferenceSystem crs(org.opengis.referencing.crs.CoordinateReferenceSystem crs); static BufferedImage draw(View v); static void drawAndShow(View v); }### Answer:
@Test public void testToFeature() { SimpleFeatureBuilder b = new SimpleFeatureBuilder(buildFeatureType()); b.add(new GeometryBuilder().point(0,0)); b.add("bomb"); b.add(1); b.add(10.99); SimpleFeature sf = b.buildFeature(null); Feature f = GT.feature(sf); assertNotNull(f.get("geometry")); assertTrue(f.get("geometry") instanceof Point); assertEquals("bomb", f.get("name")); assertEquals(1, f.get("id")); assertEquals(10.99, f.get("price")); assertTrue(f.has("geometry")); assertTrue(f.has("price")); assertFalse(f.has("NOT THERE AT ALL")); }
@Test public void testFromFeature() { Feature f = new MapFeature(null, (Map)Util.map("geometry", new GeometryBuilder().point(0,0), "id", 1, "name", "bomb", "price", 10.99)); SimpleFeature sf = GT.feature(f); assertNotNull(sf.getAttribute("geometry")); assertTrue(sf.getAttribute("geometry") instanceof Point); assertEquals("bomb", sf.getAttribute("name")); assertEquals(1, sf.getAttribute("id")); assertEquals(10.99, sf.getAttribute("price")); } |
### Question:
MBTiles extends FileDriver<MBTileSet> { public static MBTileSet open(Path path){ return new MBTileSet(path.toFile()); } static MBTileSet open(Path path); @Override String name(); @Override List<String> aliases(); @Override Class<MBTileSet> type(); @Override MBTileSet open(File file, Map<?, Object> opts); @Override Set<Capability> capabilities(); }### Answer:
@Test public void open() throws Exception { Path path = Paths.get(getClass().getClassLoader().getResource("io/jeo/mbtiles/test.mbtiles").toURI()); MBTileSet mbtileset = MBTiles.open(path); assertNotNull(mbtileset); assertEquals("test", mbtileset.name()); assertEquals("random", mbtileset.title()); mbtileset.close(); } |
### Question:
CachedRepository implements DataRepository { @Override public <T> T get(String key, Class<T> type) throws IOException { try { return type.cast(objCache.get(new Pair(key, type))); } catch (ExecutionException e) { LOG.warn("Error loading object from cache", e); return reg.get(key, type); } } CachedRepository(DataRepository reg); CachedRepository(DataRepository reg, final int cacheSize); Iterable<Handle<?>> query(Filter<? super Handle<?>> filter); @Override T get(String key, Class<T> type); @Override void close(); }### Answer:
@Test public void testWorkspace() throws IOException { Workspace ws = createMock(Workspace.class); DataRepository reg = createMock(DataRepository.class); expect(reg.get("foo", Workspace.class)).andReturn(ws).once(); replay(ws, reg); CachedRepository cached = new CachedRepository(reg); assertNotNull(cached.get("foo", Workspace.class)); assertNotNull(cached.get("foo", Workspace.class)); assertNotNull(cached.get("foo", Workspace.class)); verify(ws, reg); }
@Test public void testLayer() throws IOException { Dataset l = createMock(Dataset.class); Workspace ws = createMock(Workspace.class); expect(ws.get("bar")).andReturn(l).once(); DataRepository reg = createMock(DataRepository.class); expect(reg.get("foo", Workspace.class)).andReturn(ws).once(); replay(l, ws, reg); CachedRepository cached = new CachedRepository(reg); assertNotNull(((Workspace)cached.get("foo", Workspace.class)).get("bar")); assertNotNull(((Workspace)cached.get("foo", Workspace.class)).get("bar")); assertNotNull(((Workspace)cached.get("foo", Workspace.class)).get("bar")); verify(l, ws, reg); } |
### Question:
MBTiles extends FileDriver<MBTileSet> { @Override public String name() { return "MBTiles"; } static MBTileSet open(Path path); @Override String name(); @Override List<String> aliases(); @Override Class<MBTileSet> type(); @Override MBTileSet open(File file, Map<?, Object> opts); @Override Set<Capability> capabilities(); }### Answer:
@Test public void name() { MBTiles mbtiles = new MBTiles(); assertEquals("MBTiles", mbtiles.name()); } |
### Question:
Memory implements VectorDriver<MemWorkspace>, RasterDriver<MemWorkspace> { @Override public String name() { return "Memory"; } static MemWorkspace open(String name); @Override boolean isEnabled(Messages messages); @Override String name(); @Override List<String> aliases(); @Override Class<MemWorkspace> type(); @Override String family(); @Override List<Key<?>> keys(); @Override boolean canOpen(Map<?, Object> opts, Messages messages); @Override MemWorkspace open(Map<?, Object> opts); @Override boolean canCreate(Map<?, Object> opts, Messages msgs); @Override MemWorkspace create(Map<?, Object> opts, Schema schema); @Override Set<Capability> capabilities(); static final Key<String> NAME; }### Answer:
@Test public void testLayers() throws IOException { assertTrue(Iterables.any(mem.list(), new Predicate<Handle<Dataset>>() { @Override public boolean apply(Handle<Dataset> h) { return "widgets".equals(h.name()); } })); } |
### Question:
Kvp { public List<Pair<String,String>> parse(String val) { List<Pair<String,String>> list = new ArrayList<>(); for (String pair : val.split("\\s*"+pairDelim+"\\s*")) { pair = pair.trim(); if (pair.isEmpty()) { continue; } String[] kvp = pair.split("\\s*"+kvDelim+"\\s*"); if (kvp.length != 2) { throw new IllegalArgumentException("Invalid key/value pair: " + pair); } list.add(Pair.of(kvp[0], kvp[1])); } return list; } Kvp(String pairDelim, String kvDelim); static Kvp get(); static Kvp get(String pairDelim, String kvDelim); List<Pair<String,String>> parse(String val); }### Answer:
@Test public void testParse() { assertPairs(Kvp.get().parse("foo=bar&x=y")); } |
### Question:
Interpolate { public static List<Double> linear(double low, double high, int n) { return interpolate(low, high, n, Method.LINEAR); } static List<Double> linear(double low, double high, int n); static List<Double> exp(double low, double high, int n); static List<Double> log(double low, double high, int n); static List<Double> interpolate(double low, double high, int n, Method method); }### Answer:
@Test public void testLinear() { List<Double> vals = Interpolate.linear(0, 10, 5); assertSequence(vals, 0,2,4,6,8,10); } |
### Question:
Interpolate { public static List<Double> exp(double low, double high, int n) { return interpolate(low, high, n, Method.EXP); } static List<Double> linear(double low, double high, int n); static List<Double> exp(double low, double high, int n); static List<Double> log(double low, double high, int n); static List<Double> interpolate(double low, double high, int n, Method method); }### Answer:
@Test public void testExp() { List<Double> vals = Interpolate.exp(0d, 10d, 5); assertSequence(vals, 0.0, 0.62, 1.61, 3.22, 5.81, 10.0); } |
### Question:
Interpolate { public static List<Double> log(double low, double high, int n) { return interpolate(low, high, n, Method.LOG); } static List<Double> linear(double low, double high, int n); static List<Double> exp(double low, double high, int n); static List<Double> log(double low, double high, int n); static List<Double> interpolate(double low, double high, int n, Method method); }### Answer:
@Test public void testLog() { List<Double> vals = Interpolate.log(0d, 10d, 5); assertSequence(vals, 0.0, 2.63, 4.85, 6.78, 8.48, 10.0); } |
### Question:
Convert { public static Optional<Envelope> toEnvelope(Object obj) { if(obj instanceof Envelope) { return Optional.of((Envelope)obj); } if (obj instanceof String) { Envelope env = Bounds.parse(obj.toString()); if (env != null) { return Optional.of(env); } } return toGeometry(obj).map(new Function<Geometry, Envelope>() { @Override public Envelope apply(Geometry value) { return value.getEnvelopeInternal(); } }); } static Optional<T> to(Object obj, Class<T> clazz); static Optional<T> to(Object obj, Class<T> clazz, boolean safe); static Optional<String> toString(Object obj); static Optional<Boolean> toBoolean(Object obj); static Optional<Path> toPath(Object obj); static Optional<File> toFile(Object obj); static Optional<URL> toURL(Object obj); static Optional<URI> toURI(Object obj); static Optional<T> toNumber(Object obj, Class<T> clazz); static Optional<List<T>> toNumbers(Object obj, Class<T> clazz); static Optional<Number> toNumber(Object obj); static Optional<Reader> toReader(Object obj); static Optional<Geometry> toGeometry(Object obj); static Optional<Envelope> toEnvelope(Object obj); }### Answer:
@Test public void testConvertToEnvelope() { Envelope e = Convert.toEnvelope("POINT (0 0)").get(); assertEquals(0d, e.getMinX(), 0.1); assertEquals(0d, e.getMaxX(), 0.1); assertEquals(0d, e.getMinY(), 0.1); assertEquals(0d, e.getMaxY(), 0.1); e = Convert.toEnvelope("1, 2, 3, 4").get(); assertEquals(1d, e.getMinX(), 0.1); assertEquals(3d, e.getMaxX(), 0.1); assertEquals(2d, e.getMinY(), 0.1); assertEquals(4d, e.getMaxY(), 0.1); } |
### Question:
Rect { public Rect intersect(Rect other) { if (!intersects(other)) { return null; } int l = left > other.left ? left : other.left; int t = top > other.top ? top : other.top; int r = right < other.right ? right : other.right; int b = bottom < other.bottom ? bottom : other.bottom; return new Rect(l, t, r, b); } Rect(int left, int top, int right, int bottom); Rect(int left, int top, Dimension size); int width(); int height(); Dimension size(); int area(); Rect scale(double scx, double scy); boolean intersects(Rect other); Rect intersect(Rect other); Envelope envelope(); Rect map(Envelope bbox, Envelope other); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); final int left; }### Answer:
@Test public void testIntersect() { Rect r = new Rect(0,0,10,10); Rect i = r.intersect(new Rect(-5,5,5,15)); System.out.println(i); } |
### Question:
MBTiles extends FileDriver<MBTileSet> { @Override public List<String> aliases() { return Arrays.asList("mbt"); } static MBTileSet open(Path path); @Override String name(); @Override List<String> aliases(); @Override Class<MBTileSet> type(); @Override MBTileSet open(File file, Map<?, Object> opts); @Override Set<Capability> capabilities(); }### Answer:
@Test public void aliases() { MBTiles mbtiles = new MBTiles(); List<String> aliases = mbtiles.aliases(); assertEquals(1, aliases.size()); assertEquals("mbt", aliases.get(0)); } |
### Question:
Version implements Serializable, Comparable<Version> { @Override public int compareTo(Version v) { if (v == null) { throw new IllegalArgumentException("Unable to compare to null version"); } int i = major.compareTo(v.major); if (i > 0) { return 1; } else if (i < 0) { return -1; } else { int j = minor.compareTo(v.minor); if (j > 0) { return 1; } else if (j < 0) { return -1; } else { int k = patch.compareTo(v.patch); if (k > 0) { return 1; } else if (k < 0) { return -1; } else { return 0; } } } } Version(String version); Version(Integer major, Integer minor, Integer patch); Integer major(); Integer minor(); Integer patch(); @Override int compareTo(Version v); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer:
@Test public void testCompare() { Version v = new Version(1,2,3); assertEquals(1, v.compareTo(new Version(0,2,3))); assertEquals(1, v.compareTo(new Version(1,0,3))); assertEquals(1, v.compareTo(new Version(1,2,0))); assertEquals(-1, v.compareTo(new Version(2,2,3))); assertEquals(-1, v.compareTo(new Version(1,3,3))); assertEquals(-1, v.compareTo(new Version(1,2,4))); assertEquals(0, v.compareTo(new Version(1,2,3))); } |
### Question:
Version implements Serializable, Comparable<Version> { @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Version other = (Version) obj; if (major == null) { if (other.major != null) return false; } else if (!major.equals(other.major)) return false; if (minor == null) { if (other.minor != null) return false; } else if (!minor.equals(other.minor)) return false; if (patch == null) { if (other.patch != null) return false; } else if (!patch.equals(other.patch)) return false; return true; } Version(String version); Version(Integer major, Integer minor, Integer patch); Integer major(); Integer minor(); Integer patch(); @Override int compareTo(Version v); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer:
@Test public void testEquals() { assertEquals(new Version(1,2,3), new Version(1,2,3)); } |
### Question:
Proj { public static Integer epsgCode(CoordinateReferenceSystem crs) { String name = crs.getName(); if (name != null) { String[] split = name.split(":"); if (split.length == 2 && "epsg".equalsIgnoreCase(split[0])) { return Integer.parseInt(split[1]); } } return null; } static CoordinateReferenceSystem crs(int srid); static CoordinateReferenceSystem crs(String s); static CoordinateReferenceSystem crs(String... projdef); static CoordinateReferenceSystem crs(Geometry geom); static Geometry crs(Geometry g, CoordinateReferenceSystem crs); static Geometry crs(Geometry g, CoordinateReferenceSystem crs, boolean overwrite); static Integer epsgCode(CoordinateReferenceSystem crs); static Bounds bounds(CoordinateReferenceSystem crs); static T reproject(T g, String from, String to); static T reproject(T g, CoordinateReferenceSystem from,
CoordinateReferenceSystem to); static T transform(T g, CoordinateTransform tx); static T transform(T g, CoordinateTransform tx, boolean inPlace); static Bounds reproject(Envelope e, String from, String to); static Bounds reproject(Envelope e, CoordinateReferenceSystem from,
CoordinateReferenceSystem to); static CoordinateTransform transform(CoordinateReferenceSystem from,
CoordinateReferenceSystem to); static String toString(CoordinateReferenceSystem crs); static CoordinateReferenceSystem fromWKT(String wkt); static String toWKT(CoordinateReferenceSystem crs, boolean format); static boolean equal(CoordinateReferenceSystem crs1, CoordinateReferenceSystem crs2); static final CoordinateReferenceSystem EPSG_4326; static final CoordinateReferenceSystem EPSG_900913; }### Answer:
@Test public void testEpsgCode() { CoordinateReferenceSystem crs = Proj.crs("EPSG:4326"); assertEquals(4326, Proj.epsgCode(crs).intValue()); } |
### Question:
DataBuffer { public abstract T get(); DataBuffer(ByteBuffer buffer, DataType datatype); static DataBuffer create(ByteBuffer buffer, DataType datatype); static DataBuffer create(int size, DataType datatype); static DataBuffer<T> resample(DataBuffer<T> buffer, Dimension from, Dimension to); ByteBuffer buffer(); abstract T get(); T get(int i); DataBuffer<T> put(Object val); DataBuffer<T> put(int i, T val); DataBuffer<T> flip(); DataBuffer<T> rewind(); DataBuffer<T> word(); int size(); DataType datatype(); }### Answer:
@Test public void testGet() throws Exception { ByteBuffer bbuf = ByteBuffer.allocate(16); bbuf.asIntBuffer().put(1).put(2).put(3).put(4); DataBuffer<Byte> nbuf = DataBuffer.create(bbuf, DataType.BYTE); for (int i = 0; i < 4; i++) { assertEquals(0, nbuf.get().byteValue()); assertEquals(0, nbuf.get().byteValue()); assertEquals(0, nbuf.get().byteValue()); assertEquals((byte)(i+1), nbuf.get().byteValue()); } } |
### Question:
DataBuffer { public DataBuffer<T> put(Object val) { if (val instanceof Byte) { buffer.put((Byte)val); } else if (val instanceof Short) { buffer.putShort((Short)val); } else if (val instanceof Character) { buffer.putChar((Character)val); } else if (val instanceof Integer) { buffer.putInt((Integer)val); } else if (val instanceof Long) { buffer.putLong((Long)val); } else if (val instanceof Float) { buffer.putFloat((Float)val); } else if (val instanceof Double) { buffer.putDouble((Double)val); } else { throw new IllegalArgumentException("unknown data value: " + val); } return this; } DataBuffer(ByteBuffer buffer, DataType datatype); static DataBuffer create(ByteBuffer buffer, DataType datatype); static DataBuffer create(int size, DataType datatype); static DataBuffer<T> resample(DataBuffer<T> buffer, Dimension from, Dimension to); ByteBuffer buffer(); abstract T get(); T get(int i); DataBuffer<T> put(Object val); DataBuffer<T> put(int i, T val); DataBuffer<T> flip(); DataBuffer<T> rewind(); DataBuffer<T> word(); int size(); DataType datatype(); }### Answer:
@Test public void testPut() throws Exception { ByteBuffer bbuf = ByteBuffer.allocate(16); DataBuffer<Byte> nbuf = DataBuffer.create(bbuf, DataType.BYTE); for (int i = 0; i < 4; i++) { nbuf.put((byte)0).put((byte)0).put((byte)0).put((byte) (i + 1)); } bbuf.flip(); IntBuffer ibuf = bbuf.asIntBuffer(); assertEquals(1, ibuf.get()); assertEquals(2, ibuf.get()); assertEquals(3, ibuf.get()); assertEquals(4, ibuf.get()); } |
### Question:
MBTiles extends FileDriver<MBTileSet> { @Override public Class<MBTileSet> type() { return MBTileSet.class; } static MBTileSet open(Path path); @Override String name(); @Override List<String> aliases(); @Override Class<MBTileSet> type(); @Override MBTileSet open(File file, Map<?, Object> opts); @Override Set<Capability> capabilities(); }### Answer:
@Test public void type() { MBTiles mbtiles = new MBTiles(); assertEquals(MBTileSet.class, mbtiles.type()); } |
### Question:
Property implements Expression { @Override public Object evaluate(Object obj) { return resolve(obj); } Property(String property); String property(); boolean has(Object obj); @Override Object evaluate(Object obj); @Override R accept(FilterVisitor<R> visitor, Object obj); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer:
@Test public void testResolveObject() { Bar bar = new Bar("one"); Foo foo = new Foo(bar, "two"); assertEquals("two", new Property("baz").evaluate(foo)); assertEquals(bar, new Property("bar").evaluate(foo)); assertEquals("one", new Property("bar.bam").evaluate(foo)); }
@Test public void testResolveObjectWithNull() { assertNull(new Property("bar").evaluate(null)); assertNull(new Property("bar.bam").evaluate(new Foo(null, "blah"))); } |
### Question:
MBTileSet implements TileDataset, FileData { public String getTileFormat() { return tileFormat; } MBTileSet(Backend backend, MBTilesOpts opts); MBTileSet(File file); String getTileFormat(); @Override File file(); @Override Driver<?> driver(); @Override Map<Key<?>, Object> driverOptions(); @Override String name(); String title(); String description(); @Override CoordinateReferenceSystem crs(); @Override Bounds bounds(); @Override TilePyramid pyramid(); @Override Tile read(long z, long x, long y); @Override Cursor<Tile> read(long z1, long z2, long x1, long x2, long y1, long y2); @Override void close(); }### Answer:
@Test public void getTileFormat() throws Exception { assertEquals("image/png", tileset.getTileFormat()); } |
### Question:
FeatureCursor extends Cursor<Feature> { public FeatureCursor crs(CoordinateReferenceSystem crs) { return new CrsOverrideCursor(this, crs); } static FeatureCursor empty(); FeatureCursor reproject(CoordinateReferenceSystem crs); FeatureCursor reproject(CoordinateReferenceSystem from, CoordinateReferenceSystem to); FeatureCursor crs(CoordinateReferenceSystem crs); FeatureCursor intersect(final Envelope bbox, boolean loose); FeatureCursor multify(); FeatureCursor select(final Iterable<String> fields); @Override FeatureCursor filter(Predicate<Feature> filter); @Override FeatureCursor limit(Integer limit); @Override FeatureCursor skip(Integer offset); @Override FeatureCursor buffer(int n); static FeatureCursor wrap(Cursor<Feature> cursor); }### Answer:
@Test public void testCrs() throws Exception { Feature f = new ListFeature(Schema.build("test").field("geo", Point.class).schema(), Geom.point(0, 0)); assertNull(Features.crs(f)); assertNull(Features.schema("feature", f).crs()); f = FeatureCursor.wrap(Cursors.single(f)).crs(Proj.EPSG_900913).first().get(); assertEquals(Proj.EPSG_900913, Features.crs(f)); assertEquals(Proj.EPSG_900913, Features.schema("feature", f).crs()); } |
### Question:
MBTileSet implements TileDataset, FileData { @Override public File file() { return opts.file(); } MBTileSet(Backend backend, MBTilesOpts opts); MBTileSet(File file); String getTileFormat(); @Override File file(); @Override Driver<?> driver(); @Override Map<Key<?>, Object> driverOptions(); @Override String name(); String title(); String description(); @Override CoordinateReferenceSystem crs(); @Override Bounds bounds(); @Override TilePyramid pyramid(); @Override Tile read(long z, long x, long y); @Override Cursor<Tile> read(long z1, long z2, long x1, long x2, long y1, long y2); @Override void close(); }### Answer:
@Test public void file() { assertEquals("test.mbtiles", tileset.file().getName()); } |
### Question:
RangeValidator implements ConfigurationOption.Validator<T> { public static <T extends Comparable> RangeValidator<T> min(T min) { return new RangeValidator<>(min, null, true); } private RangeValidator(@Nullable T min, @Nullable T max, boolean mustBeInRange); static RangeValidator<T> isInRange(T min, T max); static RangeValidator<T> isNotInRange(T min, T max); static RangeValidator<T> min(T min); static RangeValidator<T> max(T max); @Override void assertValid(@Nullable T value); }### Answer:
@Test void testMin() { final RangeValidator<Integer> validator = RangeValidator.min(1); assertThatThrownBy(() -> validator.assertValid(0)).isInstanceOf(IllegalArgumentException.class); validator.assertValid(1); validator.assertValid(2); } |
### Question:
HttpUtils { public static void consumeAndClose(@Nullable HttpURLConnection connection) { if (connection != null) { IOUtils.consumeAndClose(connection.getErrorStream()); try { IOUtils.consumeAndClose(connection.getInputStream()); } catch (IOException ignored) { } } } private HttpUtils(); static String readToString(final InputStream inputStream); static void consumeAndClose(@Nullable HttpURLConnection connection); }### Answer:
@Test void consumeAndCloseIgnoresNullConnection() { HttpUtils.consumeAndClose(null); }
@Test void consumeAndCloseNoStreams() throws IOException { HttpURLConnection connection = mock(HttpURLConnection.class); when(connection.getErrorStream()).thenReturn(null); when(connection.getInputStream()).thenReturn(null); HttpUtils.consumeAndClose(connection); }
@Test void consumeAndCloseException() throws IOException { HttpURLConnection connection = mock(HttpURLConnection.class); InputStream errorStream = mockEmptyInputStream(); when(connection.getErrorStream()).thenReturn(errorStream); when(connection.getInputStream()).thenThrow(IOException.class); HttpUtils.consumeAndClose(connection); verify(errorStream).close(); }
@Test void consumeAndCloseResponseContent() throws IOException { HttpURLConnection connection = mock(HttpURLConnection.class); when(connection.getErrorStream()).thenReturn(null); InputStream responseStream = mockEmptyInputStream(); when(connection.getInputStream()).thenReturn(responseStream); HttpUtils.consumeAndClose(connection); verify(responseStream).close(); } |
### Question:
IntakeV2ReportingEventHandler extends AbstractIntakeApiHandler implements ReportingEventHandler { int getBufferSize() { return payloadSerializer.getBufferSize(); } IntakeV2ReportingEventHandler(ReporterConfiguration reporterConfiguration, ProcessorEventHandler processorEventHandler,
PayloadSerializer payloadSerializer, MetaData metaData, ApmServerClient apmServerClient); @Override void init(ApmServerReporter reporter); @Override void onEvent(ReportingEvent event, long sequence, boolean endOfBatch); @Override void endRequest(); @Override void close(); static final String INTAKE_V2_URL; }### Answer:
@Test void testNoopWhenNotConnected() { reportTransaction(nonConnectedReportingEventHandler); assertThat(nonConnectedReportingEventHandler.getBufferSize()).isEqualTo(0); } |
### Question:
IntakeV2ReportingEventHandler extends AbstractIntakeApiHandler implements ReportingEventHandler { @Override public void endRequest() { cancelTimeout(); super.endRequest(); } IntakeV2ReportingEventHandler(ReporterConfiguration reporterConfiguration, ProcessorEventHandler processorEventHandler,
PayloadSerializer payloadSerializer, MetaData metaData, ApmServerClient apmServerClient); @Override void init(ApmServerReporter reporter); @Override void onEvent(ReportingEvent event, long sequence, boolean endOfBatch); @Override void endRequest(); @Override void close(); static final String INTAKE_V2_URL; }### Answer:
@Test void testShutDown() { reportTransaction(reportingEventHandler); sendShutdownEvent(); reportSpan(); reportingEventHandler.endRequest(); final List<JsonNode> ndJsonNodes = getNdJsonNodes(); assertThat(ndJsonNodes).hasSize(2); assertThat(ndJsonNodes.get(0).get("metadata")).isNotNull(); assertThat(ndJsonNodes.get(1).get("transaction")).isNotNull(); }
@Test void testReportRoundRobinOnServerError() { mockApmServer1.stubFor(post(INTAKE_V2_URL).willReturn(serviceUnavailable())); reportTransaction(reportingEventHandler); reportingEventHandler.endRequest(); mockApmServer1.verify(postRequestedFor(urlEqualTo(INTAKE_V2_URL))); mockApmServer2.verify(0, postRequestedFor(urlEqualTo(INTAKE_V2_URL))); mockApmServer1.resetRequests(); mockApmServer2.resetRequests(); reportTransaction(reportingEventHandler); reportingEventHandler.endRequest(); mockApmServer1.verify(0, postRequestedFor(urlEqualTo(INTAKE_V2_URL))); mockApmServer2.verify(postRequestedFor(urlEqualTo(APM_SERVER_PATH + INTAKE_V2_URL))); } |
### Question:
ByteValue { public static ByteValue of(String byteString) { byteString = byteString.toLowerCase(); Matcher matcher = BYTE_PATTERN.matcher(byteString); if (matcher.matches()) { long value = Long.parseLong(matcher.group(1)); return new ByteValue(byteString, value * getUnitMultiplier(matcher.group(2))); } else { throw new IllegalArgumentException("Invalid byte value '" + byteString + "'"); } } private ByteValue(String byteString, long bytes); static ByteValue of(String byteString); long getBytes(); @Override String toString(); static final Pattern BYTE_PATTERN; }### Answer:
@Test void testParseUnitInvalid() { for (String invalid : List.of("1Kib", "-1b", " 1b", "1 b", "1b ", "1tb")) { assertThatCode(() -> ByteValue.of(invalid)).isInstanceOf(IllegalArgumentException.class); } } |
### Question:
WeakKeySoftValueLoadingCache { @Nullable public V get(K key) { final CacheValue<K, V> cacheValue = cache.get(key); if (cacheValue != null) { return cacheValue.get(key); } else { CacheValue<K, V> value = new CacheValue<>(key, valueSupplier); cache.put(key, value); return value.get(key); } } WeakKeySoftValueLoadingCache(ValueSupplier<K, V> valueSupplier); @Nullable V get(K key); }### Answer:
@Test void testGet() { WeakKeySoftValueLoadingCache<String, String> cache = new WeakKeySoftValueLoadingCache<>(String::toUpperCase); String value = cache.get("foo"); assertThat(value).isEqualTo("FOO"); assertThat(cache.get("foo")).isSameAs(value); }
@Test void testGetNull() { WeakKeySoftValueLoadingCache<String, String> cache = new WeakKeySoftValueLoadingCache<>(key -> null); assertThat(cache.get("foo")).isNull(); } |
### Question:
WildcardMatcherValueConverter implements ValueConverter<WildcardMatcher> { @Override public WildcardMatcher convert(String s) { return WildcardMatcher.valueOf(s); } @Override WildcardMatcher convert(String s); @Override String toString(WildcardMatcher value); @Override String toSafeString(WildcardMatcher value); }### Answer:
@Test void convert() { assertThat(converter.toString(converter.convert("foo*"))).isEqualTo("foo*"); assertThat(converter.toSafeString(converter.convert("foo*"))).isEqualTo("foo*"); } |
### Question:
ElasticApmTracerBuilder { public ElasticApmTracer build() { return build(false); } ElasticApmTracerBuilder(); ElasticApmTracerBuilder(@Nullable String agentArguments); ElasticApmTracerBuilder configurationRegistry(ConfigurationRegistry configurationRegistry); ElasticApmTracerBuilder reporter(Reporter reporter); ElasticApmTracerBuilder withObjectPoolFactory(ObjectPoolFactory objectPoolFactory); ElasticApmTracerBuilder withLifecycleListener(LifecycleListener listener); ElasticApmTracer build(); ElasticApmTracer buildAndStart(); }### Answer:
@Test void testConfigFileLocation(@TempDir Path tempDir) throws IOException { Path file = Files.createFile(tempDir.resolve("elastic-apm-test.properties")); Files.write(file, List.of("instrument=false")); System.setProperty("elastic.apm." + CoreConfiguration.CONFIG_FILE, file.toString()); ConfigurationRegistry configurationRegistry = new ElasticApmTracerBuilder().build().getConfigurationRegistry(); CoreConfiguration config = configurationRegistry.getConfig(CoreConfiguration.class); assertThat(config.isInstrument()).isFalse(); configurationRegistry.getString(CoreConfiguration.CONFIG_FILE); assertThat(configurationRegistry.getString(CoreConfiguration.CONFIG_FILE)).isEqualTo(file.toString()); }
@Test void testTempAttacherPropertiesFile(@TempDir Path tempDir) throws Exception { Path file = Files.createFile(tempDir.resolve("elstcapm.tmp")); Files.write(file, List.of("instrument=false")); ConfigurationRegistry configurationRegistry = new ElasticApmTracerBuilder("c=" + file.toAbsolutePath()).build().getConfigurationRegistry(); CoreConfiguration config = configurationRegistry.getConfig(CoreConfiguration.class); assertThat(config.isInstrument()).isFalse(); } |
### Question:
ProbabilitySampler implements Sampler { @Override public boolean isSampled(Id traceId) { final long leastSignificantBits = traceId.getLeastSignificantBits(); return leastSignificantBits > lowerBound && leastSignificantBits < higherBound; } private ProbabilitySampler(double samplingRate); static Sampler of(double samplingRate); @Override boolean isSampled(Id traceId); @Override double getSampleRate(); @Override String getSampleRateString(); }### Answer:
@Test void isSampledEmpiricalTest() { int sampledTransactions = 0; Id id = Id.new128BitId(); for (int i = 0; i < ITERATIONS; i++) { id.setToRandomValue(); if (sampler.isSampled(id)) { sampledTransactions++; } } assertThat(sampledTransactions).isBetween((int) (SAMPLING_RATE * ITERATIONS - DELTA), (int) (SAMPLING_RATE * ITERATIONS + DELTA)); } |
### Question:
StackFrame { public void appendFileName(StringBuilder replaceBuilder) { if (className != null) { int fileNameEnd = className.indexOf('$'); if (fileNameEnd < 0) { fileNameEnd = className.length(); } int classNameStart = className.lastIndexOf('.'); if (classNameStart < fileNameEnd && fileNameEnd <= className.length()) { replaceBuilder.append(className, classNameStart + 1, fileNameEnd); replaceBuilder.append(".java"); } else { replaceBuilder.append("<Unknown>"); } } else { replaceBuilder.append("<Unknown>"); } } StackFrame(@Nullable String className, String methodName); static StackFrame of(@Nullable String className, String methodName); @Nullable String getClassName(); String getMethodName(); void appendSimpleClassName(StringBuilder sb); void appendFileName(StringBuilder replaceBuilder); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test void testAppendFileName() { assertThat(getFileName("Baz")).isEqualTo("Baz.java"); assertThat(getFileName("foo.bar.Baz")).isEqualTo("Baz.java"); assertThat(getFileName("foo.bar.Baz$Qux")).isEqualTo("Baz.java"); assertThat(getFileName("baz")).isEqualTo("baz.java"); } |
### Question:
Transaction extends AbstractSpan<Transaction> { @Override public void resetState() { super.resetState(); context.resetState(); result = null; spanCount.resetState(); type = null; noop = false; maxSpans = 0; frameworkName = null; frameworkVersion = null; } Transaction(ElasticApmTracer tracer); @Override Transaction getTransaction(); Transaction start(TraceContext.ChildContextCreator<T> childContextCreator, @Nullable T parent, long epochMicros,
Sampler sampler, @Nullable ClassLoader initiatingClassLoader); Transaction start(TraceContext.ChildContextCreatorTwoArg<T, A> childContextCreator, @Nullable T parent, A arg,
long epochMicros, Sampler sampler, @Nullable ClassLoader initiatingClassLoader); Transaction startNoop(); @Override TransactionContext getContext(); TransactionContext getContextEnsureVisibility(); Transaction withType(@Nullable String type); @Nullable String getResult(); Transaction withResultIfUnset(@Nullable String result); Transaction withResult(@Nullable String result); void setUser(String id, String email, String username); @Override void beforeEnd(long epochMicros); SpanCount getSpanCount(); KeyListConcurrentHashMap<String, KeyListConcurrentHashMap<String, Timer>> getTimerBySpanTypeAndSubtype(); @Override void resetState(); boolean isNoop(); void ignoreTransaction(); @Nullable String getType(); void addCustomContext(String key, String value); void addCustomContext(String key, Number value); void addCustomContext(String key, Boolean value); @Override String toString(); @Override void incrementReferences(); void setFrameworkName(@Nullable String frameworkName); @Nullable String getFrameworkName(); void setFrameworkVersion(@Nullable String frameworkVersion); @Nullable String getFrameworkVersion(); static final String TYPE_REQUEST; }### Answer:
@Test void resetState() { final Transaction transaction = new Transaction(MockTracer.create()); TransactionUtils.fillTransaction(transaction); transaction.resetState(); assertThat(jsonSerializer.toJsonString(transaction)).isEqualTo(jsonSerializer.toJsonString(new Transaction(MockTracer.create()))); } |
### Question:
Span extends AbstractSpan<Span> implements Recyclable { @Override public void resetState() { super.resetState(); context.resetState(); stacktrace = null; type = null; subtype = null; action = null; parent = null; transaction = null; stackFrames = null; } Span(ElasticApmTracer tracer); void setNonDiscardable(); Span start(TraceContext.ChildContextCreator<T> childContextCreator, T parentContext, long epochMicros); @Override SpanContext getContext(); Span withType(@Nullable String type); Span withSubtype(@Nullable String subtype); Span withAction(@Nullable String action); @Deprecated void setType(@Nullable String type, @Nullable String subtype, @Nullable String action); @Nullable Throwable getStacktrace(); @Nullable String getType(); @Nullable String getSubtype(); @Nullable String getAction(); @Override void beforeEnd(long epochMicros); @Override void resetState(); @Override String toString(); Span withStacktrace(Throwable stacktrace); @Override void incrementReferences(); @Override void decrementReferences(); void setStackTrace(List<StackFrame> stackTrace); @Nullable List<StackFrame> getStackFrames(); @Nullable @Override Transaction getTransaction(); @Nullable AbstractSpan<?> getParent(); static final long MAX_LOG_INTERVAL_MICRO_SECS; }### Answer:
@Test void resetState() { Span span = new Span(MockTracer.create()) .withName("SELECT FROM product_types") .withType("db") .withSubtype("postgresql") .withAction("query"); span.getContext().getDb() .withInstance("customers") .withStatement("SELECT * FROM product_types WHERE user_id=?") .withType("sql") .withUser("readonly_user"); span.resetState(); assertThat(span.getContext().hasContent()).isFalse(); assertThat(span.getNameAsString()).isNullOrEmpty(); assertThat(span.getType()).isNull(); assertThat(span.getSubtype()).isNull(); assertThat(span.getAction()).isNull(); } |
### Question:
SanitizingWebProcessor implements Processor { @Override public void processBeforeReport(Transaction transaction) { sanitizeContext(transaction.getContext()); } SanitizingWebProcessor(ConfigurationRegistry configurationRegistry); @Override void processBeforeReport(Transaction transaction); @Override void processBeforeReport(ErrorCapture error); }### Answer:
@Test void processTransactions() { Transaction transaction = new Transaction(MockTracer.create()); fillContext(transaction.getContext()); processor.processBeforeReport(transaction); assertContainsNoSensitiveInformation(transaction.getContext()); }
@Test void processErrors() { final ErrorCapture errorCapture = new ErrorCapture(MockTracer.create()); fillContext(errorCapture.getContext()); processor.processBeforeReport(errorCapture); assertContainsNoSensitiveInformation(errorCapture.getContext()); } |
### Question:
Url implements Recyclable { @Override public void resetState() { protocol = null; full.setLength(0); hostname = null; port.setLength(0); pathname = null; search = null; } @Nullable String getProtocol(); Url withProtocol(@Nullable String protocol); StringBuilder getFull(); Url appendToFull(CharSequence charSequence); @Nullable String getHostname(); Url withHostname(@Nullable String hostname); StringBuilder getPort(); Url withPort(int port); @Nullable String getPathname(); Url withPathname(@Nullable String pathname); @Nullable String getSearch(); Url withSearch(@Nullable String search); @Override void resetState(); void copyFrom(Url other); boolean hasContent(); }### Answer:
@Test void testResetState() { final Url url = newUrl(); url.resetState(); assertThat(toJson(url)).isEqualTo(toJson(new Url())); } |
### Question:
Url implements Recyclable { public void copyFrom(Url other) { this.protocol = other.protocol; this.full.setLength(0); this.full.append(other.full); this.hostname = other.hostname; this.port.setLength(0); this.port.append(other.port); this.pathname = other.pathname; this.search = other.search; } @Nullable String getProtocol(); Url withProtocol(@Nullable String protocol); StringBuilder getFull(); Url appendToFull(CharSequence charSequence); @Nullable String getHostname(); Url withHostname(@Nullable String hostname); StringBuilder getPort(); Url withPort(int port); @Nullable String getPathname(); Url withPathname(@Nullable String pathname); @Nullable String getSearch(); Url withSearch(@Nullable String search); @Override void resetState(); void copyFrom(Url other); boolean hasContent(); }### Answer:
@Test void testCopyOf() { final Url url = newUrl(); final Url copy = new Url(); copy.copyFrom(url); assertThat(toJson(url)).isEqualTo(toJson(copy)); assertThat(toJson(url)).isNotEqualTo(toJson(new Url())); } |
### Question:
TransactionContext extends AbstractContext { public void copyFrom(TransactionContext other) { super.copyFrom(other); response.copyFrom(other.response); request.copyFrom(other.request); user.copyFrom(other.user); } void copyFrom(TransactionContext other); Object getCustom(String key); Response getResponse(); void addCustom(String key, String value); void addCustom(String key, Number value); void addCustom(String key, boolean value); boolean hasCustom(); Iterator<? extends Map.Entry<String, ?>> getCustomIterator(); Request getRequest(); User getUser(); @Override void resetState(); void onTransactionEnd(); }### Answer:
@Test void testCopyFrom() { TransactionContext context = createContext(); TransactionContext copyOfContext = new TransactionContext(); copyOfContext.copyFrom(context); assertThat(toJson(context)).isEqualTo(toJson(copyOfContext)); }
@Test void testCopyFromCopiesTags() { TransactionContext context = new TransactionContext(); context.addLabel("foo", "bar"); TransactionContext copyOfContext = new TransactionContext(); copyOfContext.copyFrom(context); assertThat(copyOfContext.getLabel("foo")).isEqualTo("bar"); } |
### Question:
Headers implements Recyclable, Iterable<Headers.Header> { public void copyFrom(Headers other) { textHeaders.copyFrom(other.textHeaders); binaryHeaders.copyFrom(other.binaryHeaders); } void add(String key, String value); boolean add(String key, byte[] value); @Override void resetState(); int size(); boolean isEmpty(); @Override Iterator<Header> iterator(); void copyFrom(Headers other); }### Answer:
@SuppressWarnings("ConstantConditions") @Test void testCopyFrom() { Headers copy = new Headers(); copy.add("bin2", "bin-val2".getBytes()); copy.add("text2", "text-val2"); copy.copyFrom(headers); assertThat(copy.size()).isEqualTo(4); Iterator<Headers.Header> iterator = copy.iterator(); Headers.Header header = iterator.next(); assertThat(header.getKey()).isEqualTo("text0"); assertThat(header.getValue().toString()).isEqualTo("text-val0"); header = iterator.next(); assertThat(header.getKey()).isEqualTo("text1"); assertThat(header.getValue().toString()).isEqualTo("text-val1"); header = iterator.next(); assertThat(header.getKey()).isEqualTo("bin0"); assertThat(header.getValue().toString()).isEqualTo("bin-val0"); header = iterator.next(); assertThat(header.getKey()).isEqualTo("bin1"); assertThat(header.getValue().toString()).isEqualTo("bin-val1"); } |
### Question:
MapsTokenScanner { Map<String, String> scanMap() { Map<String, String> map = new HashMap<>(); skipWhiteSpace(); while (hasNext()) { if (peek() == ',') { next(); break; } map.put(scanKey(), scanValue()); skipWhiteSpace(); } return map; } MapsTokenScanner(String input); static String toTokenString(List<Map<String, List<String>>> maps); List<Map<String, String>> scanMaps(); List<Map<String, List<String>>> scanMultiValueMaps(); }### Answer:
@Test void testScanMap() { for (String input : List.of("foo[bar] baz[qux]", "foo[bar]baz[qux]", "foo[bar] baz[qux] ", "foo[bar] baz[qux], quux[corge]")) { assertThat(new MapsTokenScanner(input).scanMap()).isEqualTo(Map.of("foo", "bar", "baz", "qux")); } }
@Test void testMissingValue() { assertThatThrownBy(() -> new MapsTokenScanner("foo").scanMap()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Expected value start"); }
@Test void testMissingKey() { assertThatThrownBy(() -> new MapsTokenScanner("foo[bar] [qux]").scanMap()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Empty key"); }
@Test void testMissingClosingBracket() { assertThatThrownBy(() -> new MapsTokenScanner("foo[bar").scanMap()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Expected end value token ']'"); }
@Test void testBracketWithinValue() { assertThatThrownBy(() -> new MapsTokenScanner("foo[b[a]r]").scanMap()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Invalid char '[' within a value"); } |
### Question:
MapsTokenScanner { public List<Map<String, String>> scanMaps() { skipWhiteSpace(); List<Map<String, String>> maps = new ArrayList<>(); while (hasNext()) { maps.add(scanMap()); } return maps; } MapsTokenScanner(String input); static String toTokenString(List<Map<String, List<String>>> maps); List<Map<String, String>> scanMaps(); List<Map<String, List<String>>> scanMultiValueMaps(); }### Answer:
@Test void testScanMaps() { assertThat(new MapsTokenScanner("f[b]").scanMaps()) .isEqualTo(List.of(Map.of("f", "b"))); assertThat(new MapsTokenScanner("foo bar[baz,qux ]").scanMaps()) .isEqualTo(List.of(Map.of("foo bar", "baz,qux "))); assertThat(new MapsTokenScanner(" foo[bar] baz[qux] ").scanMaps()) .isEqualTo(List.of(Map.of("foo", "bar", "baz", "qux"))); assertThat(new MapsTokenScanner(" foo[bar] baz[qux], quux[corge] ").scanMaps()) .isEqualTo(List.of(Map.of("foo", "bar", "baz", "qux"), Map.of("quux", "corge"))); assertThat(new MapsTokenScanner(" foo[bar] baz[qux] , quux[corge] ").scanMaps()) .isEqualTo(List.of(Map.of("foo", "bar", "baz", "qux"), Map.of("quux", "corge"))); } |
### Question:
MapsTokenScanner { public List<Map<String, List<String>>> scanMultiValueMaps() { skipWhiteSpace(); List<Map<String, List<String>>> maps = new ArrayList<>(); while (hasNext()) { maps.add(scanMultiValueMap()); } return maps; } MapsTokenScanner(String input); static String toTokenString(List<Map<String, List<String>>> maps); List<Map<String, String>> scanMaps(); List<Map<String, List<String>>> scanMultiValueMaps(); }### Answer:
@Test void testScanMultiValueMaps() { assertThat(new MapsTokenScanner("a[a] a[b]").scanMultiValueMaps()) .isEqualTo(List.of(Map.of("a", List.of("a", "b")))); } |
### Question:
ApmServerConfigurationSource extends AbstractConfigurationSource implements LifecycleListener { @Nullable static Integer parseMaxAge(@Nullable String cacheControlHeader) { if (cacheControlHeader == null) { return null; } Matcher matcher = MAX_AGE.matcher(cacheControlHeader); if (!matcher.find()) { return null; } return Integer.parseInt(matcher.group(1)); } ApmServerConfigurationSource(PayloadSerializer payloadSerializer, MetaData metaData, ApmServerClient apmServerClient); ApmServerConfigurationSource(PayloadSerializer payloadSerializer, MetaData metaData, ApmServerClient apmServerClient, Logger logger); @Override void reload(); @Override void init(ElasticApmTracer tracer); @Override void start(final ElasticApmTracer tracer); @Override String getValue(String key); @Override String getName(); @Override void pause(); @Override void resume(); @Override void stop(); }### Answer:
@Test public void parseMaxAgeFromCacheControlHeader() { assertThat(ApmServerConfigurationSource.parseMaxAge("max-age=1")).isEqualTo(1); assertThat(ApmServerConfigurationSource.parseMaxAge("max-age= 1")).isEqualTo(1); assertThat(ApmServerConfigurationSource.parseMaxAge("max-age =1")).isEqualTo(1); assertThat(ApmServerConfigurationSource.parseMaxAge("max-age = 1")).isEqualTo(1); assertThat(ApmServerConfigurationSource.parseMaxAge("public, max-age = 42")).isEqualTo(42); assertThat(ApmServerConfigurationSource.parseMaxAge("max-age= 42 , public")).isEqualTo(42); assertThat(ApmServerConfigurationSource.parseMaxAge("public")).isNull(); assertThat(ApmServerConfigurationSource.parseMaxAge(null)).isNull(); } |
### Question:
TailableFile implements Closeable { private void restoreState(Properties state) throws IOException { long position = Long.parseLong(state.getProperty("position", "0")); long creationTime = Long.parseLong(state.getProperty("creationTime", Long.toString(getCreationTime(file.toPath())))); long inode = Long.parseLong(state.getProperty("inode", Long.toString(getInode(file.toPath())))); if (hasRotated(creationTime, inode)) { openRotatedFile(position, creationTime, inode); } else { openExistingFile(position, file.toPath()); } } TailableFile(File file); void deleteStateFileOnExit(); void ack(); void nak(); int tail(ByteBuffer buffer, FileChangeListener listener, int maxLines); @Override void close(); File getFile(); @Override String toString(); }### Answer:
@Test void testRestoreState() throws Exception { tailableFile.tail(buffy, logListener, 1); assertThat(logListener.lines).hasSize(1); assertThat(logListener.lines.get(0)).isEqualTo("foo"); tailableFile.ack(); tailableFile.close(); setUp(); tailableFile.tail(buffy, logListener, 1); assertThat(logListener.lines).hasSize(2); assertThat(logListener.lines.get(1)).isEqualTo("bar"); } |
### Question:
PrefixingConfigurationSourceWrapper implements ConfigurationSource { @Override public String getValue(String key) { return delegate.getValue(prefix + key); } PrefixingConfigurationSourceWrapper(ConfigurationSource delegate, String prefix); @Override String getValue(String key); @Override void reload(); @Override String getName(); @Override boolean isSavingPossible(); @Override boolean isSavingPersistent(); @Override void save(String key, String value); }### Answer:
@Test void getValue() { System.setProperty("elastic.apm.foo", "bar"); assertThat(sourceWrapper.getValue("foo")).isEqualTo("bar"); } |
### Question:
TailableFile implements Closeable { static boolean skipUntil(ByteBuffer bytes, byte b) { while (bytes.hasRemaining()) { if (bytes.get() == b) { return true; } } return false; } TailableFile(File file); void deleteStateFileOnExit(); void ack(); void nak(); int tail(ByteBuffer buffer, FileChangeListener listener, int maxLines); @Override void close(); File getFile(); @Override String toString(); }### Answer:
@Test void testIndexOfNewLine() { ByteBuffer buffer = ByteBuffer.wrap(new byte[]{'c', 'a', 'f', 'e', '\n', 'b', 'a', 'b', 'e', '\r', '\n'}); assertThat(TailableFile.skipUntil(buffer, (byte) '\n')).isTrue(); assertThat(buffer.position()).isEqualTo(5); assertThat(TailableFile.skipUntil(buffer, (byte) '\n')).isTrue(); assertThat(buffer.position()).isEqualTo(11); assertThat(TailableFile.skipUntil(buffer, (byte) '\n')).isFalse(); } |
### Question:
ProcessHelper { void doEndProcess(Process process, boolean checkTerminatedProcess) { boolean terminated = !checkTerminatedProcess; if (checkTerminatedProcess) { try { process.exitValue(); terminated = true; } catch (IllegalThreadStateException e) { terminated = false; } } if (terminated) { Span span = inFlightSpans.remove(process); if (span != null) { span.end(); } } } ProcessHelper(WeakConcurrentMap<Process, Span> inFlightSpans); }### Answer:
@Test void endUntrackedProcess() { Process process = mock(Process.class); helper.doEndProcess(process, true); } |
### Question:
AsyncProfiler { public static AsyncProfiler getInstance(String profilerLibDirectory) { AsyncProfiler result = AsyncProfiler.instance; if (result != null) { return result; } synchronized (AsyncProfiler.class) { if (instance == null) { try { loadNativeLibrary(profilerLibDirectory); } catch (UnsatisfiedLinkError e) { throw new IllegalStateException(String.format("It is likely that %s is not an executable location. Consider setting " + "the profiling_inferred_spans_lib_directory property to a directory on a partition that allows execution", profilerLibDirectory), e); } instance = new AsyncProfiler(); } return instance; } } private AsyncProfiler(); static AsyncProfiler getInstance(String profilerLibDirectory); void stop(); String execute(String command); void enableProfilingThread(Thread thread); void disableProfilingThread(Thread thread); void enableProfilingCurrentThread(); void disableProfilingCurrentThread(); }### Answer:
@Test void testShouldCopyLibToTempDirectory() { String defaultTempDirectory = System.getProperty("java.io.tmpdir"); AsyncProfiler.getInstance(defaultTempDirectory); File libDirectory = new File(defaultTempDirectory); File[] libasyncProfilers = libDirectory.listFiles(getLibasyncProfilerFilenameFilter()); assertThat(libasyncProfilers).hasSizeGreaterThanOrEqualTo(1); }
@Test void testShouldCopyLibToSpecifiedDirectory(@TempDir File nonDefaultTempDirectory) { AsyncProfiler.getInstance(nonDefaultTempDirectory.getAbsolutePath()); File[] libasyncProfilers = nonDefaultTempDirectory.listFiles(getLibasyncProfilerFilenameFilter()); assertThat(libasyncProfilers).hasSizeGreaterThanOrEqualTo(1); } |
### Question:
ThreadMatcher { public <S1, S2> void forEachThread(NonCapturingPredicate<Thread, S1> predicate, S1 state1, NonCapturingConsumer<Thread, S2> consumer, S2 state2) { int count = systemThreadGroup.activeCount(); do { int expectedArrayLength = count + (count / 2) + 1; if (threads.length < expectedArrayLength) { threads = new Thread[expectedArrayLength]; } count = systemThreadGroup.enumerate(threads, true); } while (count >= threads.length); for (int i = 0; i < count; i++) { Thread thread = threads[i]; if (predicate.test(thread, state1)) { consumer.accept(thread, state2); } threads[i] = null; } } ThreadMatcher(); void forEachThread(NonCapturingPredicate<Thread, S1> predicate, S1 state1, NonCapturingConsumer<Thread, S2> consumer, S2 state2); }### Answer:
@Test void testLookup() { ArrayList<Thread> threads = new ArrayList<>(); threadMatcher.forEachThread(new ThreadMatcher.NonCapturingPredicate<Thread, Void>() { @Override public boolean test(Thread thread, Void state) { return thread.getId() == Thread.currentThread().getId(); } }, null, new ThreadMatcher.NonCapturingConsumer<Thread, List<Thread>>() { @Override public void accept(Thread thread, List<Thread> state) { state.add(thread); } }, threads); assertThat(threads).isEqualTo(List.of(Thread.currentThread())); } |
### Question:
MicrometerMetricsReporter implements Runnable { public void registerMeterRegistry(MeterRegistry meterRegistry) { if (meterRegistry instanceof CompositeMeterRegistry) { return; } boolean added = meterRegistries.add(meterRegistry); if (added) { logger.info("Registering Micrometer MeterRegistry: {}", meterRegistry); scheduleReporting(); } } MicrometerMetricsReporter(ElasticApmTracer tracer); void registerMeterRegistry(MeterRegistry meterRegistry); @Override void run(); }### Answer:
@Test void testCounterReset() { MockClock clock = new MockClock(); meterRegistry = new SimpleMeterRegistry(new SimpleConfig() { @Override public CountingMode mode() { return CountingMode.STEP; } @Override public Duration step() { return Duration.ofSeconds(30); } @Override public String get(@Nonnull String key) { return null; } }, clock); metricsReporter.registerMeterRegistry(meterRegistry); meterRegistry.counter("counter").increment(); clock.addSeconds(30); assertThat(getSingleMetricSet().get("metricset").get("samples").get("counter").get("value").doubleValue()).isEqualTo(1); clock.addSeconds(30); assertThat(getSingleMetricSet().get("metricset").get("samples").get("counter").get("value").doubleValue()).isEqualTo(0); } |
### Question:
ElasticApmAttacher { static String md5Hash(InputStream resourceAsStream) throws IOException, NoSuchAlgorithmException { try (InputStream agentJar = resourceAsStream) { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] buffer = new byte[1024]; DigestInputStream dis = new DigestInputStream(agentJar, md); while (dis.read(buffer) != -1) {} return String.format("%032x", new BigInteger(1, md.digest())); } } static void attach(); static void attach(String propertiesLocation); static void attach(Map<String, String> configuration); static void attach(String pid, Map<String, String> configuration); @Deprecated static void attach(String pid, String agentArgs); }### Answer:
@Test void testHash() throws Exception { assertThat(ElasticApmAttacher.md5Hash(getClass().getResourceAsStream(ElasticApmAttacher.class.getSimpleName() + ".class"))) .isEqualTo(DigestUtils.md5Hex(getClass().getResourceAsStream(ElasticApmAttacher.class.getSimpleName() + ".class"))); } |
### Question:
ElasticApmAttacher { static File createTempProperties(Map<String, String> configuration) { File tempFile = null; if (!configuration.isEmpty()) { Properties properties = new Properties(); properties.putAll(configuration); try { tempFile = File.createTempFile("elstcapm", ".tmp"); try (FileOutputStream outputStream = new FileOutputStream(tempFile)) { properties.store(outputStream, null); } } catch (IOException e) { e.printStackTrace(); } } return tempFile; } static void attach(); static void attach(String propertiesLocation); static void attach(Map<String, String> configuration); static void attach(String pid, Map<String, String> configuration); @Deprecated static void attach(String pid, String agentArgs); }### Answer:
@Test void testCreateTempProperties() throws Exception { File tempProperties = ElasticApmAttacher.createTempProperties(Map.of("foo", "bär")); assertThat(tempProperties).isNotNull(); tempProperties.deleteOnExit(); Properties properties = new Properties(); properties.load(new FileReader(tempProperties)); assertThat(properties.get("foo")).isEqualTo("bär"); } |
### Question:
CallDepth { public int decrement() { int depth = get() - 1; set(depth); assert depth >= 0; return depth; } private CallDepth(); static CallDepth get(Class<?> adviceClass); int increment(); boolean isNestedCallAndIncrement(); int decrement(); boolean isNestedCallAndDecrement(); }### Answer:
@Test void testNegativeCount() { assertThatThrownBy(() -> callDepth.decrement()).isInstanceOf(AssertionError.class); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.