src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
FullTextSearch { public SearchTree search(SearchRequest searchRequest) { if(!searchAdapter.isEngineRunning()) { throw new SearchEngineNotRunningException(); } SearchResults searchResults; try { searchResults = searchAdapter.searchData(searchRequest); } catch (Throwable t) { throw new SearchFailedException(t); } return new SearchTree(searchResults, searchRequest); } FullTextSearch(); FullTextSearch(final SearchAdapter search); boolean isEngineRunning(); String getEndpoint(); boolean isSearchEngineEndpointConfigured(); SearchTree search(SearchRequest searchRequest); void indexUseCases(final UseCaseScenariosList useCaseScenariosList, final BuildIdentifier buildIdentifier); void indexSteps(final List<Step> steps, final List<StepLink> stepLinkList, final Scenario scenario, final UseCase usecase, final BuildIdentifier buildIdentifier); void updateAvailableBuilds(final List<BuildImportSummary> availableBuilds); static final String STEP; static final String SCENARIO; static final String USECASE; }
@Test void searchWithoutRunningEngine() { givenNoRunningEngine(); assertThrows(SearchEngineNotRunningException.class, ()->fullTextSearch.search(new SearchRequest(new BuildIdentifier("testBranch", "testBuild"), "hi", true))); } @Test void searchWithNoResults() { givenRunningEngineWithSearchResults(); SearchTree result = fullTextSearch.search(new SearchRequest(new BuildIdentifier("testBranch", "testBuild"), "IDONOTEXIST", true)); assertEquals(0, result.getResults().getChildren().size()); assertEquals(0, result.getTotalHits()); }
FullTextSearch { public void updateAvailableBuilds(final List<BuildImportSummary> availableBuilds) { if(!searchAdapter.isEngineRunning()) { return; } List<BuildIdentifier> existingBuilds = getAvailableBuildIdentifiers(availableBuilds); searchAdapter.updateAvailableBuilds(existingBuilds); LOGGER.info("Updated available builds."); } FullTextSearch(); FullTextSearch(final SearchAdapter search); boolean isEngineRunning(); String getEndpoint(); boolean isSearchEngineEndpointConfigured(); SearchTree search(SearchRequest searchRequest); void indexUseCases(final UseCaseScenariosList useCaseScenariosList, final BuildIdentifier buildIdentifier); void indexSteps(final List<Step> steps, final List<StepLink> stepLinkList, final Scenario scenario, final UseCase usecase, final BuildIdentifier buildIdentifier); void updateAvailableBuilds(final List<BuildImportSummary> availableBuilds); static final String STEP; static final String SCENARIO; static final String USECASE; }
@Test void updateAvailableBuildsWithoutRunningEngine() { givenNoRunningEngine(); fullTextSearch.updateAvailableBuilds(Collections.emptyList()); thenJustReturns(); }
SearchTree { public ObjectTreeNode<ObjectReference> getResults() { return results; } SearchTree(SearchResults searchResults, SearchRequest searchRequest); static SearchTree empty(); ObjectTreeNode<ObjectReference> getResults(); long getHits(); long getTotalHits(); SearchRequest getSearchRequest(); }
@Test void treeWithASingleStep() { SearchTree searchTree = givenSearchTreeWithSingleStep(); ObjectTreeNode<ObjectReference> objectTree = searchTree.getResults(); thenHasNodes(objectTree, "Use Case 1", "Scenario 1", "Page 1/3/2"); }
ScenariooValidator { public boolean validate() throws InterruptedException { cleanDerivedFilesIfRequested(); Map<BuildIdentifier, BuildImportSummary> buildImportSummaries = validationBuildImporter.importBuildsAndWaitForExecutor(); return evaluateSummaries(buildImportSummaries); } ScenariooValidator(File docuDirectory, boolean doCleanDerivedFiles); boolean validate(); }
@Test void validation_successful_with_own_example_docu(@TempDir File testDirectory) throws InterruptedException, IOException { File docuDirectory = new File("../scenarioo-docu-generation-example/src/test/resources/example/documentation/scenarioDocuExample"); FileUtils.copyDirectory(docuDirectory, testDirectory); boolean result = new ScenariooValidator(testDirectory, true).validate(); assertTrue(result); } @Test void validation_failed_for_invalid_path() { File inexistentDirectory = new File("./this/path/does/not/exist"); assertThrows(IllegalArgumentException.class, () -> new ScenariooValidator(inexistentDirectory, true).validate()); }
StepIdentifier { @JsonIgnore public URI getScreenshotUriForRedirect(final String screenshotFileNameExtension) { return createUriForRedirect(RedirectType.SCREENSHOT, screenshotFileNameExtension); } StepIdentifier(); StepIdentifier(final BuildIdentifier buildIdentifier, final String usecaseName, final String scenarioName, final String pageName, final int pageOccurrence, final int stepInPageOccurrence); StepIdentifier(final BuildIdentifier buildIdentifier, final String usecaseName, final String scenarioName, final String pageName, final int pageOccurrence, final int stepInPageOccurrence, final Set<String> labels); StepIdentifier(final ScenarioIdentifier scenarioIdentifier, final String pageName, final int pageOccurrence, final int stepInPageOccurrence); StepIdentifier(final ScenarioIdentifier scenarioIdentifier, final String pageName, final int pageOccurrence, final int stepInPageOccurrence, final Set<String> labels); static StepIdentifier withDifferentStepInPageOccurrence(final StepIdentifier stepIdentifier, final int stepInPageOccurrence); static StepIdentifier withDifferentIds(final StepIdentifier stepIdentifier, final int pageOccurrence, final int stepInPageOccurrence); static StepIdentifier forFallBackScenario(final StepIdentifier originalStepIdentifier, final String fallbackUsecaseName, final String fallbackScenarioName, final int pageOccurrence, final int stepInPageOccurrence); StepIdentifier withDifferentBuildIdentifier(final BuildIdentifier buildIdentifierBeforeAliasResolution); @JsonIgnore BuildIdentifier getBuildIdentifier(); @JsonIgnore ScenarioIdentifier getScenarioIdentifier(); @JsonIgnore void setScenarioIdentifier(final ScenarioIdentifier scenarioIdentifier); @XmlElement String getBranchName(); void setBranchName(final String branchName); @XmlElement String getBuildName(); void setBuildName(final String buildName); @XmlElement String getUsecaseName(); void setUsecaseName(final String usecaseName); @XmlElement String getScenarioName(); void setScenarioName(final String scenarioName); String getPageName(); void setPageName(final String pageName); int getPageOccurrence(); void setPageOccurrence(final int pageOccurrence); int getStepInPageOccurrence(); void setStepInPageOccurrence(final int stepInPageOccurrence); Set<String> getLabels(); void setLabels(final Set<String> labels); @JsonIgnore URI getScreenshotUriForRedirect(final String screenshotFileNameExtension); @JsonIgnore URI getStepUriForRedirect(); @Override String toString(); }
@Test public void redirectUrlForScreenshot() { assertEquals( "/scenarioo/rest/branch/bugfix-branch/build/build-2014-08-12/usecase/Find the answer/scenario/Actually find it/pageName/pageName1/pageOccurrence/0/stepInPageOccurrence/0/image.jpeg", stepIdentifier.getScreenshotUriForRedirect("jpeg").getPath()); assertEquals("fallback=true", stepIdentifier.getScreenshotUriForRedirect(".jpeg").getQuery()); }
DateUtil { public static boolean isDate(String date) { return isDate(date, PATTERN_HAVE_TIME); } static boolean isDate(String date); static boolean isDate(String date, String pattern); static String format(Date date); static String formatTime(Date date); static String format(Date date, String pattern); static String getCurDatetime(); static String getCurDatetime(String pattern); static String getCurDatetime(String pattern, ZoneId zoneId); static Date getCurDate(String date, String pattern); static boolean isSameDay(Date date1, Date date2); static boolean isSameDay(Calendar cal1, Calendar cal2); static Date addYears(Date date, int year); static Date addMonths(Date date, int month); static Date addWeeks(Date date, int amount); static Date addDays(Date date, int amount); static Date addHours(Date date, int amount); static Date addMinutes(Date date, int amount); static Date addSeconds(Date date, int amount); static Date addMilliseconds(Date date, int amount); static int daysBetween(Date date1, Date date2, String pattern); static boolean isWeekEnd(Date date); Date tradingTomorrowDay(Date date, int n); static int daysBetween(Date date1, Date date2); static Long getTimestampDiff(Date time1, Date time2); static long getTimestamp(); static String getAgeByBirthday(Date birthday); static long getAgeByBirthday(String birthday, String pattern); static String getNowUTCTimeStamp(); static String timeZone(Date date); }
@Test void isDate() { System.out.println(DateUtil.isDate("2018-02-29", "yyyy-MM-dd")); }
ModeParser { static void parseOne(final String instruction, final Set<PosixFilePermission> toAdd, final Set<PosixFilePermission> toRemove) { final int plus = instruction.indexOf('+'); final int minus = instruction.indexOf('-'); if (plus < 0 && minus < 0) { throw new RuntimeException("Invalid unix mode expresson: '" + instruction + "'"); } final String who; final String what; final Set<PosixFilePermission> set; if (plus >= 0) { who = plus == 0 ? "ugo" : instruction.substring(0, plus); what = instruction.substring(plus + 1); set = toAdd; } else { who = minus == 0 ? "ugo" : instruction.substring(0, minus); what = instruction.substring(minus + 1); set = toRemove; } if (what.isEmpty()) { throw new RuntimeException("Invalid unix mode expresson: '" + instruction + "'"); } modifySet(who, what, set, instruction); } private ModeParser(); static PermissionsSet buildPermissionsSet(final String instructions); }
@Test @UseDataProvider(value = "invalidModeInstructions") public void invalidModeInstructionThrowsAppropriateException(final String instruction) { final Set<PosixFilePermission> toAdd = EnumSet.noneOf(PosixFilePermission.class); final Set<PosixFilePermission> toRemove = EnumSet.noneOf(PosixFilePermission.class); try { ModeParser.parseOne(instruction, toAdd, toRemove); shouldHaveThrown(RuntimeException.class); } catch (RuntimeException e) { assertThat(e) .isExactlyInstanceOf(RuntimeException.class) .hasMessage(String.format("Invalid unix mode expresson: '%s'", instruction)); } } @Test public void unsupportedModeInstructionThrowsAppropriateException() { final Set<PosixFilePermission> toAdd = EnumSet.noneOf(PosixFilePermission.class); final Set<PosixFilePermission> toRemove = EnumSet.noneOf(PosixFilePermission.class); String instruction; instruction = "u-X"; try { ModeParser.parseOne(instruction, toAdd, toRemove); shouldHaveThrown(UnsupportedOperationException.class); } catch (UnsupportedOperationException e) { assertThat(e) .isExactlyInstanceOf(UnsupportedOperationException.class) .hasMessage(instruction); } instruction = "a+r"; try { ModeParser.parseOne(instruction, toAdd, toRemove); shouldHaveThrown(UnsupportedOperationException.class); } catch (UnsupportedOperationException e) { assertThat(e) .isExactlyInstanceOf(UnsupportedOperationException.class) .hasMessage(instruction); } } @Test @UseDataProvider("validModeInstructions") public void validModeInstructionAddsInstructionsInAppropriateSets( final String instruction, final Set<PosixFilePermission> add, final Set<PosixFilePermission> remove) { final Set<PosixFilePermission> toAdd = EnumSet.noneOf(PosixFilePermission.class); final Set<PosixFilePermission> toRemove = EnumSet.noneOf(PosixFilePermission.class); ModeParser.parseOne(instruction, toAdd, toRemove); assertThat(toAdd).isEqualTo(add); assertThat(toRemove).isEqualTo(remove); }
ModeParser { static void parse(final String instructions, final Set<PosixFilePermission> toAdd, final Set<PosixFilePermission> toRemove) { for (final String instruction : COMMA.split(instructions)) { parseOne(instruction, toAdd, toRemove); } } private ModeParser(); static PermissionsSet buildPermissionsSet(final String instructions); }
@Test @UseDataProvider("multipleInstructions") public void validModeMultipleInstructionAddsInstructionsInAppropriateSets( final String instruction, final Set<PosixFilePermission> add, final Set<PosixFilePermission> remove) { final Set<PosixFilePermission> toAdd = EnumSet.noneOf(PosixFilePermission.class); final Set<PosixFilePermission> toRemove = EnumSet.noneOf(PosixFilePermission.class); ModeParser.parse(instruction, toAdd, toRemove); assertThat(toAdd).isEqualTo(add); assertThat(toRemove).isEqualTo(remove); }
PosixModes { public static Set<PosixFilePermission> intModeToPosix(int intMode) { if ((intMode & INT_MODE_MAX) != intMode) { throw new RuntimeException("Invalid intMode: " + intMode); } final Set<PosixFilePermission> set = EnumSet.noneOf(PosixFilePermission.class); for (int i = 0; i < PERMISSIONS_LENGTH; i++) { if ((intMode & 1) == 1) { set.add(PERMISSIONS[PERMISSIONS_LENGTH - i - 1]); } intMode >>= 1; } return set; } private PosixModes(); static Set<PosixFilePermission> intModeToPosix(int intMode); }
@Test(expected = RuntimeException.class) public void outOfRangeNumberThrowsIllegalArgumentException() { try { PosixModes.intModeToPosix(-1); shouldHaveThrown(IllegalArgumentException.class); } catch (IllegalArgumentException e) { assertThat(e).isExactlyInstanceOf(RuntimeException.class); } try { PosixModes.intModeToPosix(01000); shouldHaveThrown(IllegalArgumentException.class); } catch (IllegalArgumentException e) { assertThat(e).isExactlyInstanceOf(RuntimeException.class); } } @Test @UseDataProvider("intModeTestData") public void translatingToPosixPermissionsWorks(int intMode, String asString) { final Set<PosixFilePermission> expected = PosixFilePermissions.fromString(asString); assertThat(PosixModes.intModeToPosix(intMode)) .as("integer mode is correctly translated") .isEqualTo(expected); }
ProvisioUtils { public static String coordinateToPath(ProvisioArtifact a) { StringBuffer path = new StringBuffer() .append(a.getArtifactId()) .append("-") .append(a.getVersion()); if (a.getClassifier() != null && !a.getClassifier().isEmpty()) { path.append("-") .append(a.getClassifier()); } path.append(".") .append(a.getExtension()); return path.toString(); } static String coordinateToPath(ProvisioArtifact a); }
@Test public void validateCoordinateToPath() { ProvisioArtifact artifact = new ProvisioArtifact("io.prestosql:presto-main:332"); String path = coordinateToPath(artifact); assertEquals("presto-main-332.jar", path); }
ParametricPlane { public Vector getDirectionY() { return directionY; } ParametricPlane(Point3D basePoint, Vector directionX, Vector directionY, Vector normal); ParametricPlane(Point3D basePoint, Vector directionX, Vector directionY); ParametricPlane(Point3D basePoint, Point3D b, Vector normal); ParametricPlane(Point3D basePoint, Point3D b, Point3D c); ParametricPlane(Extrusion e); Point3D getPoint(double x, double y); Point3D getPoint(Point3D point); double[] getParameter(Point3D p); boolean isOnPlane(Point3D p); Point3D getBasePoint(); void setBasePoint(Point3D base); Vector getDirectionX(); void setDirectionX(Vector directionX); Vector getDirectionY(); void setDirectionY(Vector directionY); Vector getNormal(); }
@Test public void directionY() { ParametricPlane p = new ParametricPlane(new Point3D(0, 0, 0), new Point3D(1, 0, 0), new Vector(0, 0, 1)); Vector y = p.getDirectionY(); assertEquals(0.0, y.getX(), DELTA); assertEquals(1.0, y.getY(), DELTA); assertEquals(0.0, y.getZ(), DELTA); } @Test public void directionX() { ParametricPlane p = new ParametricPlane(new Point3D(0, 0, 0), new Point3D(0, 1, 0), new Vector(0, 0, 1)); Vector y = p.getDirectionY(); assertEquals(-1.0, y.getX(), DELTA); assertEquals(0.0, y.getY(), DELTA); assertEquals(0.0, y.getZ(), DELTA); }
ParametricPlane { public Point3D getPoint(double x, double y) { Point3D p = new Point3D(); p.setX(this.base.getX() + (this.directionX.getX() * x) + (this.directionY.getX() * y)); p.setY(this.base.getY() + (this.directionX.getY() * x) + (this.directionY.getY() * y)); p.setZ(this.base.getZ() + (this.directionX.getZ() * x) + (this.directionY.getZ() * y)); return p; } ParametricPlane(Point3D basePoint, Vector directionX, Vector directionY, Vector normal); ParametricPlane(Point3D basePoint, Vector directionX, Vector directionY); ParametricPlane(Point3D basePoint, Point3D b, Vector normal); ParametricPlane(Point3D basePoint, Point3D b, Point3D c); ParametricPlane(Extrusion e); Point3D getPoint(double x, double y); Point3D getPoint(Point3D point); double[] getParameter(Point3D p); boolean isOnPlane(Point3D p); Point3D getBasePoint(); void setBasePoint(Point3D base); Vector getDirectionX(); void setDirectionX(Vector directionX); Vector getDirectionY(); void setDirectionY(Vector directionY); Vector getNormal(); }
@Test public void point1() { ParametricPlane plane = new ParametricPlane(new Point3D(0, 0, 0), new Point3D(1, 0, 0), new Vector(0, 0, 1)); Point3D p = plane.getPoint(2.0, 3.0); assertEquals(2.0, p.getX(), DELTA); assertEquals(3.0, p.getY(), DELTA); assertEquals(0.0, p.getZ(), DELTA); }
ParametricPlane { public double[] getParameter(Point3D p) { double u = 0.0; double v = (this.directionX.getY() * this.directionY.getX()) - (this.directionX.getX() * this.directionY.getY()); if (v != 0.0) { v = ((p.getY() * this.directionY.getX()) - (this.base.getY() * this.directionY.getX()) - (this.directionY.getY() * p.getX()) + (this.base.getX() * this.directionY.getY())) / v; } if (this.directionY.getX() != 0.0) { u = (p.getX() - this.base.getX() - (this.directionX.getX() * v)) / this.directionY.getX(); } else if (this.directionY.getY() != 0.0) { u = (p.getY() - this.base.getY() - (this.directionX.getY() * v)) / this.directionY.getY(); } else if (this.directionY.getY() != 0.0) { u = (p.getZ() - this.base.getZ() - (this.directionX.getZ() * v)) / this.directionY.getZ(); } return new double[] { v, u }; } ParametricPlane(Point3D basePoint, Vector directionX, Vector directionY, Vector normal); ParametricPlane(Point3D basePoint, Vector directionX, Vector directionY); ParametricPlane(Point3D basePoint, Point3D b, Vector normal); ParametricPlane(Point3D basePoint, Point3D b, Point3D c); ParametricPlane(Extrusion e); Point3D getPoint(double x, double y); Point3D getPoint(Point3D point); double[] getParameter(Point3D p); boolean isOnPlane(Point3D p); Point3D getBasePoint(); void setBasePoint(Point3D base); Vector getDirectionX(); void setDirectionX(Vector directionX); Vector getDirectionY(); void setDirectionY(Vector directionY); Vector getNormal(); }
@Test public void parameters() { ParametricPlane plane = new ParametricPlane(new Point3D(0, 0, 0), new Point3D(1, 0, 0), new Vector(0, 0, 1)); Point3D p = new Point3D(2.0, 3.0, 0.0); double[] paras = plane.getParameter(p); assertEquals(2.0, paras[0], DELTA); assertEquals(3.0, paras[1], DELTA); }
ParametricPlane { public boolean isOnPlane(Point3D p) { double[] para = this.getParameter(p); double v = this.base.getZ() + (this.directionX.getZ() * para[0]) + (this.directionY.getZ() * para[1]); if (!(Math.abs((p.getZ() - v)) < MathUtils.DISTANCE_DELTA)) { return false; } v = this.base.getY() + (this.directionX.getY() * para[0]) + (this.directionY.getY() * para[1]); if (!(Math.abs((p.getY() - v)) < MathUtils.DISTANCE_DELTA)) { return false; } v = this.base.getX() + (this.directionX.getX() * para[0]) + (this.directionY.getX() * para[1]); if (!(Math.abs((p.getX() - v)) < MathUtils.DISTANCE_DELTA)) { return false; } return true; } ParametricPlane(Point3D basePoint, Vector directionX, Vector directionY, Vector normal); ParametricPlane(Point3D basePoint, Vector directionX, Vector directionY); ParametricPlane(Point3D basePoint, Point3D b, Vector normal); ParametricPlane(Point3D basePoint, Point3D b, Point3D c); ParametricPlane(Extrusion e); Point3D getPoint(double x, double y); Point3D getPoint(Point3D point); double[] getParameter(Point3D p); boolean isOnPlane(Point3D p); Point3D getBasePoint(); void setBasePoint(Point3D base); Vector getDirectionX(); void setDirectionX(Vector directionX); Vector getDirectionY(); void setDirectionY(Vector directionY); Vector getNormal(); }
@Test public void isOnPlane() { ParametricPlane plane = new ParametricPlane(new Point3D(0, 0, 0), new Point3D(1, 0, 0), new Vector(0, 0, 1)); Point3D p = new Point3D(2.0, 3.0, 0.0); assertTrue(plane.isOnPlane(p)); } @Test public void isNotPlane() { ParametricPlane plane = new ParametricPlane(new Point3D(0, 0, 0), new Point3D(1, 0, 0), new Vector(0, 0, 1)); Point3D p = new Point3D(2.0, 3.0, -0.01); assertFalse(plane.isOnPlane(p)); }
ParametricPlane { public Vector getNormal() { return normal; } ParametricPlane(Point3D basePoint, Vector directionX, Vector directionY, Vector normal); ParametricPlane(Point3D basePoint, Vector directionX, Vector directionY); ParametricPlane(Point3D basePoint, Point3D b, Vector normal); ParametricPlane(Point3D basePoint, Point3D b, Point3D c); ParametricPlane(Extrusion e); Point3D getPoint(double x, double y); Point3D getPoint(Point3D point); double[] getParameter(Point3D p); boolean isOnPlane(Point3D p); Point3D getBasePoint(); void setBasePoint(Point3D base); Vector getDirectionX(); void setDirectionX(Vector directionX); Vector getDirectionY(); void setDirectionY(Vector directionY); Vector getNormal(); }
@Test public void normal() { ParametricPlane plane = new ParametricPlane(new Point3D(0, 0, 0), new Point3D(1, 0, 0), new Point3D(1.0, DELTA, 0)); Vector n = plane.getNormal(); assertEquals(0.0, n.getX(), DELTA); assertEquals(0.0, n.getY(), DELTA); assertEquals(1.0, n.getZ(), DELTA); }
NURBS { public double[] getBasicFunctions(int i, double u) { double[] n = new double[degree + 1]; n[0] = 1.0; double[] left = new double[degree + 1]; double[] right = new double[degree + 1]; for (int j = 1; j <= degree; j++) { left[j] = u - this.knots[(i + 1) - j]; right[j] = this.knots[i + j] - u; double saved = 0.0; for (int r = 0; r < j; r++) { double t = n[r] / (right[r + 1] + left[j - r]); n[r] = saved + (right[r + 1] * t); saved = left[j - r] * t; } n[j] = saved; } return n; } NURBS(Point3D[] controlPoints, double[] knots, double[] weights, int degree); double[] getBasicFunctions(int i, double u); Point3D getPointAt(int i, double u); Point3D getPointAt(double u); int findSpawnIndex(double u); Point3D[] getControlPoints(); void setControlPoints(Point3D[] controlPoints); double[] getKnots(); void setKnots(double[] knots); double[] getWeights(); void setWeights(double[] weights); int getDegree(); void setDegree(int degree); boolean isClosed(); void setClosed(boolean closed); }
@Test public void baseFunctions1() { Point3D[] points = new Point3D[]{}; double[] knots = new double[]{0, 0, 0, 1, 2, 3, 4, 4, 5, 5}; double[] w = new double[]{}; NURBS n = new NURBS(points, knots, w, 2); double[] bf = n.getBasicFunctions(4, 2.5); assertEquals(3, bf.length); assertEquals(1.0 / 8.0, bf[0], DELTA); assertEquals(6.0 / 8.0, bf[1], DELTA); assertEquals(1.0 / 8.0, bf[2], DELTA); }
ExportServer { public static void init(String[] args) throws Exception { Map<String, BiConsumer<ChannelHandlerContext, HttpRequest>> mapping = new HashMap<>(); mapping.put(HEALTH, (channelHandlerContext, request) -> { ExportResult result = SyncerHealth.export(); String json = result.getJson(); Health.HealthStatus overall = result.getOverall(); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, overall == Health.HealthStatus.GREEN ? HttpResponseStatus.OK : HttpResponseStatus.INTERNAL_SERVER_ERROR, Unpooled.wrappedBuffer(json.getBytes())); response.headers().set(CONTENT_TYPE, TEXT_PLAIN); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); channelHandlerContext.write(response); }); ChannelInitializer<SocketChannel> initializer = new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ChannelPipeline p = ch.pipeline(); p.addLast(new LoggingHandler(LogLevel.INFO)); p.addLast(new HttpServerCodec()); p.addLast(new DispatchHandler(mapping)); } }; int port = PORT; HashMap<String, String> kvMap = ArgUtil.toMap(args); String cmdPort = kvMap.get("port"); if (cmdPort != null) { port = Integer.parseUnsignedInt(cmdPort); } NettyServer.startAndSync(initializer, port); } static void init(String[] args); }
@Test public void init() throws UnknownHostException, InterruptedException { HttpConnection connection = new HttpConnection(); connection.setAddress("localhost"); connection.setPort(PORT); connection.setPath(ExportServer.HEALTH); NettyHttpClient nettyClient = new NettyHttpClient(connection, new HttpClientInitializer()); nettyClient.write(HttpMethod.GET, ExportServer.HEALTH, ""); System.out.println(); }
BinlogDataId implements DataId { public String eventId() { return new StringBuilder(COMMON_LEN) .append(binlogFileName).append(SEP) .append(tableMapPos).append(SEP) .append(dataPos - tableMapPos) .toString(); } BinlogDataId(String binlogFileName, long tableMapPos, long dataPos); BinlogDataId setOrdinal(int ordinal); BinlogDataId setOffset(Integer offset); String eventId(); String dataId(); @Override boolean equals(Object o); @Override int hashCode(); @Override SyncInitMeta getSyncInitMeta(); @Override int compareTo(DataId dataId); BinlogDataId copyAndSetOrdinal(int ordinal); BinlogDataId copyAndSetOffset(int offset); @Override String toString(); }
@Test public void eventId() { }
BinlogDataId implements DataId { public String dataId() { StringBuilder append = new StringBuilder(COMMON_LEN).append(eventId()).append(SEP).append(ordinal); if (offset != null) { return append.append(SEP).append(offset).toString(); } else { return append.toString(); } } BinlogDataId(String binlogFileName, long tableMapPos, long dataPos); BinlogDataId setOrdinal(int ordinal); BinlogDataId setOffset(Integer offset); String eventId(); String dataId(); @Override boolean equals(Object o); @Override int hashCode(); @Override SyncInitMeta getSyncInitMeta(); @Override int compareTo(DataId dataId); BinlogDataId copyAndSetOrdinal(int ordinal); BinlogDataId copyAndSetOffset(int offset); @Override String toString(); }
@Test public void dataId() { }
BinlogDataId implements DataId { @Override public int compareTo(DataId dataId) { BinlogDataId o = (BinlogDataId) dataId; int cmp = getSyncInitMeta().compareTo(o.getSyncInitMeta()); if (cmp != 0) { return cmp; } cmp = Long.compare(tableMapPos, o.tableMapPos); if (cmp != 0) { return cmp; } cmp = Long.compare(dataPos, o.dataPos); if (cmp != 0) { return cmp; } cmp = Integer.compare(ordinal, o.ordinal); if (cmp != 0) { return cmp; } return Objects.equals(offset, o.offset) ? 0 : offset == null ? -1 : o.offset == null ? 1 : Objects.compare(offset, o.offset, Comparator.naturalOrder()); } BinlogDataId(String binlogFileName, long tableMapPos, long dataPos); BinlogDataId setOrdinal(int ordinal); BinlogDataId setOffset(Integer offset); String eventId(); String dataId(); @Override boolean equals(Object o); @Override int hashCode(); @Override SyncInitMeta getSyncInitMeta(); @Override int compareTo(DataId dataId); BinlogDataId copyAndSetOrdinal(int ordinal); BinlogDataId copyAndSetOffset(int offset); @Override String toString(); }
@Test public void compareTo() { BinlogDataId _0 = new BinlogDataId("mysql-bin.000117", 4, 40).setOrdinal(0).setOffset(null); BinlogDataId _00 = new BinlogDataId("mysql-bin.000117", 4, 40).setOrdinal(0).setOffset(0); BinlogDataId _1 = new BinlogDataId("mysql-bin.000117", 4, 40).setOrdinal(1).setOffset(null); BinlogDataId _14 = new BinlogDataId("mysql-bin.000117", 14, 40).setOrdinal(0).setOffset(null); BinlogDataId _118 = new BinlogDataId("mysql-bin.000118", 4, 40).setOrdinal(1).setOffset(null); Assert.assertEquals(-1, _0.compareTo(_00)); Assert.assertEquals(1, _00.compareTo(_0)); Assert.assertEquals(-1, _0.compareTo(_1)); Assert.assertEquals(-1, _00.compareTo(_1)); Assert.assertEquals(-1, _00.compareTo(_14)); Assert.assertEquals(-1, _1.compareTo(_14)); Assert.assertEquals(-1, _0.compareTo(_118)); Assert.assertEquals(-1, _1.compareTo(_118)); Assert.assertEquals(-1, _00.compareTo(_118)); Assert.assertEquals(-1, _14.compareTo(_118)); Assert.assertEquals(0, _0.compareTo(_0)); Assert.assertEquals(0, _00.compareTo(_00)); }
SyncData implements com.github.zzt93.syncer.data.SyncData, Serializable { public void recycleParseContext(ThreadLocal<StandardEvaluationContext> contexts) { inner.context = null; } SyncData(DataId dataId, SimpleEventType type, String database, String entity, String primaryKeyName, Object id, NamedChange row); private SyncData(DataId dataId, SimpleEventType type, String database, String entity, String primaryKeyName, Object id, HashMap<String, Object> full, HashMap<String, Object> beforeFull, Set<String> updated); SyncData(SyncData syncData, int offset); @Override Object getId(); @Override SyncData setId(Object id); @Override String getEntity(); @Override SyncData setEntity(String entity); @Override boolean isWrite(); @Override boolean isUpdate(); @Override boolean isDelete(); @Override SyncData toWrite(); @Override SyncData toUpdate(); @Override SyncData toDelete(); @Override String getRepo(); @Override SyncData setRepo(String repo); @Override Object getExtra(String key); @Override com.github.zzt93.syncer.data.SyncData copyMeta(int index); @Override boolean updated(); @Override boolean updated(String key); @Override Set<String> getUpdated(); @Override Object getBefore(String key); @Override HashMap<String, Object> getBefore(); @Override SyncData addExtra(String key, Object value); SyncData addField(String key, Object value); @Override SyncData setFieldNull(String key); SyncData renameField(String oldKey, String newKey); Object removeField(String key); boolean removePrimaryKey(); SyncData removeFields(String... keys); boolean containField(String key); SyncData updateField(String key, Object value); StandardEvaluationContext getContext(); void setContext(StandardEvaluationContext context); void recycleParseContext(ThreadLocal<StandardEvaluationContext> contexts); @Override HashMap<String, Object> getFields(); @Override HashMap<String, Object> getExtras(); Object getField(String key); @Override Long getFieldAsLong(String key); @Override Integer getFieldAInt(String key); String getEventId(); DataId getDataId(); String getSourceIdentifier(); SyncData setSourceIdentifier(String identifier); HashMap<String, Object> getSyncBy(); SyncByQuery syncByQuery(); ESScriptUpdate esScriptUpdate(); @Override ESScriptUpdate esScriptUpdate(String script, Map<String, Object> params); @Override ESScriptUpdate esScriptUpdate(Filter docFilter); ESScriptUpdate getEsScriptUpdate(); ExtraQuery extraQuery(String indexName, String typeName); ExtraQueryContext getExtraQueryContext(); boolean hasExtra(); SimpleEventType getType(); SyncResult getResult(); SyncData copy(); Long getPartitionId(); void setPartitionField(String fieldName); }
@Test public void testToStringDefault() { SyncData write = SyncDataTestUtil.write("test", "test"); assertEquals("SyncData(inner=Meta{dataId=mysql-bin.00001/4/6/0, context=true, connectionIdentifier='null'}, syncByQuery=null, esScriptUpdate=null, result=SyncResult(super=SyncResultBase(super=SyncMeta(eventType=WRITE, repo=test, entity=test, id=1234, primaryKeyName=id), fields={}, extras=null, before=null)), updated=null, partitionField=null, extraQueryContext=null)", write.toString()); write.recycleParseContext(null); assertEquals("SyncData(inner=Meta{dataId=mysql-bin.00001/4/6/0, context=null, connectionIdentifier='null'}, syncByQuery=null, esScriptUpdate=null, result=SyncResult(super=SyncResultBase(super=SyncMeta(eventType=WRITE, repo=test, entity=test, id=1234, primaryKeyName=id), fields={}, extras=null, before=null)), updated=null, partitionField=null, extraQueryContext=null)", write.toString()); }
SyncData implements com.github.zzt93.syncer.data.SyncData, Serializable { @Override public boolean updated() { return updated != null; } SyncData(DataId dataId, SimpleEventType type, String database, String entity, String primaryKeyName, Object id, NamedChange row); private SyncData(DataId dataId, SimpleEventType type, String database, String entity, String primaryKeyName, Object id, HashMap<String, Object> full, HashMap<String, Object> beforeFull, Set<String> updated); SyncData(SyncData syncData, int offset); @Override Object getId(); @Override SyncData setId(Object id); @Override String getEntity(); @Override SyncData setEntity(String entity); @Override boolean isWrite(); @Override boolean isUpdate(); @Override boolean isDelete(); @Override SyncData toWrite(); @Override SyncData toUpdate(); @Override SyncData toDelete(); @Override String getRepo(); @Override SyncData setRepo(String repo); @Override Object getExtra(String key); @Override com.github.zzt93.syncer.data.SyncData copyMeta(int index); @Override boolean updated(); @Override boolean updated(String key); @Override Set<String> getUpdated(); @Override Object getBefore(String key); @Override HashMap<String, Object> getBefore(); @Override SyncData addExtra(String key, Object value); SyncData addField(String key, Object value); @Override SyncData setFieldNull(String key); SyncData renameField(String oldKey, String newKey); Object removeField(String key); boolean removePrimaryKey(); SyncData removeFields(String... keys); boolean containField(String key); SyncData updateField(String key, Object value); StandardEvaluationContext getContext(); void setContext(StandardEvaluationContext context); void recycleParseContext(ThreadLocal<StandardEvaluationContext> contexts); @Override HashMap<String, Object> getFields(); @Override HashMap<String, Object> getExtras(); Object getField(String key); @Override Long getFieldAsLong(String key); @Override Integer getFieldAInt(String key); String getEventId(); DataId getDataId(); String getSourceIdentifier(); SyncData setSourceIdentifier(String identifier); HashMap<String, Object> getSyncBy(); SyncByQuery syncByQuery(); ESScriptUpdate esScriptUpdate(); @Override ESScriptUpdate esScriptUpdate(String script, Map<String, Object> params); @Override ESScriptUpdate esScriptUpdate(Filter docFilter); ESScriptUpdate getEsScriptUpdate(); ExtraQuery extraQuery(String indexName, String typeName); ExtraQueryContext getExtraQueryContext(); boolean hasExtra(); SimpleEventType getType(); SyncResult getResult(); SyncData copy(); Long getPartitionId(); void setPartitionField(String fieldName); }
@Test public void testUpdated() { HashMap<String, Object> before = new HashMap<>(); before.put("1", 1); before.put("2", "22"); before.put("3", "33".getBytes()); before.put("4", 4L); before.put("5", new Timestamp(System.currentTimeMillis())); before.put("6", "中文".getBytes(StandardCharsets.UTF_8)); before.put("7", "中文".getBytes(StandardCharsets.UTF_8)); before.put("8", 1.1); before.put("9", new BigDecimal("10000.1")); before.put("10", new BigDecimal("10000.1")); before.put("11", new Date(System.currentTimeMillis())); HashMap<String, Object> now = new HashMap<>(); now.put("1", 1); now.put("2", "2"); now.put("3", "3".getBytes()); now.put("4", 4L); now.put("5", new Timestamp(System.currentTimeMillis() + 1000)); now.put("6", "中文".getBytes(StandardCharsets.UTF_8)); now.put("7", "中文啊".getBytes(StandardCharsets.UTF_8)); now.put("8", 1.10); now.put("9", new BigDecimal("10000.10001")); now.put("10", new BigDecimal("10000.10000")); now.put("11", new Date(System.currentTimeMillis() + _1D)); NamedFullRow row = new NamedFullRow(now).setBeforeFull(before); SyncData data = new SyncData(new BinlogDataId("mysql-bin.00001", 4, 10), SimpleEventType.UPDATE, "test", "test", "id", 1L, row); assertTrue(data.updated()); assertTrue(!data.updated("1")); assertTrue(data.updated("2")); assertTrue(data.updated("3")); assertTrue(!data.updated("4")); assertTrue(data.updated("5")); assertTrue(!data.updated("6")); assertTrue(data.updated("7")); assertTrue(!data.updated("8")); assertTrue(data.updated("9")); assertTrue(data.updated("10")); assertTrue(data.updated("11")); }
SQLHelper { public static AlterMeta alterMeta(String database, String sql) { String alterTarget = isAlter(sql); if (alterTarget != null) { alterTarget = alterTarget.replaceAll("`|\\s", ""); if (!StringUtils.isEmpty(database)) { return new AlterMeta(database, alterTarget); } String[] split = alterTarget.split("\\."); assert split.length == 2; return new AlterMeta(split[0], split[1]); } return null; } static String inSQL(Object value); static String wrapCol(String col); static AlterMeta alterMeta(String database, String sql); }
@Test public void alterMeta() { AlterMeta test = SQLHelper.alterMeta(TEST, "alter table xx add yy int null after zz"); assertNotNull(test); assertEquals("", TEST, test.getSchema()); assertEquals("", XX, test.getTable()); test = SQLHelper.alterMeta("", "alter table test.xx add yy int null after zz"); assertNotNull(test); assertEquals("", TEST, test.getSchema()); assertEquals("", XX, test.getTable()); test = SQLHelper.alterMeta(TEST, "alter table xx drop column yy"); assertNotNull(test); assertEquals("", TEST, test.getSchema()); assertEquals("", XX, test.getTable()); test = SQLHelper.alterMeta("", "alter table test.xx drop column yy"); assertNotNull(test); assertEquals("", TEST, test.getSchema()); assertEquals("", XX, test.getTable()); test = SQLHelper.alterMeta(TEST, "alter table xx modify column yy int after zz"); assertNotNull(test); assertEquals("", TEST, test.getSchema()); assertEquals("", XX, test.getTable()); test = SQLHelper.alterMeta("", "alter table test.xx modify column yy int after zz"); assertNotNull(test); assertEquals("", TEST, test.getSchema()); assertEquals("", XX, test.getTable()); test = SQLHelper.alterMeta("", "alter table `test`.`xx` modify column `yy` int after `zz`"); assertNotNull(test); assertEquals("", TEST, test.getSchema()); assertEquals("", XX, test.getTable()); test = SQLHelper.alterMeta("", "alter table `test`\n.`xx`\n modify column `yy` int after `zz`"); assertNotNull(test); assertEquals("", TEST, test.getSchema()); assertEquals("", XX, test.getTable()); test = SQLHelper.alterMeta(TEST, "alter table xx add yy int null"); assertNull(test); test = SQLHelper.alterMeta("", "alter table test.xx add yy int null"); assertNull(test); }
RegexUtil { public static Pattern env() { return env; } static Pattern getRegex(String input); static Pattern env(); static boolean isClassName(String consumerId); }
@Test public void env() throws Exception { Pattern env = RegexUtil.env(); Matcher m1 = env.matcher(" - name: \"menkor_${ACTIVE_PROFILE}.*\""); Assert.assertTrue(m1.find()); String group0 = m1.group(0); String group1 = m1.group(1); Assert.assertEquals("", "${ACTIVE_PROFILE}", group0); Assert.assertEquals("", "ACTIVE_PROFILE", group1); }
RegexUtil { public static Pattern getRegex(String input) { Matcher matcher = pattern.matcher(input); if (!matcher.find()) { return null; } try { return Pattern.compile(input); } catch (PatternSyntaxException e) { return null; } } static Pattern getRegex(String input); static Pattern env(); static boolean isClassName(String consumerId); }
@Test public void getRegex() throws Exception { Pattern simple = RegexUtil.getRegex("simple"); Assert.assertNull(simple); Pattern star = RegexUtil.getRegex("dev.*"); Assert.assertNotNull(star); }
JavaMethod { public static SyncFilter build(String consumerId, SyncerFilterMeta filterMeta, String method) { String source = "import com.github.zzt93.syncer.data.*;\n" + "import com.github.zzt93.syncer.data.util.*;\n" + "import java.util.*;\n" + "import java.math.BigDecimal;\n" + "import java.sql.Timestamp;\n" + "import org.slf4j.Logger;\n" + "import org.slf4j.LoggerFactory;\n" + "\n" + "public class MethodFilterTemplate implements SyncFilter<SyncData> {\n" + "\n" + " private final Logger logger = LoggerFactory.getLogger(getClass());\n" + "\n" + addNewline(method) + "\n" + "}\n"; String className = "Filter" + consumerId; source = source.replaceFirst("MethodFilterTemplate", className); Path path = Paths.get(filterMeta.getSrc(), className + ".java"); try { Files.write(path, source.getBytes(StandardCharsets.UTF_8)); } catch (IOException e) { logger.error("No permission", e); } compile(path.toString()); Class<?> cls; try { URLClassLoader classLoader = URLClassLoader.newInstance(new URL[]{path.getParent().toUri().toURL()}, JavaMethod.class.getClassLoader()); cls = Class.forName(className, true, classLoader); return (SyncFilter) cls.newInstance(); } catch (ClassNotFoundException | IllegalAccessException | InstantiationException | MalformedURLException e) { ShutDownCenter.initShutDown(e); return null; } } static SyncFilter build(String consumerId, SyncerFilterMeta filterMeta, String method); }
@Test public void build() { SyncFilter searcher = JavaMethod.build("searcher", new SyncerFilterMeta(), " public void filter(List<SyncData> list) {\n" + " for (SyncData d : list) {\n" + " assert d.getEventId().equals(\"123/1\");\n" + " }\n" + " }\n"); searcher.filter(Lists.newArrayList(data)); }
FileBasedMap { public boolean flush() { T toFlush = getToFlush(); if (toFlush == null) { return false; } byte[] bytes = toFlush.toString().getBytes(StandardCharsets.UTF_8); putBytes(file, bytes); file.force(); return true; } FileBasedMap(Path path); static byte[] readData(Path path); boolean append(T data, int count); boolean remove(T data, int count); boolean flush(); }
@Test public void flush() throws Exception { BinlogDataId _115 = getFromString("mysql-bin.000115/1234360405/139/0"); map.append(_115, 2); map.flush(); BinlogDataId s = getFromString(new String(FileBasedMap.readData(PATH))); Assert.assertEquals(s, _115); map.remove(_115, 1); BinlogDataId _116 = getFromString("mysql-bin.000116/1305/139/0"); map.append(_116, 1); map.flush(); s = getFromString(new String(FileBasedMap.readData(PATH))); Assert.assertEquals(s, _115); map.remove(_115, 1); s = getFromString(new String(FileBasedMap.readData(PATH))); Assert.assertEquals(s, _115); map.flush(); s = getFromString(new String(FileBasedMap.readData(PATH))); Assert.assertEquals(s, _116); map.remove(_116, 1); BinlogDataId _117 = getFromString("mysql-bin.000117/1305/13/0"); map.append(_117, 1); map.flush(); s = getFromString(new String(FileBasedMap.readData(PATH))); Assert.assertEquals(s, _117); }
SyncKafkaSerializer implements Serializer<SyncResult> { @Override public byte[] serialize(String topic, SyncResult data) { return gson.toJson(data).getBytes(); } @Override void configure(Map<String, ?> configs, boolean isKey); @Override byte[] serialize(String topic, SyncResult data); @Override void close(); }
@Test public void serialize() { SyncData write = SyncDataTestUtil.write("serial", "serial"); String key = "key"; long value = ((long) Math.pow(2, 53)) + 1; assertNotEquals(value, (double)value); write.addField(key, value); byte[] serialize = serializer.serialize("", write.getResult()); assertEquals("{\"fields\":{\"key\":\"9007199254740993\"},\"eventType\":0,\"repo\":\"serial\",\"entity\":\"serial\",\"id\":\"1234\",\"primaryKeyName\":\"id\"}" , new String(serialize)); }
ESRequestMapper implements Mapper<SyncData, Object> { @ThreadSafe(safe = {SpelExpressionParser.class, ESRequestMapping.class, TransportClient.class}) @Override public Object map(SyncData data) { esQueryMapper.parseExtraQueryContext(data.getExtraQueryContext()); StandardEvaluationContext context = data.getContext(); String index = eval(indexExpr, context); String type = eval(typeExpr, context); String id = data.getId() == null ? null : data.getId().toString(); switch (data.getType()) { case WRITE: if (esRequestMapping.getNoUseIdForIndex()) { return client.prepareIndex(index, type).setSource(requestBodyMapper.map(data)); } return client.prepareIndex(index, type, id).setSource(requestBodyMapper.map(data)); case DELETE: logger.info("Deleting doc from Elasticsearch, may affect performance"); if (id != null) { return client.prepareDelete(index, type, id); } logger.warn("Deleting doc by query, may affect performance"); return DeleteByQueryAction.INSTANCE.newRequestBuilder(client) .source(index) .filter(getFilter(data)); case UPDATE: if (id != null) { if (needScript(data)) { HashMap<String, Object> map = requestBodyMapper.map(data); UpdateRequestBuilder builder = client.prepareUpdate(index, type, id) .setScript(getScript(data, map)) .setRetryOnConflict(esRequestMapping.getRetryOnUpdateConflict()); if (esRequestMapping.isUpsert()) { builder.setUpsert(getUpsert(data)).setScriptedUpsert(true); } return builder; } else { return client.prepareUpdate(index, type, id).setDoc(requestBodyMapper.map(data)) .setDocAsUpsert(esRequestMapping.isUpsert()) .setRetryOnConflict(esRequestMapping.getRetryOnUpdateConflict()); } } else { logger.warn("Updating doc by query, may affect performance"); return UpdateByQueryAction.INSTANCE.newRequestBuilder(client) .source(index) .filter(getFilter(data)) .script(getScript(data, data.getFields())); } default: throw new IllegalArgumentException("Unsupported row event type: " + data); } } ESRequestMapper(AbstractClient client, ESRequestMapping esRequestMapping); @ThreadSafe(safe = {SpelExpressionParser.class, ESRequestMapping.class, TransportClient.class}) @Override Object map(SyncData data); }
@Test public void nestedWithExtraQuery() throws Exception { AbstractClient client = ElasticTestUtil.getDevClient(); Elasticsearch elasticsearch = new Elasticsearch(); ESRequestMapper mapper = new ESRequestMapper(client, elasticsearch.getRequestMapping()); SyncData data = SyncDataTestUtil.update("role", "role").setId(1234L); data.setRepo("nested3").setEntity("nested3").addField("title", "b").addField("user_id", 2L); data.extraQuery("user", "user").filter("_id", -1L).select("username").addField("username"); data.esScriptUpdate(Filter.fieldId("roles.id")).mergeToNestedById("roles", "title", "user_id", "username"); Object builder = mapper.map(data); assertEquals("", "{\n" + " \"size\" : 1000,\n" + " \"query\" : {\n" + " \"bool\" : {\n" + " \"filter\" : [\n" + " {\n" + " \"nested\" : {\n" + " \"query\" : {\n" + " \"bool\" : {\n" + " \"filter\" : [\n" + " {\n" + " \"term\" : {\n" + " \"roles.id\" : {\n" + " \"value\" : 1234,\n" + " \"boost\" : 1.0\n" + " }\n" + " }\n" + " }\n" + " ],\n" + " \"disable_coord\" : false,\n" + " \"adjust_pure_negative\" : true,\n" + " \"boost\" : 1.0\n" + " }\n" + " },\n" + " \"path\" : \"roles\",\n" + " \"ignore_unmapped\" : false,\n" + " \"score_mode\" : \"avg\",\n" + " \"boost\" : 1.0\n" + " }\n" + " }\n" + " ],\n" + " \"disable_coord\" : false,\n" + " \"adjust_pure_negative\" : true,\n" + " \"boost\" : 1.0\n" + " }\n" + " }\n" + "}", ((AbstractBulkByScrollRequestBuilder)builder).source().toString()); assertEquals("", "update-by-query [nested3] updated with Script{type=inline, lang='painless', idOrCode='def target = ctx._source.roles.find(e -> e.id.equals(params.id));if (target != null) { target.user_id = params.user_id;target.title = params.title;target.username = params.username;}', options={}, params={id=1234, title=b, user_id=2, username=null}}", ((UpdateByQueryRequestBuilder) builder).request().toString()); }
MongoV4MasterConnector extends MongoConnectorBase { static Map getUpdatedFields(Document fullDocument, BsonDocument updatedFields, boolean bsonConversion) { if (bsonConversion) { if (fullDocument == null) { return (Map) MongoTypeUtil.convertBson(updatedFields); } HashMap<String, Object> res = new HashMap<>(); for (String key : updatedFields.keySet()) { res.put(key, fullDocument.get(key)); } return res; } return updatedFields; } MongoV4MasterConnector(MongoConnection connection, ConsumerRegistry registry, ProducerMaster.MongoV4Option mongoV4Option); @Override void configCursor(); @Override void closeCursor(); @Override void eventLoop(); }
@Test public void types() { long v = ((long) Math.pow(2, 53)) + 1; long v1 = ((long) Math.pow(2, 53)) + 3; long v2 = ((long) Math.pow(2, 53)) + 5; long v4 = System.currentTimeMillis(); double v3 = Math.pow(2, 53) + 5; String time = "time"; String id = "id"; String deep = "criteriaAuditRecords.0.auditRoleIds.0"; String str = "str"; String dou = "double"; String date = "date"; String bool = "bool"; String obj = "obj"; BsonDocument updateDoc = new BsonDocument(time, new BsonInt64(v)); Map map = getUpdatedFields(null, updateDoc, true); assertEquals(1, map.size()); assertEquals(v, map.get(time)); updateDoc.append(id, new BsonInt64(v1)); map = getUpdatedFields(null, updateDoc, true); assertEquals(2, map.size()); assertEquals(v, map.get(time)); assertEquals(v1, map.get(id)); updateDoc.append(deep, new BsonInt64(v2)); map = getUpdatedFields(null, updateDoc, true); assertEquals(3, map.size()); assertEquals(v, map.get(time)); assertEquals(v1, map.get(id)); assertEquals(v2, map.get(deep)); updateDoc.append(str, new BsonString(str)); updateDoc.append(dou, new BsonDouble(v3)); updateDoc.append(date, new BsonDateTime(v4)); updateDoc.append(bool, new BsonBoolean(true)); updateDoc.append(obj, new BsonDocument(str, new BsonString(str)).append(id, new BsonInt64(v1))); map = getUpdatedFields(null, updateDoc, true); assertEquals(8, map.size()); assertEquals(v, map.get(time)); assertEquals(v1, map.get(id)); assertEquals(v2, map.get(deep)); assertEquals(str, map.get(str)); assertEquals(v3, map.get(dou)); assertTrue(map.get(date) instanceof Date); assertEquals(v4, ((Date) map.get(date)).getTime()); assertEquals(true, map.get(bool)); assertTrue(map.get(obj) instanceof Map); assertEquals(v1, ((Map) map.get(obj)).get(id)); }
DocTimestamp implements SyncInitMeta<DocTimestamp> { @Override public int compareTo(DocTimestamp o) { if (o == this) { return 0; } if (this == earliest) { return -1; } else if (o == earliest) { return 1; } return timestamp.compareTo(o.timestamp); } DocTimestamp(BsonTimestamp data); @Override int compareTo(DocTimestamp o); @Override String toString(); static final DocTimestamp earliest; static final DocTimestamp latest; }
@Test public void compareTo() { DocTimestamp b_e = DocTimestamp.earliest; DocTimestamp b_l = DocTimestamp.latest; DocTimestamp b__l = DocTimestamp.latest; DocTimestamp b0 = new DocTimestamp( new BsonTimestamp(0)); DocTimestamp b1 = new DocTimestamp( new BsonTimestamp(1)); DocTimestamp b2 = new DocTimestamp( new BsonTimestamp(2)); DocTimestamp b_b = new DocTimestamp( new BsonTimestamp((int) (System.currentTimeMillis() / 1000) - 1, 0)); DocTimestamp bc = new DocTimestamp( new BsonTimestamp((int) (System.currentTimeMillis() / 1000) + 1, 0)); assertEquals(b_e.compareTo(b0), -1); assertEquals(b_l.compareTo(b_b), 1); assertEquals(b_l.compareTo(bc), -1); assertEquals(b_e.compareTo(b_l), -1); assertEquals(b_l.compareTo(b__l), 0); assertEquals(b0.compareTo(b2), -1); assertEquals(b1.compareTo(b2), -1); assertEquals(b2.compareTo(b0), 1); assertEquals(b2.compareTo(bc), -1); }
BinlogInfo implements SyncInitMeta<BinlogInfo> { @Override public int compareTo(BinlogInfo o) { if (o == this) { return 0; } if (this == latest || o == earliest) { return 1; } else if (this == earliest || o == latest) { return -1; } int seq = Integer.parseInt(binlogFilename.split("\\.")[1]); int oSeq = Integer.parseInt(o.binlogFilename.split("\\.")[1]); int compare = Integer.compare(seq, oSeq); return compare != 0 ? compare : Long.compare(binlogPosition, o.binlogPosition); } BinlogInfo(String binlogFilename, long binlogPosition); static BinlogInfo withFilenameCheck(String binlogFilename, long binlogPosition); String getBinlogFilename(); long getBinlogPosition(); @Override int compareTo(BinlogInfo o); @Override String toString(); static final BinlogInfo latest; static final BinlogInfo earliest; }
@Test public void compareTo() throws Exception { BinlogInfo b_e = BinlogInfo.earliest; BinlogInfo b_l = BinlogInfo.latest; BinlogInfo b__l = BinlogInfo.latest; BinlogInfo b1 = new BinlogInfo("mysql-bin.00001", 0); BinlogInfo b2 = new BinlogInfo("mysql-bin.00002", 0); BinlogInfo b2_1 = new BinlogInfo("mysql-bin.00002", 1); BinlogInfo b2_2 = new BinlogInfo("mysql-bin.00002", 2); BinlogInfo b20_2 = new BinlogInfo("mysql-bin.00020", 2); BinlogInfo b200_2 = new BinlogInfo("mysql-bin.200", 2); BinlogInfo b1200_2 = new BinlogInfo("mysql-bin.1200", 2); assertEquals(b_e.compareTo(b1), -1); assertEquals(b_l.compareTo(b1), 1); assertEquals(b_e.compareTo(b_l), -1); assertEquals(b_l.compareTo(b__l), 0); assertEquals(b1.compareTo(b2), -1); assertEquals(b2.compareTo(b2_1), -1); assertEquals(b2_1.compareTo(b2_2), -1); assertEquals(b2_2.compareTo(b20_2), -1); assertEquals(b20_2.compareTo(b200_2), -1); assertEquals(b200_2.compareTo(b1200_2), -1); }
BinlogInfo implements SyncInitMeta<BinlogInfo> { static int checkFilename(String binlogFilename) { try { return Integer.parseInt(binlogFilename.split("\\.")[1]); } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) { throw new InvalidBinlogException(e, binlogFilename, 0); } } BinlogInfo(String binlogFilename, long binlogPosition); static BinlogInfo withFilenameCheck(String binlogFilename, long binlogPosition); String getBinlogFilename(); long getBinlogPosition(); @Override int compareTo(BinlogInfo o); @Override String toString(); static final BinlogInfo latest; static final BinlogInfo earliest; }
@Test(expected = InvalidBinlogException.class) public void filenameCheck() throws Exception { BinlogInfo.checkFilename("mysql-bin1"); } @Test(expected = InvalidBinlogException.class) public void filenameCheck2() throws Exception { BinlogInfo.checkFilename("mysql-bin.00001bak"); }
WadlZipper { public void saveTo(String zipPathName) throws IOException, URISyntaxException { saveTo(new File(zipPathName)); } WadlZipper(String wadlUri); void saveTo(String zipPathName); void saveTo(File zipFile); }
@Test public void givenAWadlUri_whenSaveToFile_thenCreateZipWithWadlAndAllGrammars() throws Exception { doReturn(WADL_WITH_INCLUDE_GRAMMARS).when(httpClientMock).getAsString(new URI(WADL_URI)); wadlZipper.saveTo(httpClientMock, zipMock); final ArgumentCaptor<URI> uriArgument = ArgumentCaptor.forClass(URI.class); verify(httpClientMock, times(3)).getAsStream(uriArgument.capture()); assertThat(uriArgument.getAllValues(), contains(URI.create(REST_URI + '/' + RELATIVE_URI), URI.create(HOST_URI + ABSOLUTE_URI_WITHOUT_HOST), URI.create(ABSOLUTE_URI_WITH_HOST))); final ArgumentCaptor<String> nameArgument = ArgumentCaptor.forClass(String.class); verify(zipMock, times(4)).add(nameArgument.capture(), any(InputStream.class)); assertThat(nameArgument.getAllValues(), contains(DEFAULT_WADL_FILENAME, RELATIVE_URI + DEFAULT_SCHEMA_EXTENSION, ABSOLUTE_URI_WITHOUT_HOST.substring(1) + DEFAULT_SCHEMA_EXTENSION, ABSOLUTE_URI_WITH_HOST.substring(ABSOLUTE_URI_WITH_HOST.indexOf(" }
SingleType extends ClassType { @Override public String toSchema() { try { return tryBuildSchemaFromJaxbAnnotatedClass(); } catch (Exception e) { logger.warn("Cannot generate schema from JAXB annotations for class: " + clazz.getName() + ". Preparing generic Schema.\n" + e, e); return schemaForNonAnnotatedClass(); } } SingleType(Class<?> classType, QName qName); @Override String toSchema(); }
@Test public void givenClassWhichAttributeIsAnInterface_whenBuild_thenReturnSchemaWithTheInterface() { assertThat(new SingleType(ContactWhichAttributeIsAnInterface.class, IGNORED_Q_NAME).toSchema(), is(ContactWhichAttributeIsAnInterface.EXPECTED_SCHEMA)); } @Test public void givenNameOfNonAnnotatedJaxbClass_whenBuild_thenReturnGenericSchema() { assertThat(new SingleType(Contact.class, IGNORED_Q_NAME).toSchema(), is(Contact.EXPECTED_SCHEMA)); } @Test public void givenNameOfAnnotatedJaxbClass_whenBuild_thenReturnSchemaGeneratedByJaxb() { assertThat(new SingleType(ContactAnnotated.class, IGNORED_Q_NAME).toSchema(), is(ContactAnnotated.EXPECTED_SCHEMA)); } @Test public void givenNameOfAnnotatedJaxbClassWithSpecificTypeName_whenBuild_thenReturnSchemaGeneratedByJaxbWithSpecificName() { assertThat(new SingleType(ContactAnnotatedWithDifferentName.class, IGNORED_Q_NAME).toSchema(), is(ContactAnnotatedWithDifferentName.EXPECTED_SCHEMA)); }
ClassUtils { public static boolean isArrayOrCollection(Class<?> clazz) { return clazz.isArray() || Collection.class.isAssignableFrom(clazz); } private ClassUtils(); static boolean isArrayOrCollection(Class<?> clazz); static Class<?> getElementsClassOf(Class<?> clazz); static boolean isVoid(Class<?> clazz); }
@Test public void givenSingleType_whenAskIsArrayOrCollection_thenReturnFalse() { assertThat(isArrayOrCollection(String.class), is(false)); assertThat(isArrayOrCollection(Integer.class), is(false)); assertThat(isArrayOrCollection(Contact.class), is(false)); } @Test public void givenArray_whenAskIsArrayOrCollection_thenReturnTrue() { assertThat(isArrayOrCollection(String[].class), is(true)); assertThat(isArrayOrCollection(Integer[].class), is(true)); assertThat(isArrayOrCollection(Contact[].class), is(true)); } @Test public void givenCollection_whenAskIsArrayOrCollection_thenReturnTrue() { final List<String> stringsList = new ArrayList<String>(); final Set<Integer> integersSet = new HashSet<Integer>(); final Collection<Contact> contactsCollection = new ArrayList<Contact>(); assertThat(isArrayOrCollection(stringsList.getClass()), is(true)); assertThat(isArrayOrCollection(integersSet.getClass()), is(true)); assertThat(isArrayOrCollection(contactsCollection.getClass()), is(true)); }
ClassUtils { public static boolean isVoid(Class<?> clazz) { return Void.class.equals(clazz) || void.class.equals(clazz); } private ClassUtils(); static boolean isArrayOrCollection(Class<?> clazz); static Class<?> getElementsClassOf(Class<?> clazz); static boolean isVoid(Class<?> clazz); }
@Test public void givenNormalClass_whenAskIsVoid_thenReturnFalse() { assertThat(isVoid(String.class), is(false)); assertThat(isVoid(Integer.class), is(false)); assertThat(isVoid(Contact[].class), is(false)); } @Test public void givenVoidClass_whenAskIsVoid_thenReturnTrue() { assertThat(isVoid(Void.class), is(true)); assertThat(isVoid(void.class), is(true)); }
ClassUtils { public static Class<?> getElementsClassOf(Class<?> clazz) { if (clazz.isArray()) { return clazz.getComponentType(); } if (Collection.class.isAssignableFrom(clazz)) { logger.warn("In Java its not possible to discover de Generic type of a collection like: {}", clazz); return Object.class; } return clazz; } private ClassUtils(); static boolean isArrayOrCollection(Class<?> clazz); static Class<?> getElementsClassOf(Class<?> clazz); static boolean isVoid(Class<?> clazz); }
@Test public void givenArray_whenGetElementsClassOf_thenReturnTheClassOfElements() { assertThat(getElementsClassOf(String[].class), is(typeCompatibleWith(String.class))); assertThat(getElementsClassOf(Integer[].class), is(typeCompatibleWith(Integer.class))); assertThat(getElementsClassOf(Contact[].class), is(typeCompatibleWith(Contact.class))); }
RepresentationBuilder { Collection<Representation> build(MethodContext ctx) { final Collection<Representation> representations = new ArrayList<Representation>(); final Method javaMethod = ctx.getJavaMethod(); final GrammarsDiscoverer grammarsDiscoverer = ctx.getParentContext().getGrammarsDiscoverer(); for (MediaType mediaType : ctx.getMediaTypes()) { final Class<?> returnType = javaMethod.getReturnType(); if (isVoid(returnType)) { continue; } final QName qName = grammarsDiscoverer.discoverQNameFor(new ClassMetadataFromReturnType(javaMethod)); representations.add(new Representation().withMediaType(mediaType.toString()).withElement(qName)); } return representations; } }
@Test public void givenVoidAsMethodReturnType_whenBuildRepresentation_thenDoNotAddAnything() throws NoSuchMethodException { final ApplicationContext appCtx = new ApplicationContext(IGNORED_METHOD_CONTEXT_ITERATOR, new GrammarsDiscoverer(new ClassTypeDiscoverer(new QNameBuilderFactory().getBuilder()))); final MethodContext methodCtxMock = mock(MethodContext.class); doReturn(appCtx).when(methodCtxMock).getParentContext(); doReturn(new HashSet<MediaType>() {{ add(MediaType.APPLICATION_JSON); }}).when(methodCtxMock).getMediaTypes(); doReturn(JavaMethod.WITHOUT_PARAMETERS).when(methodCtxMock).getJavaMethod(); final Collection<Representation> representations = representationBuilder.build(methodCtxMock); assertThat(representations, Matchers.is(Matchers.empty())); }
GrammarsDiscoverer { public List<String> getSchemaUrlsForComplexTypes() { final List<String> urls = new ArrayList<String>(); for (String localPart : classTypeDiscoverer.getAllByLocalPart().keySet()) { urls.add("schema/" + localPart); } return urls; } GrammarsDiscoverer(ClassTypeDiscoverer classTypeDiscoverer); QName discoverQNameFor(ClassMetadata classMetadata); List<String> getSchemaUrlsForComplexTypes(); }
@Test public void givenSeveralClasses_whenGetURLSchemas_thenReturnURLsBasedOnLocalParts() { doReturn(new HashMap<String, ClassType>() {{ put("a", DUMMY_CLASS_TYPE); put("b", DUMMY_CLASS_TYPE); put("c", DUMMY_CLASS_TYPE); }}).when(classTypeDiscovererMock).getAllByLocalPart(); final List<String> schemaUrlsForComplexTypes = grammarsDiscoverer.getSchemaUrlsForComplexTypes(); assertThat(schemaUrlsForComplexTypes, containsInAnyOrder("schema/a", "schema/b", "schema/c")); }
IncludeBuilder { Collection<Include> build() { final List<Include> includes = new ArrayList<Include>(); for (String schemaUrl : grammarsDiscoverer.getSchemaUrlsForComplexTypes()) { includes.add(new Include().withHref(schemaUrl)); } return includes; } IncludeBuilder(GrammarsDiscoverer grammarsDiscoverer); }
@Test public void name() { doReturn(new ArrayList<String>(Arrays.asList(DUMMY_URLS))).when(grammarsDiscovererMock).getSchemaUrlsForComplexTypes(); final Collection<Include> expectedIncludes = new ArrayList<Include>(); for (String dummyUrl : DUMMY_URLS) { expectedIncludes.add(new Include().withHref(dummyUrl)); } assertThat(builder.build(), containsInAnyOrder(expectedIncludes.toArray())); }
GrammarsUrisExtractor { List<String> extractFrom(String wadl) { final List<String> uris = new ArrayList<String>(); final String[] includeElements = BY_INCLUDE.split(extractGrammarsElement(wadl)); for (int i = 1; i < includeElements.length; i++) { uris.add(extractIncludeUriFrom(includeElements[i])); } return uris; } }
@Test public void givenWadlWithSeveralGrammars_whenExtract_thenReturnListOfURIs() { assertThat(grammarsUrisExtractor.extractFrom(WADL_WITH_INCLUDE_GRAMMARS), contains(RELATIVE_URI, ABSOLUTE_URI_WITHOUT_HOST, ABSOLUTE_URI_WITH_HOST)); } @Test public void givenWadlWithoutGrammars_whenExtract_thenReturnEmptyListOfURIs() { assertThat(grammarsUrisExtractor.extractFrom(WADL_WITHOUT_INCLUDE_GRAMMARS), is(empty())); }
CollectionType extends ClassType { @Override public String toSchema() { return COLLECTION_COMPLEX_TYPE_SCHEMA .replace("???type???", elementsQName.getLocalPart()) .replace("???name???", elementsQName.getLocalPart()) .replace("???collectionType???", qName.getLocalPart()) .replace("???collectionName???", qName.getLocalPart()); } CollectionType(Class<?> collectionClass, QName collectionQName, QName elementsQName); @Override String toSchema(); QName getElementsQName(); }
@Test public void givenNameOfComplexTypeCollection_whenBuild_thenReturnSchemaWithTheCollection() { assertThat(new CollectionType(ContactAnnotated[].class, new QName("contactAnnotatedCollection"), new QName("contactAnnotated")).toSchema(), is(ContactAnnotated.EXPECTED_COLLECTION_SCHEMA)); }
ClassTypeDiscoverer { public ClassType getBy(String localPart) { final ClassType classType = classTypeStore.findBy(localPart); if (classType == null) { throw new ClassTypeNotFoundException("Cannot find class type for localPart: " + localPart); } return classType; } ClassTypeDiscoverer(QNameBuilder qNameBuilder); ClassType discoverFor(ClassMetadata classMetadata); ClassType getBy(String localPart); Map<String, ClassType> getAllByLocalPart(); }
@Test(expected = ClassTypeNotFoundException.class) public void givenNonExistingLocalPart_whenFind_thenThrowException() { classTypeDiscoverer.getBy("nonExistingLocalPart"); }
SchemaBuilder { public String buildFor(final String localPart) { return classTypeDiscoverer.getBy(localPart).toSchema(); } SchemaBuilder(ClassTypeDiscoverer classTypeDiscoverer); String buildFor(final String localPart); }
@Test public void givenExistingLocalPart_whenBuildSchema_thenReturnSchema() { final ClassType classTypeDummy = mock(ClassType.class); doReturn("dummy schema").when(classTypeDummy).toSchema(); doReturn(classTypeDummy).when(classTypeDiscovererMock).getBy("dummyLocalPart"); assertThat(schemaBuilder.buildFor("dummyLocalPart"), Matchers.is("dummy schema")); } @Test(expected = ClassTypeNotFoundException.class) public void givenNonExistingLocalPart_whenBuildSchema_thenThrowException() { doThrow(new ClassTypeNotFoundException()).when(classTypeDiscovererMock).getBy("nonExistingLocalPart"); schemaBuilder.buildFor("nonExistingLocalPart"); }
GeoRelationQuerySpec extends AbstractSearchQueryEvaluator { @Override public QueryModelNode getParentQueryModelNode() { return filter; } void setRelation(String relation); String getRelation(); void setFunctionParent(QueryModelNode functionParent); void setQueryGeometry(Literal shape); Literal getQueryGeometry(); void setFunctionValueVar(String varName); String getFunctionValueVar(); void setGeometryPattern(StatementPattern sp); String getSubjectVar(); Var getContextVar(); IRI getGeoProperty(); String getGeoVar(); void setFilter(Filter f); Filter getFilter(); @Override QueryModelNode getParentQueryModelNode(); @Override QueryModelNode removeQueryPatterns(); }
@Test public void testReplaceQueryPatternsWithNonEmptyResults() { final String expectedQueryPlan = "Projection\n" + " ProjectionElemList\n" + " ProjectionElem \"matchUri\"\n" + " ProjectionElem \"match\"\n" + " BindingSetAssignment ([[toUri=urn:subject4;to=\"POLYGON ((2.3294 48.8726, 2.2719 48.8643, 2.3370 48.8398, 2.3294 48.8726))\"^^<http: final ParsedQuery query = parseQuery(QUERY); final List<SearchQueryEvaluator> queries = new ArrayList<>(); new GeoRelationQuerySpecBuilder(new SearchIndexImpl()) .process(query.getTupleExpr(), EmptyBindingSet.getInstance(), queries); assertEquals(1, queries.size()); final GeoRelationQuerySpec querySpec = (GeoRelationQuerySpec) queries.get(0); final MapBindingSet bindingSet = new MapBindingSet(); bindingSet.addBinding("toUri", VF.createIRI("urn:subject4")); bindingSet.addBinding("to", VF.createLiteral( "POLYGON ((2.3294 48.8726, 2.2719 48.8643, 2.3370 48.8398, 2.3294 48.8726))", GEO.WKT_LITERAL)); BindingSetAssignment bsa = new BindingSetAssignment(); bsa.setBindingSets(Collections.singletonList(bindingSet)); querySpec.replaceQueryPatternsWithResults(bsa); assertEquals( expectedQueryPlan, querySpec.getParentQueryModelNode().getParentNode().toString()); } @Test public void testReplaceQueryPatternsWithEmptyResults() { final String expectedQueryPlan = "Projection\n" + " ProjectionElemList\n" + " ProjectionElem \"matchUri\"\n" + " ProjectionElem \"match\"\n" + " EmptySet\n"; final ParsedQuery query = parseQuery(QUERY); final List<SearchQueryEvaluator> queries = new ArrayList<>(); new GeoRelationQuerySpecBuilder(new SearchIndexImpl()) .process(query.getTupleExpr(), EmptyBindingSet.getInstance(), queries); assertEquals(1, queries.size()); final GeoRelationQuerySpec querySpec = (GeoRelationQuerySpec) queries.get(0); BindingSetAssignment bsa = new BindingSetAssignment(); querySpec.replaceQueryPatternsWithResults(bsa); assertEquals( expectedQueryPlan, querySpec.getParentQueryModelNode().getParentNode().toString()); } @Test public void testReplaceQueryPatternsWithNonEmptyResults() { final String expectedQueryPlan = "Projection\n" + " ProjectionElemList\n" + " ProjectionElem \"matchUri\"\n" + " ProjectionElem \"match\"\n" + " BindingSetAssignment ([[toUri=urn:subject4;to=\"POLYGON ((2.3294 48.8726, 2.2719 48.8643, 2.3370 48.8398, 2.3294 48.8726))\"^^<http: final ParsedQuery query = parseQuery(QUERY); final List<SearchQueryEvaluator> queries = new ArrayList<>(); new GeoRelationQuerySpecBuilder(new SearchIndexImpl()) .process(query.getTupleExpr(), EmptyBindingSet.getInstance(), queries); assertEquals(1, queries.size()); final GeoRelationQuerySpec querySpec = (GeoRelationQuerySpec) queries.get(0); final MapBindingSet bindingSet = new MapBindingSet(); bindingSet.addBinding("toUri", VF.createIRI("urn:subject4")); bindingSet.addBinding("to", VF.createLiteral( "POLYGON ((2.3294 48.8726, 2.2719 48.8643, 2.3370 48.8398, 2.3294 48.8726))", GEO.WKT_LITERAL)); BindingSetAssignment bsa = new BindingSetAssignment(); bsa.setBindingSets(Collections.singletonList(bindingSet)); querySpec.replaceQueryPatternsWithResults(bsa); String result = querySpec.getParentQueryModelNode().getParentNode().toString().replaceAll("\r\n|\r", "\n"); assertEquals(expectedQueryPlan, result); } @Test public void testReplaceQueryPatternsWithEmptyResults() { final String expectedQueryPlan = "Projection\n" + " ProjectionElemList\n" + " ProjectionElem \"matchUri\"\n" + " ProjectionElem \"match\"\n" + " EmptySet\n"; final ParsedQuery query = parseQuery(QUERY); final List<SearchQueryEvaluator> queries = new ArrayList<>(); new GeoRelationQuerySpecBuilder(new SearchIndexImpl()) .process(query.getTupleExpr(), EmptyBindingSet.getInstance(), queries); assertEquals(1, queries.size()); final GeoRelationQuerySpec querySpec = (GeoRelationQuerySpec) queries.get(0); BindingSetAssignment bsa = new BindingSetAssignment(); querySpec.replaceQueryPatternsWithResults(bsa); String result = querySpec.getParentQueryModelNode().getParentNode().toString().replaceAll("\r\n|\r", "\n"); assertEquals(expectedQueryPlan, result); }
UpperCase implements Function { @Override public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length != 1) { throw new ValueExprEvaluationException("UCASE requires exactly 1 argument, got " + args.length); } if (args[0] instanceof Literal) { Literal literal = (Literal) args[0]; if (QueryEvaluationUtil.isStringLiteral(literal)) { String lexicalValue = literal.getLabel().toUpperCase(); Optional<String> language = literal.getLanguage(); if (language.isPresent()) { return valueFactory.createLiteral(lexicalValue, language.get()); } else if (XMLSchema.STRING.equals(literal.getDatatype())) { return valueFactory.createLiteral(lexicalValue, XMLSchema.STRING); } else { return valueFactory.createLiteral(lexicalValue); } } else { throw new ValueExprEvaluationException("unexpected input value for function: " + args[0]); } } else { throw new ValueExprEvaluationException("unexpected input value for function: " + args[0]); } } @Override String getURI(); @Override Literal evaluate(ValueFactory valueFactory, Value... args); }
@Test public void testEvaluate1() { Literal pattern = f.createLiteral("foobar"); try { Literal result = ucaseFunc.evaluate(f, pattern); assertTrue(result.getLabel().equals("FOOBAR")); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } } @Test public void testEvaluate2() { Literal pattern = f.createLiteral("FooBar"); try { Literal result = ucaseFunc.evaluate(f, pattern); assertTrue(result.getLabel().equals("FOOBAR")); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } } @Test public void testEvaluate3() { Literal pattern = f.createLiteral("FooBar"); Literal startIndex = f.createLiteral(4); try { ucaseFunc.evaluate(f, pattern, startIndex); fail("illegal number of parameters"); } catch (ValueExprEvaluationException e) { } }
LowerCase implements Function { @Override public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length != 1) { throw new ValueExprEvaluationException("LCASE requires exactly 1 argument, got " + args.length); } if (args[0] instanceof Literal) { Literal literal = (Literal) args[0]; if (QueryEvaluationUtil.isStringLiteral(literal)) { String lexicalValue = literal.getLabel().toLowerCase(); Optional<String> language = literal.getLanguage(); if (language.isPresent()) { return valueFactory.createLiteral(lexicalValue, language.get()); } else if (XMLSchema.STRING.equals(literal.getDatatype())) { return valueFactory.createLiteral(lexicalValue, XMLSchema.STRING); } else { return valueFactory.createLiteral(lexicalValue); } } else { throw new ValueExprEvaluationException("unexpected input value for function: " + args[0]); } } else { throw new ValueExprEvaluationException("unexpected input value for function: " + args[0]); } } @Override String getURI(); @Override Literal evaluate(ValueFactory valueFactory, Value... args); }
@Test public void testEvaluate1() { Literal pattern = f.createLiteral("foobar"); try { Literal result = lcaseFunc.evaluate(f, pattern); assertTrue(result.getLabel().equals("foobar")); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } } @Test public void testEvaluate2() { Literal pattern = f.createLiteral("FooBar"); try { Literal result = lcaseFunc.evaluate(f, pattern); assertTrue(result.getLabel().equals("foobar")); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } } @Test public void testEvaluate3() { Literal pattern = f.createLiteral("FooBar"); Literal startIndex = f.createLiteral(4); try { lcaseFunc.evaluate(f, pattern, startIndex); fail("illegal number of parameters"); } catch (ValueExprEvaluationException e) { } }
StrBefore implements Function { @Override public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length != 2) { throw new ValueExprEvaluationException("Incorrect number of arguments for STRBEFORE: " + args.length); } Value leftArg = args[0]; Value rightArg = args[1]; if (leftArg instanceof Literal && rightArg instanceof Literal) { Literal leftLit = (Literal) leftArg; Literal rightLit = (Literal) rightArg; if (QueryEvaluationUtil.compatibleArguments(leftLit, rightLit)) { Optional<String> leftLanguage = leftLit.getLanguage(); IRI leftDt = leftLit.getDatatype(); String lexicalValue = leftLit.getLabel(); String substring = rightLit.getLabel(); int index = lexicalValue.indexOf(substring); String substringBefore = ""; if (index > -1) { substringBefore = lexicalValue.substring(0, index); } else { leftLanguage = Optional.empty(); leftDt = null; } if (leftLanguage.isPresent()) { return valueFactory.createLiteral(substringBefore, leftLanguage.get()); } else if (leftDt != null) { return valueFactory.createLiteral(substringBefore, leftDt); } else { return valueFactory.createLiteral(substringBefore); } } else { throw new ValueExprEvaluationException( "incompatible operands for STRBEFORE: " + leftArg + ", " + rightArg); } } else { throw new ValueExprEvaluationException("incompatible operands for STRBEFORE: " + leftArg + ", " + rightArg); } } @Override String getURI(); @Override Literal evaluate(ValueFactory valueFactory, Value... args); }
@Test public void testEvaluate4() { Literal leftArg = f.createLiteral("foobar", XMLSchema.STRING); Literal rightArg = f.createLiteral("b"); try { Literal result = strBeforeFunc.evaluate(f, leftArg, rightArg); assertEquals("foo", result.getLabel()); assertEquals(XMLSchema.STRING, result.getDatatype()); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } } @Test public void testEvaluate4a() { Literal leftArg = f.createLiteral("foobar"); Literal rightArg = f.createLiteral("b", XMLSchema.STRING); try { Literal result = strBeforeFunc.evaluate(f, leftArg, rightArg); assertEquals("foo", result.getLabel()); assertEquals(XMLSchema.STRING, result.getDatatype()); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } } @Test public void testEvaluate5() { Literal leftArg = f.createLiteral("foobar", XMLSchema.STRING); Literal rightArg = f.createLiteral("b", XMLSchema.DATE); try { Literal result = strBeforeFunc.evaluate(f, leftArg, rightArg); fail("operand with incompatible datatype, should have resulted in error"); } catch (ValueExprEvaluationException e) { assertEquals( "incompatible operands for STRBEFORE: \"foobar\", \"b\"^^<http: e.getMessage()); } } @Test public void testEvaluate10() { Literal leftArg = f.createLiteral("foobar", "en"); Literal rightArg = f.createLiteral("b", XMLSchema.STRING); try { Literal result = strBeforeFunc.evaluate(f, leftArg, rightArg); assertEquals("foo", result.getLabel()); assertEquals(RDF.LANGSTRING, result.getDatatype()); assertEquals("en", result.getLanguage().orElse(null)); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } } @Test public void testEvaluate1() { Literal leftArg = f.createLiteral("foobar"); Literal rightArg = f.createLiteral("ba"); try { Literal result = strBeforeFunc.evaluate(f, leftArg, rightArg); assertEquals("foo", result.getLabel()); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } } @Test public void testEvaluate2() { Literal leftArg = f.createLiteral("foobar"); Literal rightArg = f.createLiteral("xyz"); try { Literal result = strBeforeFunc.evaluate(f, leftArg, rightArg); assertEquals("", result.getLabel()); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } } @Test public void testEvaluate3() { Literal leftArg = f.createLiteral("foobar", "en"); Literal rightArg = f.createLiteral("b"); try { Literal result = strBeforeFunc.evaluate(f, leftArg, rightArg); assertEquals("foo", result.getLabel()); assertEquals("en", result.getLanguage().orElse(null)); assertEquals(RDF.LANGSTRING, result.getDatatype()); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } } @Test public void testEvaluate4() { Literal leftArg = f.createLiteral("foobar", XSD.STRING); Literal rightArg = f.createLiteral("b"); try { Literal result = strBeforeFunc.evaluate(f, leftArg, rightArg); assertEquals("foo", result.getLabel()); assertEquals(XSD.STRING, result.getDatatype()); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } } @Test public void testEvaluate4a() { Literal leftArg = f.createLiteral("foobar"); Literal rightArg = f.createLiteral("b", XSD.STRING); try { Literal result = strBeforeFunc.evaluate(f, leftArg, rightArg); assertEquals("foo", result.getLabel()); assertEquals(XSD.STRING, result.getDatatype()); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } } @Test public void testEvaluate5() { Literal leftArg = f.createLiteral("foobar", XSD.STRING); Literal rightArg = f.createLiteral("b", XSD.DATE); try { Literal result = strBeforeFunc.evaluate(f, leftArg, rightArg); fail("operand with incompatible datatype, should have resulted in error"); } catch (ValueExprEvaluationException e) { assertEquals( "incompatible operands for STRBEFORE: \"foobar\", \"b\"^^<http: e.getMessage()); } } @Test public void testEvaluate6() { Literal leftArg = f.createLiteral(10); Literal rightArg = f.createLiteral("b"); try { Literal result = strBeforeFunc.evaluate(f, leftArg, rightArg); fail("operand with incompatible datatype, should have resulted in error"); } catch (ValueExprEvaluationException e) { assertEquals("incompatible operands for STRBEFORE: \"10\"^^<http: e.getMessage()); } } @Test public void testEvaluate7() { IRI leftArg = f.createIRI("http: Literal rightArg = f.createLiteral("b"); try { Literal result = strBeforeFunc.evaluate(f, leftArg, rightArg); fail("operand of incompatible type, should have resulted in error"); } catch (ValueExprEvaluationException e) { assertEquals("incompatible operands for STRBEFORE: http: } } @Test public void testEvaluate8() { Literal leftArg = f.createLiteral("foobar", "en"); Literal rightArg = f.createLiteral("b", "nl"); try { Literal result = strBeforeFunc.evaluate(f, leftArg, rightArg); fail("operand of incompatible type, should have resulted in error"); } catch (ValueExprEvaluationException e) { assertEquals("incompatible operands for STRBEFORE: \"foobar\"@en, \"b\"@nl", e.getMessage()); } } @Test public void testEvaluate9() { Literal leftArg = f.createLiteral("foobar"); Literal rightArg = f.createLiteral("b", "nl"); try { Literal result = strBeforeFunc.evaluate(f, leftArg, rightArg); fail("operand of incompatible type, should have resulted in error"); } catch (ValueExprEvaluationException e) { assertEquals("incompatible operands for STRBEFORE: \"foobar\", \"b\"@nl", e.getMessage()); } } @Test public void testEvaluate10() { Literal leftArg = f.createLiteral("foobar", "en"); Literal rightArg = f.createLiteral("b", XSD.STRING); try { Literal result = strBeforeFunc.evaluate(f, leftArg, rightArg); assertEquals("foo", result.getLabel()); assertEquals(RDF.LANGSTRING, result.getDatatype()); assertEquals("en", result.getLanguage().orElse(null)); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } } @Test public void testEvaluate11() { Literal leftArg = f.createLiteral("foobar", "nl"); Literal rightArg = f.createLiteral("b", "nl"); try { Literal result = strBeforeFunc.evaluate(f, leftArg, rightArg); assertEquals("foo", result.getLabel()); assertEquals(RDF.LANGSTRING, result.getDatatype()); assertEquals("nl", result.getLanguage().orElse(null)); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } }
HashFunction implements Function { @Override public abstract Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException; @Override abstract Literal evaluate(ValueFactory valueFactory, Value... args); }
@Test public void testEvaluate() { try { Literal hash = getHashFunction().evaluate(f, f.createLiteral(getToHash())); assertNotNull(hash); assertEquals(XMLSchema.STRING, hash.getDatatype()); assertEquals(hash.getLabel(), getExpectedDigest()); } catch (ValueExprEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testEvaluate2() { try { Literal hash = getHashFunction().evaluate(f, f.createLiteral(getToHash(), XMLSchema.STRING)); assertNotNull(hash); assertEquals(XMLSchema.STRING, hash.getDatatype()); assertEquals(hash.getLabel(), getExpectedDigest()); } catch (ValueExprEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testEvaluate3() { try { getHashFunction().evaluate(f, f.createLiteral("4", XMLSchema.INTEGER)); fail("incompatible operand should have resulted in type error."); } catch (ValueExprEvaluationException e) { } } @Test public void testEvaluate() { try { Literal hash = getHashFunction().evaluate(f, f.createLiteral(getToHash())); assertNotNull(hash); assertEquals(XSD.STRING, hash.getDatatype()); assertEquals(hash.getLabel(), getExpectedDigest()); } catch (ValueExprEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testEvaluate2() { try { Literal hash = getHashFunction().evaluate(f, f.createLiteral(getToHash(), XSD.STRING)); assertNotNull(hash); assertEquals(XSD.STRING, hash.getDatatype()); assertEquals(hash.getLabel(), getExpectedDigest()); } catch (ValueExprEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testEvaluate3() { try { getHashFunction().evaluate(f, f.createLiteral("4", XSD.INTEGER)); fail("incompatible operand should have resulted in type error."); } catch (ValueExprEvaluationException e) { } }
StringCast extends CastFunction { @Override public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length != 1) { throw new ValueExprEvaluationException( getXsdName() + " cast requires exactly 1 argument, got " + args.length); } if (args[0] instanceof Literal) { Literal literal = (Literal) args[0]; IRI datatype = literal.getDatatype(); if (QueryEvaluationUtil.isSimpleLiteral(literal)) { String lexicalValue = XMLDatatypeUtil.collapseWhiteSpace(literal.getLabel()); if (isValidForDatatype(lexicalValue)) { return valueFactory.createLiteral(lexicalValue, getXsdDatatype()); } } else if (datatype != null) { if (datatype.equals(getXsdDatatype())) { return literal; } } return convert(valueFactory, literal); } else { return convert(valueFactory, args[0]); } } @Override Literal evaluate(ValueFactory valueFactory, Value... args); }
@Test public void testCastPlainLiteral() { Literal plainLit = f.createLiteral("foo"); try { Literal result = stringCast.evaluate(f, plainLit); assertNotNull(result); assertEquals(XMLSchema.STRING, result.getDatatype()); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } } @Test public void testCastIntegerLiteral() { Literal intLit = f.createLiteral(10); try { Literal result = stringCast.evaluate(f, intLit); assertNotNull(result); assertEquals(XMLSchema.STRING, result.getDatatype()); assertFalse(result.getLanguage().isPresent()); assertEquals("10", result.getLabel()); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } } @Test public void testCastDateTimeLiteral() { String lexVal = "2000-01-01T00:00:00"; Literal dtLit = f.createLiteral(XMLDatatypeUtil.parseCalendar(lexVal)); try { Literal result = stringCast.evaluate(f, dtLit); assertNotNull(result); assertEquals(XMLSchema.STRING, result.getDatatype()); assertFalse(result.getLanguage().isPresent()); assertEquals(lexVal, result.getLabel()); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } } @Test public void testCastUnknownDatatypedLiteral() { String lexVal = "foobar"; Literal dtLit = f.createLiteral(lexVal, f.createIRI("foo:unknownDt")); try { Literal result = stringCast.evaluate(f, dtLit); assertNotNull(result); assertEquals(XMLSchema.STRING, result.getDatatype()); assertFalse(result.getLanguage().isPresent()); assertEquals(lexVal, result.getLabel()); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } } @Test public void testCastPlainLiteral() { Literal plainLit = f.createLiteral("foo"); try { Literal result = stringCast.evaluate(f, plainLit); assertNotNull(result); assertEquals(XSD.STRING, result.getDatatype()); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } } @Test public void testCastLangtagLiteral() { Literal langLit = f.createLiteral("foo", "en"); try { Literal result = stringCast.evaluate(f, langLit); fail("casting of language-tagged literal to xsd:string should result in type error"); } catch (ValueExprEvaluationException e) { } } @Test public void testCastIntegerLiteral() { Literal intLit = f.createLiteral(10); try { Literal result = stringCast.evaluate(f, intLit); assertNotNull(result); assertEquals(XSD.STRING, result.getDatatype()); assertFalse(result.getLanguage().isPresent()); assertEquals("10", result.getLabel()); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } } @Test public void testCastDateTimeLiteral() { String lexVal = "2000-01-01T00:00:00"; Literal dtLit = f.createLiteral(XMLDatatypeUtil.parseCalendar(lexVal)); try { Literal result = stringCast.evaluate(f, dtLit); assertNotNull(result); assertEquals(XSD.STRING, result.getDatatype()); assertFalse(result.getLanguage().isPresent()); assertEquals(lexVal, result.getLabel()); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } } @Test public void testCastUnknownDatatypedLiteral() { String lexVal = "foobar"; Literal dtLit = f.createLiteral(lexVal, f.createIRI("foo:unknownDt")); try { Literal result = stringCast.evaluate(f, dtLit); assertNotNull(result); assertEquals(XSD.STRING, result.getDatatype()); assertFalse(result.getLanguage().isPresent()); assertEquals(lexVal, result.getLabel()); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } }
StrictEvaluationStrategy implements EvaluationStrategy, FederatedServiceResolverClient, UUIDable { @Override public CloseableIteration<BindingSet, QueryEvaluationException> evaluate(TupleExpr expr, BindingSet bindings) throws QueryEvaluationException { if (expr instanceof StatementPattern) { return evaluate((StatementPattern) expr, bindings); } else if (expr instanceof UnaryTupleOperator) { return evaluate((UnaryTupleOperator) expr, bindings); } else if (expr instanceof BinaryTupleOperator) { return evaluate((BinaryTupleOperator) expr, bindings); } else if (expr instanceof SingletonSet) { return evaluate((SingletonSet) expr, bindings); } else if (expr instanceof EmptySet) { return evaluate((EmptySet) expr, bindings); } else if (expr instanceof ExternalSet) { return evaluate((ExternalSet) expr, bindings); } else if (expr instanceof ZeroLengthPath) { return evaluate((ZeroLengthPath) expr, bindings); } else if (expr instanceof ArbitraryLengthPath) { return evaluate((ArbitraryLengthPath) expr, bindings); } else if (expr instanceof BindingSetAssignment) { return evaluate((BindingSetAssignment) expr, bindings); } else if (expr == null) { throw new IllegalArgumentException("expr must not be null"); } else { throw new QueryEvaluationException("Unsupported tuple expr type: " + expr.getClass()); } } StrictEvaluationStrategy(TripleSource tripleSource, FederatedServiceResolver serviceResolver); StrictEvaluationStrategy(TripleSource tripleSource, Dataset dataset, FederatedServiceResolver serviceResolver); StrictEvaluationStrategy(TripleSource tripleSource, Dataset dataset, FederatedServiceResolver serviceResolver, long iterationCacheSyncTreshold, EvaluationStatistics evaluationStatistics); @Override UUID getUUID(); @Override void setFederatedServiceResolver(FederatedServiceResolver resolver); @Override FederatedService getService(String serviceUrl); @Override void setOptimizerPipeline(QueryOptimizerPipeline pipeline); @Override TupleExpr optimize(TupleExpr expr, EvaluationStatistics evaluationStatistics, BindingSet bindings); @Override CloseableIteration<BindingSet, QueryEvaluationException> evaluate(TupleExpr expr, BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(ArbitraryLengthPath alp, final BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(ZeroLengthPath zlp, final BindingSet bindings); @Override CloseableIteration<BindingSet, QueryEvaluationException> evaluate(Service service, String serviceUri, CloseableIteration<BindingSet, QueryEvaluationException> bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(Service service, BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(DescribeOperator operator, final BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(StatementPattern sp, final BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(UnaryTupleOperator expr, BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(BindingSetAssignment bsa, BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(Projection projection, BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(MultiProjection multiProjection, BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(Filter filter, BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(Slice slice, BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(Extension extension, BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(Distinct distinct, BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(Reduced reduced, BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(Group node, BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(Order node, BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(BinaryTupleOperator expr, BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(Join join, BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(LeftJoin leftJoin, final BindingSet bindings); @SuppressWarnings("unchecked") CloseableIteration<BindingSet, QueryEvaluationException> evaluate(final Union union, final BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(final Intersection intersection, final BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(final Difference difference, final BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(SingletonSet singletonSet, BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(EmptySet emptySet, BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(ExternalSet external, BindingSet bindings); @Override Value evaluate(ValueExpr expr, BindingSet bindings); Value evaluate(Var var, BindingSet bindings); Value evaluate(ValueConstant valueConstant, BindingSet bindings); Value evaluate(BNodeGenerator node, BindingSet bindings); Value evaluate(Bound node, BindingSet bindings); Value evaluate(Str node, BindingSet bindings); Value evaluate(Label node, BindingSet bindings); Value evaluate(Lang node, BindingSet bindings); Value evaluate(Datatype node, BindingSet bindings); Value evaluate(Namespace node, BindingSet bindings); Value evaluate(LocalName node, BindingSet bindings); Value evaluate(IsResource node, BindingSet bindings); Value evaluate(IsURI node, BindingSet bindings); Value evaluate(IsBNode node, BindingSet bindings); Value evaluate(IsLiteral node, BindingSet bindings); Value evaluate(IsNumeric node, BindingSet bindings); IRI evaluate(IRIFunction node, BindingSet bindings); Value evaluate(Regex node, BindingSet bindings); Value evaluate(LangMatches node, BindingSet bindings); Value evaluate(Like node, BindingSet bindings); Value evaluate(FunctionCall node, BindingSet bindings); Value evaluate(And node, BindingSet bindings); Value evaluate(Or node, BindingSet bindings); Value evaluate(Not node, BindingSet bindings); Value evaluate(Now node, BindingSet bindings); Value evaluate(SameTerm node, BindingSet bindings); Value evaluate(Coalesce node, BindingSet bindings); Value evaluate(Compare node, BindingSet bindings); Value evaluate(MathExpr node, BindingSet bindings); Value evaluate(If node, BindingSet bindings); Value evaluate(In node, BindingSet bindings); Value evaluate(ListMemberOperator node, BindingSet bindings); Value evaluate(CompareAny node, BindingSet bindings); Value evaluate(CompareAll node, BindingSet bindings); Value evaluate(Exists node, BindingSet bindings); @Override boolean isTrue(ValueExpr expr, BindingSet bindings); }
@Test public void testBindings() throws Exception { String query = "SELECT ?a ?b WHERE {}"; ParsedQuery pq = QueryParserUtil.parseQuery(QueryLanguage.SPARQL, query, null); final ValueFactory vf = SimpleValueFactory.getInstance(); QueryBindingSet constants = new QueryBindingSet(); constants.addBinding("a", vf.createLiteral("foo")); constants.addBinding("b", vf.createLiteral("bar")); constants.addBinding("x", vf.createLiteral("X")); constants.addBinding("y", vf.createLiteral("Y")); CloseableIteration<BindingSet, QueryEvaluationException> result = strategy.evaluate(pq.getTupleExpr(), constants); assertNotNull(result); assertTrue(result.hasNext()); BindingSet bs = result.next(); assertTrue(bs.hasBinding("a")); assertTrue(bs.hasBinding("b")); assertFalse(bs.hasBinding("x")); assertFalse(bs.hasBinding("y")); }
StrictEvaluationStrategy implements EvaluationStrategy, FederatedServiceResolverClient, UUIDable { @Override public TupleExpr optimize(TupleExpr expr, EvaluationStatistics evaluationStatistics, BindingSet bindings) { TupleExpr optimizedExpr = expr; for (QueryOptimizer optimizer : pipeline.getOptimizers()) { optimizer.optimize(optimizedExpr, dataset, bindings); } return optimizedExpr; } StrictEvaluationStrategy(TripleSource tripleSource, FederatedServiceResolver serviceResolver); StrictEvaluationStrategy(TripleSource tripleSource, Dataset dataset, FederatedServiceResolver serviceResolver); StrictEvaluationStrategy(TripleSource tripleSource, Dataset dataset, FederatedServiceResolver serviceResolver, long iterationCacheSyncTreshold, EvaluationStatistics evaluationStatistics); @Override UUID getUUID(); @Override void setFederatedServiceResolver(FederatedServiceResolver resolver); @Override FederatedService getService(String serviceUrl); @Override void setOptimizerPipeline(QueryOptimizerPipeline pipeline); @Override TupleExpr optimize(TupleExpr expr, EvaluationStatistics evaluationStatistics, BindingSet bindings); @Override CloseableIteration<BindingSet, QueryEvaluationException> evaluate(TupleExpr expr, BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(ArbitraryLengthPath alp, final BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(ZeroLengthPath zlp, final BindingSet bindings); @Override CloseableIteration<BindingSet, QueryEvaluationException> evaluate(Service service, String serviceUri, CloseableIteration<BindingSet, QueryEvaluationException> bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(Service service, BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(DescribeOperator operator, final BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(StatementPattern sp, final BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(UnaryTupleOperator expr, BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(BindingSetAssignment bsa, BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(Projection projection, BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(MultiProjection multiProjection, BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(Filter filter, BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(Slice slice, BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(Extension extension, BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(Distinct distinct, BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(Reduced reduced, BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(Group node, BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(Order node, BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(BinaryTupleOperator expr, BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(Join join, BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(LeftJoin leftJoin, final BindingSet bindings); @SuppressWarnings("unchecked") CloseableIteration<BindingSet, QueryEvaluationException> evaluate(final Union union, final BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(final Intersection intersection, final BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(final Difference difference, final BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(SingletonSet singletonSet, BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(EmptySet emptySet, BindingSet bindings); CloseableIteration<BindingSet, QueryEvaluationException> evaluate(ExternalSet external, BindingSet bindings); @Override Value evaluate(ValueExpr expr, BindingSet bindings); Value evaluate(Var var, BindingSet bindings); Value evaluate(ValueConstant valueConstant, BindingSet bindings); Value evaluate(BNodeGenerator node, BindingSet bindings); Value evaluate(Bound node, BindingSet bindings); Value evaluate(Str node, BindingSet bindings); Value evaluate(Label node, BindingSet bindings); Value evaluate(Lang node, BindingSet bindings); Value evaluate(Datatype node, BindingSet bindings); Value evaluate(Namespace node, BindingSet bindings); Value evaluate(LocalName node, BindingSet bindings); Value evaluate(IsResource node, BindingSet bindings); Value evaluate(IsURI node, BindingSet bindings); Value evaluate(IsBNode node, BindingSet bindings); Value evaluate(IsLiteral node, BindingSet bindings); Value evaluate(IsNumeric node, BindingSet bindings); IRI evaluate(IRIFunction node, BindingSet bindings); Value evaluate(Regex node, BindingSet bindings); Value evaluate(LangMatches node, BindingSet bindings); Value evaluate(Like node, BindingSet bindings); Value evaluate(FunctionCall node, BindingSet bindings); Value evaluate(And node, BindingSet bindings); Value evaluate(Or node, BindingSet bindings); Value evaluate(Not node, BindingSet bindings); Value evaluate(Now node, BindingSet bindings); Value evaluate(SameTerm node, BindingSet bindings); Value evaluate(Coalesce node, BindingSet bindings); Value evaluate(Compare node, BindingSet bindings); Value evaluate(MathExpr node, BindingSet bindings); Value evaluate(If node, BindingSet bindings); Value evaluate(In node, BindingSet bindings); Value evaluate(ListMemberOperator node, BindingSet bindings); Value evaluate(CompareAny node, BindingSet bindings); Value evaluate(CompareAll node, BindingSet bindings); Value evaluate(Exists node, BindingSet bindings); @Override boolean isTrue(ValueExpr expr, BindingSet bindings); }
@Test public void testOptimize() throws Exception { QueryOptimizer optimizer1 = mock(QueryOptimizer.class); QueryOptimizer optimizer2 = mock(QueryOptimizer.class); strategy.setOptimizerPipeline(new QueryOptimizerPipeline() { @Override public Iterable<QueryOptimizer> getOptimizers() { return Arrays.asList(optimizer1, optimizer2); } }); TupleExpr expr = mock(TupleExpr.class); EvaluationStatistics stats = new EvaluationStatistics(); BindingSet bindings = new QueryBindingSet(); strategy.optimize(expr, stats, bindings); verify(optimizer1, times(1)).optimize(expr, null, bindings); verify(optimizer2, times(1)).optimize(expr, null, bindings); }
QueryModelNormalizer extends AbstractQueryModelVisitor<RuntimeException> implements QueryOptimizer { @Override public void meet(Join join) { super.meet(join); TupleExpr leftArg = join.getLeftArg(); TupleExpr rightArg = join.getRightArg(); if (leftArg instanceof EmptySet || rightArg instanceof EmptySet) { join.replaceWith(new EmptySet()); } else if (leftArg instanceof SingletonSet) { join.replaceWith(rightArg); } else if (rightArg instanceof SingletonSet) { join.replaceWith(leftArg); } else if (leftArg instanceof Union) { Union union = (Union) leftArg; Join leftJoin = new Join(union.getLeftArg(), rightArg.clone()); Join rightJoin = new Join(union.getRightArg(), rightArg.clone()); Union newUnion = new Union(leftJoin, rightJoin); join.replaceWith(newUnion); newUnion.visit(this); } else if (rightArg instanceof Union) { Union union = (Union) rightArg; Join leftJoin = new Join(leftArg.clone(), union.getLeftArg()); Join rightJoin = new Join(leftArg.clone(), union.getRightArg()); Union newUnion = new Union(leftJoin, rightJoin); join.replaceWith(newUnion); newUnion.visit(this); } else if (leftArg instanceof LeftJoin && isWellDesigned(((LeftJoin) leftArg))) { LeftJoin leftJoin = (LeftJoin) leftArg; join.replaceWith(leftJoin); join.setLeftArg(leftJoin.getLeftArg()); leftJoin.setLeftArg(join); leftJoin.visit(this); } else if (rightArg instanceof LeftJoin && isWellDesigned(((LeftJoin) rightArg))) { LeftJoin leftJoin = (LeftJoin) rightArg; join.replaceWith(leftJoin); join.setRightArg(leftJoin.getLeftArg()); leftJoin.setLeftArg(join); leftJoin.visit(this); } } QueryModelNormalizer(); @Override void optimize(TupleExpr tupleExpr, Dataset dataset, BindingSet bindings); @Override void meet(Join join); @Override void meet(LeftJoin leftJoin); @Override void meet(Union union); @Override void meet(Difference difference); @Override void meet(Intersection intersection); @Override void meet(Filter node); @Override void meet(Or or); @Override void meet(And and); }
@Test public void testNormalizeUnionWithEmptyLeft() { Projection p = new Projection(); Union union = new Union(); SingletonSet s = new SingletonSet(); union.setLeftArg(new EmptySet()); union.setRightArg(s); p.setArg(union); subject.meet(union); assertThat(p.getArg()).isEqualTo(s); } @Test public void testNormalizeUnionWithEmptyRight() { Projection p = new Projection(); Union union = new Union(); SingletonSet s = new SingletonSet(); union.setRightArg(new EmptySet()); union.setLeftArg(s); p.setArg(union); subject.meet(union); assertThat(p.getArg()).isEqualTo(s); } @Test public void testNormalizeUnionWithTwoSingletons() { Projection p = new Projection(); Union union = new Union(); union.setRightArg(new SingletonSet()); union.setLeftArg(new SingletonSet()); p.setArg(union); subject.meet(union); assertThat(p.getArg()).isEqualTo(union); }
ShaclSailConfig extends AbstractDelegatingSailImplConfig { @Override public void parse(Model m, Resource implNode) throws SailConfigException { super.parse(m, implNode); try { Models.objectLiteral(m.filter(implNode, PARALLEL_VALIDATION, null)) .ifPresent(l -> setParallelValidation(l.booleanValue())); Models.objectLiteral(m.filter(implNode, UNDEFINED_TARGET_VALIDATES_ALL_SUBJECTS, null)) .ifPresent(l -> setUndefinedTargetValidatesAllSubjects(l.booleanValue())); Models.objectLiteral(m.filter(implNode, LOG_VALIDATION_PLANS, null)) .ifPresent(l -> setLogValidationPlans(l.booleanValue())); Models.objectLiteral(m.filter(implNode, LOG_VALIDATION_VIOLATIONS, null)) .ifPresent(l -> setLogValidationViolations(l.booleanValue())); Models.objectLiteral(m.filter(implNode, IGNORE_NO_SHAPES_LOADED_EXCEPTION, null)) .ifPresent(l -> setIgnoreNoShapesLoadedException(l.booleanValue())); Models.objectLiteral(m.filter(implNode, VALIDATION_ENABLED, null)) .ifPresent(l -> setValidationEnabled(l.booleanValue())); Models.objectLiteral(m.filter(implNode, CACHE_SELECT_NODES, null)) .ifPresent(l -> setCacheSelectNodes(l.booleanValue())); Models.objectLiteral(m.filter(implNode, GLOBAL_LOG_VALIDATION_EXECUTION, null)) .ifPresent(l -> setGlobalLogValidationExecution(l.booleanValue())); Models.objectLiteral(m.filter(implNode, RDFS_SUB_CLASS_REASONING, null)) .ifPresent(l -> setRdfsSubClassReasoning(l.booleanValue())); Models.objectLiteral(m.filter(implNode, PERFORMANCE_LOGGING, null)) .ifPresent(l -> setPerformanceLogging(l.booleanValue())); Models.objectLiteral(m.filter(implNode, SERIALIZABLE_VALIDATION, null)) .ifPresent(l -> setSerializableValidation(l.booleanValue())); } catch (IllegalArgumentException e) { throw new SailConfigException("error parsing Sail configuration", e); } } ShaclSailConfig(); boolean isUndefinedTargetValidatesAllSubjects(); boolean isLogValidationPlans(); boolean isLogValidationViolations(); boolean isGlobalLogValidationExecution(); boolean isIgnoreNoShapesLoadedException(); boolean isValidationEnabled(); boolean isParallelValidation(); boolean isCacheSelectNodes(); void setParallelValidation(boolean parallelValidation); void setUndefinedTargetValidatesAllSubjects(boolean undefinedTargetValidatesAllSubjects); void setLogValidationPlans(boolean logValidationPlans); void setLogValidationViolations(boolean logValidationViolations); void setIgnoreNoShapesLoadedException(boolean ignoreNoShapesLoadedException); void setValidationEnabled(boolean validationEnabled); void setCacheSelectNodes(boolean cacheSelectNodes); void setGlobalLogValidationExecution(boolean globalLogValidationExecution); boolean isRdfsSubClassReasoning(); void setRdfsSubClassReasoning(boolean rdfsSubClassReasoning); boolean isPerformanceLogging(); void setPerformanceLogging(boolean performanceLogging); boolean isSerializableValidation(); void setSerializableValidation(boolean serializableValidation); @Override Resource export(Model m); @Override void parse(Model m, Resource implNode); static final boolean PARALLEL_VALIDATION_DEFAULT; static final boolean UNDEFINED_TARGET_VALIDATES_ALL_SUBJECTS_DEFAULT; static final boolean LOG_VALIDATION_PLANS_DEFAULT; static final boolean LOG_VALIDATION_VIOLATIONS_DEFAULT; static final boolean IGNORE_NO_SHAPES_LOADED_EXCEPTION_DEFAULT; static final boolean VALIDATION_ENABLED_DEFAULT; static final boolean CACHE_SELECT_NODES_DEFAULT; static final boolean GLOBAL_LOG_VALIDATION_EXECUTION_DEFAULT; static final boolean RDFS_SUB_CLASS_REASONING_DEFAULT; static final boolean PERFORMANCE_LOGGING_DEFAULT; static final boolean SERIALIZABLE_VALIDATION_DEFAULT; }
@Test(expected = SailConfigException.class) public void parseInvalidModelGivesCorrectException() { mb.add(PARALLEL_VALIDATION, "I'm not a boolean"); subject.parse(mb.build(), implNode); }
ShaclSailConfig extends AbstractDelegatingSailImplConfig { @Override public Resource export(Model m) { Resource implNode = super.export(m); m.setNamespace("sail-shacl", NAMESPACE); m.add(implNode, PARALLEL_VALIDATION, BooleanLiteral.valueOf(isParallelValidation())); m.add(implNode, UNDEFINED_TARGET_VALIDATES_ALL_SUBJECTS, BooleanLiteral.valueOf(isUndefinedTargetValidatesAllSubjects())); m.add(implNode, LOG_VALIDATION_PLANS, BooleanLiteral.valueOf(isLogValidationPlans())); m.add(implNode, LOG_VALIDATION_VIOLATIONS, BooleanLiteral.valueOf(isLogValidationViolations())); m.add(implNode, IGNORE_NO_SHAPES_LOADED_EXCEPTION, BooleanLiteral.valueOf(isIgnoreNoShapesLoadedException())); m.add(implNode, VALIDATION_ENABLED, BooleanLiteral.valueOf(isValidationEnabled())); m.add(implNode, CACHE_SELECT_NODES, BooleanLiteral.valueOf(isCacheSelectNodes())); m.add(implNode, GLOBAL_LOG_VALIDATION_EXECUTION, BooleanLiteral.valueOf(isGlobalLogValidationExecution())); m.add(implNode, RDFS_SUB_CLASS_REASONING, BooleanLiteral.valueOf(isRdfsSubClassReasoning())); m.add(implNode, PERFORMANCE_LOGGING, BooleanLiteral.valueOf(isPerformanceLogging())); m.add(implNode, SERIALIZABLE_VALIDATION, BooleanLiteral.valueOf(isSerializableValidation())); return implNode; } ShaclSailConfig(); boolean isUndefinedTargetValidatesAllSubjects(); boolean isLogValidationPlans(); boolean isLogValidationViolations(); boolean isGlobalLogValidationExecution(); boolean isIgnoreNoShapesLoadedException(); boolean isValidationEnabled(); boolean isParallelValidation(); boolean isCacheSelectNodes(); void setParallelValidation(boolean parallelValidation); void setUndefinedTargetValidatesAllSubjects(boolean undefinedTargetValidatesAllSubjects); void setLogValidationPlans(boolean logValidationPlans); void setLogValidationViolations(boolean logValidationViolations); void setIgnoreNoShapesLoadedException(boolean ignoreNoShapesLoadedException); void setValidationEnabled(boolean validationEnabled); void setCacheSelectNodes(boolean cacheSelectNodes); void setGlobalLogValidationExecution(boolean globalLogValidationExecution); boolean isRdfsSubClassReasoning(); void setRdfsSubClassReasoning(boolean rdfsSubClassReasoning); boolean isPerformanceLogging(); void setPerformanceLogging(boolean performanceLogging); boolean isSerializableValidation(); void setSerializableValidation(boolean serializableValidation); @Override Resource export(Model m); @Override void parse(Model m, Resource implNode); static final boolean PARALLEL_VALIDATION_DEFAULT; static final boolean UNDEFINED_TARGET_VALIDATES_ALL_SUBJECTS_DEFAULT; static final boolean LOG_VALIDATION_PLANS_DEFAULT; static final boolean LOG_VALIDATION_VIOLATIONS_DEFAULT; static final boolean IGNORE_NO_SHAPES_LOADED_EXCEPTION_DEFAULT; static final boolean VALIDATION_ENABLED_DEFAULT; static final boolean CACHE_SELECT_NODES_DEFAULT; static final boolean GLOBAL_LOG_VALIDATION_EXECUTION_DEFAULT; static final boolean RDFS_SUB_CLASS_REASONING_DEFAULT; static final boolean PERFORMANCE_LOGGING_DEFAULT; static final boolean SERIALIZABLE_VALIDATION_DEFAULT; }
@Test public void exportAddsAllConfigData() { Model m = new TreeModel(); Resource node = subject.export(m); assertThat(m.contains(node, PARALLEL_VALIDATION, null)).isTrue(); assertThat(m.contains(node, UNDEFINED_TARGET_VALIDATES_ALL_SUBJECTS, null)).isTrue(); assertThat(m.contains(node, LOG_VALIDATION_PLANS, null)).isTrue(); assertThat(m.contains(node, LOG_VALIDATION_VIOLATIONS, null)).isTrue(); assertThat(m.contains(node, IGNORE_NO_SHAPES_LOADED_EXCEPTION, null)).isTrue(); assertThat(m.contains(node, VALIDATION_ENABLED, null)).isTrue(); assertThat(m.contains(node, CACHE_SELECT_NODES, null)).isTrue(); assertThat(m.contains(node, GLOBAL_LOG_VALIDATION_EXECUTION, null)).isTrue(); assertThat(m.contains(node, RDFS_SUB_CLASS_REASONING, null)).isTrue(); assertThat(m.contains(node, PERFORMANCE_LOGGING, null)).isTrue(); assertThat(m.contains(node, SERIALIZABLE_VALIDATION, null)).isTrue(); }
ShaclSailFactory implements SailFactory { @Override public String getSailType() { return SAIL_TYPE; } @Override String getSailType(); @Override SailImplConfig getConfig(); @Override Sail getSail(SailImplConfig config); static final String SAIL_TYPE; }
@Test public void getSailTypeReturnsCorrectValue() { assertThat(subject.getSailType()).isEqualTo(ShaclSailFactory.SAIL_TYPE); } @Test public void getSailTypeReturnsCorrectValue() { ShaclSailFactory subject = new ShaclSailFactory(); assertThat(subject.getSailType()).isEqualTo(ShaclSailFactory.SAIL_TYPE); }
ShaclSailFactory implements SailFactory { @Override public Sail getSail(SailImplConfig config) throws SailConfigException { if (!SAIL_TYPE.equals(config.getType())) { throw new SailConfigException("Invalid Sail type: " + config.getType()); } ShaclSail sail = new ShaclSail(); if (config instanceof ShaclSailConfig) { ShaclSailConfig shaclSailConfig = (ShaclSailConfig) config; if (shaclSailConfig.isValidationEnabled()) { sail.enableValidation(); } else { sail.disableValidation(); } sail.setCacheSelectNodes(shaclSailConfig.isCacheSelectNodes()); sail.setUndefinedTargetValidatesAllSubjects(shaclSailConfig.isUndefinedTargetValidatesAllSubjects()); sail.setIgnoreNoShapesLoadedException(shaclSailConfig.isIgnoreNoShapesLoadedException()); sail.setLogValidationPlans(shaclSailConfig.isLogValidationPlans()); sail.setLogValidationViolations(shaclSailConfig.isLogValidationViolations()); sail.setParallelValidation(shaclSailConfig.isParallelValidation()); sail.setGlobalLogValidationExecution(shaclSailConfig.isGlobalLogValidationExecution()); sail.setPerformanceLogging(shaclSailConfig.isPerformanceLogging()); sail.setSerializableValidation(shaclSailConfig.isSerializableValidation()); sail.setRdfsSubClassReasoning(shaclSailConfig.isRdfsSubClassReasoning()); } return sail; } @Override String getSailType(); @Override SailImplConfig getConfig(); @Override Sail getSail(SailImplConfig config); static final String SAIL_TYPE; }
@Test public void getSailWithDefaultConfigSetsConfigurationCorrectly() { ShaclSailConfig config = new ShaclSailConfig(); ShaclSail sail = (ShaclSail) subject.getSail(config); assertMatchesConfig(sail, config); } @Test public void getSailWithCustomConfigSetsConfigurationCorrectly() { ShaclSailConfig config = new ShaclSailConfig(); config.setCacheSelectNodes(!config.isCacheSelectNodes()); config.setGlobalLogValidationExecution(!config.isGlobalLogValidationExecution()); config.setIgnoreNoShapesLoadedException(!config.isIgnoreNoShapesLoadedException()); config.setLogValidationPlans(!config.isLogValidationPlans()); config.setLogValidationViolations(!config.isLogValidationViolations()); config.setParallelValidation(!config.isParallelValidation()); config.setUndefinedTargetValidatesAllSubjects(!config.isUndefinedTargetValidatesAllSubjects()); config.setValidationEnabled(!config.isValidationEnabled()); config.setPerformanceLogging(!config.isPerformanceLogging()); config.setSerializableValidation(!config.isSerializableValidation()); config.setRdfsSubClassReasoning(!config.isRdfsSubClassReasoning()); ShaclSail sail = (ShaclSail) subject.getSail(config); assertMatchesConfig(sail, config); }
Buffer implements Function { @Override public Value evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length != 3) { throw new ValueExprEvaluationException(getURI() + " requires exactly 3 arguments, got " + args.length); } SpatialContext geoContext = SpatialSupport.getSpatialContext(); Shape geom = FunctionArguments.getShape(this, args[0], geoContext); double radiusUom = FunctionArguments.getDouble(this, args[1]); IRI units = FunctionArguments.getUnits(this, args[2]); double radiusDegs = FunctionArguments.convertToDegrees(radiusUom, units); Shape buffered = SpatialSupport.getSpatialAlgebra().buffer(geom, radiusDegs); String wkt; try { wkt = SpatialSupport.getWktWriter().toWkt(buffered); } catch (IOException ioe) { throw new ValueExprEvaluationException(ioe); } return valueFactory.createLiteral(wkt, GEO.WKT_LITERAL); } @Override String getURI(); @Override Value evaluate(ValueFactory valueFactory, Value... args); }
@Test public void testEvaluateWithDecimalRadius() { Value result = buffer.evaluate(f, point, f.createLiteral("1.0", XMLSchema.DECIMAL), unit); assertNotNull(result); } @Test(expected = ValueExprEvaluationException.class) public void testEvaluateWithInvalidRadius() { buffer.evaluate(f, point, f.createLiteral("foobar", XMLSchema.DECIMAL), unit); } @Test public void testEvaluateWithIntRadius() { Value result = buffer.evaluate(f, point, f.createLiteral(1), unit); assertNotNull(result); } @Test public void testEvaluateWithDoubleRadius() { Value result = buffer.evaluate(f, point, f.createLiteral(1.0), unit); assertNotNull(result); } @Test public void testEvaluateWithDecimalRadius() { Value result = buffer.evaluate(f, point, f.createLiteral("1.0", XSD.DECIMAL), unit); assertNotNull(result); } @Test public void resultIsPolygonWKT() { Literal result = (Literal) buffer.evaluate(f, point, f.createLiteral(1), unit); assertNotNull(result); assertThat(result.getDatatype()).isEqualTo(GEO.WKT_LITERAL); assertThat(result.getLabel()).startsWith("POLYGON ((23.708505"); } @Test(expected = ValueExprEvaluationException.class) public void testEvaluateWithInvalidRadius() { buffer.evaluate(f, point, f.createLiteral("foobar", XSD.DECIMAL), unit); } @Test(expected = ValueExprEvaluationException.class) public void testEvaluateWithInvalidUnit() { buffer.evaluate(f, point, f.createLiteral(1.0), FOAF.PERSON); }
ProxyRepository extends AbstractRepository implements RepositoryResolverClient { @Override public RepositoryConnection getConnection() throws RepositoryException { return getProxiedRepository().getConnection(); } ProxyRepository(); ProxyRepository(String proxiedIdentity); ProxyRepository(RepositoryResolver resolver, String proxiedIdentity); final void setProxiedIdentity(String value); String getProxiedIdentity(); @Override final void setRepositoryResolver(RepositoryResolver resolver); @Override void setDataDir(File dataDir); @Override File getDataDir(); @Override boolean isWritable(); @Override RepositoryConnection getConnection(); @Override ValueFactory getValueFactory(); }
@Test public final void addDataToProxiedAndCompareToProxy() throws RepositoryException, RDFParseException, IOException { proxied.initialize(); RepositoryConnection connection = proxied.getConnection(); long count; try { connection.add(Thread.currentThread().getContextClassLoader().getResourceAsStream("proxy.ttl"), "http: count = connection.size(); assertThat(count).isNotEqualTo(0L); } finally { connection.close(); } connection = repository.getConnection(); try { assertThat(connection.size()).isEqualTo(count); } finally { connection.close(); } }
SPARQLUpdateDataBlockParser extends TriGParser { @Override protected void parseGraph() throws RDFParseException, RDFHandlerException, IOException { super.parseGraph(); skipOptionalPeriod(); } SPARQLUpdateDataBlockParser(); SPARQLUpdateDataBlockParser(ValueFactory valueFactory); @Override RDFFormat getRDFFormat(); boolean isAllowBlankNodes(); void setAllowBlankNodes(boolean allowBlankNodes); void setLineNumberOffset(int lineNumberOffset); }
@Test public void testParseGraph() throws RDFParseException, RDFHandlerException, IOException { SPARQLUpdateDataBlockParser parser = new SPARQLUpdateDataBlockParser(); String blocksToCheck[] = new String[] { "graph <u:g1> {<u:1> <p:1> 1 } . <u:2> <p:2> 2.", "graph <u:g1> {<u:1> <p:1> 1 .} . <u:2> <p:2> 2." }; for (String block : blocksToCheck) { parser.parse(new StringReader(block), "http: } }
ProxyRepositoryFactory implements RepositoryFactory { @Override public Repository getRepository(RepositoryImplConfig config) throws RepositoryConfigException { ProxyRepository result = null; if (config instanceof ProxyRepositoryConfig) { result = new ProxyRepository(((ProxyRepositoryConfig) config).getProxiedRepositoryID()); } else { throw new RepositoryConfigException("Invalid configuration class: " + config.getClass()); } return result; } @Override String getRepositoryType(); @Override RepositoryImplConfig getConfig(); @Override Repository getRepository(RepositoryImplConfig config); static final String REPOSITORY_TYPE; }
@Test public final void testGetRepository() throws RDF4JException, IOException { Model graph = Rio.parse(this.getClass().getResourceAsStream("/proxy.ttl"), RepositoryConfigSchema.NAMESPACE, RDFFormat.TURTLE); RepositoryConfig config = RepositoryConfig.create(graph, Models.subject(graph.filter(null, RDF.TYPE, RepositoryConfigSchema.REPOSITORY)) .orElseThrow(() -> new RepositoryConfigException("missing Repository instance in config"))); config.validate(); assertThat(config.getID()).isEqualTo("proxy"); assertThat(config.getTitle()).isEqualTo("Test Proxy for 'memory'"); RepositoryImplConfig implConfig = config.getRepositoryImplConfig(); assertThat(implConfig.getType()).isEqualTo("openrdf:ProxyRepository"); assertThat(implConfig).isInstanceOf(ProxyRepositoryConfig.class); assertThat(((ProxyRepositoryConfig) implConfig).getProxiedRepositoryID()).isEqualTo("memory"); ProxyRepository repository = (ProxyRepository) factory.getRepository(implConfig); repository.setRepositoryResolver(mock(RepositoryResolver.class)); assertThat(repository).isInstanceOf(ProxyRepository.class); } @Test public final void testGetRepository() throws RDF4JException, IOException { Model graph = Rio.parse(this.getClass().getResourceAsStream("/proxy.ttl"), RepositoryConfigSchema.NAMESPACE, RDFFormat.TURTLE); RepositoryConfig config = RepositoryConfig.create(graph, Models.subject(graph.getStatements(null, RDF.TYPE, RepositoryConfigSchema.REPOSITORY)) .orElseThrow(() -> new RepositoryConfigException("missing Repository instance in config"))); config.validate(); assertThat(config.getID()).isEqualTo("proxy"); assertThat(config.getTitle()).isEqualTo("Test Proxy for 'memory'"); RepositoryImplConfig implConfig = config.getRepositoryImplConfig(); assertThat(implConfig.getType()).isEqualTo("openrdf:ProxyRepository"); assertThat(implConfig).isInstanceOf(ProxyRepositoryConfig.class); assertThat(((ProxyRepositoryConfig) implConfig).getProxiedRepositoryID()).isEqualTo("memory"); ProxyRepository repository = (ProxyRepository) factory.getRepository(implConfig); repository.setRepositoryResolver(mock(RepositoryResolver.class)); assertThat(repository).isInstanceOf(ProxyRepository.class); }
OrderComparator implements Comparator<BindingSet>, Serializable { @Override public int compare(BindingSet o1, BindingSet o2) { try { for (OrderElem element : order.getElements()) { Value v1 = evaluate(element.getExpr(), o1); Value v2 = evaluate(element.getExpr(), o2); int compare = cmp.compare(v1, v2); if (compare != 0) { return element.isAscending() ? compare : -compare; } } if (o1 == null || o2 == null) { if (o1 == null) { return o2 == null ? 0 : 1; } if (o2 == null) { return o1 == null ? 0 : -1; } } if (o2.size() != o1.size()) { return o1.size() < o2.size() ? 1 : -1; } final ArrayList<String> o1bindingNamesOrdered = new ArrayList<>(o1.getBindingNames()); Collections.sort(o1bindingNamesOrdered); if (!o1.getBindingNames().equals(o2.getBindingNames())) { final ArrayList<String> o2bindingNamesOrdered = new ArrayList<>(o2.getBindingNames()); Collections.sort(o2bindingNamesOrdered); for (int i = 0; i < o1bindingNamesOrdered.size(); i++) { String o1bn = o1bindingNamesOrdered.get(i); String o2bn = o2bindingNamesOrdered.get(i); int compare = o1bn.compareTo(o2bn); if (compare != 0) { return compare; } } } for (String bindingName : o1bindingNamesOrdered) { final Value v1 = o1.getValue(bindingName); final Value v2 = o2.getValue(bindingName); final int compare = cmp.compare(v1, v2); if (compare != 0) { return compare; } } return 0; } catch (QueryEvaluationException e) { logger.debug(e.getMessage(), e); return 0; } catch (IllegalArgumentException e) { logger.debug(e.getMessage(), e); return 0; } } OrderComparator(EvaluationStrategy strategy, Order order, ValueComparator vcmp); @Override int compare(BindingSet o1, BindingSet o2); }
@Test public void testEquals() throws Exception { order.addElement(asc); cmp.setIterator(Arrays.asList(ZERO).iterator()); OrderComparator sud = new OrderComparator(strategy, order, cmp); assertTrue(sud.compare(null, null) == 0); } @Test public void testZero() throws Exception { order.addElement(asc); order.addElement(asc); cmp.setIterator(Arrays.asList(ZERO, POS).iterator()); OrderComparator sud = new OrderComparator(strategy, order, cmp); assertTrue(sud.compare(null, null) > 0); } @Test public void testTerm() throws Exception { order.addElement(asc); order.addElement(asc); cmp.setIterator(Arrays.asList(POS, NEG).iterator()); OrderComparator sud = new OrderComparator(strategy, order, cmp); assertTrue(sud.compare(null, null) > 0); } @Test public void testAscLessThan() throws Exception { order.addElement(asc); cmp.setIterator(Arrays.asList(NEG).iterator()); OrderComparator sud = new OrderComparator(strategy, order, cmp); assertTrue(sud.compare(null, null) < 0); } @Test public void testAscGreaterThan() throws Exception { order.addElement(asc); cmp.setIterator(Arrays.asList(POS).iterator()); OrderComparator sud = new OrderComparator(strategy, order, cmp); assertTrue(sud.compare(null, null) > 0); } @Test public void testDescLessThan() throws Exception { order.addElement(desc); cmp.setIterator(Arrays.asList(NEG).iterator()); OrderComparator sud = new OrderComparator(strategy, order, cmp); assertTrue(sud.compare(null, null) > 0); } @Test public void testDescGreaterThan() throws Exception { order.addElement(desc); cmp.setIterator(Arrays.asList(POS).iterator()); OrderComparator sud = new OrderComparator(strategy, order, cmp); assertTrue(sud.compare(null, null) < 0); } @Test public void testDisjunctBindingNames() throws Exception { OrderComparator sud = new OrderComparator(strategy, order, cmp); QueryBindingSet a = new QueryBindingSet(); QueryBindingSet b = new QueryBindingSet(); a.addBinding("a", ValueFactoryImpl.getInstance().createLiteral("a")); b.addBinding("b", ValueFactoryImpl.getInstance().createLiteral("b")); assertTrue(sud.compare(a, b) != 0); assertTrue(sud.compare(a, b) != sud.compare(b, a)); } @Test public void testEqualBindingNamesUnequalValues() { OrderComparator sud = new OrderComparator(strategy, order, new ValueComparator()); QueryBindingSet a = new QueryBindingSet(); QueryBindingSet b = new QueryBindingSet(); a.addBinding("a", ValueFactoryImpl.getInstance().createLiteral("ab")); a.addBinding("b", ValueFactoryImpl.getInstance().createLiteral("b")); b.addBinding("b", ValueFactoryImpl.getInstance().createLiteral("b")); b.addBinding("a", ValueFactoryImpl.getInstance().createLiteral("ac")); assertTrue(sud.compare(a, b) < 0); assertTrue(sud.compare(a, b) != sud.compare(b, a)); }
QuerySpecBuilder implements SearchQueryInterpreter { @SuppressWarnings("unchecked") @Deprecated public Set<QuerySpec> process(TupleExpr tupleExpr, BindingSet bindings) throws SailException { HashSet<QuerySpec> result = new HashSet<>(); process(tupleExpr, bindings, (Collection<SearchQueryEvaluator>) (Collection<?>) result); return result; } QuerySpecBuilder(boolean incompleteQueryFails); @SuppressWarnings("unchecked") @Deprecated Set<QuerySpec> process(TupleExpr tupleExpr, BindingSet bindings); @Override void process(TupleExpr tupleExpr, BindingSet bindings, Collection<SearchQueryEvaluator> result); }
@Test public void testMultipleQueriesInterpretation() throws Exception { StringBuilder buffer = new StringBuilder(); buffer.append("SELECT sub1, score1, snippet1, sub2, score2, snippet2, x, p1, p2 "); buffer.append("FROM {sub1} <" + MATCHES + "> {} "); buffer.append("<" + TYPE + "> {<" + LUCENE_QUERY + ">}; "); buffer.append("<" + QUERY + "> {\"my Lucene query\"}; "); buffer.append("<" + SCORE + "> {score1}; "); buffer.append("<" + SNIPPET + "> {snippet1}, "); buffer.append("{sub2} <" + MATCHES + "> {} "); buffer.append("<" + TYPE + "> {<" + LUCENE_QUERY + ">}; "); buffer.append("<" + QUERY + "> {\"second lucene query\"}; "); buffer.append("<" + SCORE + "> {score2}; "); buffer.append("<" + SNIPPET + "> {snippet2}, "); buffer.append("{sub1} p1 {x}, {x} p2 {sub2} "); ParsedQuery query = parser.parseQuery(buffer.toString(), null); TupleExpr tupleExpr = query.getTupleExpr(); Collection<SearchQueryEvaluator> queries = process(interpreter, tupleExpr); assertEquals(2, queries.size()); Iterator<SearchQueryEvaluator> i = queries.iterator(); boolean matched1 = false; boolean matched2 = false; while (i.hasNext()) { QuerySpec querySpec = (QuerySpec) i.next(); if ("sub1".equals(querySpec.getMatchesVariableName())) { assertEquals("sub1", querySpec.getMatchesPattern().getSubjectVar().getName()); assertEquals("my Lucene query", ((Literal) querySpec.getQueryPattern().getObjectVar().getValue()).getLabel()); assertEquals("score1", querySpec.getScorePattern().getObjectVar().getName()); assertEquals("snippet1", querySpec.getSnippetPattern().getObjectVar().getName()); assertEquals(LUCENE_QUERY, querySpec.getTypePattern().getObjectVar().getValue()); assertEquals("my Lucene query", querySpec.getQueryString()); assertNull(querySpec.getSubject()); matched1 = true; } else if ("sub2".equals(querySpec.getMatchesVariableName())) { assertEquals("sub2", querySpec.getMatchesPattern().getSubjectVar().getName()); assertEquals("second lucene query", ((Literal) querySpec.getQueryPattern().getObjectVar().getValue()).getLabel()); assertEquals("score2", querySpec.getScorePattern().getObjectVar().getName()); assertEquals("snippet2", querySpec.getSnippetPattern().getObjectVar().getName()); assertEquals(LUCENE_QUERY, querySpec.getTypePattern().getObjectVar().getValue()); assertEquals("second lucene query", querySpec.getQueryString()); assertNull(querySpec.getSubject()); matched2 = true; } else fail("Found unexpected query spec: " + querySpec.toString()); } if (!matched1) fail("did not find query patter sub1"); if (!matched2) fail("did not find query patter sub2"); } @Test public void testQueryInterpretation() throws Exception { StringBuilder buffer = new StringBuilder(); buffer.append("SELECT Subject, Score, Snippet "); buffer.append("FROM {Subject} <" + MATCHES + "> {} "); buffer.append("<" + TYPE + "> {<" + LUCENE_QUERY + ">}; "); buffer.append("<" + QUERY + "> {\"my Lucene query\"}; "); buffer.append("<" + SCORE + "> {Score}; "); buffer.append("<" + SNIPPET + "> {Snippet} "); ParsedQuery query = parser.parseQuery(buffer.toString(), null); TupleExpr tupleExpr = query.getTupleExpr(); System.out.print(buffer.toString()); Collection<SearchQueryEvaluator> queries = process(interpreter, tupleExpr); assertEquals(1, queries.size()); QuerySpec querySpec = (QuerySpec) queries.iterator().next(); assertEquals("Subject", querySpec.getMatchesPattern().getSubjectVar().getName()); assertEquals("my Lucene query", ((Literal) querySpec.getQueryPattern().getObjectVar().getValue()).getLabel()); assertEquals("Score", querySpec.getScorePattern().getObjectVar().getName()); assertEquals("Snippet", querySpec.getSnippetPattern().getObjectVar().getName()); assertEquals(LUCENE_QUERY, querySpec.getTypePattern().getObjectVar().getValue()); assertEquals("my Lucene query", querySpec.getQueryString()); assertNull(querySpec.getSubject()); } @Test public void testMultipleQueriesInterpretation() throws Exception { StringBuilder buffer = new StringBuilder(); buffer.append("SELECT sub1, score1, snippet1, sub2, score2, snippet2, x, p1, p2 "); buffer.append("FROM {sub1} <" + MATCHES + "> {} "); buffer.append("<" + TYPE + "> {<" + LUCENE_QUERY + ">}; "); buffer.append("<" + QUERY + "> {\"my Lucene query\"}; "); buffer.append("<" + SCORE + "> {score1}; "); buffer.append("<" + SNIPPET + "> {snippet1}, "); buffer.append("{sub2} <" + MATCHES + "> {} "); buffer.append("<" + TYPE + "> {<" + LUCENE_QUERY + ">}; "); buffer.append("<" + QUERY + "> {\"second lucene query\"}; "); buffer.append("<" + SCORE + "> {score2}; "); buffer.append("<" + SNIPPET + "> {snippet2}, "); buffer.append("{sub1} p1 {x}, {x} p2 {sub2} "); ParsedQuery query = parser.parseQuery(buffer.toString(), null); TupleExpr tupleExpr = query.getTupleExpr(); Collection<SearchQueryEvaluator> queries = process(interpreter, tupleExpr); assertEquals(2, queries.size()); Iterator<SearchQueryEvaluator> i = queries.iterator(); boolean matched1 = false; boolean matched2 = false; while (i.hasNext()) { QuerySpec querySpec = (QuerySpec) i.next(); if ("sub1".equals(querySpec.getMatchesVariableName())) { assertEquals("sub1", querySpec.getMatchesPattern().getSubjectVar().getName()); assertEquals("my Lucene query", ((Literal) querySpec.getQueryPattern().getObjectVar().getValue()).getLabel()); assertEquals("score1", querySpec.getScorePattern().getObjectVar().getName()); assertEquals("snippet1", querySpec.getSnippetPattern().getObjectVar().getName()); assertEquals(LUCENE_QUERY, querySpec.getTypePattern().getObjectVar().getValue()); assertEquals("my Lucene query", querySpec.getQueryString()); assertNull(querySpec.getSubject()); matched1 = true; } else if ("sub2".equals(querySpec.getMatchesVariableName())) { assertEquals("sub2", querySpec.getMatchesPattern().getSubjectVar().getName()); assertEquals("second lucene query", ((Literal) querySpec.getQueryPattern().getObjectVar().getValue()).getLabel()); assertEquals("score2", querySpec.getScorePattern().getObjectVar().getName()); assertEquals("snippet2", querySpec.getSnippetPattern().getObjectVar().getName()); assertEquals(LUCENE_QUERY, querySpec.getTypePattern().getObjectVar().getValue()); assertEquals("second lucene query", querySpec.getQueryString()); assertNull(querySpec.getSubject()); matched2 = true; } else { fail("Found unexpected query spec: " + querySpec.toString()); } } if (!matched1) { fail("did not find query patter sub1"); } if (!matched2) { fail("did not find query patter sub2"); } }
ValueComparator implements Comparator<Value> { @Override public int compare(Value o1, Value o2) { if (ObjectUtil.nullEquals(o1, o2)) { return 0; } if (o1 == null) { return -1; } if (o2 == null) { return 1; } boolean b1 = o1 instanceof BNode; boolean b2 = o2 instanceof BNode; if (b1 && b2) { return compareBNodes((BNode) o1, (BNode) o2); } if (b1) { return -1; } if (b2) { return 1; } boolean u1 = o1 instanceof IRI; boolean u2 = o2 instanceof IRI; if (u1 && u2) { return compareURIs((IRI) o1, (IRI) o2); } if (u1) { return -1; } if (u2) { return 1; } return compareLiterals((Literal) o1, (Literal) o2); } @Override int compare(Value o1, Value o2); }
@Test public void testBothNull() throws Exception { assertTrue(cmp.compare(null, null) == 0); } @Test public void testLeftNull() throws Exception { assertTrue(cmp.compare(null, typed1) < 0); } @Test public void testRightNull() throws Exception { assertTrue(cmp.compare(typed1, null) > 0); } @Test public void testBothBnode() throws Exception { assertTrue(cmp.compare(bnode1, bnode1) == 0); assertTrue(cmp.compare(bnode2, bnode2) == 0); assertTrue(cmp.compare(bnode1, bnode2) != cmp.compare(bnode2, bnode1)); assertTrue(cmp.compare(bnode1, bnode2) == -1 * cmp.compare(bnode2, bnode1)); } @Test public void testLeftBnode() throws Exception { assertTrue(cmp.compare(bnode1, typed1) < 0); } @Test public void testRightBnode() throws Exception { assertTrue(cmp.compare(typed1, bnode1) > 0); } @Test public void testBothURI() throws Exception { assertTrue(cmp.compare(uri1, uri1) == 0); assertTrue(cmp.compare(uri1, uri2) < 0); assertTrue(cmp.compare(uri1, uri3) < 0); assertTrue(cmp.compare(uri2, uri1) > 0); assertTrue(cmp.compare(uri2, uri2) == 0); assertTrue(cmp.compare(uri2, uri3) < 0); assertTrue(cmp.compare(uri3, uri1) > 0); assertTrue(cmp.compare(uri3, uri2) > 0); assertTrue(cmp.compare(uri3, uri3) == 0); } @Test public void testLeftURI() throws Exception { assertTrue(cmp.compare(uri1, typed1) < 0); } @Test public void testRightURI() throws Exception { assertTrue(cmp.compare(typed1, uri1) > 0); }
DistanceQuerySpec extends AbstractSearchQueryEvaluator { @Override public QueryModelNode getParentQueryModelNode() { return filter; } DistanceQuerySpec(FunctionCall distanceFunction, ValueExpr distanceExpr, String distVar, Filter filter); DistanceQuerySpec(Literal from, IRI units, double dist, String distVar, IRI geoProperty, String geoVar, String subjectVar, Var contextVar); void setFrom(Literal from); Literal getFrom(); void setUnits(IRI units); IRI getUnits(); void setDistance(double d); double getDistance(); void setDistanceVar(String varName); String getDistanceVar(); void setGeometryPattern(StatementPattern sp); String getSubjectVar(); Var getContextVar(); IRI getGeoProperty(); String getGeoVar(); void setDistanceFunctionCall(FunctionCall distanceFunction); FunctionCall getDistanceFunctionCall(); ValueExpr getDistanceExpr(); void setFilter(Filter f); Filter getFilter(); @Override QueryModelNode getParentQueryModelNode(); @Override QueryModelNode removeQueryPatterns(); boolean isEvaluable(); }
@Test public void testReplaceQueryPatternsWithNonEmptyResults() { final String expectedQueryPlan = "Projection\n" + " ProjectionElemList\n" + " ProjectionElem \"toUri\"\n" + " ProjectionElem \"to\"\n" + " BindingSetAssignment ([[toUri=urn:subject1;to=\"POINT (2.2945 48.8582)\"^^<http: final ParsedQuery query = parseQuery(QUERY); final List<SearchQueryEvaluator> queries = new ArrayList<>(); new DistanceQuerySpecBuilder(new SearchIndexImpl()) .process(query.getTupleExpr(), EmptyBindingSet.getInstance(), queries); assertEquals(1, queries.size()); final DistanceQuerySpec querySpec = (DistanceQuerySpec) queries.get(0); final MapBindingSet bindingSet = new MapBindingSet(); bindingSet.addBinding("toUri", VF.createIRI("urn:subject1")); bindingSet.addBinding("to", VF.createLiteral("POINT (2.2945 48.8582)", GEO.WKT_LITERAL)); BindingSetAssignment bsa = new BindingSetAssignment(); bsa.setBindingSets(Collections.singletonList(bindingSet)); querySpec.replaceQueryPatternsWithResults(bsa); assertEquals( expectedQueryPlan, querySpec.getParentQueryModelNode().getParentNode().toString()); } @Test public void testReplaceQueryPatternsWithEmptyResults() { final String expectedQueryPlan = "Projection\n" + " ProjectionElemList\n" + " ProjectionElem \"toUri\"\n" + " ProjectionElem \"to\"\n" + " EmptySet\n"; final ParsedQuery query = parseQuery(QUERY); final List<SearchQueryEvaluator> queries = new ArrayList<>(); new DistanceQuerySpecBuilder(new SearchIndexImpl()) .process(query.getTupleExpr(), EmptyBindingSet.getInstance(), queries); assertEquals(1, queries.size()); final DistanceQuerySpec querySpec = (DistanceQuerySpec) queries.get(0); querySpec.replaceQueryPatternsWithResults(new BindingSetAssignment()); assertEquals( expectedQueryPlan, querySpec.getParentQueryModelNode().getParentNode().toString()); } @Test public void testReplaceQueryPatternsWithNonEmptyResults() { final String expectedQueryPlan = "Projection\n" + " ProjectionElemList\n" + " ProjectionElem \"toUri\"\n" + " ProjectionElem \"to\"\n" + " BindingSetAssignment ([[toUri=urn:subject1;to=\"POINT (2.2945 48.8582)\"^^<http: final ParsedQuery query = parseQuery(QUERY); final List<SearchQueryEvaluator> queries = new ArrayList<>(); new DistanceQuerySpecBuilder(new SearchIndexImpl()) .process(query.getTupleExpr(), EmptyBindingSet.getInstance(), queries); assertEquals(1, queries.size()); final DistanceQuerySpec querySpec = (DistanceQuerySpec) queries.get(0); final MapBindingSet bindingSet = new MapBindingSet(); bindingSet.addBinding("toUri", VF.createIRI("urn:subject1")); bindingSet.addBinding("to", VF.createLiteral("POINT (2.2945 48.8582)", GEO.WKT_LITERAL)); BindingSetAssignment bsa = new BindingSetAssignment(); bsa.setBindingSets(Collections.singletonList(bindingSet)); querySpec.replaceQueryPatternsWithResults(bsa); String result = querySpec.getParentQueryModelNode().getParentNode().toString().replaceAll("\r\n|\r", "\n"); assertEquals(expectedQueryPlan, result); } @Test public void testReplaceQueryPatternsWithEmptyResults() { final String expectedQueryPlan = "Projection\n" + " ProjectionElemList\n" + " ProjectionElem \"toUri\"\n" + " ProjectionElem \"to\"\n" + " EmptySet\n"; final ParsedQuery query = parseQuery(QUERY); final List<SearchQueryEvaluator> queries = new ArrayList<>(); new DistanceQuerySpecBuilder(new SearchIndexImpl()) .process(query.getTupleExpr(), EmptyBindingSet.getInstance(), queries); assertEquals(1, queries.size()); final DistanceQuerySpec querySpec = (DistanceQuerySpec) queries.get(0); querySpec.replaceQueryPatternsWithResults(new BindingSetAssignment()); String result = querySpec.getParentQueryModelNode().getParentNode().toString().replaceAll("\r\n|\r", "\n"); assertEquals(expectedQueryPlan, result); }
XMLDatatypeMathUtil { public static Literal compute(Literal leftLit, Literal rightLit, MathOp op) throws ValueExprEvaluationException { IRI leftDatatype = leftLit.getDatatype(); IRI rightDatatype = rightLit.getDatatype(); if (XMLDatatypeUtil.isNumericDatatype(leftDatatype) && XMLDatatypeUtil.isNumericDatatype(rightDatatype)) { return MathUtil.compute(leftLit, rightLit, op); } else if (XMLDatatypeUtil.isDurationDatatype(leftDatatype) && XMLDatatypeUtil.isDurationDatatype(rightDatatype)) { return operationsBetweenDurations(leftLit, rightLit, op); } else if (XMLDatatypeUtil.isDecimalDatatype(leftDatatype) && XMLDatatypeUtil.isDurationDatatype(rightDatatype)) { return operationsBetweenDurationAndDecimal(rightLit, leftLit, op); } else if (XMLDatatypeUtil.isDurationDatatype(leftDatatype) && XMLDatatypeUtil.isDecimalDatatype(rightDatatype)) { return operationsBetweenDurationAndDecimal(leftLit, rightLit, op); } else if (XMLDatatypeUtil.isCalendarDatatype(leftDatatype) && XMLDatatypeUtil.isDurationDatatype(rightDatatype)) { return operationsBetweenCalendarAndDuration(leftLit, rightLit, op); } else if (XMLDatatypeUtil.isDurationDatatype(leftDatatype) && XMLDatatypeUtil.isCalendarDatatype(rightDatatype)) { return operationsBetweenDurationAndCalendar(leftLit, rightLit, op); } else { throw new ValueExprEvaluationException("Mathematical operators are not supported on these operands"); } } static Literal compute(Literal leftLit, Literal rightLit, MathOp op); }
@Test public void testCompute() throws Exception { Literal float1 = vf.createLiteral("12", XMLSchema.INTEGER); Literal float2 = vf.createLiteral("2", XMLSchema.INTEGER); Literal duration1 = vf.createLiteral("P1Y1M", XMLSchema.YEARMONTHDURATION); Literal duration2 = vf.createLiteral("P1Y", XMLSchema.YEARMONTHDURATION); Literal yearMonth1 = vf.createLiteral("2012-10", XMLSchema.GYEARMONTH); assertComputeEquals(vf.createLiteral("14", XMLSchema.INTEGER), float1, float2, MathOp.PLUS); assertComputeEquals(vf.createLiteral("10", XMLSchema.INTEGER), float1, float2, MathOp.MINUS); assertComputeEquals(vf.createLiteral("24", XMLSchema.INTEGER), float1, float2, MathOp.MULTIPLY); assertComputeEquals(vf.createLiteral("6", XMLSchema.DECIMAL), float1, float2, MathOp.DIVIDE); assertComputeEquals(vf.createLiteral("P2Y1M", XMLSchema.YEARMONTHDURATION), duration1, duration2, MathOp.PLUS); assertComputeEquals(vf.createLiteral("P0Y1M", XMLSchema.YEARMONTHDURATION), duration1, duration2, MathOp.MINUS); assertComputeEquals(vf.createLiteral("P12Y", XMLSchema.YEARMONTHDURATION), float1, duration2, MathOp.MULTIPLY); assertComputeEquals(vf.createLiteral("P12Y", XMLSchema.YEARMONTHDURATION), duration2, float1, MathOp.MULTIPLY); assertComputeEquals(vf.createLiteral("2013-11", XMLSchema.GYEARMONTH), yearMonth1, duration1, MathOp.PLUS); assertComputeEquals(vf.createLiteral("2011-09", XMLSchema.GYEARMONTH), yearMonth1, duration1, MathOp.MINUS); assertComputeEquals(vf.createLiteral("2013-11", XMLSchema.GYEARMONTH), duration1, yearMonth1, MathOp.PLUS); } @Test public void testCompute() throws Exception { Literal float1 = vf.createLiteral("12", XSD.INTEGER); Literal float2 = vf.createLiteral("2", XSD.INTEGER); Literal duration1 = vf.createLiteral("P1Y1M", XSD.YEARMONTHDURATION); Literal duration2 = vf.createLiteral("P1Y", XSD.YEARMONTHDURATION); Literal yearMonth1 = vf.createLiteral("2012-10", XSD.GYEARMONTH); assertComputeEquals(vf.createLiteral("14", XSD.INTEGER), float1, float2, MathOp.PLUS); assertComputeEquals(vf.createLiteral("10", XSD.INTEGER), float1, float2, MathOp.MINUS); assertComputeEquals(vf.createLiteral("24", XSD.INTEGER), float1, float2, MathOp.MULTIPLY); assertComputeEquals(vf.createLiteral("6", XSD.DECIMAL), float1, float2, MathOp.DIVIDE); assertComputeEquals(vf.createLiteral("P2Y1M", XSD.YEARMONTHDURATION), duration1, duration2, MathOp.PLUS); assertComputeEquals(vf.createLiteral("P0Y1M", XSD.YEARMONTHDURATION), duration1, duration2, MathOp.MINUS); assertComputeEquals(vf.createLiteral("P12Y", XSD.YEARMONTHDURATION), float1, duration2, MathOp.MULTIPLY); assertComputeEquals(vf.createLiteral("P12Y", XSD.YEARMONTHDURATION), duration2, float1, MathOp.MULTIPLY); assertComputeEquals(vf.createLiteral("2013-11", XSD.GYEARMONTH), yearMonth1, duration1, MathOp.PLUS); assertComputeEquals(vf.createLiteral("2011-09", XSD.GYEARMONTH), yearMonth1, duration1, MathOp.MINUS); assertComputeEquals(vf.createLiteral("2013-11", XSD.GYEARMONTH), duration1, yearMonth1, MathOp.PLUS); }
Rand implements Function { @Override public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length != 0) { throw new ValueExprEvaluationException("RAND requires 0 arguments, got " + args.length); } Random randomGenerator = new Random(); double randomValue = randomGenerator.nextDouble(); return valueFactory.createLiteral(randomValue); } @Override String getURI(); @Override Literal evaluate(ValueFactory valueFactory, Value... args); }
@Test public void testEvaluate() { try { Literal random = rand.evaluate(f); assertNotNull(random); assertEquals(XMLSchema.DOUBLE, random.getDatatype()); double randomValue = random.doubleValue(); assertTrue(randomValue >= 0.0d); assertTrue(randomValue < 1.0d); } catch (ValueExprEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testEvaluate() { try { Literal random = rand.evaluate(f); assertNotNull(random); assertEquals(XSD.DOUBLE, random.getDatatype()); double randomValue = random.doubleValue(); assertTrue(randomValue >= 0.0d); assertTrue(randomValue < 1.0d); } catch (ValueExprEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } }
Round implements Function { @Override public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length != 1) { throw new ValueExprEvaluationException("ROUND requires exactly 1 argument, got " + args.length); } if (args[0] instanceof Literal) { Literal literal = (Literal) args[0]; IRI datatype = literal.getDatatype(); if (datatype != null && XMLDatatypeUtil.isNumericDatatype(datatype)) { if (XMLDatatypeUtil.isIntegerDatatype(datatype)) { return literal; } else if (XMLDatatypeUtil.isDecimalDatatype(datatype)) { BigDecimal rounded = literal.decimalValue().setScale(0, RoundingMode.HALF_UP); return valueFactory.createLiteral(rounded.toPlainString(), datatype); } else if (XMLDatatypeUtil.isFloatingPointDatatype(datatype)) { double ceilingValue = Math.round(literal.doubleValue()); return valueFactory.createLiteral(Double.toString(ceilingValue), datatype); } else { throw new ValueExprEvaluationException("unexpected datatype for function operand: " + args[0]); } } else { throw new ValueExprEvaluationException("unexpected input value for function: " + args[0]); } } else { throw new ValueExprEvaluationException("unexpected input value for function: " + args[0]); } } @Override String getURI(); @Override Literal evaluate(ValueFactory valueFactory, Value... args); }
@Test public void testEvaluateBigDecimal() { try { BigDecimal bd = new BigDecimal(1234567.567); Literal rounded = round.evaluate(f, f.createLiteral(bd.toPlainString(), XMLSchema.DECIMAL)); BigDecimal roundValue = rounded.decimalValue(); assertEquals(new BigDecimal(1234568.0), roundValue); } catch (ValueExprEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testEvaluateDouble() { try { double dVal = 1.6; Literal rounded = round.evaluate(f, f.createLiteral(dVal)); double roundValue = rounded.doubleValue(); assertEquals((double) 2.0, roundValue, 0.001d); } catch (ValueExprEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testEvaluateInt() { try { int iVal = 1; Literal rounded = round.evaluate(f, f.createLiteral(iVal)); int roundValue = rounded.intValue(); assertEquals(iVal, roundValue); } catch (ValueExprEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testEvaluateBigDecimal() { try { BigDecimal bd = new BigDecimal(1234567.567); Literal rounded = round.evaluate(f, f.createLiteral(bd.toPlainString(), XSD.DECIMAL)); BigDecimal roundValue = rounded.decimalValue(); assertEquals(new BigDecimal(1234568.0), roundValue); } catch (ValueExprEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } }
Tz implements Function { @Override public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length != 1) { throw new ValueExprEvaluationException("TZ requires 1 argument, got " + args.length); } Value argValue = args[0]; if (argValue instanceof Literal) { Literal literal = (Literal) argValue; IRI datatype = literal.getDatatype(); if (datatype != null && XMLDatatypeUtil.isCalendarDatatype(datatype)) { String lexValue = literal.getLabel(); Pattern pattern = Pattern.compile("Z|[+-]\\d\\d:\\d\\d"); Matcher m = pattern.matcher(lexValue); String timeZone = ""; if (m.find()) { timeZone = m.group(); } return valueFactory.createLiteral(timeZone); } else { throw new ValueExprEvaluationException("unexpected input value for function: " + argValue); } } else { throw new ValueExprEvaluationException("unexpected input value for function: " + args[0]); } } @Override String getURI(); @Override Literal evaluate(ValueFactory valueFactory, Value... args); }
@Test public void testEvaluate1() { try { Literal result = tz.evaluate(f, f.createLiteral("2011-01-10T14:45:13.815-05:00", XMLSchema.DATETIME)); assertNotNull(result); assertEquals(XMLSchema.STRING, result.getDatatype()); assertEquals("-05:00", result.getLabel()); } catch (ValueExprEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testEvaluate2() { try { Literal result = tz.evaluate(f, f.createLiteral("2011-01-10T14:45:13.815Z", XMLSchema.DATETIME)); assertNotNull(result); assertEquals(XMLSchema.STRING, result.getDatatype()); assertEquals("Z", result.getLabel()); } catch (ValueExprEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testEvaluate3() { try { Literal result = tz.evaluate(f, f.createLiteral("2011-01-10T14:45:13.815", XMLSchema.DATETIME)); assertNotNull(result); assertEquals(XMLSchema.STRING, result.getDatatype()); assertEquals("", result.getLabel()); } catch (ValueExprEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testEvaluate1() { try { Literal result = tz.evaluate(f, f.createLiteral("2011-01-10T14:45:13.815-05:00", XSD.DATETIME)); assertNotNull(result); assertEquals(XSD.STRING, result.getDatatype()); assertEquals("-05:00", result.getLabel()); } catch (ValueExprEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testEvaluate2() { try { Literal result = tz.evaluate(f, f.createLiteral("2011-01-10T14:45:13.815Z", XSD.DATETIME)); assertNotNull(result); assertEquals(XSD.STRING, result.getDatatype()); assertEquals("Z", result.getLabel()); } catch (ValueExprEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testEvaluate3() { try { Literal result = tz.evaluate(f, f.createLiteral("2011-01-10T14:45:13.815", XSD.DATETIME)); assertNotNull(result); assertEquals(XSD.STRING, result.getDatatype()); assertEquals("", result.getLabel()); } catch (ValueExprEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } }
Timezone implements Function { @Override public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length != 1) { throw new ValueExprEvaluationException("TIMEZONE requires 1 argument, got " + args.length); } Value argValue = args[0]; if (argValue instanceof Literal) { Literal literal = (Literal) argValue; IRI datatype = literal.getDatatype(); if (datatype != null && XMLDatatypeUtil.isCalendarDatatype(datatype)) { try { XMLGregorianCalendar calValue = literal.calendarValue(); int timezoneOffset = calValue.getTimezone(); if (DatatypeConstants.FIELD_UNDEFINED != timezoneOffset) { int minutes = Math.abs(timezoneOffset); int hours = minutes / 60; minutes = minutes - (hours * 60); StringBuilder tzDuration = new StringBuilder(); if (timezoneOffset < 0) { tzDuration.append("-"); } tzDuration.append("PT"); if (hours > 0) { tzDuration.append(hours + "H"); } if (minutes > 0) { tzDuration.append(minutes + "M"); } if (timezoneOffset == 0) { tzDuration.append("0S"); } return valueFactory.createLiteral(tzDuration.toString(), XMLSchema.DAYTIMEDURATION); } else { throw new ValueExprEvaluationException("can not determine timezone from value: " + argValue); } } catch (IllegalArgumentException e) { throw new ValueExprEvaluationException("illegal calendar value: " + argValue); } } else { throw new ValueExprEvaluationException("unexpected input value for function: " + argValue); } } else { throw new ValueExprEvaluationException("unexpected input value for function: " + args[0]); } } @Override String getURI(); @Override Literal evaluate(ValueFactory valueFactory, Value... args); }
@Test public void testEvaluate1() { try { Literal result = timezone.evaluate(f, f.createLiteral("2011-01-10T14:45:13.815-05:00", XMLSchema.DATETIME)); assertNotNull(result); assertEquals(XMLSchema.DAYTIMEDURATION, result.getDatatype()); assertEquals("-PT5H", result.getLabel()); } catch (ValueExprEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testEvaluate2() { try { Literal result = timezone.evaluate(f, f.createLiteral("2011-01-10T14:45:13.815Z", XMLSchema.DATETIME)); assertNotNull(result); assertEquals(XMLSchema.DAYTIMEDURATION, result.getDatatype()); assertEquals("PT0S", result.getLabel()); } catch (ValueExprEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testEvaluate3() { try { timezone.evaluate(f, f.createLiteral("2011-01-10T14:45:13.815", XMLSchema.DATETIME)); fail("should have resulted in a type error"); } catch (ValueExprEvaluationException e) { } }
SpinParser { public SpinParser() { this(Input.TEXT_FIRST); } SpinParser(); SpinParser(Input input); SpinParser(Input input, Function<IRI, String> wellKnownVarsMapper, Function<IRI, String> wellKnownFuncMapper); List<FunctionParser> getFunctionParsers(); void setFunctionParsers(List<FunctionParser> functionParsers); List<TupleFunctionParser> getTupleFunctionParsers(); void setTupleFunctionParsers(List<TupleFunctionParser> tupleFunctionParsers); boolean isStrictFunctionChecking(); void setStrictFunctionChecking(boolean strictFunctionChecking); Map<IRI, RuleProperty> parseRuleProperties(TripleSource store); boolean isThisUnbound(Resource subj, TripleSource store); ConstraintViolation parseConstraintViolation(Resource subj, TripleSource store); ParsedOperation parse(Resource queryResource, TripleSource store); ParsedQuery parseQuery(Resource queryResource, TripleSource store); ParsedGraphQuery parseConstructQuery(Resource queryResource, TripleSource store); ParsedTupleQuery parseSelectQuery(Resource queryResource, TripleSource store); ParsedBooleanQuery parseAskQuery(Resource queryResource, TripleSource store); ParsedDescribeQuery parseDescribeQuery(Resource queryResource, TripleSource store); ParsedUpdate parseUpdate(Resource queryResource, TripleSource store); org.eclipse.rdf4j.query.algebra.evaluation.function.Function parseFunction(IRI funcUri, TripleSource store); TupleFunction parseMagicProperty(IRI propUri, TripleSource store); Map<IRI, Argument> parseArguments(final IRI moduleUri, final TripleSource store); ValueExpr parseExpression(Value expr, TripleSource store); void reset(IRI... uris); static List<IRI> orderArguments(Set<IRI> args); }
@Test public void testSpinParser() throws IOException, RDF4JException { StatementCollector expected = new StatementCollector(); RDFParser parser = Rio.createParser(RDFFormat.TURTLE); parser.setRDFHandler(expected); try (InputStream rdfStream = testURL.openStream()) { parser.parse(rdfStream, testURL.toString()); } Resource queryResource = null; for (Statement stmt : expected.getStatements()) { if (SP.TEXT_PROPERTY.equals(stmt.getPredicate())) { queryResource = stmt.getSubject(); break; } } assertNotNull(queryResource); TripleSource store = new ModelTripleSource(new TreeModel(expected.getStatements())); ParsedOperation textParsedOp = textParser.parse(queryResource, store); ParsedOperation rdfParsedOp = rdfParser.parse(queryResource, store); if (textParsedOp instanceof ParsedQuery) { assertEquals(((ParsedQuery) textParsedOp).getTupleExpr(), ((ParsedQuery) rdfParsedOp).getTupleExpr()); } else { assertEquals(((ParsedUpdate) textParsedOp).getUpdateExprs(), ((ParsedUpdate) rdfParsedOp).getUpdateExprs()); } } @Test public void testSpinParser() throws IOException, RDF4JException { StatementCollector expected = new StatementCollector(); RDFParser parser = Rio.createParser(RDFFormat.TURTLE); parser.setRDFHandler(expected); try (InputStream rdfStream = testURL.openStream()) { parser.parse(rdfStream, testURL.toString()); } Resource queryResource = null; for (Statement stmt : expected.getStatements()) { if (SP.TEXT_PROPERTY.equals(stmt.getPredicate())) { queryResource = stmt.getSubject(); break; } } assertNotNull(queryResource); TripleSource store = new ModelTripleSource(new TreeModel(expected.getStatements())); ParsedOperation textParsedOp = textParser.parse(queryResource, store); ParsedOperation rdfParsedOp = rdfParser.parse(queryResource, store); if (textParsedOp instanceof ParsedQuery) { assertEquals(((ParsedQuery) textParsedOp).getTupleExpr(), ((ParsedQuery) rdfParsedOp).getTupleExpr()); } else { List<UpdateExpr> textUpdates = ((ParsedUpdate) textParsedOp).getUpdateExprs(); List<UpdateExpr> rdfUpdates = ((ParsedUpdate) rdfParsedOp).getUpdateExprs(); assertThat(textUpdates).isEqualTo(rdfUpdates); } }
Concat implements Function { @Override public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length == 0) { throw new ValueExprEvaluationException("CONCAT requires at least 1 argument, got " + args.length); } StringBuilder concatBuilder = new StringBuilder(); String commonLanguageTag = null; boolean useLanguageTag = true; for (Value arg : args) { if (arg instanceof Literal) { Literal lit = (Literal) arg; if (!QueryEvaluationUtil.isStringLiteral(lit)) { throw new ValueExprEvaluationException("unexpected datatype for CONCAT operand: " + lit); } if (useLanguageTag && Literals.isLanguageLiteral(lit)) { if (commonLanguageTag == null) { commonLanguageTag = lit.getLanguage().get(); } else if (!commonLanguageTag.equals(lit.getLanguage().orElse(null))) { commonLanguageTag = null; useLanguageTag = false; } } else { useLanguageTag = false; } concatBuilder.append(lit.getLabel()); } else { throw new ValueExprEvaluationException("unexpected argument type for CONCAT operator: " + arg); } } Literal result = null; if (useLanguageTag) { result = valueFactory.createLiteral(concatBuilder.toString(), commonLanguageTag); } else { result = valueFactory.createLiteral(concatBuilder.toString()); } return result; } @Override String getURI(); @Override Literal evaluate(ValueFactory valueFactory, Value... args); }
@Test public void stringLiteralHandling() { Literal result = concatFunc.evaluate(vf, foo, bar); assertThat(result.stringValue()).isEqualTo("foobar"); assertThat(result.getDatatype()).isEqualTo(XMLSchema.STRING); assertThat(result.getLanguage().isPresent()).isFalse(); } @Test public void mixedLanguageLiteralHandling() { Literal result = concatFunc.evaluate(vf, foo_nl, bar_en); assertThat(result.stringValue()).isEqualTo("foobar"); assertThat(result.getDatatype()).isEqualTo(XMLSchema.STRING); assertThat(result.getLanguage().isPresent()).isFalse(); } @Test public void mixedLiteralHandling() { Literal result = concatFunc.evaluate(vf, foo, bar_en); assertThat(result.stringValue()).isEqualTo("foobar"); assertThat(result.getDatatype()).isEqualTo(XMLSchema.STRING); assertThat(result.getLanguage().isPresent()).isFalse(); } @Test public void stringLiteralHandling() { Literal result = concatFunc.evaluate(vf, foo, bar); assertThat(result.stringValue()).isEqualTo("foobar"); assertThat(result.getDatatype()).isEqualTo(XSD.STRING); assertThat(result.getLanguage().isPresent()).isFalse(); } @Test public void commonLanguageLiteralHandling() { Literal result = concatFunc.evaluate(vf, foo_en, bar_en); assertThat(result.stringValue()).isEqualTo("foobar"); assertThat(result.getDatatype()).isEqualTo(RDF.LANGSTRING); assertThat(result.getLanguage().get()).isEqualTo("en"); } @Test public void mixedLanguageLiteralHandling() { Literal result = concatFunc.evaluate(vf, foo_nl, bar_en); assertThat(result.stringValue()).isEqualTo("foobar"); assertThat(result.getDatatype()).isEqualTo(XSD.STRING); assertThat(result.getLanguage().isPresent()).isFalse(); } @Test public void mixedLiteralHandling() { Literal result = concatFunc.evaluate(vf, foo, bar_en); assertThat(result.stringValue()).isEqualTo("foobar"); assertThat(result.getDatatype()).isEqualTo(XSD.STRING); assertThat(result.getLanguage().isPresent()).isFalse(); } @Test public void nonStringLiteralHandling() { try { concatFunc.evaluate(vf, RDF.TYPE, BooleanLiteral.TRUE); fail("CONCAT expected to fail on non-stringliteral argument"); } catch (ValueExprEvaluationException e) { } } @Test public void nonLiteralHandling() { try { concatFunc.evaluate(vf, RDF.TYPE, bar_en); fail("CONCAT expected to fail on non-literal argument"); } catch (ValueExprEvaluationException e) { } }
StrAfter implements Function { @Override public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length != 2) { throw new ValueExprEvaluationException("Incorrect number of arguments for STRAFTER: " + args.length); } Value leftArg = args[0]; Value rightArg = args[1]; if (leftArg instanceof Literal && rightArg instanceof Literal) { Literal leftLit = (Literal) leftArg; Literal rightLit = (Literal) rightArg; if (QueryEvaluationUtil.compatibleArguments(leftLit, rightLit)) { String lexicalValue = leftLit.getLabel(); String substring = rightLit.getLabel(); Optional<String> leftLanguage = leftLit.getLanguage(); IRI leftDt = leftLit.getDatatype(); int index = lexicalValue.indexOf(substring); String substringAfter = ""; if (index > -1) { index += substring.length() - 1; substringAfter = lexicalValue.substring(index + 1, lexicalValue.length()); } else { leftLanguage = Optional.empty(); leftDt = null; } if (leftLanguage.isPresent()) { return valueFactory.createLiteral(substringAfter, leftLanguage.get()); } else if (leftDt != null) { return valueFactory.createLiteral(substringAfter, leftDt); } else { return valueFactory.createLiteral(substringAfter); } } else { throw new ValueExprEvaluationException( "incompatible operands for STRAFTER: " + leftArg + ", " + rightArg); } } else { throw new ValueExprEvaluationException("incompatible operands for STRAFTER: " + leftArg + ", " + rightArg); } } @Override String getURI(); @Override Literal evaluate(ValueFactory valueFactory, Value... args); }
@Test public void testEvaluate4() { Literal leftArg = f.createLiteral("foobar", XMLSchema.STRING); Literal rightArg = f.createLiteral("b"); try { Literal result = strAfterFunc.evaluate(f, leftArg, rightArg); assertEquals("ar", result.getLabel()); assertEquals(XMLSchema.STRING, result.getDatatype()); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } } @Test public void testEvaluate4a() { Literal leftArg = f.createLiteral("foobar"); Literal rightArg = f.createLiteral("b", XMLSchema.STRING); try { Literal result = strAfterFunc.evaluate(f, leftArg, rightArg); assertEquals("ar", result.getLabel()); assertEquals(XMLSchema.STRING, result.getDatatype()); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } } @Test public void testEvaluate5() { Literal leftArg = f.createLiteral("foobar", XMLSchema.STRING); Literal rightArg = f.createLiteral("b", XMLSchema.DATE); try { Literal result = strAfterFunc.evaluate(f, leftArg, rightArg); fail("operand with incompatible datatype, should have resulted in error"); } catch (ValueExprEvaluationException e) { assertEquals( "incompatible operands for STRAFTER: \"foobar\", \"b\"^^<http: e.getMessage()); } } @Test public void testEvaluate10() { Literal leftArg = f.createLiteral("foobar", "en"); Literal rightArg = f.createLiteral("b", XMLSchema.STRING); try { Literal result = strAfterFunc.evaluate(f, leftArg, rightArg); assertEquals("ar", result.getLabel()); assertEquals(RDF.LANGSTRING, result.getDatatype()); assertEquals("en", result.getLanguage().orElse(null)); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } } @Test public void testEvaluate1() { Literal leftArg = f.createLiteral("foobar"); Literal rightArg = f.createLiteral("ba"); try { Literal result = strAfterFunc.evaluate(f, leftArg, rightArg); assertEquals("r", result.getLabel()); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } } @Test public void testEvaluate2() { Literal leftArg = f.createLiteral("foobar"); Literal rightArg = f.createLiteral("xyz"); try { Literal result = strAfterFunc.evaluate(f, leftArg, rightArg); assertEquals("", result.getLabel()); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } } @Test public void testEvaluate3() { Literal leftArg = f.createLiteral("foobar", "en"); Literal rightArg = f.createLiteral("b"); try { Literal result = strAfterFunc.evaluate(f, leftArg, rightArg); assertEquals("ar", result.getLabel()); assertEquals("en", result.getLanguage().orElse(null)); assertEquals(RDF.LANGSTRING, result.getDatatype()); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } } @Test public void testEvaluate4() { Literal leftArg = f.createLiteral("foobar", XSD.STRING); Literal rightArg = f.createLiteral("b"); try { Literal result = strAfterFunc.evaluate(f, leftArg, rightArg); assertEquals("ar", result.getLabel()); assertEquals(XSD.STRING, result.getDatatype()); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } } @Test public void testEvaluate4a() { Literal leftArg = f.createLiteral("foobar"); Literal rightArg = f.createLiteral("b", XSD.STRING); try { Literal result = strAfterFunc.evaluate(f, leftArg, rightArg); assertEquals("ar", result.getLabel()); assertEquals(XSD.STRING, result.getDatatype()); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } } @Test public void testEvaluate5() { Literal leftArg = f.createLiteral("foobar", XSD.STRING); Literal rightArg = f.createLiteral("b", XSD.DATE); try { Literal result = strAfterFunc.evaluate(f, leftArg, rightArg); fail("operand with incompatible datatype, should have resulted in error"); } catch (ValueExprEvaluationException e) { assertEquals( "incompatible operands for STRAFTER: \"foobar\", \"b\"^^<http: e.getMessage()); } } @Test public void testEvaluate6() { Literal leftArg = f.createLiteral(10); Literal rightArg = f.createLiteral("b"); try { Literal result = strAfterFunc.evaluate(f, leftArg, rightArg); fail("operand with incompatible datatype, should have resulted in error"); } catch (ValueExprEvaluationException e) { assertEquals("incompatible operands for STRAFTER: \"10\"^^<http: e.getMessage()); } } @Test public void testEvaluate7() { IRI leftArg = f.createIRI("http: Literal rightArg = f.createLiteral("b"); try { Literal result = strAfterFunc.evaluate(f, leftArg, rightArg); fail("operand of incompatible type, should have resulted in error"); } catch (ValueExprEvaluationException e) { assertEquals("incompatible operands for STRAFTER: http: } } @Test public void testEvaluate8() { Literal leftArg = f.createLiteral("foobar", "en"); Literal rightArg = f.createLiteral("b", "nl"); try { Literal result = strAfterFunc.evaluate(f, leftArg, rightArg); fail("operand of incompatible type, should have resulted in error"); } catch (ValueExprEvaluationException e) { assertEquals("incompatible operands for STRAFTER: \"foobar\"@en, \"b\"@nl", e.getMessage()); } } @Test public void testEvaluate9() { Literal leftArg = f.createLiteral("foobar"); Literal rightArg = f.createLiteral("b", "nl"); try { Literal result = strAfterFunc.evaluate(f, leftArg, rightArg); fail("operand of incompatible type, should have resulted in error"); } catch (ValueExprEvaluationException e) { assertEquals("incompatible operands for STRAFTER: \"foobar\", \"b\"@nl", e.getMessage()); } } @Test public void testEvaluate10() { Literal leftArg = f.createLiteral("foobar", "en"); Literal rightArg = f.createLiteral("b", XSD.STRING); try { Literal result = strAfterFunc.evaluate(f, leftArg, rightArg); assertEquals("ar", result.getLabel()); assertEquals(RDF.LANGSTRING, result.getDatatype()); assertEquals("en", result.getLanguage().orElse(null)); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } } @Test public void testEvaluate11() { Literal leftArg = f.createLiteral("foobar", "nl"); Literal rightArg = f.createLiteral("b", "nl"); try { Literal result = strAfterFunc.evaluate(f, leftArg, rightArg); assertEquals("ar", result.getLabel()); assertEquals(RDF.LANGSTRING, result.getDatatype()); assertEquals("nl", result.getLanguage().orElse(null)); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } }
Substring implements Function { @Override public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length < 2 || args.length > 3) { throw new ValueExprEvaluationException("Incorrect number of arguments for SUBSTR: " + args.length); } Value argValue = args[0]; Value startIndexValue = args[1]; Value lengthValue = null; if (args.length > 2) { lengthValue = args[2]; } if (argValue instanceof Literal) { Literal literal = (Literal) argValue; if (QueryEvaluationUtil.isStringLiteral(literal)) { String lexicalValue = literal.getLabel(); int startIndex = 0; if (startIndexValue instanceof Literal) { int startLiteral = intFromLiteral((Literal) startIndexValue); try { startIndex = startLiteral - 1; } catch (NumberFormatException e) { throw new ValueExprEvaluationException( "illegal start index value (expected int value): " + startIndexValue); } } else if (startIndexValue != null) { throw new ValueExprEvaluationException( "illegal start index value (expected literal value): " + startIndexValue); } int endIndex = lexicalValue.length(); if (lengthValue instanceof Literal) { try { int length = intFromLiteral((Literal) lengthValue); if (length < 1) { return convert("", literal, valueFactory); } endIndex = Math.min(startIndex + length, endIndex); if (endIndex < 0) { return convert("", literal, valueFactory); } } catch (NumberFormatException e) { throw new ValueExprEvaluationException( "illegal length value (expected int value): " + lengthValue); } } else if (lengthValue != null) { throw new ValueExprEvaluationException( "illegal length value (expected literal value): " + lengthValue); } try { startIndex = Math.max(startIndex, 0); lexicalValue = lexicalValue.substring(startIndex, endIndex); return convert(lexicalValue, literal, valueFactory); } catch (IndexOutOfBoundsException e) { throw new ValueExprEvaluationException( "could not determine substring, index out of bounds " + startIndex + "length:" + endIndex, e); } } else { throw new ValueExprEvaluationException("unexpected input value for function substring: " + argValue); } } else { throw new ValueExprEvaluationException("unexpected input value for function substring: " + argValue); } } @Override String getURI(); @Override Literal evaluate(ValueFactory valueFactory, Value... args); static int intFromLiteral(Literal literal); }
@Test public void testEvaluateStartBefore1() { Literal pattern = f.createLiteral("ABC"); Literal startIndex = f.createLiteral(0); Literal length = f.createLiteral(1); try { Literal result = substrFunc.evaluate(f, pattern, startIndex, length); assertTrue(result.getLabel().equals("")); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } } @Test public void testEvaluate1() { Literal pattern = f.createLiteral("foobar"); Literal startIndex = f.createLiteral(4); try { Literal result = substrFunc.evaluate(f, pattern, startIndex); assertTrue(result.getLabel().equals("bar")); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } } @Test public void testEvaluate2() { Literal pattern = f.createLiteral("foobar"); Literal startIndex = f.createLiteral(4); Literal length = f.createLiteral(2); try { Literal result = substrFunc.evaluate(f, pattern, startIndex, length); assertTrue(result.getLabel().equals("ba")); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } } @Test public void testEvaluate3() { Literal pattern = f.createLiteral("foobar"); Literal startIndex = f.createLiteral(4); Literal length = f.createLiteral(5); assertEquals("bar", substrFunc.evaluate(f, pattern, startIndex, length).getLabel()); } @Test public void testEvaluate4() { Literal pattern = f.createLiteral("foobar"); try { substrFunc.evaluate(f, pattern); fail("illegal number of args hould have resulted in error"); } catch (ValueExprEvaluationException e) { } } @Test public void testEvaluateStartBefore1() { Literal pattern = f.createLiteral("ABC"); Literal startIndex = f.createLiteral(0); Literal length = f.createLiteral(1); try { Literal result = substrFunc.evaluate(f, pattern, startIndex, length); assertTrue(result.getLabel().isEmpty()); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } } @Test public void testXpathExamples1() { Literal pattern = f.createLiteral("motor car"); Literal startIndex = f.createLiteral(6); Literal result = substrFunc.evaluate(f, pattern, startIndex); assertEquals(" car", result.getLabel()); } @Test public void testXpathExamples2() { Literal pattern = f.createLiteral("metadata"); Literal startIndex = f.createLiteral(4); Literal length = f.createLiteral(3); Literal result = substrFunc.evaluate(f, pattern, startIndex, length); assertEquals("ada", result.getLabel()); } @Test public void testXpathExamples3() { Literal pattern = f.createLiteral("12345"); Literal startIndex = f.createLiteral(1.5); Literal length = f.createLiteral(2.6); try { Literal result = substrFunc.evaluate(f, pattern, startIndex, length); fail("illegal use of float args hould have resulted in error"); } catch (ValueExprEvaluationException e) { } } @Test public void testXpathExamples3int() { Literal pattern = f.createLiteral("12345"); Literal startIndex = f.createLiteral(2); Literal length = f.createLiteral(3); Literal result = substrFunc.evaluate(f, pattern, startIndex, length); assertEquals("234", result.getLabel()); } @Test public void testXpathExamples4() { Literal pattern = f.createLiteral("12345"); Literal startIndex = f.createLiteral(0); Literal length = f.createLiteral(3); Literal result = substrFunc.evaluate(f, pattern, startIndex, length); assertEquals("12", result.getLabel()); } @Test public void testXpathExamples5() { Literal pattern = f.createLiteral("12345"); Literal startIndex = f.createLiteral(5); Literal length = f.createLiteral(-3); Literal result = substrFunc.evaluate(f, pattern, startIndex, length); assertEquals("", result.getLabel()); } @Test public void testXpathExamples6() { Literal pattern = f.createLiteral("12345"); Literal startIndex = f.createLiteral(-3); Literal length = f.createLiteral(5); Literal result = substrFunc.evaluate(f, pattern, startIndex, length); assertEquals("1", result.getLabel()); } @Test public void testXpathExamples7() { Literal pattern = f.createLiteral("12345"); Literal startIndex = f.createLiteral(1); Literal length = f.createLiteral(Float.NaN); try { Literal result = substrFunc.evaluate(f, pattern, startIndex, length); } catch (ValueExprEvaluationException e) { } } @Test public void testXpathExample8Inspired() { Literal pattern = f.createLiteral("12345"); Literal startIndex = f.createLiteral(-42); Literal length = f.createLiteral(50); Literal result = substrFunc.evaluate(f, pattern, startIndex, length); assertEquals("12345", result.getLabel()); } @Test public void testXpathExamples9() { Literal pattern = f.createLiteral("12345"); Literal startIndex = f.createLiteral(Float.NEGATIVE_INFINITY); Literal length = f.createLiteral(Float.POSITIVE_INFINITY); try { Literal result = substrFunc.evaluate(f, pattern, startIndex, length); fail("illegal use of float args hould have resulted in error"); } catch (ValueExprEvaluationException e) { } }
Util { public static Resource[] getContexts(String[] tokens, int pos, Repository repository) throws IllegalArgumentException { Resource[] contexts = new Resource[] {}; if (tokens.length > pos) { contexts = new Resource[tokens.length - pos]; for (int i = pos; i < tokens.length; i++) { contexts[i - pos] = getContext(repository, tokens[i]); } } return contexts; } static Resource getContext(Repository repository, String ctxID); static Resource[] getContexts(String[] tokens, int pos, Repository repository); static Path getPath(String file); static String getPrefixedValue(Value value, Map<String, String> namespaces); @Deprecated static String formatToWidth(int width, String padding, String str, String separator); }
@Test public final void testContextsTwo() { String ONE = "http: String TWO = "_:two"; ValueFactory f = repo.getValueFactory(); Resource[] check = new Resource[] { f.createIRI(ONE), f.createBNode(TWO.substring(2)) }; String[] tokens = { "command", ONE, TWO }; Resource[] ctxs = Util.getContexts(tokens, 1, repo); assertTrue("Not equal", Arrays.equals(check, ctxs)); } @Test public final void testContextsNull() { String[] tokens = { "command", "command2", "NULL" }; Resource[] ctxs = Util.getContexts(tokens, 2, repo); assertTrue("Not null", ctxs[0] == null); } @Test public final void testContextsInvalid() { String[] tokens = { "command", "invalid" }; try { Resource[] ctxs = Util.getContexts(tokens, 1, repo); fail("No exception generated"); } catch (IllegalArgumentException expected) { } }
Verify extends ConsoleCommand { @Override public void execute(String... tokens) { if (tokens.length != 2 && tokens.length != 4) { consoleIO.writeln(getHelpLong()); return; } String dataPath = parseDataPath(tokens[1]); verify(dataPath); if (tokens.length == 4) { String shaclPath = parseDataPath(tokens[2]); String reportFile = tokens[3]; shacl(dataPath, shaclPath, reportFile); } } Verify(ConsoleIO consoleIO); @Override String getName(); @Override String getHelpShort(); @Override String getHelpLong(); @Override void execute(String... tokens); }
@Test public final void testVerifyMissingType() throws IOException { cmd.execute("verify", copyFromRes("missing_type.ttl")); assertTrue(io.wasErrorWritten()); } @Test public final void testVerifySpaceIRI() throws IOException { cmd.execute("verify", copyFromRes("space_iri.ttl")); assertTrue(io.wasErrorWritten()); } @Test public final void testVerifyWrongLang() throws IOException { cmd.execute("verify", copyFromRes("wrong_lang.ttl")); assertTrue(io.wasErrorWritten()); } @Test public final void testShaclInvalid() throws IOException { File report = LOCATION.newFile(); cmd.execute("verify", copyFromRes("ok.ttl"), copyFromRes("shacl_invalid.ttl"), report.toString()); assertTrue(io.wasErrorWritten()); assertTrue(Files.size(report.toPath()) > 0); } @Test public final void testShaclValid() throws IOException { File report = LOCATION.newFile(); cmd.execute("verify", copyFromRes("ok.ttl"), copyFromRes("shacl_valid.ttl"), report.toString()); assertFalse(Files.size(report.toPath()) > 0); assertFalse(io.wasErrorWritten()); } @Test public final void testVerifyWrongFormat() { cmd.execute("verify", "does-not-exist.docx"); assertTrue(io.wasErrorWritten()); } @Test public final void testVerifyOK() throws IOException { cmd.execute("verify", copyFromRes("ok.ttl")); assertFalse(io.wasErrorWritten()); } @Test public final void testVerifyBrokenFile() throws IOException { cmd.execute("verify", copyFromRes("broken.ttl")); assertTrue(io.wasErrorWritten()); }
Federate extends ConsoleCommand { @Override public void execute(String... parameters) throws IOException { if (parameters.length < 4) { consoleIO.writeln(getHelpLong()); } else { LinkedList<String> plist = new LinkedList<>(Arrays.asList(parameters)); plist.remove(); boolean distinct = getOptionalParamValue(plist, "distinct", false); boolean readonly = getOptionalParamValue(plist, "readonly", true); if (distinctValues(plist)) { String fedID = plist.pop(); federate(distinct, readonly, fedID, plist); } else { consoleIO.writeError("Duplicate repository id's specified."); } } } Federate(ConsoleIO consoleIO, ConsoleState state); @Override String getName(); @Override String getHelpShort(); @Override String getHelpLong(); @Override void execute(String... parameters); }
@Test public void testInvalidArgumentPrintsError() throws Exception { execute("type=memory", FED_ID, MEMORY_MEMBER_ID1, MEMORY_MEMBER_ID2); verifyFailure(); } @Test public void testDuplicateMembersPrintsError() throws Exception { execute(FED_ID, MEMORY_MEMBER_ID1, MEMORY_MEMBER_ID1); verifyFailure(); } @Test public void testFedSameAsMemberPrintsError() throws Exception { execute(FED_ID, MEMORY_MEMBER_ID1, FED_ID, MEMORY_MEMBER_ID1); verifyFailure(); } @Test public void testSparqlAndNotReadOnlyPrintsError() throws Exception { execute("readonly=false", FED_ID, SPARQL_MEMBER_ID, SPARQL2_MEMBER_ID); verifyFailure(SPARQL_MEMBER_ID + " is read-only."); verifyFailure(SPARQL2_MEMBER_ID + " is read-only."); } @Test public void testFedAlreadyExistsPrintsSpecificError() throws Exception { execute(MEMORY_MEMBER_ID1, FED_ID, MEMORY_MEMBER_ID2); verifyFailure(MEMORY_MEMBER_ID1 + " already exists."); } @Test public void testNonexistentMemberPrintsSpecificError() throws Exception { execute(FED_ID, MEMORY_MEMBER_ID1, "FreeLunch"); verifyFailure("FreeLunch does not exist."); } @Test public void testFederateMemoryMembersSuccess() throws Exception { execute(FED_ID, MEMORY_MEMBER_ID1, MEMORY_MEMBER_ID2); verifySuccess(ProxyRepositoryFactory.REPOSITORY_TYPE, ProxyRepositoryFactory.REPOSITORY_TYPE); long expectedSize = getSize(MEMORY_MEMBER_ID1) + getSize(MEMORY_MEMBER_ID2); assertThat(getSize(FED_ID)).isEqualTo(expectedSize); } @Test public void testFederateSucceedsWithHTTPandSPARQLmembers() throws Exception { execute(FED_ID, HTTP_MEMBER_ID, SPARQL_MEMBER_ID); verifySuccess(HTTPRepositoryFactory.REPOSITORY_TYPE, SPARQLRepositoryFactory.REPOSITORY_TYPE); } @Test public void testFederateHTTPtypeSucceeds() throws Exception { execute(FED_ID, HTTP_MEMBER_ID, HTTP2_MEMBER_ID); verifySuccess(HTTPRepositoryFactory.REPOSITORY_TYPE, HTTPRepositoryFactory.REPOSITORY_TYPE); } @Test public void testFederateSPARQLtypeSucceeds() throws Exception { execute(FED_ID, SPARQL_MEMBER_ID, SPARQL2_MEMBER_ID); verifySuccess(SPARQLRepositoryFactory.REPOSITORY_TYPE, SPARQLRepositoryFactory.REPOSITORY_TYPE); } @Test public void testSuccessWithNonDefaultReadonlyAndDistinct() throws Exception { execute(FED_ID, "distinct=true", "readonly=false", MEMORY_MEMBER_ID1, MEMORY_MEMBER_ID2); verifySuccess(false, true, ProxyRepositoryFactory.REPOSITORY_TYPE, ProxyRepositoryFactory.REPOSITORY_TYPE); long expectedSize = getSize(MEMORY_MEMBER_ID1) + getSize(MEMORY_MEMBER_ID2); assertThat(getSize(FED_ID)).isEqualTo(expectedSize); } @Test public void testFullyHeterogeneousSuccess() throws Exception { execute(FED_ID, SPARQL_MEMBER_ID, MEMORY_MEMBER_ID1, HTTP_MEMBER_ID); verifySuccess(SPARQLRepositoryFactory.REPOSITORY_TYPE, ProxyRepositoryFactory.REPOSITORY_TYPE, HTTPRepositoryFactory.REPOSITORY_TYPE); }
Export extends ConsoleCommand { @Override public void execute(String... tokens) { Repository repository = state.getRepository(); if (repository == null) { consoleIO.writeUnopenedError(); return; } if (tokens.length < 2) { consoleIO.writeln(getHelpLong()); return; } String fileName = tokens[1]; Resource[] contexts; try { contexts = Util.getContexts(tokens, 2, repository); } catch (IllegalArgumentException ioe) { consoleIO.writeError(ioe.getMessage()); return; } export(repository, fileName, contexts); } Export(ConsoleIO consoleIO, ConsoleState state); @Override String getName(); @Override String getHelpShort(); @Override String getHelpLong(); @Override void execute(String... tokens); }
@Test public final void testExportAll() throws RepositoryException, IOException { File nq = LOCATION.newFile("all.nq"); export.execute("export", nq.toString()); Model exp = Rio.parse(Files.newReader(nq, StandardCharsets.UTF_8), "http: assertTrue("File is empty", nq.length() > 0); assertEquals("Number of contexts incorrect", 3, exp.contexts().size()); nq.delete(); } @Test public final void testExportContexts() throws RepositoryException, IOException { File nq = LOCATION.newFile("default.nq"); export.execute("export", nq.toString(), "null", "http: Model exp = Rio.parse(Files.newReader(nq, StandardCharsets.UTF_8), "http: assertTrue("File is empty", nq.length() > 0); assertEquals("Number of contexts incorrect", 2, exp.contexts().size()); assertEquals("Number of triples incorrect", 4, exp.size()); nq.delete(); }
Convert extends ConsoleCommand { private void convert(String fileFrom, String fileTo) { Path pathFrom = Util.getPath(fileFrom); if (pathFrom == null) { consoleIO.writeError("Invalid file name (from) " + fileFrom); return; } if (Files.notExists(pathFrom)) { consoleIO.writeError("File not found (from) " + fileFrom); return; } Optional<RDFFormat> fmtFrom = Rio.getParserFormatForFileName(fileFrom); if (!fmtFrom.isPresent()) { consoleIO.writeError("No RDF parser for " + fileFrom); return; } Path pathTo = Util.getPath(fileTo); if (pathTo == null) { consoleIO.writeError("Invalid file name (to) " + pathTo); return; } Optional<RDFFormat> fmtTo = Rio.getWriterFormatForFileName(fileTo); if (!fmtTo.isPresent()) { consoleIO.writeError("No RDF writer for " + fileTo); return; } if (Files.exists(pathTo)) { try { boolean overwrite = consoleIO.askProceed("File exists, continue ?", false); if (!overwrite) { consoleIO.writeln("Conversion aborted"); return; } } catch (IOException ioe) { consoleIO.writeError("I/O error " + ioe.getMessage()); } } RDFParser parser = Rio.createParser(fmtFrom.get()); String baseURI = pathFrom.toUri().toString(); try (BufferedInputStream r = new BufferedInputStream(Files.newInputStream(pathFrom)); BufferedWriter w = Files.newBufferedWriter(pathTo)) { RDFWriter writer = Rio.createWriter(fmtTo.get(), w); parser.setRDFHandler(writer); long startTime = System.nanoTime(); consoleIO.writeln("Converting file ..."); parser.parse(r, baseURI); long diff = (System.nanoTime() - startTime) / 1_000_000; consoleIO.writeln("Data has been written to file (" + diff + " ms)"); } catch (IOException | RDFParseException | RDFHandlerException e) { consoleIO.writeError("Failed to convert data: " + e.getMessage()); } } Convert(ConsoleIO consoleIO, ConsoleState state); @Override String getName(); @Override String getHelpShort(); @Override String getHelpLong(); @Override void execute(String... tokens); }
@Test public final void testConvert() throws IOException { File json = LOCATION.newFile("alien.jsonld"); convert.execute("convert", from.toString(), json.toString()); assertTrue("File is empty", json.length() > 0); Object o = null; try { o = JsonUtils.fromInputStream(Files.newInputStream(json.toPath())); } catch (IOException ioe) { } assertTrue("Invalid JSON", o != null); }
Convert extends ConsoleCommand { @Override public void execute(String... tokens) { if (tokens.length < 3) { consoleIO.writeln(getHelpLong()); return; } convert(tokens[1], tokens[2]); } Convert(ConsoleIO consoleIO, ConsoleState state); @Override String getName(); @Override String getHelpShort(); @Override String getHelpLong(); @Override void execute(String... tokens); }
@Test public final void testConvertParseError() throws IOException { File wrong = LOCATION.newFile("wrong.nt"); Files.write(wrong.toPath(), "error".getBytes()); File json = LOCATION.newFile("empty.jsonld"); convert.execute("convert", wrong.toString(), json.toString()); verify(mockConsoleIO).writeError(anyString()); } @Test public final void testConvertInvalidFormat() throws IOException { File qyx = LOCATION.newFile("alien.qyx"); convert.execute("convert", from.toString(), qyx.toString()); verify(mockConsoleIO).writeError("No RDF writer for " + qyx.toString()); }
SetParameters extends ConsoleCommand { @Override public void execute(String... tokens) { switch (tokens.length) { case 0: consoleIO.writeln(getHelpLong()); break; case 1: for (String setting : settings.keySet()) { showSetting(setting); } break; default: String param = tokens[1]; int eqIdx = param.indexOf('='); if (eqIdx < 0) { showSetting(param); } else { String key = param.substring(0, eqIdx); String values = String.join(" ", tokens); eqIdx = values.indexOf('='); setParameter(key, values.substring(eqIdx + 1)); } } } SetParameters(ConsoleIO consoleIO, ConsoleState state, Map<String, ConsoleSetting> settings); @Override String getName(); @Override String getHelpShort(); @Override String getHelpLong(); @Override void execute(String... tokens); }
@Test public void testUnknownParametersAreErrors() { setParameters.execute("set", "unknown"); verify(mockConsoleIO).writeError("Unknown parameter: unknown"); verifyNoMoreInteractions(mockConsoleIO); }
ValueDecoder { protected Value decodeValue(String string) throws BadRequestException { Value result = null; try { if (string != null) { String value = string.trim(); if (!value.isEmpty() && !"null".equals(value)) { if (value.startsWith("_:")) { String label = value.substring("_:".length()); result = factory.createBNode(label); } else { if (value.charAt(0) == '<' && value.endsWith(">")) { result = factory.createIRI(value.substring(1, value.length() - 1)); } else { if (value.charAt(0) == '"') { result = parseLiteral(value); } else { result = parseURI(value); } } } } } } catch (Exception exc) { LOGGER.warn(exc.toString(), exc); throw new BadRequestException("Malformed value: " + string, exc); } return result; } protected ValueDecoder(Repository repository, ValueFactory factory); }
@Test public final void testLiteralWithURIType() throws BadRequestException { Value value = decoder.decodeValue("\"1\"^^<" + XMLSchema.INT + ">"); assertThat(value).isInstanceOf(Literal.class); assertThat((Literal) value).isEqualTo(factory.createLiteral(1)); } @Test public final void testQnamePropertyValue() throws BadRequestException { Value value = decoder.decodeValue("rdfs:label"); assertThat(value).isInstanceOf(IRI.class); assertThat((IRI) value).isEqualTo(RDFS.LABEL); } @Test public final void testPlainStringLiteral() throws BadRequestException { Value value = decoder.decodeValue("\"plain string\""); assertThat(value).isInstanceOf(Literal.class); assertThat((Literal) value).isEqualTo(factory.createLiteral("plain string")); } @Test public final void testUnexpectedLiteralAttribute() throws BadRequestException { try { decoder.decodeValue("\"datatype oops\"^rdfs:label"); fail("Expected BadRequestException."); } catch (BadRequestException bre) { Throwable rootCause = bre.getRootCause(); assertThat(rootCause).isInstanceOf(BadRequestException.class); assertThat(rootCause).hasMessageStartingWith("Malformed language tag or datatype: "); } } @Test public final void testLiteralWithQNameType() throws BadRequestException { Value value = decoder.decodeValue("\"1\"^^xsd:int"); assertThat(value).isInstanceOf(Literal.class); assertThat((Literal) value).isEqualTo(factory.createLiteral(1)); } @Test public final void testLiteralWithURIType() throws BadRequestException { Value value = decoder.decodeValue("\"1\"^^<" + XSD.INT + ">"); assertThat(value).isInstanceOf(Literal.class); assertThat((Literal) value).isEqualTo(factory.createLiteral(1)); } @Test public final void testLanguageLiteral() throws BadRequestException { Value value = decoder.decodeValue("\"color\"@en-US"); assertThat(value).isInstanceOf(Literal.class); assertThat((Literal) value).isEqualTo(factory.createLiteral("color", "en-US")); }
Util { @Deprecated public static String formatToWidth(int width, String padding, String str, String separator) { if (str.isEmpty()) { return ""; } int padLen = padding.length(); int strLen = str.length(); int sepLen = separator.length(); if (strLen + padLen <= width) { return padding + str; } String[] values = str.split(separator); StringBuilder builder = new StringBuilder(strLen + 4 * padLen + 8 * sepLen); int colpos = width; for (String value : values) { int len = value.length(); if (colpos + sepLen + len <= width) { builder.append(separator); } else { builder.append("\n").append(padding); colpos = padLen; } builder.append(value); colpos += len; } return builder.substring(1); } static Resource getContext(Repository repository, String ctxID); static Resource[] getContexts(String[] tokens, int pos, Repository repository); static Path getPath(String file); static String getPrefixedValue(Value value, Map<String, String> namespaces); @Deprecated static String formatToWidth(int width, String padding, String str, String separator); }
@Test public final void testFormatToWidth() { String str = "one, two, three, four, five, six, seven, eight"; String expect = " one, two\n" + " three\n" + " four\n" + " five, six\n" + " seven\n" + " eight"; String fmt = Util.formatToWidth(10, " ", str, ", "); System.err.println(fmt); assertTrue("Format not OK", expect.equals(fmt)); }
Drop extends ConsoleCommand { @Override public void execute(String... tokens) throws IOException { if (tokens.length < 2) { consoleIO.writeln(getHelpLong()); } else { final String repoID = tokens[1]; try { dropRepository(repoID); } catch (RepositoryConfigException e) { consoleIO.writeError("Unable to drop repository '" + repoID + "': " + e.getMessage()); LOGGER.warn("Unable to drop repository '" + repoID + "'", e); } catch (RepositoryReadOnlyException e) { try { if (LockRemover.tryToRemoveLock(state.getManager().getSystemRepository(), consoleIO)) { execute(tokens); } else { consoleIO.writeError("Failed to drop repository"); LOGGER.error("Failed to drop repository", e); } } catch (RepositoryException e2) { consoleIO.writeError("Failed to restart system: " + e2.getMessage()); LOGGER.error("Failed to restart system", e2); } } catch (RepositoryException e) { consoleIO.writeError("Failed to update configuration in system repository: " + e.getMessage()); LOGGER.warn("Failed to update configuration in system repository", e); } } } Drop(ConsoleIO consoleIO, ConsoleState state, Close close); @Override String getName(); @Override String getHelpShort(); @Override String getHelpLong(); @Override void execute(String... tokens); }
@Test public final void testSafeDrop() throws RepositoryException, IOException { setUserDropConfirm(true); assertThat(manager.isSafeToRemove(PROXY_ID)).isTrue(); drop.execute("drop", PROXY_ID); verify(mockConsoleIO).writeln("Dropped repository '" + PROXY_ID + "'"); assertThat(manager.isSafeToRemove(MEMORY_MEMBER_ID1)).isTrue(); drop.execute("drop", MEMORY_MEMBER_ID1); verify(mockConsoleIO).writeln("Dropped repository '" + MEMORY_MEMBER_ID1 + "'"); } @Test public final void testUnsafeDropCancel() throws RepositoryException, IOException { setUserDropConfirm(true); assertThat(manager.isSafeToRemove(MEMORY_MEMBER_ID1)).isFalse(); when(mockConsoleIO.askProceed(startsWith("WARNING: dropping this repository may break"), anyBoolean())) .thenReturn(false); drop.execute("drop", MEMORY_MEMBER_ID1); verify(mockConsoleIO).writeln("Drop aborted"); } @Test public final void testUserAbortedUnsafeDropBeforeWarning() throws IOException { setUserDropConfirm(false); drop.execute("drop", MEMORY_MEMBER_ID1); verify(mockConsoleIO, never()).askProceed(startsWith("WARNING: dropping this repository may break"), anyBoolean()); verify(mockConsoleIO).writeln("Drop aborted"); }
InfoServlet extends TransformationServlet { @Override protected void service(WorkbenchRequest req, HttpServletResponse resp, String xslPath) throws Exception { String id = info.getId(); if (null != id && !manager.hasRepositoryConfig(id)) { throw new RepositoryConfigException(id + " does not exist."); } TupleResultBuilder builder = getTupleResultBuilder(req, resp, resp.getOutputStream()); builder.start("id", "description", "location", "server", "readable", "writeable", "default-limit", "default-queryLn", "default-infer", "default-Accept", "default-Content-Type", "upload-format", "query-format", "graph-download-format", "tuple-download-format", "boolean-download-format"); String desc = info.getDescription(); URL loc = info.getLocation(); URL server = getServer(); builder.result(id, desc, loc, server, info.isReadable(), info.isWritable()); builder.namedResult("default-limit", req.getParameter("limit")); builder.namedResult("default-queryLn", req.getParameter("queryLn")); builder.namedResult("default-infer", req.getParameter("infer")); builder.namedResult("default-Accept", req.getParameter("Accept")); builder.namedResult("default-Content-Type", req.getParameter("Content-Type")); for (RDFParserFactory parser : RDFParserRegistry.getInstance().getAll()) { String mimeType = parser.getRDFFormat().getDefaultMIMEType(); String name = parser.getRDFFormat().getName(); builder.namedResult("upload-format", mimeType + " " + name); } for (QueryParserFactory factory : getInstance().getAll()) { String name = factory.getQueryLanguage().getName(); builder.namedResult("query-format", name + " " + name); } for (RDFWriterFactory writer : RDFWriterRegistry.getInstance().getAll()) { String mimeType = writer.getRDFFormat().getDefaultMIMEType(); String name = writer.getRDFFormat().getName(); builder.namedResult("graph-download-format", mimeType + " " + name); } for (TupleQueryResultWriterFactory writer : TupleQueryResultWriterRegistry.getInstance().getAll()) { String mimeType = writer.getTupleQueryResultFormat().getDefaultMIMEType(); String name = writer.getTupleQueryResultFormat().getName(); builder.namedResult("tuple-download-format", mimeType + " " + name); } for (BooleanQueryResultWriterFactory writer : BooleanQueryResultWriterRegistry.getInstance().getAll()) { String mimeType = writer.getBooleanQueryResultFormat().getDefaultMIMEType(); String name = writer.getBooleanQueryResultFormat().getName(); builder.namedResult("boolean-download-format", mimeType + " " + name); } builder.end(); } @Override String[] getCookieNames(); }
@Test public final void testSES1770regression() throws Exception { when(manager.hasRepositoryConfig(null)).thenThrow(new NullPointerException()); WorkbenchRequest req = mock(WorkbenchRequest.class); when(req.getParameter(anyString())).thenReturn(SESAME.NIL.toString()); HttpServletResponse resp = mock(HttpServletResponse.class); when(resp.getOutputStream()).thenReturn(mock(ServletOutputStream.class)); servlet.service(req, resp, ""); } @Test public final void testSES1770regression() throws Exception { when(manager.hasRepositoryConfig(null)).thenThrow(new NullPointerException()); WorkbenchRequest req = mock(WorkbenchRequest.class); when(req.getParameter(anyString())).thenReturn(RDF4J.NIL.toString()); HttpServletResponse resp = mock(HttpServletResponse.class); when(resp.getOutputStream()).thenReturn(mock(ServletOutputStream.class)); servlet.service(req, resp, ""); }
DBDecryptor implements Decryptor { public void decryptDB(File input, File output) throws IOException, GeneralSecurityException { if (input == null) throw new IllegalArgumentException("input cannot be null"); if (output == null) throw new IllegalArgumentException("output cannot be null"); decryptStream(new FileInputStream(input), new FileOutputStream(output)); } void decryptDB(File input, File output); static void main(String[] args); }
@Test public void shouldDecryptDatabase() throws Exception { File out = File.createTempFile("db-test", ".sql"); dbDecryptor.decryptDB(Fixtures.TEST_DB_1, out); verifyDB(out); } @Test(expected = IllegalArgumentException.class) public void shouldThrowWithNullInput() throws Exception { dbDecryptor.decryptDB(null, new File(("/out"))); } @Test(expected = IllegalArgumentException.class) public void shouldThrowWithNullOutput() throws Exception { dbDecryptor.decryptDB(new File(("/in")), null); }
Whassup { public long getMostRecentTimestamp(boolean ignoreGroups) throws IOException { File currentDB = dbProvider.getDBFile(); if (currentDB == null) { return DEFAULT_MOST_RECENT; } else { SQLiteDatabase db = getSqLiteDatabase(decryptDB(currentDB)); Cursor cursor = null; try { String query = "SELECT MAX(" + TIMESTAMP + ") FROM " + WhatsAppMessage.TABLE; if (ignoreGroups) { query += " WHERE " + KEY_REMOTE_JID + " NOT LIKE ?"; } cursor = db.rawQuery( query, ignoreGroups ? new String[]{ "%@" + WhatsAppMessage.GROUP } : null ); if (cursor != null && cursor.moveToNext()) { return cursor.getLong(0); } else { return DEFAULT_MOST_RECENT; } } catch (SQLiteException e) { Log.w(TAG, e); return DEFAULT_MOST_RECENT; } finally { if (cursor != null) cursor.close(); } } } Whassup(Context context); Whassup(DecryptorFactory decryptorFactory, DBProvider dbProvider, DBOpener dbOpener); Cursor queryMessages(); Cursor queryMessages(long timestamp, int max); long getMostRecentTimestamp(boolean ignoreGroups); List<WhatsAppMessage> getMessages(long timestamp, int max); List<WhatsAppMessage> getMessages(); boolean hasBackupDB(); }
@Test public void shouldGetMostRecentTimestamp() throws Exception { assertThat(whassup.getMostRecentTimestamp(true)).isEqualTo(1369589322298L); assertThat(whassup.getMostRecentTimestamp(false)).isEqualTo(1369589322298L); }
Whassup { public List<WhatsAppMessage> getMessages(long timestamp, int max) throws IOException { Cursor cursor = queryMessages(timestamp, max); try { if (cursor != null) { List<WhatsAppMessage> messages = new ArrayList<WhatsAppMessage>(cursor.getCount()); while (cursor.moveToNext()) { messages.add(new WhatsAppMessage(cursor)); } return messages; } else { return Collections.emptyList(); } } finally { if (cursor != null) { cursor.close(); } } } Whassup(Context context); Whassup(DecryptorFactory decryptorFactory, DBProvider dbProvider, DBOpener dbOpener); Cursor queryMessages(); Cursor queryMessages(long timestamp, int max); long getMostRecentTimestamp(boolean ignoreGroups); List<WhatsAppMessage> getMessages(long timestamp, int max); List<WhatsAppMessage> getMessages(); boolean hasBackupDB(); }
@Test public void shouldGetMedia() throws Exception { List<WhatsAppMessage> messages = whassup.getMessages(); WhatsAppMessage msg = null; for (WhatsAppMessage message : messages) { if (message.getId() == 82) { msg = message; break; } } assertThat(msg).isNotNull(); assertThat(msg.getMedia()).isNotNull(); Media mediaData = msg.getMedia(); assertThat(mediaData).isNotNull(); assertThat(mediaData.getFileSize()).isEqualTo(67731L); assertThat(mediaData.getFile().getAbsolutePath()).isEqualTo("/storage/emulated/0/WhatsApp/Media/WhatsApp Images/IMG-20130526-WA0000.jpg"); } @Test public void shouldReturnMessagesInAscendingTimestampOrder() throws Exception { List<WhatsAppMessage> messages = whassup.getMessages(); assertThat(messages).isSortedAccordingTo(WhatsAppMessage.TimestampComparator.INSTANCE); WhatsAppMessage first = messages.get(0); WhatsAppMessage last = messages.get(messages.size() - 1); assertThat(first.getTimestamp()).isBefore(last.getTimestamp()); } @Test public void shouldGetAllMessages() throws Exception { List<WhatsAppMessage> messages = whassup.getMessages(); assertThat(messages).isNotEmpty(); assertThat(messages).hasSize(82); } @Test public void shouldGetMessagesSinceASpecificTimestamp() throws Exception { List<WhatsAppMessage> messages = whassup.getMessages(1367349391104L, -1); assertThat(messages).isNotEmpty(); assertThat(messages).hasSize(15); } @Test public void shouldGetMessagesSinceASpecificTimestampAndLimit() throws Exception { List<WhatsAppMessage> messages = whassup.getMessages(1367349391104L, 3); assertThat(messages).isNotEmpty(); assertThat(messages).hasSize(3); }
Whassup { public boolean hasBackupDB() { return dbProvider.getDBFile() != null; } Whassup(Context context); Whassup(DecryptorFactory decryptorFactory, DBProvider dbProvider, DBOpener dbOpener); Cursor queryMessages(); Cursor queryMessages(long timestamp, int max); long getMostRecentTimestamp(boolean ignoreGroups); List<WhatsAppMessage> getMessages(long timestamp, int max); List<WhatsAppMessage> getMessages(); boolean hasBackupDB(); }
@Test public void shouldCheckIfDbIsAvailable() throws Exception { when(dbProvider.getDBFile()).thenReturn(null); assertThat(whassup.hasBackupDB()).isFalse(); when(dbProvider.getDBFile()).thenReturn(Fixtures.TEST_DB_1); assertThat(whassup.hasBackupDB()).isTrue(); }
Whassup { public Cursor queryMessages() throws IOException { return queryMessages(0, -1); } Whassup(Context context); Whassup(DecryptorFactory decryptorFactory, DBProvider dbProvider, DBOpener dbOpener); Cursor queryMessages(); Cursor queryMessages(long timestamp, int max); long getMostRecentTimestamp(boolean ignoreGroups); List<WhatsAppMessage> getMessages(long timestamp, int max); List<WhatsAppMessage> getMessages(); boolean hasBackupDB(); }
@Test(expected = IOException.class) public void shouldCatchSQLiteExceptionWhenOpeningDatabase() throws Exception { DBOpener dbOpener = mock(DBOpener.class); when(dbOpener.openDatabase(any(File.class))).thenThrow(new SQLiteException("failz")); new Whassup(decryptorFactory, dbProvider, dbOpener).queryMessages(); } @Test public void shouldQueryMessages() throws Exception { Cursor cursor = whassup.queryMessages(); assertThat(cursor).isNotNull(); assertThat(cursor.getCount()).isEqualTo(82); cursor.close(); } @Test public void shouldQueryMessagesSinceASpecificTimestamp() throws Exception { Cursor cursor = whassup.queryMessages(1367349391104L, -1); assertThat(cursor).isNotNull(); assertThat(cursor.getCount()).isEqualTo(15); } @Test public void shouldQueryMessagesSinceASpecificTimestampAndLimit() throws Exception { Cursor cursor = whassup.queryMessages(1367349391104L, 3); assertThat(cursor).isNotNull(); assertThat(cursor.getCount()).isEqualTo(3); }
WhatsAppMessage implements Comparable<WhatsAppMessage> { public Date getTimestamp() { return new Date(timestamp); } WhatsAppMessage(); WhatsAppMessage(Cursor c); long getId(); boolean isReceived(); Date getTimestamp(); String getText(); String getFilteredText(); int getStatus(); double getLongitude(); double getLatitude(); int getRecipientCount(); String getNumber(); Media getMedia(); Receipt getReceipt(); boolean hasMediaAttached(); boolean hasText(); @Override String toString(); @Override int compareTo(WhatsAppMessage another); boolean isDirectMessage(); boolean isGroupMessage(); static final String TABLE; static final String GROUP; static final String DIRECT; }
@Test public void shouldParseTimestamp() throws Exception { WhatsAppMessage m = new WhatsAppMessage(); m.timestamp = 1358086780000L; assertThat(m.getTimestamp().getTime()).isEqualTo(1358086780000L); }
WhatsAppMessage implements Comparable<WhatsAppMessage> { public String getNumber() { if (TextUtils.isEmpty(key_remote_jid)) return null; String[] components = key_remote_jid.split("@", 2); if (components.length > 1) { if (!isGroupMessage()) { return components[0]; } else { return components[0].split("-")[0]; } } else { return null; } } WhatsAppMessage(); WhatsAppMessage(Cursor c); long getId(); boolean isReceived(); Date getTimestamp(); String getText(); String getFilteredText(); int getStatus(); double getLongitude(); double getLatitude(); int getRecipientCount(); String getNumber(); Media getMedia(); Receipt getReceipt(); boolean hasMediaAttached(); boolean hasText(); @Override String toString(); @Override int compareTo(WhatsAppMessage another); boolean isDirectMessage(); boolean isGroupMessage(); static final String TABLE; static final String GROUP; static final String DIRECT; }
@Test public void shouldParseNumber() throws Exception { WhatsAppMessage m = new WhatsAppMessage(); m.key_remote_jid = "[email protected]"; assertThat(m.getNumber()).isEqualTo("4915773981234"); } @Test public void shouldParseNumberFromGroupMessage() throws Exception { WhatsAppMessage m = new WhatsAppMessage(); m.key_remote_jid = "[email protected]"; assertThat(m.getNumber()).isEqualTo("4915773981234"); } @Test public void shouldParseNumberWithInvalidSpec() throws Exception { WhatsAppMessage m = new WhatsAppMessage(); assertThat(m.getNumber()).isNull(); m.key_remote_jid = "foobaz"; assertThat(m.getNumber()).isNull(); }
WhatsAppMessage implements Comparable<WhatsAppMessage> { @Override public int compareTo(WhatsAppMessage another) { return TimestampComparator.INSTANCE.compare(this, another); } WhatsAppMessage(); WhatsAppMessage(Cursor c); long getId(); boolean isReceived(); Date getTimestamp(); String getText(); String getFilteredText(); int getStatus(); double getLongitude(); double getLatitude(); int getRecipientCount(); String getNumber(); Media getMedia(); Receipt getReceipt(); boolean hasMediaAttached(); boolean hasText(); @Override String toString(); @Override int compareTo(WhatsAppMessage another); boolean isDirectMessage(); boolean isGroupMessage(); static final String TABLE; static final String GROUP; static final String DIRECT; }
@Test public void shouldImplementComparableBasedOnTimestamp() throws Exception { WhatsAppMessage m1 = new WhatsAppMessage(); WhatsAppMessage m2 = new WhatsAppMessage(); m1.timestamp = 1; m2.timestamp = 2; assertThat(m1.compareTo(m2)).isLessThan(0); assertThat(m2.compareTo(m1)).isGreaterThan(0); assertThat(m2.compareTo(m2)).isEqualTo(0); assertThat(m1.compareTo(m1)).isEqualTo(0); }
WhatsAppMessage implements Comparable<WhatsAppMessage> { public boolean hasText() { return !TextUtils.isEmpty(data); } WhatsAppMessage(); WhatsAppMessage(Cursor c); long getId(); boolean isReceived(); Date getTimestamp(); String getText(); String getFilteredText(); int getStatus(); double getLongitude(); double getLatitude(); int getRecipientCount(); String getNumber(); Media getMedia(); Receipt getReceipt(); boolean hasMediaAttached(); boolean hasText(); @Override String toString(); @Override int compareTo(WhatsAppMessage another); boolean isDirectMessage(); boolean isGroupMessage(); static final String TABLE; static final String GROUP; static final String DIRECT; }
@Test public void shouldHaveTextIfNonEmptyString() throws Exception { WhatsAppMessage m = new WhatsAppMessage(); assertThat(m.hasText()).isFalse(); m.data = ""; assertThat(m.hasText()).isFalse(); m.data = "some text"; assertThat(m.hasText()).isTrue(); }
WhatsAppMessage implements Comparable<WhatsAppMessage> { public boolean isReceived() { return key_from_me == 0; } WhatsAppMessage(); WhatsAppMessage(Cursor c); long getId(); boolean isReceived(); Date getTimestamp(); String getText(); String getFilteredText(); int getStatus(); double getLongitude(); double getLatitude(); int getRecipientCount(); String getNumber(); Media getMedia(); Receipt getReceipt(); boolean hasMediaAttached(); boolean hasText(); @Override String toString(); @Override int compareTo(WhatsAppMessage another); boolean isDirectMessage(); boolean isGroupMessage(); static final String TABLE; static final String GROUP; static final String DIRECT; }
@Test public void shouldCheckIfReceived() throws Exception { WhatsAppMessage m = new WhatsAppMessage(); assertThat(m.isReceived()).isTrue(); m.key_from_me = 1; assertThat(m.isReceived()).isFalse(); }
WhatsAppMessage implements Comparable<WhatsAppMessage> { static String filterPrivateBlock(String s) { if (s == null) return null; final StringBuilder sb = new StringBuilder(); for (int i=0; i<s.length(); ) { int codepoint = s.codePointAt(i); Character.UnicodeBlock block = Character.UnicodeBlock.of(codepoint); if (block != Character.UnicodeBlock.PRIVATE_USE_AREA) { sb.append(Character.toChars(codepoint)); } i += Character.charCount(codepoint); } return sb.toString(); } WhatsAppMessage(); WhatsAppMessage(Cursor c); long getId(); boolean isReceived(); Date getTimestamp(); String getText(); String getFilteredText(); int getStatus(); double getLongitude(); double getLatitude(); int getRecipientCount(); String getNumber(); Media getMedia(); Receipt getReceipt(); boolean hasMediaAttached(); boolean hasText(); @Override String toString(); @Override int compareTo(WhatsAppMessage another); boolean isDirectMessage(); boolean isGroupMessage(); static final String TABLE; static final String GROUP; static final String DIRECT; }
@Test public void shouldFilterPrivateUnicodeCharacters() throws Exception { byte[] b = new byte[] { (byte) 0xee, (byte) 0x90, (byte) 0x87, (byte) 0xf0, (byte) 0x9f, (byte) 0x98, (byte) 0xa4, (byte) 0xee, (byte) 0x84, (byte) 0x87 }; String s = new String(b, Charset.forName("UTF-8")); assertThat(s.length()).isEqualTo(4); String filtered = WhatsAppMessage.filterPrivateBlock(s); assertThat(filtered).isEqualTo("\uD83D\uDE24"); assertThat(filtered.length()).isEqualTo(2); } @Test public void shouldFilterPrivateUnicodeCharactersNull() throws Exception { assertThat(WhatsAppMessage.filterPrivateBlock(null)).isNull(); }
Media { public File getFile() { MediaData md = getMediaData(); return md == null ? null : md.getFile(); } Media(); Media(Cursor c); byte[] getRawData(); String getMimeType(); String getUrl(); int getSize(); File getFile(); long getFileSize(); @Override String toString(); }
@Test public void shouldHandleSerializedDataOfWrongType() throws Exception { Media media = new Media(); media.thumb_image = fileToBytes(Fixtures.VECTOR_SERIALIZED); assertThat(media.getFile()).isNull(); } @Test public void shouldHandleInvalidSerializedData() throws Exception { Media media = new Media(); media.thumb_image = new byte[] {(byte) 0xde, (byte) 0xad, (byte) 0xbe, (byte) 0xef}; assertThat(media.getFile()).isNull(); }
DBDecryptor implements Decryptor { protected void decryptStream(InputStream in, OutputStream out) throws GeneralSecurityException, IOException { Cipher cipher = getCipher(Cipher.DECRYPT_MODE); CipherInputStream cis = null; try { cis = new CipherInputStream(in, cipher); byte[] buffer = new byte[8192]; int n; while ((n = cis.read(buffer)) != -1) { out.write(buffer, 0, n); } } finally { try { if (cis != null) cis.close(); out.close(); } catch (IOException ignored) {} } } void decryptDB(File input, File output); static void main(String[] args); }
@Test public void shouldDecryptStream() throws Exception { File out = File.createTempFile("db-test", ".sql"); FileOutputStream fos = new FileOutputStream(out); dbDecryptor.decryptStream(new FileInputStream(Fixtures.TEST_DB_1), fos); verifyDB(out); }
RepositoryPersonService implements PersonService { @Transactional(readOnly = true) @Override public List<Person> search(String searchTerm, int pageIndex) { LOGGER.debug("Searching persons with search term: " + searchTerm); return personRepository.findPersonsForPage(searchTerm, pageIndex); } @Transactional @Override Person create(PersonDTO created); @Transactional @Override long count(String searchTerm); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person delete(Long personId); @Transactional(readOnly = true) @Override List<Person> findAll(); @Transactional(readOnly = true) @Override Person findById(Long id); @Transactional(readOnly = true) @Override List<Person> search(String searchTerm, int pageIndex); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person update(PersonDTO updated); }
@Test public void search() { personService.search(SEARCH_TERM, PAGE_INDEX); verify(personRepositoryMock, times(1)).findPersonsForPage(SEARCH_TERM, PAGE_INDEX); verifyNoMoreInteractions(personRepositoryMock); }