target
stringlengths 20
113k
| src_fm
stringlengths 11
86.3k
| src_fm_fc
stringlengths 21
86.4k
| src_fm_fc_co
stringlengths 30
86.4k
| src_fm_fc_ms
stringlengths 42
86.8k
| src_fm_fc_ms_ff
stringlengths 43
86.8k
|
---|---|---|---|---|---|
@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); } | @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 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 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); } | 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); } | 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 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); } | @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 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 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); } | 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); } | 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 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); } | @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 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 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); } | 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); } | 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 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); } | @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 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 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); } | 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); } | 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 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); } | @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 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 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); } | 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); } | 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 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)); } | @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 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 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); } | 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); } | 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 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)); } | @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 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 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); } | 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); } | 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 testBothNull() throws Exception { assertTrue(cmp.compare(null, null) == 0); } | @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); } | 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); } } | 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); } } | 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); } | 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 testLeftNull() throws Exception { assertTrue(cmp.compare(null, typed1) < 0); } | @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); } | 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); } } | 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); } } | 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); } | 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 testRightNull() throws Exception { assertTrue(cmp.compare(typed1, null) > 0); } | @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); } | 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); } } | 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); } } | 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); } | 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 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()); } | @Override public QueryModelNode getParentQueryModelNode() { return filter; } | DistanceQuerySpec extends AbstractSearchQueryEvaluator { @Override public QueryModelNode getParentQueryModelNode() { return filter; } } | 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); } | 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(); } | 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 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)); } | @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); } | 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); } } | 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); } } | 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); } | 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 testLeftBnode() throws Exception { assertTrue(cmp.compare(bnode1, typed1) < 0); } | @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); } | 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); } } | 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); } } | 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); } | 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 testRightBnode() throws Exception { assertTrue(cmp.compare(typed1, bnode1) > 0); } | @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); } | 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); } } | 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); } } | 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); } | 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 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); } | @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); } | 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); } } | 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); } } | 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); } | 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 testLeftURI() throws Exception { assertTrue(cmp.compare(uri1, typed1) < 0); } | @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); } | 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); } } | 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); } } | 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); } | 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 testRightURI() throws Exception { assertTrue(cmp.compare(typed1, uri1) > 0); } | @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); } | 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); } } | 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); } } | 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); } | 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 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); } | 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"); } } | 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"); } } } | 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"); } } } | 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); } | 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 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()); } } | @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); } | 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); } } | 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); } } | 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); } | 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 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()); } | @Override public QueryModelNode getParentQueryModelNode() { return filter; } | DistanceQuerySpec extends AbstractSearchQueryEvaluator { @Override public QueryModelNode getParentQueryModelNode() { return filter; } } | 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); } | 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(); } | 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 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()); } } | @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]); } } | 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]); } } } | 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]); } } } | 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); } | 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 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()); } } | @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]); } } | 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]); } } } | 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]); } } } | 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); } | 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 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()); } } | @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]); } } | 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]); } } } | 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]); } } } | 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); } | 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 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()); } } | @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]); } } | 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]); } } } | 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]); } } } | 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); } | 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 = 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()); } } | @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]); } } | 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]); } } } | 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]); } } } | 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); } | 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 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()); } } | @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]); } } | 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]); } } } | 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]); } } } | 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); } | 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 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) { } } | @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]); } } | 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]); } } } | 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]); } } } | 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); } | 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 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()); } } | public SpinParser() { this(Input.TEXT_FIRST); } | SpinParser { public SpinParser() { this(Input.TEXT_FIRST); } } | SpinParser { public SpinParser() { this(Input.TEXT_FIRST); } SpinParser(); SpinParser(Input input); SpinParser(Input input, Function<IRI, String> wellKnownVarsMapper,
Function<IRI, String> wellKnownFuncMapper); } | 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); } | 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 stringLiteralHandling() { Literal result = concatFunc.evaluate(vf, foo, bar); assertThat(result.stringValue()).isEqualTo("foobar"); assertThat(result.getDatatype()).isEqualTo(XMLSchema.STRING); assertThat(result.getLanguage().isPresent()).isFalse(); } | @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; } | 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; } } | 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; } } | 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); } | 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 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(); } | @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; } | 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; } } | 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; } } | 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); } | 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 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(); } | @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; } | 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; } } | 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; } } | 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); } | 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 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()); } } | @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); } } | 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); } } } | 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); } } } | 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); } | 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 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()); } } | @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); } } | 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); } } } | 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); } } } | 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); } | 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 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()); } } | @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); } } | 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); } } } | 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); } } } | 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); } | 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 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()); } } | @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); } } | 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); } } } | 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); } } } | 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); } | 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 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()); } } | @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); } } | 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); } } } | 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); } } } | 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); } | 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 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)); } | 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; } | 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; } } | 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; } } | 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); } | 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 testVerifyMissingType() throws IOException { cmd.execute("verify", copyFromRes("missing_type.ttl")); assertTrue(io.wasErrorWritten()); } | @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 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 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); } | 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); } | 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 testVerifySpaceIRI() throws IOException { cmd.execute("verify", copyFromRes("space_iri.ttl")); assertTrue(io.wasErrorWritten()); } | @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 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 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); } | 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); } | 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 testVerifyWrongLang() throws IOException { cmd.execute("verify", copyFromRes("wrong_lang.ttl")); assertTrue(io.wasErrorWritten()); } | @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 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 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); } | 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); } | 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 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); } | @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 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 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); } | 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); } | 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 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()); } | @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 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 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); } | 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); } | 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 void testInvalidArgumentPrintsError() throws Exception { execute("type=memory", FED_ID, MEMORY_MEMBER_ID1, MEMORY_MEMBER_ID2); verifyFailure(); } | @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 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 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); } | 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); } | 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 testDuplicateMembersPrintsError() throws Exception { execute(FED_ID, MEMORY_MEMBER_ID1, MEMORY_MEMBER_ID1); verifyFailure(); } | @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 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 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); } | 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); } | 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 testFedSameAsMemberPrintsError() throws Exception { execute(FED_ID, MEMORY_MEMBER_ID1, FED_ID, MEMORY_MEMBER_ID1); verifyFailure(); } | @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 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 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); } | 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); } | 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 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."); } | @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 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 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); } | 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); } | 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 testFedAlreadyExistsPrintsSpecificError() throws Exception { execute(MEMORY_MEMBER_ID1, FED_ID, MEMORY_MEMBER_ID2); verifyFailure(MEMORY_MEMBER_ID1 + " already exists."); } | @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 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 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); } | 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); } | 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 final void testContextsNull() { String[] tokens = { "command", "command2", "NULL" }; Resource[] ctxs = Util.getContexts(tokens, 2, repo); assertTrue("Not null", ctxs[0] == null); } | 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; } | 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; } } | 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; } } | 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); } | 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 void testNonexistentMemberPrintsSpecificError() throws Exception { execute(FED_ID, MEMORY_MEMBER_ID1, "FreeLunch"); verifyFailure("FreeLunch does not exist."); } | @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 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 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); } | 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); } | 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 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); } | @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 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 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); } | 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); } | 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 testFederateSucceedsWithHTTPandSPARQLmembers() throws Exception { execute(FED_ID, HTTP_MEMBER_ID, SPARQL_MEMBER_ID); verifySuccess(HTTPRepositoryFactory.REPOSITORY_TYPE, SPARQLRepositoryFactory.REPOSITORY_TYPE); } | @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 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 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); } | 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); } | 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 testFederateHTTPtypeSucceeds() throws Exception { execute(FED_ID, HTTP_MEMBER_ID, HTTP2_MEMBER_ID); verifySuccess(HTTPRepositoryFactory.REPOSITORY_TYPE, HTTPRepositoryFactory.REPOSITORY_TYPE); } | @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 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 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); } | 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); } | 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 testFederateSPARQLtypeSucceeds() throws Exception { execute(FED_ID, SPARQL_MEMBER_ID, SPARQL2_MEMBER_ID); verifySuccess(SPARQLRepositoryFactory.REPOSITORY_TYPE, SPARQLRepositoryFactory.REPOSITORY_TYPE); } | @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 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 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); } | 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); } | 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 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); } | @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 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 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); } | 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); } | 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 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); } | @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 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 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); } | 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); } | 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 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(); } | @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 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 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); } | 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); } | 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 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(); } | @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 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 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); } | 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); } | 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 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); } | 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 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 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); } | 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); } | 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 testContextsInvalid() { String[] tokens = { "command", "invalid" }; try { Resource[] ctxs = Util.getContexts(tokens, 1, repo); fail("No exception generated"); } catch (IllegalArgumentException expected) { } } | 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; } | 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; } } | 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; } } | 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); } | 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 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()); } | @Override public void execute(String... tokens) { if (tokens.length < 3) { consoleIO.writeln(getHelpLong()); return; } convert(tokens[1], tokens[2]); } | Convert extends ConsoleCommand { @Override public void execute(String... tokens) { if (tokens.length < 3) { consoleIO.writeln(getHelpLong()); return; } convert(tokens[1], tokens[2]); } } | 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); } | 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); } | 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 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()); } | @Override public void execute(String... tokens) { if (tokens.length < 3) { consoleIO.writeln(getHelpLong()); return; } convert(tokens[1], tokens[2]); } | Convert extends ConsoleCommand { @Override public void execute(String... tokens) { if (tokens.length < 3) { consoleIO.writeln(getHelpLong()); return; } convert(tokens[1], tokens[2]); } } | 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); } | 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); } | 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 void testUnknownParametersAreErrors() { setParameters.execute("set", "unknown"); verify(mockConsoleIO).writeError("Unknown parameter: unknown"); verifyNoMoreInteractions(mockConsoleIO); } | @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 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 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); } | 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); } | 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 final void testLiteralWithURIType() throws BadRequestException { Value value = decoder.decodeValue("\"1\"^^<" + XMLSchema.INT + ">"); assertThat(value).isInstanceOf(Literal.class); assertThat((Literal) value).isEqualTo(factory.createLiteral(1)); } | 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; } | 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; } } | 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); } | 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); } | 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 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)); } | @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); } | 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); } } | 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); } } | 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); } | 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 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 + "'"); } | @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 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 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); } | 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); } | 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 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, ""); } | @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(); } | 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(); } } | 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(); } } | 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(); } | 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 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"); } | @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 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 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); } | 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); } | 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 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"); } | @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 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 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); } | 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); } | 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 testVerifyWrongFormat() { cmd.execute("verify", "does-not-exist.docx"); assertTrue(io.wasErrorWritten()); } | @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 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 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); } | 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); } | 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 testVerifyOK() throws IOException { cmd.execute("verify", copyFromRes("ok.ttl")); assertFalse(io.wasErrorWritten()); } | @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 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 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); } | 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); } | 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 testVerifyBrokenFile() throws IOException { cmd.execute("verify", copyFromRes("broken.ttl")); assertTrue(io.wasErrorWritten()); } | @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 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 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); } | 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); } | 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 void shouldDecryptDatabase() throws Exception { File out = File.createTempFile("db-test", ".sql"); dbDecryptor.decryptDB(Fixtures.TEST_DB_1, out); verifyDB(out); } | 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)); } | 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)); } } | 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)); } } | 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); } | 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 shouldGetMostRecentTimestamp() throws Exception { assertThat(whassup.getMostRecentTimestamp(true)).isEqualTo(1369589322298L); assertThat(whassup.getMostRecentTimestamp(false)).isEqualTo(1369589322298L); } | 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 { 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 { 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); } | 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(); } | 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 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"); } | 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 { 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 { 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); } | 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(); } | 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 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()); } | 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 { 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 { 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); } | 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(); } | 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 shouldCheckIfDbIsAvailable() throws Exception { when(dbProvider.getDBFile()).thenReturn(null); assertThat(whassup.hasBackupDB()).isFalse(); when(dbProvider.getDBFile()).thenReturn(Fixtures.TEST_DB_1); assertThat(whassup.hasBackupDB()).isTrue(); } | public boolean hasBackupDB() { return dbProvider.getDBFile() != null; } | Whassup { public boolean hasBackupDB() { return dbProvider.getDBFile() != null; } } | Whassup { public boolean hasBackupDB() { return dbProvider.getDBFile() != null; } Whassup(Context context); Whassup(DecryptorFactory decryptorFactory, DBProvider dbProvider, DBOpener dbOpener); } | 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(); } | 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(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(); } | public Cursor queryMessages() throws IOException { return queryMessages(0, -1); } | Whassup { public Cursor queryMessages() throws IOException { return queryMessages(0, -1); } } | Whassup { public Cursor queryMessages() throws IOException { return queryMessages(0, -1); } Whassup(Context context); Whassup(DecryptorFactory decryptorFactory, DBProvider dbProvider, DBOpener dbOpener); } | 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(); } | 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 public void shouldParseTimestamp() throws Exception { WhatsAppMessage m = new WhatsAppMessage(); m.timestamp = 1358086780000L; assertThat(m.getTimestamp().getTime()).isEqualTo(1358086780000L); } | public Date getTimestamp() { return new Date(timestamp); } | WhatsAppMessage implements Comparable<WhatsAppMessage> { public Date getTimestamp() { return new Date(timestamp); } } | WhatsAppMessage implements Comparable<WhatsAppMessage> { public Date getTimestamp() { return new Date(timestamp); } WhatsAppMessage(); WhatsAppMessage(Cursor c); } | 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(); } | 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 shouldParseNumber() throws Exception { WhatsAppMessage m = new WhatsAppMessage(); m.key_remote_jid = "[email protected]"; assertThat(m.getNumber()).isEqualTo("4915773981234"); } | 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 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 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); } | 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(); } | 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 shouldParseNumberFromGroupMessage() throws Exception { WhatsAppMessage m = new WhatsAppMessage(); m.key_remote_jid = "[email protected]"; assertThat(m.getNumber()).isEqualTo("4915773981234"); } | 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 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 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); } | 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(); } | 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 shouldParseNumberWithInvalidSpec() throws Exception { WhatsAppMessage m = new WhatsAppMessage(); assertThat(m.getNumber()).isNull(); m.key_remote_jid = "foobaz"; assertThat(m.getNumber()).isNull(); } | 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 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 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); } | 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(); } | 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 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); } | @Override public int compareTo(WhatsAppMessage another) { return TimestampComparator.INSTANCE.compare(this, another); } | WhatsAppMessage implements Comparable<WhatsAppMessage> { @Override public int compareTo(WhatsAppMessage another) { return TimestampComparator.INSTANCE.compare(this, another); } } | WhatsAppMessage implements Comparable<WhatsAppMessage> { @Override public int compareTo(WhatsAppMessage another) { return TimestampComparator.INSTANCE.compare(this, another); } WhatsAppMessage(); WhatsAppMessage(Cursor c); } | 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(); } | 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(expected = IllegalArgumentException.class) public void shouldThrowWithNullInput() throws Exception { dbDecryptor.decryptDB(null, new File(("/out"))); } | 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)); } | 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)); } } | 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)); } } | 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); } | 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 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(); } | public boolean hasText() { return !TextUtils.isEmpty(data); } | WhatsAppMessage implements Comparable<WhatsAppMessage> { public boolean hasText() { return !TextUtils.isEmpty(data); } } | WhatsAppMessage implements Comparable<WhatsAppMessage> { public boolean hasText() { return !TextUtils.isEmpty(data); } WhatsAppMessage(); WhatsAppMessage(Cursor c); } | 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(); } | 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 shouldCheckIfReceived() throws Exception { WhatsAppMessage m = new WhatsAppMessage(); assertThat(m.isReceived()).isTrue(); m.key_from_me = 1; assertThat(m.isReceived()).isFalse(); } | public boolean isReceived() { return key_from_me == 0; } | WhatsAppMessage implements Comparable<WhatsAppMessage> { public boolean isReceived() { return key_from_me == 0; } } | WhatsAppMessage implements Comparable<WhatsAppMessage> { public boolean isReceived() { return key_from_me == 0; } WhatsAppMessage(); WhatsAppMessage(Cursor c); } | 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(); } | 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 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); } | 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 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 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); } | 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(); } | 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 shouldFilterPrivateUnicodeCharactersNull() throws Exception { assertThat(WhatsAppMessage.filterPrivateBlock(null)).isNull(); } | 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 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 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); } | 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(); } | 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 shouldHandleSerializedDataOfWrongType() throws Exception { Media media = new Media(); media.thumb_image = fileToBytes(Fixtures.VECTOR_SERIALIZED); assertThat(media.getFile()).isNull(); } | public File getFile() { MediaData md = getMediaData(); return md == null ? null : md.getFile(); } | Media { public File getFile() { MediaData md = getMediaData(); return md == null ? null : md.getFile(); } } | Media { public File getFile() { MediaData md = getMediaData(); return md == null ? null : md.getFile(); } Media(); Media(Cursor c); } | 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(); } | 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 shouldHandleInvalidSerializedData() throws Exception { Media media = new Media(); media.thumb_image = new byte[] {(byte) 0xde, (byte) 0xad, (byte) 0xbe, (byte) 0xef}; assertThat(media.getFile()).isNull(); } | public File getFile() { MediaData md = getMediaData(); return md == null ? null : md.getFile(); } | Media { public File getFile() { MediaData md = getMediaData(); return md == null ? null : md.getFile(); } } | Media { public File getFile() { MediaData md = getMediaData(); return md == null ? null : md.getFile(); } Media(); Media(Cursor c); } | 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(); } | 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(expected = IllegalArgumentException.class) public void shouldThrowWithNullOutput() throws Exception { dbDecryptor.decryptDB(new File(("/in")), null); } | 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)); } | 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)); } } | 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)); } } | 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); } | 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 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); } | 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) {} } } | 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) {} } } } | 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) {} } } } | 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); } | 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 shouldGetAllMessages() throws Exception { List<WhatsAppMessage> messages = whassup.getMessages(); assertThat(messages).isNotEmpty(); assertThat(messages).hasSize(82); } | 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 { 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 { 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); } | 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(); } | 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 shouldQueryMessages() throws Exception { Cursor cursor = whassup.queryMessages(); assertThat(cursor).isNotNull(); assertThat(cursor.getCount()).isEqualTo(82); cursor.close(); } | public Cursor queryMessages() throws IOException { return queryMessages(0, -1); } | Whassup { public Cursor queryMessages() throws IOException { return queryMessages(0, -1); } } | Whassup { public Cursor queryMessages() throws IOException { return queryMessages(0, -1); } Whassup(Context context); Whassup(DecryptorFactory decryptorFactory, DBProvider dbProvider, DBOpener dbOpener); } | 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(); } | 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 public void shouldGetMessagesSinceASpecificTimestamp() throws Exception { List<WhatsAppMessage> messages = whassup.getMessages(1367349391104L, -1); assertThat(messages).isNotEmpty(); assertThat(messages).hasSize(15); } | 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 { 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 { 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); } | 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(); } | 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 shouldQueryMessagesSinceASpecificTimestamp() throws Exception { Cursor cursor = whassup.queryMessages(1367349391104L, -1); assertThat(cursor).isNotNull(); assertThat(cursor.getCount()).isEqualTo(15); } | public Cursor queryMessages() throws IOException { return queryMessages(0, -1); } | Whassup { public Cursor queryMessages() throws IOException { return queryMessages(0, -1); } } | Whassup { public Cursor queryMessages() throws IOException { return queryMessages(0, -1); } Whassup(Context context); Whassup(DecryptorFactory decryptorFactory, DBProvider dbProvider, DBOpener dbOpener); } | 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(); } | 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 public void shouldGetMessagesSinceASpecificTimestampAndLimit() throws Exception { List<WhatsAppMessage> messages = whassup.getMessages(1367349391104L, 3); assertThat(messages).isNotEmpty(); assertThat(messages).hasSize(3); } | 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 { 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 { 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); } | 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(); } | 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 shouldQueryMessagesSinceASpecificTimestampAndLimit() throws Exception { Cursor cursor = whassup.queryMessages(1367349391104L, 3); assertThat(cursor).isNotNull(); assertThat(cursor.getCount()).isEqualTo(3); } | public Cursor queryMessages() throws IOException { return queryMessages(0, -1); } | Whassup { public Cursor queryMessages() throws IOException { return queryMessages(0, -1); } } | Whassup { public Cursor queryMessages() throws IOException { return queryMessages(0, -1); } Whassup(Context context); Whassup(DecryptorFactory decryptorFactory, DBProvider dbProvider, DBOpener dbOpener); } | 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(); } | 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 public void search() { personService.search(SEARCH_TERM, PAGE_INDEX); verify(personRepositoryMock, times(1)).findPersonsForPage(SEARCH_TERM, PAGE_INDEX); verifyNoMoreInteractions(personRepositoryMock); } | @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); } | 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); } } | 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); } } | 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); } | 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 lastNameIsLike() { Path lastNamePathMock = mock(Path.class); when(personRootMock.get(Person_.lastName)).thenReturn(lastNamePathMock); Expression lastNameToLowerExpressionMock = mock(Expression.class); when(criteriaBuilderMock.lower(lastNamePathMock)).thenReturn(lastNameToLowerExpressionMock); Predicate lastNameIsLikePredicateMock = mock(Predicate.class); when(criteriaBuilderMock.like(lastNameToLowerExpressionMock, SEARCH_TERM_LIKE_PATTERN)).thenReturn(lastNameIsLikePredicateMock); Specification<Person> actual = PersonSpecifications.lastNameIsLike(SEARCH_TERM); Predicate actualPredicate = actual.toPredicate(personRootMock, criteriaQueryMock, criteriaBuilderMock); verify(personRootMock, times(1)).get(Person_.lastName); verifyNoMoreInteractions(personRootMock); verify(criteriaBuilderMock, times(1)).lower(lastNamePathMock); verify(criteriaBuilderMock, times(1)).like(lastNameToLowerExpressionMock, SEARCH_TERM_LIKE_PATTERN); verifyNoMoreInteractions(criteriaBuilderMock); verifyZeroInteractions(criteriaQueryMock, lastNamePathMock, lastNameIsLikePredicateMock); assertEquals(lastNameIsLikePredicateMock, actualPredicate); } | public static Specification<Person> lastNameIsLike(final String searchTerm) { return new Specification<Person>() { @Override public Predicate toPredicate(Root<Person> personRoot, CriteriaQuery<?> query, CriteriaBuilder cb) { String likePattern = getLikePattern(searchTerm); return cb.like(cb.lower(personRoot.<String>get(Person_.lastName)), likePattern); } private String getLikePattern(final String searchTerm) { StringBuilder pattern = new StringBuilder(); pattern.append(searchTerm.toLowerCase()); pattern.append("%"); return pattern.toString(); } }; } | PersonSpecifications { public static Specification<Person> lastNameIsLike(final String searchTerm) { return new Specification<Person>() { @Override public Predicate toPredicate(Root<Person> personRoot, CriteriaQuery<?> query, CriteriaBuilder cb) { String likePattern = getLikePattern(searchTerm); return cb.like(cb.lower(personRoot.<String>get(Person_.lastName)), likePattern); } private String getLikePattern(final String searchTerm) { StringBuilder pattern = new StringBuilder(); pattern.append(searchTerm.toLowerCase()); pattern.append("%"); return pattern.toString(); } }; } } | PersonSpecifications { public static Specification<Person> lastNameIsLike(final String searchTerm) { return new Specification<Person>() { @Override public Predicate toPredicate(Root<Person> personRoot, CriteriaQuery<?> query, CriteriaBuilder cb) { String likePattern = getLikePattern(searchTerm); return cb.like(cb.lower(personRoot.<String>get(Person_.lastName)), likePattern); } private String getLikePattern(final String searchTerm) { StringBuilder pattern = new StringBuilder(); pattern.append(searchTerm.toLowerCase()); pattern.append("%"); return pattern.toString(); } }; } } | PersonSpecifications { public static Specification<Person> lastNameIsLike(final String searchTerm) { return new Specification<Person>() { @Override public Predicate toPredicate(Root<Person> personRoot, CriteriaQuery<?> query, CriteriaBuilder cb) { String likePattern = getLikePattern(searchTerm); return cb.like(cb.lower(personRoot.<String>get(Person_.lastName)), likePattern); } private String getLikePattern(final String searchTerm) { StringBuilder pattern = new StringBuilder(); pattern.append(searchTerm.toLowerCase()); pattern.append("%"); return pattern.toString(); } }; } static Specification<Person> lastNameIsLike(final String searchTerm); } | PersonSpecifications { public static Specification<Person> lastNameIsLike(final String searchTerm) { return new Specification<Person>() { @Override public Predicate toPredicate(Root<Person> personRoot, CriteriaQuery<?> query, CriteriaBuilder cb) { String likePattern = getLikePattern(searchTerm); return cb.like(cb.lower(personRoot.<String>get(Person_.lastName)), likePattern); } private String getLikePattern(final String searchTerm) { StringBuilder pattern = new StringBuilder(); pattern.append(searchTerm.toLowerCase()); pattern.append("%"); return pattern.toString(); } }; } static Specification<Person> lastNameIsLike(final String searchTerm); } |
@Test public void update() throws PersonNotFoundException { PersonDTO updated = PersonTestUtil.createDTO(PERSON_ID, FIRST_NAME_UPDATED, LAST_NAME_UPDATED); Person person = PersonTestUtil.createModelObject(PERSON_ID, FIRST_NAME, LAST_NAME); when(personRepositoryMock.findOne(updated.getId())).thenReturn(person); Person returned = personService.update(updated); verify(personRepositoryMock, times(1)).findOne(updated.getId()); verifyNoMoreInteractions(personRepositoryMock); assertPerson(updated, returned); } | @Transactional(rollbackFor = PersonNotFoundException.class) @Override public Person update(PersonDTO updated) throws PersonNotFoundException { LOGGER.debug("Updating person with information: " + updated); Person person = personRepository.findOne(updated.getId()); if (person == null) { LOGGER.debug("No person found with id: " + updated.getId()); throw new PersonNotFoundException(); } person.update(updated.getFirstName(), updated.getLastName()); return person; } | RepositoryPersonService implements PersonService { @Transactional(rollbackFor = PersonNotFoundException.class) @Override public Person update(PersonDTO updated) throws PersonNotFoundException { LOGGER.debug("Updating person with information: " + updated); Person person = personRepository.findOne(updated.getId()); if (person == null) { LOGGER.debug("No person found with id: " + updated.getId()); throw new PersonNotFoundException(); } person.update(updated.getFirstName(), updated.getLastName()); return person; } } | RepositoryPersonService implements PersonService { @Transactional(rollbackFor = PersonNotFoundException.class) @Override public Person update(PersonDTO updated) throws PersonNotFoundException { LOGGER.debug("Updating person with information: " + updated); Person person = personRepository.findOne(updated.getId()); if (person == null) { LOGGER.debug("No person found with id: " + updated.getId()); throw new PersonNotFoundException(); } person.update(updated.getFirstName(), updated.getLastName()); return person; } } | RepositoryPersonService implements PersonService { @Transactional(rollbackFor = PersonNotFoundException.class) @Override public Person update(PersonDTO updated) throws PersonNotFoundException { LOGGER.debug("Updating person with information: " + updated); Person person = personRepository.findOne(updated.getId()); if (person == null) { LOGGER.debug("No person found with id: " + updated.getId()); throw new PersonNotFoundException(); } person.update(updated.getFirstName(), updated.getLastName()); return person; } @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); } | RepositoryPersonService implements PersonService { @Transactional(rollbackFor = PersonNotFoundException.class) @Override public Person update(PersonDTO updated) throws PersonNotFoundException { LOGGER.debug("Updating person with information: " + updated); Person person = personRepository.findOne(updated.getId()); if (person == null) { LOGGER.debug("No person found with id: " + updated.getId()); throw new PersonNotFoundException(); } person.update(updated.getFirstName(), updated.getLastName()); return person; } @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); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.