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(expected = AuditPropertyException.class) public void should_fail_on_invalid_entity() { InvalidEntity entity = new InvalidEntity(); new TimestampsProvider().prePersist(entity); fail(); }
@Override public void prePersist(Object entity) { updateTimestamps(entity, true); }
TimestampsProvider extends AuditProvider { @Override public void prePersist(Object entity) { updateTimestamps(entity, true); } }
TimestampsProvider extends AuditProvider { @Override public void prePersist(Object entity) { updateTimestamps(entity, true); } }
TimestampsProvider extends AuditProvider { @Override public void prePersist(Object entity) { updateTimestamps(entity, true); } @Override void prePersist(Object entity); @Override void preUpdate(Object entity); }
TimestampsProvider extends AuditProvider { @Override public void prePersist(Object entity) { updateTimestamps(entity, true); } @Override void prePersist(Object entity); @Override void preUpdate(Object entity); }
@Test(expected = MethodExpressionException.class) public void should_fail_in_where() { final String name = "findByInvalid"; QueryRoot.create(name, repo, prefix(name)); }
public static QueryRoot create(String method, RepositoryMetadata repo, RepositoryMethodPrefix prefix) { QueryRoot root = new QueryRoot(repo.getEntityMetadata().getEntityName(), prefix); root.build(method, method, repo); root.createJpql(); return root; }
QueryRoot extends QueryPart { public static QueryRoot create(String method, RepositoryMetadata repo, RepositoryMethodPrefix prefix) { QueryRoot root = new QueryRoot(repo.getEntityMetadata().getEntityName(), prefix); root.build(method, method, repo); root.createJpql(); return root; } }
QueryRoot extends QueryPart { public static QueryRoot create(String method, RepositoryMetadata repo, RepositoryMethodPrefix prefix) { QueryRoot root = new QueryRoot(repo.getEntityMetadata().getEntityName(), prefix); root.build(method, method, repo); root.createJpql(); return root; } protected QueryRoot(String entityName, RepositoryMethodPrefix methodPrefix); }
QueryRoot extends QueryPart { public static QueryRoot create(String method, RepositoryMetadata repo, RepositoryMethodPrefix prefix) { QueryRoot root = new QueryRoot(repo.getEntityMetadata().getEntityName(), prefix); root.build(method, method, repo); root.createJpql(); return root; } protected QueryRoot(String entityName, RepositoryMethodPrefix methodPrefix); static QueryRoot create(String method, RepositoryMetadata repo, RepositoryMethodPrefix prefix); String getJpqlQuery(); List<ParameterUpdate> getParameterUpdates(); }
QueryRoot extends QueryPart { public static QueryRoot create(String method, RepositoryMetadata repo, RepositoryMethodPrefix prefix) { QueryRoot root = new QueryRoot(repo.getEntityMetadata().getEntityName(), prefix); root.build(method, method, repo); root.createJpql(); return root; } protected QueryRoot(String entityName, RepositoryMethodPrefix methodPrefix); static QueryRoot create(String method, RepositoryMetadata repo, RepositoryMethodPrefix prefix); String getJpqlQuery(); List<ParameterUpdate> getParameterUpdates(); static final QueryRoot UNKNOWN_ROOT; }
@Test(expected = MethodExpressionException.class) public void should_fail_with_prefix_only() { final String name = "findBy"; QueryRoot.create(name, repo, prefix(name)); }
public static QueryRoot create(String method, RepositoryMetadata repo, RepositoryMethodPrefix prefix) { QueryRoot root = new QueryRoot(repo.getEntityMetadata().getEntityName(), prefix); root.build(method, method, repo); root.createJpql(); return root; }
QueryRoot extends QueryPart { public static QueryRoot create(String method, RepositoryMetadata repo, RepositoryMethodPrefix prefix) { QueryRoot root = new QueryRoot(repo.getEntityMetadata().getEntityName(), prefix); root.build(method, method, repo); root.createJpql(); return root; } }
QueryRoot extends QueryPart { public static QueryRoot create(String method, RepositoryMetadata repo, RepositoryMethodPrefix prefix) { QueryRoot root = new QueryRoot(repo.getEntityMetadata().getEntityName(), prefix); root.build(method, method, repo); root.createJpql(); return root; } protected QueryRoot(String entityName, RepositoryMethodPrefix methodPrefix); }
QueryRoot extends QueryPart { public static QueryRoot create(String method, RepositoryMetadata repo, RepositoryMethodPrefix prefix) { QueryRoot root = new QueryRoot(repo.getEntityMetadata().getEntityName(), prefix); root.build(method, method, repo); root.createJpql(); return root; } protected QueryRoot(String entityName, RepositoryMethodPrefix methodPrefix); static QueryRoot create(String method, RepositoryMetadata repo, RepositoryMethodPrefix prefix); String getJpqlQuery(); List<ParameterUpdate> getParameterUpdates(); }
QueryRoot extends QueryPart { public static QueryRoot create(String method, RepositoryMetadata repo, RepositoryMethodPrefix prefix) { QueryRoot root = new QueryRoot(repo.getEntityMetadata().getEntityName(), prefix); root.build(method, method, repo); root.createJpql(); return root; } protected QueryRoot(String entityName, RepositoryMethodPrefix methodPrefix); static QueryRoot create(String method, RepositoryMetadata repo, RepositoryMethodPrefix prefix); String getJpqlQuery(); List<ParameterUpdate> getParameterUpdates(); static final QueryRoot UNKNOWN_ROOT; }
@Test public void should_not_accept_class_without_entity_annotation() { boolean isValid = EntityUtils.isEntityClass(EntityWithoutId.class); Assert.assertFalse(isValid); }
public static boolean isEntityClass(Class<?> entityClass) { return entityClass.isAnnotationPresent(Entity.class) || PersistenceUnitDescriptorProvider.getInstance().isEntity(entityClass); }
EntityUtils { public static boolean isEntityClass(Class<?> entityClass) { return entityClass.isAnnotationPresent(Entity.class) || PersistenceUnitDescriptorProvider.getInstance().isEntity(entityClass); } }
EntityUtils { public static boolean isEntityClass(Class<?> entityClass) { return entityClass.isAnnotationPresent(Entity.class) || PersistenceUnitDescriptorProvider.getInstance().isEntity(entityClass); } private EntityUtils(); }
EntityUtils { public static boolean isEntityClass(Class<?> entityClass) { return entityClass.isAnnotationPresent(Entity.class) || PersistenceUnitDescriptorProvider.getInstance().isEntity(entityClass); } private EntityUtils(); @SuppressWarnings({ "unchecked", "rawtypes" }) static Class<? extends Serializable> primaryKeyClass(Class<?> entityClass); static Object primaryKeyValue(Object entity); static Object primaryKeyValue(Object entity, Property<Serializable> primaryKeyProperty); static String entityName(Class<?> entityClass); static String tableName(Class<?> entityClass, EntityManager entityManager); static boolean isEntityClass(Class<?> entityClass); static Property<Serializable> primaryKeyProperty(Class<?> entityClass); static Property<Serializable> getVersionProperty(Class<?> entityClass); }
EntityUtils { public static boolean isEntityClass(Class<?> entityClass) { return entityClass.isAnnotationPresent(Entity.class) || PersistenceUnitDescriptorProvider.getInstance().isEntity(entityClass); } private EntityUtils(); @SuppressWarnings({ "unchecked", "rawtypes" }) static Class<? extends Serializable> primaryKeyClass(Class<?> entityClass); static Object primaryKeyValue(Object entity); static Object primaryKeyValue(Object entity, Property<Serializable> primaryKeyProperty); static String entityName(Class<?> entityClass); static String tableName(Class<?> entityClass, EntityManager entityManager); static boolean isEntityClass(Class<?> entityClass); static Property<Serializable> primaryKeyProperty(Class<?> entityClass); static Property<Serializable> getVersionProperty(Class<?> entityClass); }
@Test(expected = MethodExpressionException.class) public void should_fail_in_order_by() { final String name = "findByNameOrderByInvalidDesc"; QueryRoot.create(name, repo, prefix(name)); }
public static QueryRoot create(String method, RepositoryMetadata repo, RepositoryMethodPrefix prefix) { QueryRoot root = new QueryRoot(repo.getEntityMetadata().getEntityName(), prefix); root.build(method, method, repo); root.createJpql(); return root; }
QueryRoot extends QueryPart { public static QueryRoot create(String method, RepositoryMetadata repo, RepositoryMethodPrefix prefix) { QueryRoot root = new QueryRoot(repo.getEntityMetadata().getEntityName(), prefix); root.build(method, method, repo); root.createJpql(); return root; } }
QueryRoot extends QueryPart { public static QueryRoot create(String method, RepositoryMetadata repo, RepositoryMethodPrefix prefix) { QueryRoot root = new QueryRoot(repo.getEntityMetadata().getEntityName(), prefix); root.build(method, method, repo); root.createJpql(); return root; } protected QueryRoot(String entityName, RepositoryMethodPrefix methodPrefix); }
QueryRoot extends QueryPart { public static QueryRoot create(String method, RepositoryMetadata repo, RepositoryMethodPrefix prefix) { QueryRoot root = new QueryRoot(repo.getEntityMetadata().getEntityName(), prefix); root.build(method, method, repo); root.createJpql(); return root; } protected QueryRoot(String entityName, RepositoryMethodPrefix methodPrefix); static QueryRoot create(String method, RepositoryMetadata repo, RepositoryMethodPrefix prefix); String getJpqlQuery(); List<ParameterUpdate> getParameterUpdates(); }
QueryRoot extends QueryPart { public static QueryRoot create(String method, RepositoryMetadata repo, RepositoryMethodPrefix prefix) { QueryRoot root = new QueryRoot(repo.getEntityMetadata().getEntityName(), prefix); root.build(method, method, repo); root.createJpql(); return root; } protected QueryRoot(String entityName, RepositoryMethodPrefix methodPrefix); static QueryRoot create(String method, RepositoryMetadata repo, RepositoryMethodPrefix prefix); String getJpqlQuery(); List<ParameterUpdate> getParameterUpdates(); static final QueryRoot UNKNOWN_ROOT; }
@Test public void testStreamWithoutExpression_mustBeUnmodified() throws Exception { final String data = "aa\nbbbb\ncccc\ndddd\n\n"; byte[] dataArray = data.getBytes(); ValueExpressionEvaluationInputStream inputStream = new ValueExpressionEvaluationInputStream( FacesContext.getCurrentInstance(), new ByteArrayInputStream(dataArray)); byte[] inputStreamDataArray = new byte[dataArray.length]; inputStream.read(inputStreamDataArray); Assert.assertArrayEquals(dataArray, inputStreamDataArray); Assert.assertEquals(-1, inputStream.read()); }
@Override public int read() throws IOException { if (currentValueIndex != -1) { if (currentValueIndex < currentValue.length()) { return currentValue.charAt(currentValueIndex++); } else { currentValueIndex = -1; } } int c1 = wrapped.read(); if (c1 != '#') { return c1; } else { int c2 = wrapped.read(); if (c2 != '{') { wrapped.unread(c2); return c1; } else { List<Integer> possibleValueExpression = new LinkedList<Integer>(); int c = wrapped.read(); boolean insideString = (c == '\''); while (c != -1 && c != '\n' && (insideString || c != '}')) { possibleValueExpression.add(c); c = wrapped.read(); if (c == '\'') { insideString = !insideString; } } if (c != '}') { if (c != -1) { wrapped.unread(c); } ListIterator<Integer> it = possibleValueExpression.listIterator(possibleValueExpression.size()); while (it.hasPrevious()) { wrapped.unread(it.previous()); } wrapped.unread(c2); return c1; } else { String expressionString = createExpressionString(possibleValueExpression); String expressionValue = facesContext.getApplication() .evaluateExpressionGet(facesContext, expressionString, String.class); if (expressionValue == null) { if (log.isLoggable(Level.WARNING)) { log.warning("ValueExpression " + expressionString + " evaluated to null."); } expressionValue = "null"; } this.currentValue = expressionValue; if (currentValue.length() != 0) { this.currentValueIndex = 0; return currentValue.charAt(currentValueIndex++); } else { this.currentValueIndex = -1; return read(); } } } } }
ValueExpressionEvaluationInputStream extends InputStream { @Override public int read() throws IOException { if (currentValueIndex != -1) { if (currentValueIndex < currentValue.length()) { return currentValue.charAt(currentValueIndex++); } else { currentValueIndex = -1; } } int c1 = wrapped.read(); if (c1 != '#') { return c1; } else { int c2 = wrapped.read(); if (c2 != '{') { wrapped.unread(c2); return c1; } else { List<Integer> possibleValueExpression = new LinkedList<Integer>(); int c = wrapped.read(); boolean insideString = (c == '\''); while (c != -1 && c != '\n' && (insideString || c != '}')) { possibleValueExpression.add(c); c = wrapped.read(); if (c == '\'') { insideString = !insideString; } } if (c != '}') { if (c != -1) { wrapped.unread(c); } ListIterator<Integer> it = possibleValueExpression.listIterator(possibleValueExpression.size()); while (it.hasPrevious()) { wrapped.unread(it.previous()); } wrapped.unread(c2); return c1; } else { String expressionString = createExpressionString(possibleValueExpression); String expressionValue = facesContext.getApplication() .evaluateExpressionGet(facesContext, expressionString, String.class); if (expressionValue == null) { if (log.isLoggable(Level.WARNING)) { log.warning("ValueExpression " + expressionString + " evaluated to null."); } expressionValue = "null"; } this.currentValue = expressionValue; if (currentValue.length() != 0) { this.currentValueIndex = 0; return currentValue.charAt(currentValueIndex++); } else { this.currentValueIndex = -1; return read(); } } } } } }
ValueExpressionEvaluationInputStream extends InputStream { @Override public int read() throws IOException { if (currentValueIndex != -1) { if (currentValueIndex < currentValue.length()) { return currentValue.charAt(currentValueIndex++); } else { currentValueIndex = -1; } } int c1 = wrapped.read(); if (c1 != '#') { return c1; } else { int c2 = wrapped.read(); if (c2 != '{') { wrapped.unread(c2); return c1; } else { List<Integer> possibleValueExpression = new LinkedList<Integer>(); int c = wrapped.read(); boolean insideString = (c == '\''); while (c != -1 && c != '\n' && (insideString || c != '}')) { possibleValueExpression.add(c); c = wrapped.read(); if (c == '\'') { insideString = !insideString; } } if (c != '}') { if (c != -1) { wrapped.unread(c); } ListIterator<Integer> it = possibleValueExpression.listIterator(possibleValueExpression.size()); while (it.hasPrevious()) { wrapped.unread(it.previous()); } wrapped.unread(c2); return c1; } else { String expressionString = createExpressionString(possibleValueExpression); String expressionValue = facesContext.getApplication() .evaluateExpressionGet(facesContext, expressionString, String.class); if (expressionValue == null) { if (log.isLoggable(Level.WARNING)) { log.warning("ValueExpression " + expressionString + " evaluated to null."); } expressionValue = "null"; } this.currentValue = expressionValue; if (currentValue.length() != 0) { this.currentValueIndex = 0; return currentValue.charAt(currentValueIndex++); } else { this.currentValueIndex = -1; return read(); } } } } } ValueExpressionEvaluationInputStream(FacesContext facesContext, InputStream inputStream); }
ValueExpressionEvaluationInputStream extends InputStream { @Override public int read() throws IOException { if (currentValueIndex != -1) { if (currentValueIndex < currentValue.length()) { return currentValue.charAt(currentValueIndex++); } else { currentValueIndex = -1; } } int c1 = wrapped.read(); if (c1 != '#') { return c1; } else { int c2 = wrapped.read(); if (c2 != '{') { wrapped.unread(c2); return c1; } else { List<Integer> possibleValueExpression = new LinkedList<Integer>(); int c = wrapped.read(); boolean insideString = (c == '\''); while (c != -1 && c != '\n' && (insideString || c != '}')) { possibleValueExpression.add(c); c = wrapped.read(); if (c == '\'') { insideString = !insideString; } } if (c != '}') { if (c != -1) { wrapped.unread(c); } ListIterator<Integer> it = possibleValueExpression.listIterator(possibleValueExpression.size()); while (it.hasPrevious()) { wrapped.unread(it.previous()); } wrapped.unread(c2); return c1; } else { String expressionString = createExpressionString(possibleValueExpression); String expressionValue = facesContext.getApplication() .evaluateExpressionGet(facesContext, expressionString, String.class); if (expressionValue == null) { if (log.isLoggable(Level.WARNING)) { log.warning("ValueExpression " + expressionString + " evaluated to null."); } expressionValue = "null"; } this.currentValue = expressionValue; if (currentValue.length() != 0) { this.currentValueIndex = 0; return currentValue.charAt(currentValueIndex++); } else { this.currentValueIndex = -1; return read(); } } } } } ValueExpressionEvaluationInputStream(FacesContext facesContext, InputStream inputStream); @Override int read(); }
ValueExpressionEvaluationInputStream extends InputStream { @Override public int read() throws IOException { if (currentValueIndex != -1) { if (currentValueIndex < currentValue.length()) { return currentValue.charAt(currentValueIndex++); } else { currentValueIndex = -1; } } int c1 = wrapped.read(); if (c1 != '#') { return c1; } else { int c2 = wrapped.read(); if (c2 != '{') { wrapped.unread(c2); return c1; } else { List<Integer> possibleValueExpression = new LinkedList<Integer>(); int c = wrapped.read(); boolean insideString = (c == '\''); while (c != -1 && c != '\n' && (insideString || c != '}')) { possibleValueExpression.add(c); c = wrapped.read(); if (c == '\'') { insideString = !insideString; } } if (c != '}') { if (c != -1) { wrapped.unread(c); } ListIterator<Integer> it = possibleValueExpression.listIterator(possibleValueExpression.size()); while (it.hasPrevious()) { wrapped.unread(it.previous()); } wrapped.unread(c2); return c1; } else { String expressionString = createExpressionString(possibleValueExpression); String expressionValue = facesContext.getApplication() .evaluateExpressionGet(facesContext, expressionString, String.class); if (expressionValue == null) { if (log.isLoggable(Level.WARNING)) { log.warning("ValueExpression " + expressionString + " evaluated to null."); } expressionValue = "null"; } this.currentValue = expressionValue; if (currentValue.length() != 0) { this.currentValueIndex = 0; return currentValue.charAt(currentValueIndex++); } else { this.currentValueIndex = -1; return read(); } } } } } ValueExpressionEvaluationInputStream(FacesContext facesContext, InputStream inputStream); @Override int read(); }
@Test public void testStreamWithSimpleExpression_mustBeEvaluated() throws Exception { final String data = "aa\nbbbb\ncc#{requestScope.test}cc\ndddd\n\n"; final String evaluatedData = "aa\nbbbb\ncctest-valuecc\ndddd\n\n"; byte[] dataArray = data.getBytes(); byte[] evaluatedDataArray = evaluatedData.getBytes(); FacesContext.getCurrentInstance().getExternalContext().getRequestMap().put("test", "test-value"); ValueExpressionEvaluationInputStream inputStream = new ValueExpressionEvaluationInputStream( FacesContext.getCurrentInstance(), new ByteArrayInputStream(dataArray)); byte[] inputStreamDataArray = new byte[evaluatedDataArray.length]; inputStream.read(inputStreamDataArray); Assert.assertArrayEquals(evaluatedDataArray, inputStreamDataArray); Assert.assertEquals(-1, inputStream.read()); }
@Override public int read() throws IOException { if (currentValueIndex != -1) { if (currentValueIndex < currentValue.length()) { return currentValue.charAt(currentValueIndex++); } else { currentValueIndex = -1; } } int c1 = wrapped.read(); if (c1 != '#') { return c1; } else { int c2 = wrapped.read(); if (c2 != '{') { wrapped.unread(c2); return c1; } else { List<Integer> possibleValueExpression = new LinkedList<Integer>(); int c = wrapped.read(); boolean insideString = (c == '\''); while (c != -1 && c != '\n' && (insideString || c != '}')) { possibleValueExpression.add(c); c = wrapped.read(); if (c == '\'') { insideString = !insideString; } } if (c != '}') { if (c != -1) { wrapped.unread(c); } ListIterator<Integer> it = possibleValueExpression.listIterator(possibleValueExpression.size()); while (it.hasPrevious()) { wrapped.unread(it.previous()); } wrapped.unread(c2); return c1; } else { String expressionString = createExpressionString(possibleValueExpression); String expressionValue = facesContext.getApplication() .evaluateExpressionGet(facesContext, expressionString, String.class); if (expressionValue == null) { if (log.isLoggable(Level.WARNING)) { log.warning("ValueExpression " + expressionString + " evaluated to null."); } expressionValue = "null"; } this.currentValue = expressionValue; if (currentValue.length() != 0) { this.currentValueIndex = 0; return currentValue.charAt(currentValueIndex++); } else { this.currentValueIndex = -1; return read(); } } } } }
ValueExpressionEvaluationInputStream extends InputStream { @Override public int read() throws IOException { if (currentValueIndex != -1) { if (currentValueIndex < currentValue.length()) { return currentValue.charAt(currentValueIndex++); } else { currentValueIndex = -1; } } int c1 = wrapped.read(); if (c1 != '#') { return c1; } else { int c2 = wrapped.read(); if (c2 != '{') { wrapped.unread(c2); return c1; } else { List<Integer> possibleValueExpression = new LinkedList<Integer>(); int c = wrapped.read(); boolean insideString = (c == '\''); while (c != -1 && c != '\n' && (insideString || c != '}')) { possibleValueExpression.add(c); c = wrapped.read(); if (c == '\'') { insideString = !insideString; } } if (c != '}') { if (c != -1) { wrapped.unread(c); } ListIterator<Integer> it = possibleValueExpression.listIterator(possibleValueExpression.size()); while (it.hasPrevious()) { wrapped.unread(it.previous()); } wrapped.unread(c2); return c1; } else { String expressionString = createExpressionString(possibleValueExpression); String expressionValue = facesContext.getApplication() .evaluateExpressionGet(facesContext, expressionString, String.class); if (expressionValue == null) { if (log.isLoggable(Level.WARNING)) { log.warning("ValueExpression " + expressionString + " evaluated to null."); } expressionValue = "null"; } this.currentValue = expressionValue; if (currentValue.length() != 0) { this.currentValueIndex = 0; return currentValue.charAt(currentValueIndex++); } else { this.currentValueIndex = -1; return read(); } } } } } }
ValueExpressionEvaluationInputStream extends InputStream { @Override public int read() throws IOException { if (currentValueIndex != -1) { if (currentValueIndex < currentValue.length()) { return currentValue.charAt(currentValueIndex++); } else { currentValueIndex = -1; } } int c1 = wrapped.read(); if (c1 != '#') { return c1; } else { int c2 = wrapped.read(); if (c2 != '{') { wrapped.unread(c2); return c1; } else { List<Integer> possibleValueExpression = new LinkedList<Integer>(); int c = wrapped.read(); boolean insideString = (c == '\''); while (c != -1 && c != '\n' && (insideString || c != '}')) { possibleValueExpression.add(c); c = wrapped.read(); if (c == '\'') { insideString = !insideString; } } if (c != '}') { if (c != -1) { wrapped.unread(c); } ListIterator<Integer> it = possibleValueExpression.listIterator(possibleValueExpression.size()); while (it.hasPrevious()) { wrapped.unread(it.previous()); } wrapped.unread(c2); return c1; } else { String expressionString = createExpressionString(possibleValueExpression); String expressionValue = facesContext.getApplication() .evaluateExpressionGet(facesContext, expressionString, String.class); if (expressionValue == null) { if (log.isLoggable(Level.WARNING)) { log.warning("ValueExpression " + expressionString + " evaluated to null."); } expressionValue = "null"; } this.currentValue = expressionValue; if (currentValue.length() != 0) { this.currentValueIndex = 0; return currentValue.charAt(currentValueIndex++); } else { this.currentValueIndex = -1; return read(); } } } } } ValueExpressionEvaluationInputStream(FacesContext facesContext, InputStream inputStream); }
ValueExpressionEvaluationInputStream extends InputStream { @Override public int read() throws IOException { if (currentValueIndex != -1) { if (currentValueIndex < currentValue.length()) { return currentValue.charAt(currentValueIndex++); } else { currentValueIndex = -1; } } int c1 = wrapped.read(); if (c1 != '#') { return c1; } else { int c2 = wrapped.read(); if (c2 != '{') { wrapped.unread(c2); return c1; } else { List<Integer> possibleValueExpression = new LinkedList<Integer>(); int c = wrapped.read(); boolean insideString = (c == '\''); while (c != -1 && c != '\n' && (insideString || c != '}')) { possibleValueExpression.add(c); c = wrapped.read(); if (c == '\'') { insideString = !insideString; } } if (c != '}') { if (c != -1) { wrapped.unread(c); } ListIterator<Integer> it = possibleValueExpression.listIterator(possibleValueExpression.size()); while (it.hasPrevious()) { wrapped.unread(it.previous()); } wrapped.unread(c2); return c1; } else { String expressionString = createExpressionString(possibleValueExpression); String expressionValue = facesContext.getApplication() .evaluateExpressionGet(facesContext, expressionString, String.class); if (expressionValue == null) { if (log.isLoggable(Level.WARNING)) { log.warning("ValueExpression " + expressionString + " evaluated to null."); } expressionValue = "null"; } this.currentValue = expressionValue; if (currentValue.length() != 0) { this.currentValueIndex = 0; return currentValue.charAt(currentValueIndex++); } else { this.currentValueIndex = -1; return read(); } } } } } ValueExpressionEvaluationInputStream(FacesContext facesContext, InputStream inputStream); @Override int read(); }
ValueExpressionEvaluationInputStream extends InputStream { @Override public int read() throws IOException { if (currentValueIndex != -1) { if (currentValueIndex < currentValue.length()) { return currentValue.charAt(currentValueIndex++); } else { currentValueIndex = -1; } } int c1 = wrapped.read(); if (c1 != '#') { return c1; } else { int c2 = wrapped.read(); if (c2 != '{') { wrapped.unread(c2); return c1; } else { List<Integer> possibleValueExpression = new LinkedList<Integer>(); int c = wrapped.read(); boolean insideString = (c == '\''); while (c != -1 && c != '\n' && (insideString || c != '}')) { possibleValueExpression.add(c); c = wrapped.read(); if (c == '\'') { insideString = !insideString; } } if (c != '}') { if (c != -1) { wrapped.unread(c); } ListIterator<Integer> it = possibleValueExpression.listIterator(possibleValueExpression.size()); while (it.hasPrevious()) { wrapped.unread(it.previous()); } wrapped.unread(c2); return c1; } else { String expressionString = createExpressionString(possibleValueExpression); String expressionValue = facesContext.getApplication() .evaluateExpressionGet(facesContext, expressionString, String.class); if (expressionValue == null) { if (log.isLoggable(Level.WARNING)) { log.warning("ValueExpression " + expressionString + " evaluated to null."); } expressionValue = "null"; } this.currentValue = expressionValue; if (currentValue.length() != 0) { this.currentValueIndex = 0; return currentValue.charAt(currentValueIndex++); } else { this.currentValueIndex = -1; return read(); } } } } } ValueExpressionEvaluationInputStream(FacesContext facesContext, InputStream inputStream); @Override int read(); }
@Test public void testStreamWithHalfExpressionAtEnd_mustBeUnmodified() throws Exception { final String data = "aa\nbbbb\ncccc\ndddd\n\n#{requestScope.test"; byte[] dataArray = data.getBytes(); FacesContext.getCurrentInstance().getExternalContext().getRequestMap().put("test", "test-value"); ValueExpressionEvaluationInputStream inputStream = new ValueExpressionEvaluationInputStream( FacesContext.getCurrentInstance(), new ByteArrayInputStream(dataArray)); byte[] inputStreamDataArray = new byte[dataArray.length]; inputStream.read(inputStreamDataArray); Assert.assertArrayEquals(dataArray, inputStreamDataArray); Assert.assertEquals(-1, inputStream.read()); }
@Override public int read() throws IOException { if (currentValueIndex != -1) { if (currentValueIndex < currentValue.length()) { return currentValue.charAt(currentValueIndex++); } else { currentValueIndex = -1; } } int c1 = wrapped.read(); if (c1 != '#') { return c1; } else { int c2 = wrapped.read(); if (c2 != '{') { wrapped.unread(c2); return c1; } else { List<Integer> possibleValueExpression = new LinkedList<Integer>(); int c = wrapped.read(); boolean insideString = (c == '\''); while (c != -1 && c != '\n' && (insideString || c != '}')) { possibleValueExpression.add(c); c = wrapped.read(); if (c == '\'') { insideString = !insideString; } } if (c != '}') { if (c != -1) { wrapped.unread(c); } ListIterator<Integer> it = possibleValueExpression.listIterator(possibleValueExpression.size()); while (it.hasPrevious()) { wrapped.unread(it.previous()); } wrapped.unread(c2); return c1; } else { String expressionString = createExpressionString(possibleValueExpression); String expressionValue = facesContext.getApplication() .evaluateExpressionGet(facesContext, expressionString, String.class); if (expressionValue == null) { if (log.isLoggable(Level.WARNING)) { log.warning("ValueExpression " + expressionString + " evaluated to null."); } expressionValue = "null"; } this.currentValue = expressionValue; if (currentValue.length() != 0) { this.currentValueIndex = 0; return currentValue.charAt(currentValueIndex++); } else { this.currentValueIndex = -1; return read(); } } } } }
ValueExpressionEvaluationInputStream extends InputStream { @Override public int read() throws IOException { if (currentValueIndex != -1) { if (currentValueIndex < currentValue.length()) { return currentValue.charAt(currentValueIndex++); } else { currentValueIndex = -1; } } int c1 = wrapped.read(); if (c1 != '#') { return c1; } else { int c2 = wrapped.read(); if (c2 != '{') { wrapped.unread(c2); return c1; } else { List<Integer> possibleValueExpression = new LinkedList<Integer>(); int c = wrapped.read(); boolean insideString = (c == '\''); while (c != -1 && c != '\n' && (insideString || c != '}')) { possibleValueExpression.add(c); c = wrapped.read(); if (c == '\'') { insideString = !insideString; } } if (c != '}') { if (c != -1) { wrapped.unread(c); } ListIterator<Integer> it = possibleValueExpression.listIterator(possibleValueExpression.size()); while (it.hasPrevious()) { wrapped.unread(it.previous()); } wrapped.unread(c2); return c1; } else { String expressionString = createExpressionString(possibleValueExpression); String expressionValue = facesContext.getApplication() .evaluateExpressionGet(facesContext, expressionString, String.class); if (expressionValue == null) { if (log.isLoggable(Level.WARNING)) { log.warning("ValueExpression " + expressionString + " evaluated to null."); } expressionValue = "null"; } this.currentValue = expressionValue; if (currentValue.length() != 0) { this.currentValueIndex = 0; return currentValue.charAt(currentValueIndex++); } else { this.currentValueIndex = -1; return read(); } } } } } }
ValueExpressionEvaluationInputStream extends InputStream { @Override public int read() throws IOException { if (currentValueIndex != -1) { if (currentValueIndex < currentValue.length()) { return currentValue.charAt(currentValueIndex++); } else { currentValueIndex = -1; } } int c1 = wrapped.read(); if (c1 != '#') { return c1; } else { int c2 = wrapped.read(); if (c2 != '{') { wrapped.unread(c2); return c1; } else { List<Integer> possibleValueExpression = new LinkedList<Integer>(); int c = wrapped.read(); boolean insideString = (c == '\''); while (c != -1 && c != '\n' && (insideString || c != '}')) { possibleValueExpression.add(c); c = wrapped.read(); if (c == '\'') { insideString = !insideString; } } if (c != '}') { if (c != -1) { wrapped.unread(c); } ListIterator<Integer> it = possibleValueExpression.listIterator(possibleValueExpression.size()); while (it.hasPrevious()) { wrapped.unread(it.previous()); } wrapped.unread(c2); return c1; } else { String expressionString = createExpressionString(possibleValueExpression); String expressionValue = facesContext.getApplication() .evaluateExpressionGet(facesContext, expressionString, String.class); if (expressionValue == null) { if (log.isLoggable(Level.WARNING)) { log.warning("ValueExpression " + expressionString + " evaluated to null."); } expressionValue = "null"; } this.currentValue = expressionValue; if (currentValue.length() != 0) { this.currentValueIndex = 0; return currentValue.charAt(currentValueIndex++); } else { this.currentValueIndex = -1; return read(); } } } } } ValueExpressionEvaluationInputStream(FacesContext facesContext, InputStream inputStream); }
ValueExpressionEvaluationInputStream extends InputStream { @Override public int read() throws IOException { if (currentValueIndex != -1) { if (currentValueIndex < currentValue.length()) { return currentValue.charAt(currentValueIndex++); } else { currentValueIndex = -1; } } int c1 = wrapped.read(); if (c1 != '#') { return c1; } else { int c2 = wrapped.read(); if (c2 != '{') { wrapped.unread(c2); return c1; } else { List<Integer> possibleValueExpression = new LinkedList<Integer>(); int c = wrapped.read(); boolean insideString = (c == '\''); while (c != -1 && c != '\n' && (insideString || c != '}')) { possibleValueExpression.add(c); c = wrapped.read(); if (c == '\'') { insideString = !insideString; } } if (c != '}') { if (c != -1) { wrapped.unread(c); } ListIterator<Integer> it = possibleValueExpression.listIterator(possibleValueExpression.size()); while (it.hasPrevious()) { wrapped.unread(it.previous()); } wrapped.unread(c2); return c1; } else { String expressionString = createExpressionString(possibleValueExpression); String expressionValue = facesContext.getApplication() .evaluateExpressionGet(facesContext, expressionString, String.class); if (expressionValue == null) { if (log.isLoggable(Level.WARNING)) { log.warning("ValueExpression " + expressionString + " evaluated to null."); } expressionValue = "null"; } this.currentValue = expressionValue; if (currentValue.length() != 0) { this.currentValueIndex = 0; return currentValue.charAt(currentValueIndex++); } else { this.currentValueIndex = -1; return read(); } } } } } ValueExpressionEvaluationInputStream(FacesContext facesContext, InputStream inputStream); @Override int read(); }
ValueExpressionEvaluationInputStream extends InputStream { @Override public int read() throws IOException { if (currentValueIndex != -1) { if (currentValueIndex < currentValue.length()) { return currentValue.charAt(currentValueIndex++); } else { currentValueIndex = -1; } } int c1 = wrapped.read(); if (c1 != '#') { return c1; } else { int c2 = wrapped.read(); if (c2 != '{') { wrapped.unread(c2); return c1; } else { List<Integer> possibleValueExpression = new LinkedList<Integer>(); int c = wrapped.read(); boolean insideString = (c == '\''); while (c != -1 && c != '\n' && (insideString || c != '}')) { possibleValueExpression.add(c); c = wrapped.read(); if (c == '\'') { insideString = !insideString; } } if (c != '}') { if (c != -1) { wrapped.unread(c); } ListIterator<Integer> it = possibleValueExpression.listIterator(possibleValueExpression.size()); while (it.hasPrevious()) { wrapped.unread(it.previous()); } wrapped.unread(c2); return c1; } else { String expressionString = createExpressionString(possibleValueExpression); String expressionValue = facesContext.getApplication() .evaluateExpressionGet(facesContext, expressionString, String.class); if (expressionValue == null) { if (log.isLoggable(Level.WARNING)) { log.warning("ValueExpression " + expressionString + " evaluated to null."); } expressionValue = "null"; } this.currentValue = expressionValue; if (currentValue.length() != 0) { this.currentValueIndex = 0; return currentValue.charAt(currentValueIndex++); } else { this.currentValueIndex = -1; return read(); } } } } } ValueExpressionEvaluationInputStream(FacesContext facesContext, InputStream inputStream); @Override int read(); }
@Test public void testStreamWithHalfExpressionAtLineEnd_mustBeUnmodified() throws Exception { final String data = "aa\nbb#{requestScope.test\n}bb\ncccc\ndddd\n\n"; byte[] dataArray = data.getBytes(); FacesContext.getCurrentInstance().getExternalContext().getRequestMap().put("test", "test-value"); ValueExpressionEvaluationInputStream inputStream = new ValueExpressionEvaluationInputStream( FacesContext.getCurrentInstance(), new ByteArrayInputStream(dataArray)); byte[] inputStreamDataArray = new byte[dataArray.length]; inputStream.read(inputStreamDataArray); Assert.assertArrayEquals(dataArray, inputStreamDataArray); Assert.assertEquals(-1, inputStream.read()); }
@Override public int read() throws IOException { if (currentValueIndex != -1) { if (currentValueIndex < currentValue.length()) { return currentValue.charAt(currentValueIndex++); } else { currentValueIndex = -1; } } int c1 = wrapped.read(); if (c1 != '#') { return c1; } else { int c2 = wrapped.read(); if (c2 != '{') { wrapped.unread(c2); return c1; } else { List<Integer> possibleValueExpression = new LinkedList<Integer>(); int c = wrapped.read(); boolean insideString = (c == '\''); while (c != -1 && c != '\n' && (insideString || c != '}')) { possibleValueExpression.add(c); c = wrapped.read(); if (c == '\'') { insideString = !insideString; } } if (c != '}') { if (c != -1) { wrapped.unread(c); } ListIterator<Integer> it = possibleValueExpression.listIterator(possibleValueExpression.size()); while (it.hasPrevious()) { wrapped.unread(it.previous()); } wrapped.unread(c2); return c1; } else { String expressionString = createExpressionString(possibleValueExpression); String expressionValue = facesContext.getApplication() .evaluateExpressionGet(facesContext, expressionString, String.class); if (expressionValue == null) { if (log.isLoggable(Level.WARNING)) { log.warning("ValueExpression " + expressionString + " evaluated to null."); } expressionValue = "null"; } this.currentValue = expressionValue; if (currentValue.length() != 0) { this.currentValueIndex = 0; return currentValue.charAt(currentValueIndex++); } else { this.currentValueIndex = -1; return read(); } } } } }
ValueExpressionEvaluationInputStream extends InputStream { @Override public int read() throws IOException { if (currentValueIndex != -1) { if (currentValueIndex < currentValue.length()) { return currentValue.charAt(currentValueIndex++); } else { currentValueIndex = -1; } } int c1 = wrapped.read(); if (c1 != '#') { return c1; } else { int c2 = wrapped.read(); if (c2 != '{') { wrapped.unread(c2); return c1; } else { List<Integer> possibleValueExpression = new LinkedList<Integer>(); int c = wrapped.read(); boolean insideString = (c == '\''); while (c != -1 && c != '\n' && (insideString || c != '}')) { possibleValueExpression.add(c); c = wrapped.read(); if (c == '\'') { insideString = !insideString; } } if (c != '}') { if (c != -1) { wrapped.unread(c); } ListIterator<Integer> it = possibleValueExpression.listIterator(possibleValueExpression.size()); while (it.hasPrevious()) { wrapped.unread(it.previous()); } wrapped.unread(c2); return c1; } else { String expressionString = createExpressionString(possibleValueExpression); String expressionValue = facesContext.getApplication() .evaluateExpressionGet(facesContext, expressionString, String.class); if (expressionValue == null) { if (log.isLoggable(Level.WARNING)) { log.warning("ValueExpression " + expressionString + " evaluated to null."); } expressionValue = "null"; } this.currentValue = expressionValue; if (currentValue.length() != 0) { this.currentValueIndex = 0; return currentValue.charAt(currentValueIndex++); } else { this.currentValueIndex = -1; return read(); } } } } } }
ValueExpressionEvaluationInputStream extends InputStream { @Override public int read() throws IOException { if (currentValueIndex != -1) { if (currentValueIndex < currentValue.length()) { return currentValue.charAt(currentValueIndex++); } else { currentValueIndex = -1; } } int c1 = wrapped.read(); if (c1 != '#') { return c1; } else { int c2 = wrapped.read(); if (c2 != '{') { wrapped.unread(c2); return c1; } else { List<Integer> possibleValueExpression = new LinkedList<Integer>(); int c = wrapped.read(); boolean insideString = (c == '\''); while (c != -1 && c != '\n' && (insideString || c != '}')) { possibleValueExpression.add(c); c = wrapped.read(); if (c == '\'') { insideString = !insideString; } } if (c != '}') { if (c != -1) { wrapped.unread(c); } ListIterator<Integer> it = possibleValueExpression.listIterator(possibleValueExpression.size()); while (it.hasPrevious()) { wrapped.unread(it.previous()); } wrapped.unread(c2); return c1; } else { String expressionString = createExpressionString(possibleValueExpression); String expressionValue = facesContext.getApplication() .evaluateExpressionGet(facesContext, expressionString, String.class); if (expressionValue == null) { if (log.isLoggable(Level.WARNING)) { log.warning("ValueExpression " + expressionString + " evaluated to null."); } expressionValue = "null"; } this.currentValue = expressionValue; if (currentValue.length() != 0) { this.currentValueIndex = 0; return currentValue.charAt(currentValueIndex++); } else { this.currentValueIndex = -1; return read(); } } } } } ValueExpressionEvaluationInputStream(FacesContext facesContext, InputStream inputStream); }
ValueExpressionEvaluationInputStream extends InputStream { @Override public int read() throws IOException { if (currentValueIndex != -1) { if (currentValueIndex < currentValue.length()) { return currentValue.charAt(currentValueIndex++); } else { currentValueIndex = -1; } } int c1 = wrapped.read(); if (c1 != '#') { return c1; } else { int c2 = wrapped.read(); if (c2 != '{') { wrapped.unread(c2); return c1; } else { List<Integer> possibleValueExpression = new LinkedList<Integer>(); int c = wrapped.read(); boolean insideString = (c == '\''); while (c != -1 && c != '\n' && (insideString || c != '}')) { possibleValueExpression.add(c); c = wrapped.read(); if (c == '\'') { insideString = !insideString; } } if (c != '}') { if (c != -1) { wrapped.unread(c); } ListIterator<Integer> it = possibleValueExpression.listIterator(possibleValueExpression.size()); while (it.hasPrevious()) { wrapped.unread(it.previous()); } wrapped.unread(c2); return c1; } else { String expressionString = createExpressionString(possibleValueExpression); String expressionValue = facesContext.getApplication() .evaluateExpressionGet(facesContext, expressionString, String.class); if (expressionValue == null) { if (log.isLoggable(Level.WARNING)) { log.warning("ValueExpression " + expressionString + " evaluated to null."); } expressionValue = "null"; } this.currentValue = expressionValue; if (currentValue.length() != 0) { this.currentValueIndex = 0; return currentValue.charAt(currentValueIndex++); } else { this.currentValueIndex = -1; return read(); } } } } } ValueExpressionEvaluationInputStream(FacesContext facesContext, InputStream inputStream); @Override int read(); }
ValueExpressionEvaluationInputStream extends InputStream { @Override public int read() throws IOException { if (currentValueIndex != -1) { if (currentValueIndex < currentValue.length()) { return currentValue.charAt(currentValueIndex++); } else { currentValueIndex = -1; } } int c1 = wrapped.read(); if (c1 != '#') { return c1; } else { int c2 = wrapped.read(); if (c2 != '{') { wrapped.unread(c2); return c1; } else { List<Integer> possibleValueExpression = new LinkedList<Integer>(); int c = wrapped.read(); boolean insideString = (c == '\''); while (c != -1 && c != '\n' && (insideString || c != '}')) { possibleValueExpression.add(c); c = wrapped.read(); if (c == '\'') { insideString = !insideString; } } if (c != '}') { if (c != -1) { wrapped.unread(c); } ListIterator<Integer> it = possibleValueExpression.listIterator(possibleValueExpression.size()); while (it.hasPrevious()) { wrapped.unread(it.previous()); } wrapped.unread(c2); return c1; } else { String expressionString = createExpressionString(possibleValueExpression); String expressionValue = facesContext.getApplication() .evaluateExpressionGet(facesContext, expressionString, String.class); if (expressionValue == null) { if (log.isLoggable(Level.WARNING)) { log.warning("ValueExpression " + expressionString + " evaluated to null."); } expressionValue = "null"; } this.currentValue = expressionValue; if (currentValue.length() != 0) { this.currentValueIndex = 0; return currentValue.charAt(currentValueIndex++); } else { this.currentValueIndex = -1; return read(); } } } } } ValueExpressionEvaluationInputStream(FacesContext facesContext, InputStream inputStream); @Override int read(); }
@Test public void testStreamWithExpressionEvaluatingToExpressionString_mustOnlyEvaluateFirstExpression() throws Exception { final String data = "aa\nbbbb\ncc#{requestScope.test}cc\ndddd\n\n"; final String evaluatedData = "aa\nbbbb\ncc#{requestScope.test2}cc\ndddd\n\n"; byte[] dataArray = data.getBytes(); byte[] evaluatedDataArray = evaluatedData.getBytes(); FacesContext.getCurrentInstance().getExternalContext().getRequestMap().put("test", "#{requestScope.test2}"); FacesContext.getCurrentInstance().getExternalContext().getRequestMap().put("test2", "test-value"); ValueExpressionEvaluationInputStream inputStream = new ValueExpressionEvaluationInputStream( FacesContext.getCurrentInstance(), new ByteArrayInputStream(dataArray)); byte[] inputStreamDataArray = new byte[evaluatedDataArray.length]; inputStream.read(inputStreamDataArray); Assert.assertArrayEquals(evaluatedDataArray, inputStreamDataArray); Assert.assertEquals(-1, inputStream.read()); }
@Override public int read() throws IOException { if (currentValueIndex != -1) { if (currentValueIndex < currentValue.length()) { return currentValue.charAt(currentValueIndex++); } else { currentValueIndex = -1; } } int c1 = wrapped.read(); if (c1 != '#') { return c1; } else { int c2 = wrapped.read(); if (c2 != '{') { wrapped.unread(c2); return c1; } else { List<Integer> possibleValueExpression = new LinkedList<Integer>(); int c = wrapped.read(); boolean insideString = (c == '\''); while (c != -1 && c != '\n' && (insideString || c != '}')) { possibleValueExpression.add(c); c = wrapped.read(); if (c == '\'') { insideString = !insideString; } } if (c != '}') { if (c != -1) { wrapped.unread(c); } ListIterator<Integer> it = possibleValueExpression.listIterator(possibleValueExpression.size()); while (it.hasPrevious()) { wrapped.unread(it.previous()); } wrapped.unread(c2); return c1; } else { String expressionString = createExpressionString(possibleValueExpression); String expressionValue = facesContext.getApplication() .evaluateExpressionGet(facesContext, expressionString, String.class); if (expressionValue == null) { if (log.isLoggable(Level.WARNING)) { log.warning("ValueExpression " + expressionString + " evaluated to null."); } expressionValue = "null"; } this.currentValue = expressionValue; if (currentValue.length() != 0) { this.currentValueIndex = 0; return currentValue.charAt(currentValueIndex++); } else { this.currentValueIndex = -1; return read(); } } } } }
ValueExpressionEvaluationInputStream extends InputStream { @Override public int read() throws IOException { if (currentValueIndex != -1) { if (currentValueIndex < currentValue.length()) { return currentValue.charAt(currentValueIndex++); } else { currentValueIndex = -1; } } int c1 = wrapped.read(); if (c1 != '#') { return c1; } else { int c2 = wrapped.read(); if (c2 != '{') { wrapped.unread(c2); return c1; } else { List<Integer> possibleValueExpression = new LinkedList<Integer>(); int c = wrapped.read(); boolean insideString = (c == '\''); while (c != -1 && c != '\n' && (insideString || c != '}')) { possibleValueExpression.add(c); c = wrapped.read(); if (c == '\'') { insideString = !insideString; } } if (c != '}') { if (c != -1) { wrapped.unread(c); } ListIterator<Integer> it = possibleValueExpression.listIterator(possibleValueExpression.size()); while (it.hasPrevious()) { wrapped.unread(it.previous()); } wrapped.unread(c2); return c1; } else { String expressionString = createExpressionString(possibleValueExpression); String expressionValue = facesContext.getApplication() .evaluateExpressionGet(facesContext, expressionString, String.class); if (expressionValue == null) { if (log.isLoggable(Level.WARNING)) { log.warning("ValueExpression " + expressionString + " evaluated to null."); } expressionValue = "null"; } this.currentValue = expressionValue; if (currentValue.length() != 0) { this.currentValueIndex = 0; return currentValue.charAt(currentValueIndex++); } else { this.currentValueIndex = -1; return read(); } } } } } }
ValueExpressionEvaluationInputStream extends InputStream { @Override public int read() throws IOException { if (currentValueIndex != -1) { if (currentValueIndex < currentValue.length()) { return currentValue.charAt(currentValueIndex++); } else { currentValueIndex = -1; } } int c1 = wrapped.read(); if (c1 != '#') { return c1; } else { int c2 = wrapped.read(); if (c2 != '{') { wrapped.unread(c2); return c1; } else { List<Integer> possibleValueExpression = new LinkedList<Integer>(); int c = wrapped.read(); boolean insideString = (c == '\''); while (c != -1 && c != '\n' && (insideString || c != '}')) { possibleValueExpression.add(c); c = wrapped.read(); if (c == '\'') { insideString = !insideString; } } if (c != '}') { if (c != -1) { wrapped.unread(c); } ListIterator<Integer> it = possibleValueExpression.listIterator(possibleValueExpression.size()); while (it.hasPrevious()) { wrapped.unread(it.previous()); } wrapped.unread(c2); return c1; } else { String expressionString = createExpressionString(possibleValueExpression); String expressionValue = facesContext.getApplication() .evaluateExpressionGet(facesContext, expressionString, String.class); if (expressionValue == null) { if (log.isLoggable(Level.WARNING)) { log.warning("ValueExpression " + expressionString + " evaluated to null."); } expressionValue = "null"; } this.currentValue = expressionValue; if (currentValue.length() != 0) { this.currentValueIndex = 0; return currentValue.charAt(currentValueIndex++); } else { this.currentValueIndex = -1; return read(); } } } } } ValueExpressionEvaluationInputStream(FacesContext facesContext, InputStream inputStream); }
ValueExpressionEvaluationInputStream extends InputStream { @Override public int read() throws IOException { if (currentValueIndex != -1) { if (currentValueIndex < currentValue.length()) { return currentValue.charAt(currentValueIndex++); } else { currentValueIndex = -1; } } int c1 = wrapped.read(); if (c1 != '#') { return c1; } else { int c2 = wrapped.read(); if (c2 != '{') { wrapped.unread(c2); return c1; } else { List<Integer> possibleValueExpression = new LinkedList<Integer>(); int c = wrapped.read(); boolean insideString = (c == '\''); while (c != -1 && c != '\n' && (insideString || c != '}')) { possibleValueExpression.add(c); c = wrapped.read(); if (c == '\'') { insideString = !insideString; } } if (c != '}') { if (c != -1) { wrapped.unread(c); } ListIterator<Integer> it = possibleValueExpression.listIterator(possibleValueExpression.size()); while (it.hasPrevious()) { wrapped.unread(it.previous()); } wrapped.unread(c2); return c1; } else { String expressionString = createExpressionString(possibleValueExpression); String expressionValue = facesContext.getApplication() .evaluateExpressionGet(facesContext, expressionString, String.class); if (expressionValue == null) { if (log.isLoggable(Level.WARNING)) { log.warning("ValueExpression " + expressionString + " evaluated to null."); } expressionValue = "null"; } this.currentValue = expressionValue; if (currentValue.length() != 0) { this.currentValueIndex = 0; return currentValue.charAt(currentValueIndex++); } else { this.currentValueIndex = -1; return read(); } } } } } ValueExpressionEvaluationInputStream(FacesContext facesContext, InputStream inputStream); @Override int read(); }
ValueExpressionEvaluationInputStream extends InputStream { @Override public int read() throws IOException { if (currentValueIndex != -1) { if (currentValueIndex < currentValue.length()) { return currentValue.charAt(currentValueIndex++); } else { currentValueIndex = -1; } } int c1 = wrapped.read(); if (c1 != '#') { return c1; } else { int c2 = wrapped.read(); if (c2 != '{') { wrapped.unread(c2); return c1; } else { List<Integer> possibleValueExpression = new LinkedList<Integer>(); int c = wrapped.read(); boolean insideString = (c == '\''); while (c != -1 && c != '\n' && (insideString || c != '}')) { possibleValueExpression.add(c); c = wrapped.read(); if (c == '\'') { insideString = !insideString; } } if (c != '}') { if (c != -1) { wrapped.unread(c); } ListIterator<Integer> it = possibleValueExpression.listIterator(possibleValueExpression.size()); while (it.hasPrevious()) { wrapped.unread(it.previous()); } wrapped.unread(c2); return c1; } else { String expressionString = createExpressionString(possibleValueExpression); String expressionValue = facesContext.getApplication() .evaluateExpressionGet(facesContext, expressionString, String.class); if (expressionValue == null) { if (log.isLoggable(Level.WARNING)) { log.warning("ValueExpression " + expressionString + " evaluated to null."); } expressionValue = "null"; } this.currentValue = expressionValue; if (currentValue.length() != 0) { this.currentValueIndex = 0; return currentValue.charAt(currentValueIndex++); } else { this.currentValueIndex = -1; return read(); } } } } } ValueExpressionEvaluationInputStream(FacesContext facesContext, InputStream inputStream); @Override int read(); }
@Test public void testStreamThatOnlyConsistsOfExpression_mustEvaluateExpression() throws Exception { final String data = "#{requestScope.test}"; final String evaluatedData = "test-value"; byte[] dataArray = data.getBytes(); byte[] evaluatedDataArray = evaluatedData.getBytes(); FacesContext.getCurrentInstance().getExternalContext().getRequestMap().put("test", "test-value"); ValueExpressionEvaluationInputStream inputStream = new ValueExpressionEvaluationInputStream( FacesContext.getCurrentInstance(), new ByteArrayInputStream(dataArray)); byte[] inputStreamDataArray = new byte[evaluatedDataArray.length]; inputStream.read(inputStreamDataArray); Assert.assertArrayEquals(evaluatedDataArray, inputStreamDataArray); Assert.assertEquals(-1, inputStream.read()); }
@Override public int read() throws IOException { if (currentValueIndex != -1) { if (currentValueIndex < currentValue.length()) { return currentValue.charAt(currentValueIndex++); } else { currentValueIndex = -1; } } int c1 = wrapped.read(); if (c1 != '#') { return c1; } else { int c2 = wrapped.read(); if (c2 != '{') { wrapped.unread(c2); return c1; } else { List<Integer> possibleValueExpression = new LinkedList<Integer>(); int c = wrapped.read(); boolean insideString = (c == '\''); while (c != -1 && c != '\n' && (insideString || c != '}')) { possibleValueExpression.add(c); c = wrapped.read(); if (c == '\'') { insideString = !insideString; } } if (c != '}') { if (c != -1) { wrapped.unread(c); } ListIterator<Integer> it = possibleValueExpression.listIterator(possibleValueExpression.size()); while (it.hasPrevious()) { wrapped.unread(it.previous()); } wrapped.unread(c2); return c1; } else { String expressionString = createExpressionString(possibleValueExpression); String expressionValue = facesContext.getApplication() .evaluateExpressionGet(facesContext, expressionString, String.class); if (expressionValue == null) { if (log.isLoggable(Level.WARNING)) { log.warning("ValueExpression " + expressionString + " evaluated to null."); } expressionValue = "null"; } this.currentValue = expressionValue; if (currentValue.length() != 0) { this.currentValueIndex = 0; return currentValue.charAt(currentValueIndex++); } else { this.currentValueIndex = -1; return read(); } } } } }
ValueExpressionEvaluationInputStream extends InputStream { @Override public int read() throws IOException { if (currentValueIndex != -1) { if (currentValueIndex < currentValue.length()) { return currentValue.charAt(currentValueIndex++); } else { currentValueIndex = -1; } } int c1 = wrapped.read(); if (c1 != '#') { return c1; } else { int c2 = wrapped.read(); if (c2 != '{') { wrapped.unread(c2); return c1; } else { List<Integer> possibleValueExpression = new LinkedList<Integer>(); int c = wrapped.read(); boolean insideString = (c == '\''); while (c != -1 && c != '\n' && (insideString || c != '}')) { possibleValueExpression.add(c); c = wrapped.read(); if (c == '\'') { insideString = !insideString; } } if (c != '}') { if (c != -1) { wrapped.unread(c); } ListIterator<Integer> it = possibleValueExpression.listIterator(possibleValueExpression.size()); while (it.hasPrevious()) { wrapped.unread(it.previous()); } wrapped.unread(c2); return c1; } else { String expressionString = createExpressionString(possibleValueExpression); String expressionValue = facesContext.getApplication() .evaluateExpressionGet(facesContext, expressionString, String.class); if (expressionValue == null) { if (log.isLoggable(Level.WARNING)) { log.warning("ValueExpression " + expressionString + " evaluated to null."); } expressionValue = "null"; } this.currentValue = expressionValue; if (currentValue.length() != 0) { this.currentValueIndex = 0; return currentValue.charAt(currentValueIndex++); } else { this.currentValueIndex = -1; return read(); } } } } } }
ValueExpressionEvaluationInputStream extends InputStream { @Override public int read() throws IOException { if (currentValueIndex != -1) { if (currentValueIndex < currentValue.length()) { return currentValue.charAt(currentValueIndex++); } else { currentValueIndex = -1; } } int c1 = wrapped.read(); if (c1 != '#') { return c1; } else { int c2 = wrapped.read(); if (c2 != '{') { wrapped.unread(c2); return c1; } else { List<Integer> possibleValueExpression = new LinkedList<Integer>(); int c = wrapped.read(); boolean insideString = (c == '\''); while (c != -1 && c != '\n' && (insideString || c != '}')) { possibleValueExpression.add(c); c = wrapped.read(); if (c == '\'') { insideString = !insideString; } } if (c != '}') { if (c != -1) { wrapped.unread(c); } ListIterator<Integer> it = possibleValueExpression.listIterator(possibleValueExpression.size()); while (it.hasPrevious()) { wrapped.unread(it.previous()); } wrapped.unread(c2); return c1; } else { String expressionString = createExpressionString(possibleValueExpression); String expressionValue = facesContext.getApplication() .evaluateExpressionGet(facesContext, expressionString, String.class); if (expressionValue == null) { if (log.isLoggable(Level.WARNING)) { log.warning("ValueExpression " + expressionString + " evaluated to null."); } expressionValue = "null"; } this.currentValue = expressionValue; if (currentValue.length() != 0) { this.currentValueIndex = 0; return currentValue.charAt(currentValueIndex++); } else { this.currentValueIndex = -1; return read(); } } } } } ValueExpressionEvaluationInputStream(FacesContext facesContext, InputStream inputStream); }
ValueExpressionEvaluationInputStream extends InputStream { @Override public int read() throws IOException { if (currentValueIndex != -1) { if (currentValueIndex < currentValue.length()) { return currentValue.charAt(currentValueIndex++); } else { currentValueIndex = -1; } } int c1 = wrapped.read(); if (c1 != '#') { return c1; } else { int c2 = wrapped.read(); if (c2 != '{') { wrapped.unread(c2); return c1; } else { List<Integer> possibleValueExpression = new LinkedList<Integer>(); int c = wrapped.read(); boolean insideString = (c == '\''); while (c != -1 && c != '\n' && (insideString || c != '}')) { possibleValueExpression.add(c); c = wrapped.read(); if (c == '\'') { insideString = !insideString; } } if (c != '}') { if (c != -1) { wrapped.unread(c); } ListIterator<Integer> it = possibleValueExpression.listIterator(possibleValueExpression.size()); while (it.hasPrevious()) { wrapped.unread(it.previous()); } wrapped.unread(c2); return c1; } else { String expressionString = createExpressionString(possibleValueExpression); String expressionValue = facesContext.getApplication() .evaluateExpressionGet(facesContext, expressionString, String.class); if (expressionValue == null) { if (log.isLoggable(Level.WARNING)) { log.warning("ValueExpression " + expressionString + " evaluated to null."); } expressionValue = "null"; } this.currentValue = expressionValue; if (currentValue.length() != 0) { this.currentValueIndex = 0; return currentValue.charAt(currentValueIndex++); } else { this.currentValueIndex = -1; return read(); } } } } } ValueExpressionEvaluationInputStream(FacesContext facesContext, InputStream inputStream); @Override int read(); }
ValueExpressionEvaluationInputStream extends InputStream { @Override public int read() throws IOException { if (currentValueIndex != -1) { if (currentValueIndex < currentValue.length()) { return currentValue.charAt(currentValueIndex++); } else { currentValueIndex = -1; } } int c1 = wrapped.read(); if (c1 != '#') { return c1; } else { int c2 = wrapped.read(); if (c2 != '{') { wrapped.unread(c2); return c1; } else { List<Integer> possibleValueExpression = new LinkedList<Integer>(); int c = wrapped.read(); boolean insideString = (c == '\''); while (c != -1 && c != '\n' && (insideString || c != '}')) { possibleValueExpression.add(c); c = wrapped.read(); if (c == '\'') { insideString = !insideString; } } if (c != '}') { if (c != -1) { wrapped.unread(c); } ListIterator<Integer> it = possibleValueExpression.listIterator(possibleValueExpression.size()); while (it.hasPrevious()) { wrapped.unread(it.previous()); } wrapped.unread(c2); return c1; } else { String expressionString = createExpressionString(possibleValueExpression); String expressionValue = facesContext.getApplication() .evaluateExpressionGet(facesContext, expressionString, String.class); if (expressionValue == null) { if (log.isLoggable(Level.WARNING)) { log.warning("ValueExpression " + expressionString + " evaluated to null."); } expressionValue = "null"; } this.currentValue = expressionValue; if (currentValue.length() != 0) { this.currentValueIndex = 0; return currentValue.charAt(currentValueIndex++); } else { this.currentValueIndex = -1; return read(); } } } } } ValueExpressionEvaluationInputStream(FacesContext facesContext, InputStream inputStream); @Override int read(); }
@Test public void testStreamWithNullExpression_mustEvaluateToEmptyString() throws Exception { final String data = "aa\nbbbb\ncc#{requestScope.test}cc\ndddd\n\n"; final String evaluatedData = "aa\nbbbb\ncccc\ndddd\n\n"; byte[] dataArray = data.getBytes(); byte[] evaluatedDataArray = evaluatedData.getBytes(); FacesContext.getCurrentInstance().getExternalContext().getRequestMap().remove("test"); ValueExpressionEvaluationInputStream inputStream = new ValueExpressionEvaluationInputStream( FacesContext.getCurrentInstance(), new ByteArrayInputStream(dataArray)); byte[] inputStreamDataArray = new byte[evaluatedDataArray.length]; inputStream.read(inputStreamDataArray); Assert.assertArrayEquals(evaluatedDataArray, inputStreamDataArray); Assert.assertEquals(-1, inputStream.read()); }
@Override public int read() throws IOException { if (currentValueIndex != -1) { if (currentValueIndex < currentValue.length()) { return currentValue.charAt(currentValueIndex++); } else { currentValueIndex = -1; } } int c1 = wrapped.read(); if (c1 != '#') { return c1; } else { int c2 = wrapped.read(); if (c2 != '{') { wrapped.unread(c2); return c1; } else { List<Integer> possibleValueExpression = new LinkedList<Integer>(); int c = wrapped.read(); boolean insideString = (c == '\''); while (c != -1 && c != '\n' && (insideString || c != '}')) { possibleValueExpression.add(c); c = wrapped.read(); if (c == '\'') { insideString = !insideString; } } if (c != '}') { if (c != -1) { wrapped.unread(c); } ListIterator<Integer> it = possibleValueExpression.listIterator(possibleValueExpression.size()); while (it.hasPrevious()) { wrapped.unread(it.previous()); } wrapped.unread(c2); return c1; } else { String expressionString = createExpressionString(possibleValueExpression); String expressionValue = facesContext.getApplication() .evaluateExpressionGet(facesContext, expressionString, String.class); if (expressionValue == null) { if (log.isLoggable(Level.WARNING)) { log.warning("ValueExpression " + expressionString + " evaluated to null."); } expressionValue = "null"; } this.currentValue = expressionValue; if (currentValue.length() != 0) { this.currentValueIndex = 0; return currentValue.charAt(currentValueIndex++); } else { this.currentValueIndex = -1; return read(); } } } } }
ValueExpressionEvaluationInputStream extends InputStream { @Override public int read() throws IOException { if (currentValueIndex != -1) { if (currentValueIndex < currentValue.length()) { return currentValue.charAt(currentValueIndex++); } else { currentValueIndex = -1; } } int c1 = wrapped.read(); if (c1 != '#') { return c1; } else { int c2 = wrapped.read(); if (c2 != '{') { wrapped.unread(c2); return c1; } else { List<Integer> possibleValueExpression = new LinkedList<Integer>(); int c = wrapped.read(); boolean insideString = (c == '\''); while (c != -1 && c != '\n' && (insideString || c != '}')) { possibleValueExpression.add(c); c = wrapped.read(); if (c == '\'') { insideString = !insideString; } } if (c != '}') { if (c != -1) { wrapped.unread(c); } ListIterator<Integer> it = possibleValueExpression.listIterator(possibleValueExpression.size()); while (it.hasPrevious()) { wrapped.unread(it.previous()); } wrapped.unread(c2); return c1; } else { String expressionString = createExpressionString(possibleValueExpression); String expressionValue = facesContext.getApplication() .evaluateExpressionGet(facesContext, expressionString, String.class); if (expressionValue == null) { if (log.isLoggable(Level.WARNING)) { log.warning("ValueExpression " + expressionString + " evaluated to null."); } expressionValue = "null"; } this.currentValue = expressionValue; if (currentValue.length() != 0) { this.currentValueIndex = 0; return currentValue.charAt(currentValueIndex++); } else { this.currentValueIndex = -1; return read(); } } } } } }
ValueExpressionEvaluationInputStream extends InputStream { @Override public int read() throws IOException { if (currentValueIndex != -1) { if (currentValueIndex < currentValue.length()) { return currentValue.charAt(currentValueIndex++); } else { currentValueIndex = -1; } } int c1 = wrapped.read(); if (c1 != '#') { return c1; } else { int c2 = wrapped.read(); if (c2 != '{') { wrapped.unread(c2); return c1; } else { List<Integer> possibleValueExpression = new LinkedList<Integer>(); int c = wrapped.read(); boolean insideString = (c == '\''); while (c != -1 && c != '\n' && (insideString || c != '}')) { possibleValueExpression.add(c); c = wrapped.read(); if (c == '\'') { insideString = !insideString; } } if (c != '}') { if (c != -1) { wrapped.unread(c); } ListIterator<Integer> it = possibleValueExpression.listIterator(possibleValueExpression.size()); while (it.hasPrevious()) { wrapped.unread(it.previous()); } wrapped.unread(c2); return c1; } else { String expressionString = createExpressionString(possibleValueExpression); String expressionValue = facesContext.getApplication() .evaluateExpressionGet(facesContext, expressionString, String.class); if (expressionValue == null) { if (log.isLoggable(Level.WARNING)) { log.warning("ValueExpression " + expressionString + " evaluated to null."); } expressionValue = "null"; } this.currentValue = expressionValue; if (currentValue.length() != 0) { this.currentValueIndex = 0; return currentValue.charAt(currentValueIndex++); } else { this.currentValueIndex = -1; return read(); } } } } } ValueExpressionEvaluationInputStream(FacesContext facesContext, InputStream inputStream); }
ValueExpressionEvaluationInputStream extends InputStream { @Override public int read() throws IOException { if (currentValueIndex != -1) { if (currentValueIndex < currentValue.length()) { return currentValue.charAt(currentValueIndex++); } else { currentValueIndex = -1; } } int c1 = wrapped.read(); if (c1 != '#') { return c1; } else { int c2 = wrapped.read(); if (c2 != '{') { wrapped.unread(c2); return c1; } else { List<Integer> possibleValueExpression = new LinkedList<Integer>(); int c = wrapped.read(); boolean insideString = (c == '\''); while (c != -1 && c != '\n' && (insideString || c != '}')) { possibleValueExpression.add(c); c = wrapped.read(); if (c == '\'') { insideString = !insideString; } } if (c != '}') { if (c != -1) { wrapped.unread(c); } ListIterator<Integer> it = possibleValueExpression.listIterator(possibleValueExpression.size()); while (it.hasPrevious()) { wrapped.unread(it.previous()); } wrapped.unread(c2); return c1; } else { String expressionString = createExpressionString(possibleValueExpression); String expressionValue = facesContext.getApplication() .evaluateExpressionGet(facesContext, expressionString, String.class); if (expressionValue == null) { if (log.isLoggable(Level.WARNING)) { log.warning("ValueExpression " + expressionString + " evaluated to null."); } expressionValue = "null"; } this.currentValue = expressionValue; if (currentValue.length() != 0) { this.currentValueIndex = 0; return currentValue.charAt(currentValueIndex++); } else { this.currentValueIndex = -1; return read(); } } } } } ValueExpressionEvaluationInputStream(FacesContext facesContext, InputStream inputStream); @Override int read(); }
ValueExpressionEvaluationInputStream extends InputStream { @Override public int read() throws IOException { if (currentValueIndex != -1) { if (currentValueIndex < currentValue.length()) { return currentValue.charAt(currentValueIndex++); } else { currentValueIndex = -1; } } int c1 = wrapped.read(); if (c1 != '#') { return c1; } else { int c2 = wrapped.read(); if (c2 != '{') { wrapped.unread(c2); return c1; } else { List<Integer> possibleValueExpression = new LinkedList<Integer>(); int c = wrapped.read(); boolean insideString = (c == '\''); while (c != -1 && c != '\n' && (insideString || c != '}')) { possibleValueExpression.add(c); c = wrapped.read(); if (c == '\'') { insideString = !insideString; } } if (c != '}') { if (c != -1) { wrapped.unread(c); } ListIterator<Integer> it = possibleValueExpression.listIterator(possibleValueExpression.size()); while (it.hasPrevious()) { wrapped.unread(it.previous()); } wrapped.unread(c2); return c1; } else { String expressionString = createExpressionString(possibleValueExpression); String expressionValue = facesContext.getApplication() .evaluateExpressionGet(facesContext, expressionString, String.class); if (expressionValue == null) { if (log.isLoggable(Level.WARNING)) { log.warning("ValueExpression " + expressionString + " evaluated to null."); } expressionValue = "null"; } this.currentValue = expressionValue; if (currentValue.length() != 0) { this.currentValueIndex = 0; return currentValue.charAt(currentValueIndex++); } else { this.currentValueIndex = -1; return read(); } } } } } ValueExpressionEvaluationInputStream(FacesContext facesContext, InputStream inputStream); @Override int read(); }
@Test public void shouldNotRetrieveMethodBasedOnSameReturnType() throws Exception { Method m = InnerTwo.class.getMethod("getCollection"); Method method = ClassUtils.extractPossiblyGenericMethod(InnerOne.class, m); Assert.assertEquals(InnerOne.class.getMethod("getCollection"), method); }
public static Method extractPossiblyGenericMethod(Class<?> clazz, Method sourceMethod) { Method exactMethod = extractMethod(clazz, sourceMethod); if (exactMethod == null) { String methodName = sourceMethod.getName(); Class<?>[] parameterTypes = sourceMethod.getParameterTypes(); for (Method method : clazz.getMethods()) { if (method.getName().equals(methodName) && allSameType(method.getParameterTypes(), parameterTypes)) { return method; } } return null; } else { return exactMethod; } }
ClassUtils { public static Method extractPossiblyGenericMethod(Class<?> clazz, Method sourceMethod) { Method exactMethod = extractMethod(clazz, sourceMethod); if (exactMethod == null) { String methodName = sourceMethod.getName(); Class<?>[] parameterTypes = sourceMethod.getParameterTypes(); for (Method method : clazz.getMethods()) { if (method.getName().equals(methodName) && allSameType(method.getParameterTypes(), parameterTypes)) { return method; } } return null; } else { return exactMethod; } } }
ClassUtils { public static Method extractPossiblyGenericMethod(Class<?> clazz, Method sourceMethod) { Method exactMethod = extractMethod(clazz, sourceMethod); if (exactMethod == null) { String methodName = sourceMethod.getName(); Class<?>[] parameterTypes = sourceMethod.getParameterTypes(); for (Method method : clazz.getMethods()) { if (method.getName().equals(methodName) && allSameType(method.getParameterTypes(), parameterTypes)) { return method; } } return null; } else { return exactMethod; } } private ClassUtils(); }
ClassUtils { public static Method extractPossiblyGenericMethod(Class<?> clazz, Method sourceMethod) { Method exactMethod = extractMethod(clazz, sourceMethod); if (exactMethod == null) { String methodName = sourceMethod.getName(); Class<?>[] parameterTypes = sourceMethod.getParameterTypes(); for (Method method : clazz.getMethods()) { if (method.getName().equals(methodName) && allSameType(method.getParameterTypes(), parameterTypes)) { return method; } } return null; } else { return exactMethod; } } private ClassUtils(); static ClassLoader getClassLoader(Object o); static boolean isProxyableClass(Type type); static Class<T> tryToLoadClassForName(String name, Class<T> targetType); static Class<T> tryToLoadClassForName(String name, Class<T> targetType, ClassLoader classLoader); static Class tryToLoadClassForName(String name); static Class tryToLoadClassForName(String name, ClassLoader classLoader); static Class loadClassForName(String name); static T tryToInstantiateClass(Class<T> targetClass); static T tryToInstantiateClassForName(String className, Class<T> targetType); static Object tryToInstantiateClassForName(String className); static Object instantiateClassForName(String className); static String getJarVersion(Class targetClass); static String getRevision(Class targetClass); static boolean containsMethod(Class<?> targetClass, Method method); static Method extractMethod(Class<?> clazz, Method sourceMethod); static boolean containsPossiblyGenericMethod(Class<?> targetClass, Method method); static Method extractPossiblyGenericMethod(Class<?> clazz, Method sourceMethod); static boolean returns(Method method, Class<?> clazz); }
ClassUtils { public static Method extractPossiblyGenericMethod(Class<?> clazz, Method sourceMethod) { Method exactMethod = extractMethod(clazz, sourceMethod); if (exactMethod == null) { String methodName = sourceMethod.getName(); Class<?>[] parameterTypes = sourceMethod.getParameterTypes(); for (Method method : clazz.getMethods()) { if (method.getName().equals(methodName) && allSameType(method.getParameterTypes(), parameterTypes)) { return method; } } return null; } else { return exactMethod; } } private ClassUtils(); static ClassLoader getClassLoader(Object o); static boolean isProxyableClass(Type type); static Class<T> tryToLoadClassForName(String name, Class<T> targetType); static Class<T> tryToLoadClassForName(String name, Class<T> targetType, ClassLoader classLoader); static Class tryToLoadClassForName(String name); static Class tryToLoadClassForName(String name, ClassLoader classLoader); static Class loadClassForName(String name); static T tryToInstantiateClass(Class<T> targetClass); static T tryToInstantiateClassForName(String className, Class<T> targetType); static Object tryToInstantiateClassForName(String className); static Object instantiateClassForName(String className); static String getJarVersion(Class targetClass); static String getRevision(Class targetClass); static boolean containsMethod(Class<?> targetClass, Method method); static Method extractMethod(Class<?> clazz, Method sourceMethod); static boolean containsPossiblyGenericMethod(Class<?> targetClass, Method method); static Method extractPossiblyGenericMethod(Class<?> clazz, Method sourceMethod); static boolean returns(Method method, Class<?> clazz); }
@Test public void shouldRetrieveMethodBasedOnCastableType() throws Exception { Method m = InnerThree.class.getMethod("getCollection"); Method method = ClassUtils.extractPossiblyGenericMethod(InnerOne.class, m); Assert.assertEquals(InnerOne.class.getMethod("getCollection"), method); }
public static Method extractPossiblyGenericMethod(Class<?> clazz, Method sourceMethod) { Method exactMethod = extractMethod(clazz, sourceMethod); if (exactMethod == null) { String methodName = sourceMethod.getName(); Class<?>[] parameterTypes = sourceMethod.getParameterTypes(); for (Method method : clazz.getMethods()) { if (method.getName().equals(methodName) && allSameType(method.getParameterTypes(), parameterTypes)) { return method; } } return null; } else { return exactMethod; } }
ClassUtils { public static Method extractPossiblyGenericMethod(Class<?> clazz, Method sourceMethod) { Method exactMethod = extractMethod(clazz, sourceMethod); if (exactMethod == null) { String methodName = sourceMethod.getName(); Class<?>[] parameterTypes = sourceMethod.getParameterTypes(); for (Method method : clazz.getMethods()) { if (method.getName().equals(methodName) && allSameType(method.getParameterTypes(), parameterTypes)) { return method; } } return null; } else { return exactMethod; } } }
ClassUtils { public static Method extractPossiblyGenericMethod(Class<?> clazz, Method sourceMethod) { Method exactMethod = extractMethod(clazz, sourceMethod); if (exactMethod == null) { String methodName = sourceMethod.getName(); Class<?>[] parameterTypes = sourceMethod.getParameterTypes(); for (Method method : clazz.getMethods()) { if (method.getName().equals(methodName) && allSameType(method.getParameterTypes(), parameterTypes)) { return method; } } return null; } else { return exactMethod; } } private ClassUtils(); }
ClassUtils { public static Method extractPossiblyGenericMethod(Class<?> clazz, Method sourceMethod) { Method exactMethod = extractMethod(clazz, sourceMethod); if (exactMethod == null) { String methodName = sourceMethod.getName(); Class<?>[] parameterTypes = sourceMethod.getParameterTypes(); for (Method method : clazz.getMethods()) { if (method.getName().equals(methodName) && allSameType(method.getParameterTypes(), parameterTypes)) { return method; } } return null; } else { return exactMethod; } } private ClassUtils(); static ClassLoader getClassLoader(Object o); static boolean isProxyableClass(Type type); static Class<T> tryToLoadClassForName(String name, Class<T> targetType); static Class<T> tryToLoadClassForName(String name, Class<T> targetType, ClassLoader classLoader); static Class tryToLoadClassForName(String name); static Class tryToLoadClassForName(String name, ClassLoader classLoader); static Class loadClassForName(String name); static T tryToInstantiateClass(Class<T> targetClass); static T tryToInstantiateClassForName(String className, Class<T> targetType); static Object tryToInstantiateClassForName(String className); static Object instantiateClassForName(String className); static String getJarVersion(Class targetClass); static String getRevision(Class targetClass); static boolean containsMethod(Class<?> targetClass, Method method); static Method extractMethod(Class<?> clazz, Method sourceMethod); static boolean containsPossiblyGenericMethod(Class<?> targetClass, Method method); static Method extractPossiblyGenericMethod(Class<?> clazz, Method sourceMethod); static boolean returns(Method method, Class<?> clazz); }
ClassUtils { public static Method extractPossiblyGenericMethod(Class<?> clazz, Method sourceMethod) { Method exactMethod = extractMethod(clazz, sourceMethod); if (exactMethod == null) { String methodName = sourceMethod.getName(); Class<?>[] parameterTypes = sourceMethod.getParameterTypes(); for (Method method : clazz.getMethods()) { if (method.getName().equals(methodName) && allSameType(method.getParameterTypes(), parameterTypes)) { return method; } } return null; } else { return exactMethod; } } private ClassUtils(); static ClassLoader getClassLoader(Object o); static boolean isProxyableClass(Type type); static Class<T> tryToLoadClassForName(String name, Class<T> targetType); static Class<T> tryToLoadClassForName(String name, Class<T> targetType, ClassLoader classLoader); static Class tryToLoadClassForName(String name); static Class tryToLoadClassForName(String name, ClassLoader classLoader); static Class loadClassForName(String name); static T tryToInstantiateClass(Class<T> targetClass); static T tryToInstantiateClassForName(String className, Class<T> targetType); static Object tryToInstantiateClassForName(String className); static Object instantiateClassForName(String className); static String getJarVersion(Class targetClass); static String getRevision(Class targetClass); static boolean containsMethod(Class<?> targetClass, Method method); static Method extractMethod(Class<?> clazz, Method sourceMethod); static boolean containsPossiblyGenericMethod(Class<?> targetClass, Method method); static Method extractPossiblyGenericMethod(Class<?> clazz, Method sourceMethod); static boolean returns(Method method, Class<?> clazz); }
@Test public void should_unwrap_query_even_proxied() { String extracted = factory.extract((Query) newProxyInstance(currentThread().getContextClassLoader(), new Class[] { Query.class }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("toString")) { return "Unknown provider wrapper for tests."; } if (method.getName().equals("unwrap")) { Class<?> clazz = (Class<?>) args[0]; if (clazz.getName().contains("hibernate") || clazz.getName().contains("openjpa") || clazz.getName().contains("eclipse")) { return createProxy(clazz); } else { throw new PersistenceException("Unable to unwrap for " + clazz); } } return null; } }) ); assertEquals(QUERY_STRING, extracted); }
public String extract(final Query query) { for (final QueryStringExtractor extractor : extractors) { final String compare = extractor.getClass().getAnnotation(ProviderSpecific.class).value(); final Object implQuery = toImplQuery(compare, query); if (implQuery != null) { return extractor.extractFrom(implQuery); } } throw new RuntimeException("Persistence provider not supported"); }
QueryStringExtractorFactory { public String extract(final Query query) { for (final QueryStringExtractor extractor : extractors) { final String compare = extractor.getClass().getAnnotation(ProviderSpecific.class).value(); final Object implQuery = toImplQuery(compare, query); if (implQuery != null) { return extractor.extractFrom(implQuery); } } throw new RuntimeException("Persistence provider not supported"); } }
QueryStringExtractorFactory { public String extract(final Query query) { for (final QueryStringExtractor extractor : extractors) { final String compare = extractor.getClass().getAnnotation(ProviderSpecific.class).value(); final Object implQuery = toImplQuery(compare, query); if (implQuery != null) { return extractor.extractFrom(implQuery); } } throw new RuntimeException("Persistence provider not supported"); } }
QueryStringExtractorFactory { public String extract(final Query query) { for (final QueryStringExtractor extractor : extractors) { final String compare = extractor.getClass().getAnnotation(ProviderSpecific.class).value(); final Object implQuery = toImplQuery(compare, query); if (implQuery != null) { return extractor.extractFrom(implQuery); } } throw new RuntimeException("Persistence provider not supported"); } String extract(final Query query); }
QueryStringExtractorFactory { public String extract(final Query query) { for (final QueryStringExtractor extractor : extractors) { final String compare = extractor.getClass().getAnnotation(ProviderSpecific.class).value(); final Object implQuery = toImplQuery(compare, query); if (implQuery != null) { return extractor.extractFrom(implQuery); } } throw new RuntimeException("Persistence provider not supported"); } String extract(final Query query); }
@Test public void shouldReturnNameOrNull() throws Exception { Method method = getClass().getDeclaredMethod("someMethod", String.class); String parameterName = ParameterUtil.getName(method, 0); Assert.assertTrue(parameterName.equals("arg0") || parameterName.equals("firstParameter")); }
public static String getName(Method method, int parameterIndex) { if (!isParameterSupported() || method == null) { return null; } try { Object[] parameters = (Object[]) getParametersMethod.invoke(method); return (String) getNameMethod.invoke(parameters[parameterIndex]); } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } return null; }
ParameterUtil { public static String getName(Method method, int parameterIndex) { if (!isParameterSupported() || method == null) { return null; } try { Object[] parameters = (Object[]) getParametersMethod.invoke(method); return (String) getNameMethod.invoke(parameters[parameterIndex]); } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } return null; } }
ParameterUtil { public static String getName(Method method, int parameterIndex) { if (!isParameterSupported() || method == null) { return null; } try { Object[] parameters = (Object[]) getParametersMethod.invoke(method); return (String) getNameMethod.invoke(parameters[parameterIndex]); } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } return null; } }
ParameterUtil { public static String getName(Method method, int parameterIndex) { if (!isParameterSupported() || method == null) { return null; } try { Object[] parameters = (Object[]) getParametersMethod.invoke(method); return (String) getNameMethod.invoke(parameters[parameterIndex]); } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } return null; } static boolean isParameterSupported(); static String getName(Method method, int parameterIndex); }
ParameterUtil { public static String getName(Method method, int parameterIndex) { if (!isParameterSupported() || method == null) { return null; } try { Object[] parameters = (Object[]) getParametersMethod.invoke(method); return (String) getNameMethod.invoke(parameters[parameterIndex]); } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } return null; } static boolean isParameterSupported(); static String getName(Method method, int parameterIndex); }
@Test public void run() throws IOException, URISyntaxException { test.result = PropertyFileUtils.resolvePropertyFiles(test.file); test.run(); }
public static Enumeration<URL> resolvePropertyFiles(String propertyFileName) throws IOException { if (propertyFileName != null && (propertyFileName.contains(": { Vector<URL> propertyFileUrls = new Vector<URL>(); URL url = new URL(propertyFileName); if (propertyFileName.startsWith("file:")) { try { File file = new File(url.toURI()); if (file.exists()) { propertyFileUrls.add(url); } } catch (URISyntaxException e) { throw new IllegalStateException("Property file URL is malformed", e); } } else { propertyFileUrls.add(url); } return propertyFileUrls.elements(); } if (propertyFileName != null) { File file = new File(propertyFileName); if (file.exists()) { return Collections.enumeration(Collections.singleton(file.toURI().toURL())); } } ClassLoader cl = ClassUtils.getClassLoader(null); Enumeration<URL> propertyFileUrls = cl.getResources(propertyFileName); if (!propertyFileUrls.hasMoreElements()) { cl = PropertyFileUtils.class.getClassLoader(); propertyFileUrls = cl.getResources(propertyFileName); } return propertyFileUrls; }
PropertyFileUtils { public static Enumeration<URL> resolvePropertyFiles(String propertyFileName) throws IOException { if (propertyFileName != null && (propertyFileName.contains(": { Vector<URL> propertyFileUrls = new Vector<URL>(); URL url = new URL(propertyFileName); if (propertyFileName.startsWith("file:")) { try { File file = new File(url.toURI()); if (file.exists()) { propertyFileUrls.add(url); } } catch (URISyntaxException e) { throw new IllegalStateException("Property file URL is malformed", e); } } else { propertyFileUrls.add(url); } return propertyFileUrls.elements(); } if (propertyFileName != null) { File file = new File(propertyFileName); if (file.exists()) { return Collections.enumeration(Collections.singleton(file.toURI().toURL())); } } ClassLoader cl = ClassUtils.getClassLoader(null); Enumeration<URL> propertyFileUrls = cl.getResources(propertyFileName); if (!propertyFileUrls.hasMoreElements()) { cl = PropertyFileUtils.class.getClassLoader(); propertyFileUrls = cl.getResources(propertyFileName); } return propertyFileUrls; } }
PropertyFileUtils { public static Enumeration<URL> resolvePropertyFiles(String propertyFileName) throws IOException { if (propertyFileName != null && (propertyFileName.contains(": { Vector<URL> propertyFileUrls = new Vector<URL>(); URL url = new URL(propertyFileName); if (propertyFileName.startsWith("file:")) { try { File file = new File(url.toURI()); if (file.exists()) { propertyFileUrls.add(url); } } catch (URISyntaxException e) { throw new IllegalStateException("Property file URL is malformed", e); } } else { propertyFileUrls.add(url); } return propertyFileUrls.elements(); } if (propertyFileName != null) { File file = new File(propertyFileName); if (file.exists()) { return Collections.enumeration(Collections.singleton(file.toURI().toURL())); } } ClassLoader cl = ClassUtils.getClassLoader(null); Enumeration<URL> propertyFileUrls = cl.getResources(propertyFileName); if (!propertyFileUrls.hasMoreElements()) { cl = PropertyFileUtils.class.getClassLoader(); propertyFileUrls = cl.getResources(propertyFileName); } return propertyFileUrls; } private PropertyFileUtils(); }
PropertyFileUtils { public static Enumeration<URL> resolvePropertyFiles(String propertyFileName) throws IOException { if (propertyFileName != null && (propertyFileName.contains(": { Vector<URL> propertyFileUrls = new Vector<URL>(); URL url = new URL(propertyFileName); if (propertyFileName.startsWith("file:")) { try { File file = new File(url.toURI()); if (file.exists()) { propertyFileUrls.add(url); } } catch (URISyntaxException e) { throw new IllegalStateException("Property file URL is malformed", e); } } else { propertyFileUrls.add(url); } return propertyFileUrls.elements(); } if (propertyFileName != null) { File file = new File(propertyFileName); if (file.exists()) { return Collections.enumeration(Collections.singleton(file.toURI().toURL())); } } ClassLoader cl = ClassUtils.getClassLoader(null); Enumeration<URL> propertyFileUrls = cl.getResources(propertyFileName); if (!propertyFileUrls.hasMoreElements()) { cl = PropertyFileUtils.class.getClassLoader(); propertyFileUrls = cl.getResources(propertyFileName); } return propertyFileUrls; } private PropertyFileUtils(); static Enumeration<URL> resolvePropertyFiles(String propertyFileName); static Properties loadProperties(URL url); static ResourceBundle getResourceBundle(String bundleName); static ResourceBundle getResourceBundle(String bundleName, Locale locale); }
PropertyFileUtils { public static Enumeration<URL> resolvePropertyFiles(String propertyFileName) throws IOException { if (propertyFileName != null && (propertyFileName.contains(": { Vector<URL> propertyFileUrls = new Vector<URL>(); URL url = new URL(propertyFileName); if (propertyFileName.startsWith("file:")) { try { File file = new File(url.toURI()); if (file.exists()) { propertyFileUrls.add(url); } } catch (URISyntaxException e) { throw new IllegalStateException("Property file URL is malformed", e); } } else { propertyFileUrls.add(url); } return propertyFileUrls.elements(); } if (propertyFileName != null) { File file = new File(propertyFileName); if (file.exists()) { return Collections.enumeration(Collections.singleton(file.toURI().toURL())); } } ClassLoader cl = ClassUtils.getClassLoader(null); Enumeration<URL> propertyFileUrls = cl.getResources(propertyFileName); if (!propertyFileUrls.hasMoreElements()) { cl = PropertyFileUtils.class.getClassLoader(); propertyFileUrls = cl.getResources(propertyFileName); } return propertyFileUrls; } private PropertyFileUtils(); static Enumeration<URL> resolvePropertyFiles(String propertyFileName); static Properties loadProperties(URL url); static ResourceBundle getResourceBundle(String bundleName); static ResourceBundle getResourceBundle(String bundleName, Locale locale); }
@Test public void should_save() throws Exception { Simple simple = new Simple("test"); simple = repo.save(simple); assertNotNull(simple.getId()); }
@Override @RequiresTransaction public E save(E entity) { if (context.isNew(entity)) { entityManager().persist(entity); return entity; } return entityManager().merge(entity); }
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @Override @RequiresTransaction public E save(E entity) { if (context.isNew(entity)) { entityManager().persist(entity); return entity; } return entityManager().merge(entity); } }
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @Override @RequiresTransaction public E save(E entity) { if (context.isNew(entity)) { entityManager().persist(entity); return entity; } return entityManager().merge(entity); } }
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @Override @RequiresTransaction public E save(E entity) { if (context.isNew(entity)) { entityManager().persist(entity); return entity; } return entityManager().merge(entity); } @Override @RequiresTransaction E save(E entity); @Override @RequiresTransaction E saveAndFlush(E entity); @Override @RequiresTransaction E saveAndFlushAndRefresh(E entity); @Override @RequiresTransaction void refresh(E entity); @Override E findBy(PK primaryKey); @Override Optional<E> findOptionalBy(PK primaryKey); @Override List<E> findBy(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findBy(E example, int start, int max, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, int start, int max, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override List<E> findAll(); @SuppressWarnings("unchecked") @Override List<E> findAll(int start, int max); @Override Long count(); @Override Long count(E example, SingularAttribute<E, ?>... attributes); @Override Long countLike(E example, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override PK getPrimaryKey(E entity); @Override @RequiresTransaction void remove(E entity); @Override @RequiresTransaction void removeAndFlush(E entity); @Override @RequiresTransaction void attachAndRemove(E entity); @Override @RequiresTransaction void flush(); EntityManager entityManager(); CriteriaQuery<E> criteriaQuery(); TypedQuery<E> typedQuery(String qlString); @SuppressWarnings("unchecked") Class<E> entityClass(); String tableName(); String entityName(); }
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @Override @RequiresTransaction public E save(E entity) { if (context.isNew(entity)) { entityManager().persist(entity); return entity; } return entityManager().merge(entity); } @Override @RequiresTransaction E save(E entity); @Override @RequiresTransaction E saveAndFlush(E entity); @Override @RequiresTransaction E saveAndFlushAndRefresh(E entity); @Override @RequiresTransaction void refresh(E entity); @Override E findBy(PK primaryKey); @Override Optional<E> findOptionalBy(PK primaryKey); @Override List<E> findBy(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findBy(E example, int start, int max, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, int start, int max, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override List<E> findAll(); @SuppressWarnings("unchecked") @Override List<E> findAll(int start, int max); @Override Long count(); @Override Long count(E example, SingularAttribute<E, ?>... attributes); @Override Long countLike(E example, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override PK getPrimaryKey(E entity); @Override @RequiresTransaction void remove(E entity); @Override @RequiresTransaction void removeAndFlush(E entity); @Override @RequiresTransaction void attachAndRemove(E entity); @Override @RequiresTransaction void flush(); EntityManager entityManager(); CriteriaQuery<E> criteriaQuery(); TypedQuery<E> typedQuery(String qlString); @SuppressWarnings("unchecked") Class<E> entityClass(); String tableName(); String entityName(); }
@Test public void should_merge() throws Exception { Simple simple = testData.createSimple("testMerge"); Long id = simple.getId(); final String newName = "testMergeUpdated"; simple.setName(newName); simple = repo.save(simple); assertEquals(id, simple.getId()); assertEquals(newName, simple.getName()); }
@Override @RequiresTransaction public E save(E entity) { if (context.isNew(entity)) { entityManager().persist(entity); return entity; } return entityManager().merge(entity); }
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @Override @RequiresTransaction public E save(E entity) { if (context.isNew(entity)) { entityManager().persist(entity); return entity; } return entityManager().merge(entity); } }
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @Override @RequiresTransaction public E save(E entity) { if (context.isNew(entity)) { entityManager().persist(entity); return entity; } return entityManager().merge(entity); } }
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @Override @RequiresTransaction public E save(E entity) { if (context.isNew(entity)) { entityManager().persist(entity); return entity; } return entityManager().merge(entity); } @Override @RequiresTransaction E save(E entity); @Override @RequiresTransaction E saveAndFlush(E entity); @Override @RequiresTransaction E saveAndFlushAndRefresh(E entity); @Override @RequiresTransaction void refresh(E entity); @Override E findBy(PK primaryKey); @Override Optional<E> findOptionalBy(PK primaryKey); @Override List<E> findBy(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findBy(E example, int start, int max, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, int start, int max, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override List<E> findAll(); @SuppressWarnings("unchecked") @Override List<E> findAll(int start, int max); @Override Long count(); @Override Long count(E example, SingularAttribute<E, ?>... attributes); @Override Long countLike(E example, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override PK getPrimaryKey(E entity); @Override @RequiresTransaction void remove(E entity); @Override @RequiresTransaction void removeAndFlush(E entity); @Override @RequiresTransaction void attachAndRemove(E entity); @Override @RequiresTransaction void flush(); EntityManager entityManager(); CriteriaQuery<E> criteriaQuery(); TypedQuery<E> typedQuery(String qlString); @SuppressWarnings("unchecked") Class<E> entityClass(); String tableName(); String entityName(); }
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @Override @RequiresTransaction public E save(E entity) { if (context.isNew(entity)) { entityManager().persist(entity); return entity; } return entityManager().merge(entity); } @Override @RequiresTransaction E save(E entity); @Override @RequiresTransaction E saveAndFlush(E entity); @Override @RequiresTransaction E saveAndFlushAndRefresh(E entity); @Override @RequiresTransaction void refresh(E entity); @Override E findBy(PK primaryKey); @Override Optional<E> findOptionalBy(PK primaryKey); @Override List<E> findBy(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findBy(E example, int start, int max, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, int start, int max, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override List<E> findAll(); @SuppressWarnings("unchecked") @Override List<E> findAll(int start, int max); @Override Long count(); @Override Long count(E example, SingularAttribute<E, ?>... attributes); @Override Long countLike(E example, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override PK getPrimaryKey(E entity); @Override @RequiresTransaction void remove(E entity); @Override @RequiresTransaction void removeAndFlush(E entity); @Override @RequiresTransaction void attachAndRemove(E entity); @Override @RequiresTransaction void flush(); EntityManager entityManager(); CriteriaQuery<E> criteriaQuery(); TypedQuery<E> typedQuery(String qlString); @SuppressWarnings("unchecked") Class<E> entityClass(); String tableName(); String entityName(); }
@Test public void should_save_and_flush() throws Exception { Simple simple = new Simple("test"); simple = repo.saveAndFlush(simple); Simple fetch = (Simple) getEntityManager() .createNativeQuery("select * from SIMPLE_TABLE where id = ?", Simple.class) .setParameter(1, simple.getId()) .getSingleResult(); assertEquals(simple.getId(), fetch.getId()); }
@Override @RequiresTransaction public E saveAndFlush(E entity) { E result = save(entity); flush(); return result; }
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @Override @RequiresTransaction public E saveAndFlush(E entity) { E result = save(entity); flush(); return result; } }
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @Override @RequiresTransaction public E saveAndFlush(E entity) { E result = save(entity); flush(); return result; } }
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @Override @RequiresTransaction public E saveAndFlush(E entity) { E result = save(entity); flush(); return result; } @Override @RequiresTransaction E save(E entity); @Override @RequiresTransaction E saveAndFlush(E entity); @Override @RequiresTransaction E saveAndFlushAndRefresh(E entity); @Override @RequiresTransaction void refresh(E entity); @Override E findBy(PK primaryKey); @Override Optional<E> findOptionalBy(PK primaryKey); @Override List<E> findBy(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findBy(E example, int start, int max, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, int start, int max, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override List<E> findAll(); @SuppressWarnings("unchecked") @Override List<E> findAll(int start, int max); @Override Long count(); @Override Long count(E example, SingularAttribute<E, ?>... attributes); @Override Long countLike(E example, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override PK getPrimaryKey(E entity); @Override @RequiresTransaction void remove(E entity); @Override @RequiresTransaction void removeAndFlush(E entity); @Override @RequiresTransaction void attachAndRemove(E entity); @Override @RequiresTransaction void flush(); EntityManager entityManager(); CriteriaQuery<E> criteriaQuery(); TypedQuery<E> typedQuery(String qlString); @SuppressWarnings("unchecked") Class<E> entityClass(); String tableName(); String entityName(); }
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @Override @RequiresTransaction public E saveAndFlush(E entity) { E result = save(entity); flush(); return result; } @Override @RequiresTransaction E save(E entity); @Override @RequiresTransaction E saveAndFlush(E entity); @Override @RequiresTransaction E saveAndFlushAndRefresh(E entity); @Override @RequiresTransaction void refresh(E entity); @Override E findBy(PK primaryKey); @Override Optional<E> findOptionalBy(PK primaryKey); @Override List<E> findBy(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findBy(E example, int start, int max, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, int start, int max, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override List<E> findAll(); @SuppressWarnings("unchecked") @Override List<E> findAll(int start, int max); @Override Long count(); @Override Long count(E example, SingularAttribute<E, ?>... attributes); @Override Long countLike(E example, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override PK getPrimaryKey(E entity); @Override @RequiresTransaction void remove(E entity); @Override @RequiresTransaction void removeAndFlush(E entity); @Override @RequiresTransaction void attachAndRemove(E entity); @Override @RequiresTransaction void flush(); EntityManager entityManager(); CriteriaQuery<E> criteriaQuery(); TypedQuery<E> typedQuery(String qlString); @SuppressWarnings("unchecked") Class<E> entityClass(); String tableName(); String entityName(); }
@Test public void should_save_with_string_id() { SimpleStringId foo = new SimpleStringId("foo", "bar"); foo = stringIdRepo.save(foo); assertNotNull(foo); }
@Override @RequiresTransaction public E save(E entity) { if (context.isNew(entity)) { entityManager().persist(entity); return entity; } return entityManager().merge(entity); }
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @Override @RequiresTransaction public E save(E entity) { if (context.isNew(entity)) { entityManager().persist(entity); return entity; } return entityManager().merge(entity); } }
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @Override @RequiresTransaction public E save(E entity) { if (context.isNew(entity)) { entityManager().persist(entity); return entity; } return entityManager().merge(entity); } }
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @Override @RequiresTransaction public E save(E entity) { if (context.isNew(entity)) { entityManager().persist(entity); return entity; } return entityManager().merge(entity); } @Override @RequiresTransaction E save(E entity); @Override @RequiresTransaction E saveAndFlush(E entity); @Override @RequiresTransaction E saveAndFlushAndRefresh(E entity); @Override @RequiresTransaction void refresh(E entity); @Override E findBy(PK primaryKey); @Override Optional<E> findOptionalBy(PK primaryKey); @Override List<E> findBy(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findBy(E example, int start, int max, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, int start, int max, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override List<E> findAll(); @SuppressWarnings("unchecked") @Override List<E> findAll(int start, int max); @Override Long count(); @Override Long count(E example, SingularAttribute<E, ?>... attributes); @Override Long countLike(E example, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override PK getPrimaryKey(E entity); @Override @RequiresTransaction void remove(E entity); @Override @RequiresTransaction void removeAndFlush(E entity); @Override @RequiresTransaction void attachAndRemove(E entity); @Override @RequiresTransaction void flush(); EntityManager entityManager(); CriteriaQuery<E> criteriaQuery(); TypedQuery<E> typedQuery(String qlString); @SuppressWarnings("unchecked") Class<E> entityClass(); String tableName(); String entityName(); }
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @Override @RequiresTransaction public E save(E entity) { if (context.isNew(entity)) { entityManager().persist(entity); return entity; } return entityManager().merge(entity); } @Override @RequiresTransaction E save(E entity); @Override @RequiresTransaction E saveAndFlush(E entity); @Override @RequiresTransaction E saveAndFlushAndRefresh(E entity); @Override @RequiresTransaction void refresh(E entity); @Override E findBy(PK primaryKey); @Override Optional<E> findOptionalBy(PK primaryKey); @Override List<E> findBy(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findBy(E example, int start, int max, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, int start, int max, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override List<E> findAll(); @SuppressWarnings("unchecked") @Override List<E> findAll(int start, int max); @Override Long count(); @Override Long count(E example, SingularAttribute<E, ?>... attributes); @Override Long countLike(E example, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override PK getPrimaryKey(E entity); @Override @RequiresTransaction void remove(E entity); @Override @RequiresTransaction void removeAndFlush(E entity); @Override @RequiresTransaction void attachAndRemove(E entity); @Override @RequiresTransaction void flush(); EntityManager entityManager(); CriteriaQuery<E> criteriaQuery(); TypedQuery<E> typedQuery(String qlString); @SuppressWarnings("unchecked") Class<E> entityClass(); String tableName(); String entityName(); }
@Test public void should_refresh() throws Exception { final String name = "testRefresh"; Simple simple = testData.createSimple(name); simple.setName("override"); repo.refresh(simple); assertEquals(name, simple.getName()); }
@Override @RequiresTransaction public void refresh(E entity) { entityManager().refresh(entity); }
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @Override @RequiresTransaction public void refresh(E entity) { entityManager().refresh(entity); } }
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @Override @RequiresTransaction public void refresh(E entity) { entityManager().refresh(entity); } }
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @Override @RequiresTransaction public void refresh(E entity) { entityManager().refresh(entity); } @Override @RequiresTransaction E save(E entity); @Override @RequiresTransaction E saveAndFlush(E entity); @Override @RequiresTransaction E saveAndFlushAndRefresh(E entity); @Override @RequiresTransaction void refresh(E entity); @Override E findBy(PK primaryKey); @Override Optional<E> findOptionalBy(PK primaryKey); @Override List<E> findBy(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findBy(E example, int start, int max, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, int start, int max, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override List<E> findAll(); @SuppressWarnings("unchecked") @Override List<E> findAll(int start, int max); @Override Long count(); @Override Long count(E example, SingularAttribute<E, ?>... attributes); @Override Long countLike(E example, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override PK getPrimaryKey(E entity); @Override @RequiresTransaction void remove(E entity); @Override @RequiresTransaction void removeAndFlush(E entity); @Override @RequiresTransaction void attachAndRemove(E entity); @Override @RequiresTransaction void flush(); EntityManager entityManager(); CriteriaQuery<E> criteriaQuery(); TypedQuery<E> typedQuery(String qlString); @SuppressWarnings("unchecked") Class<E> entityClass(); String tableName(); String entityName(); }
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @Override @RequiresTransaction public void refresh(E entity) { entityManager().refresh(entity); } @Override @RequiresTransaction E save(E entity); @Override @RequiresTransaction E saveAndFlush(E entity); @Override @RequiresTransaction E saveAndFlushAndRefresh(E entity); @Override @RequiresTransaction void refresh(E entity); @Override E findBy(PK primaryKey); @Override Optional<E> findOptionalBy(PK primaryKey); @Override List<E> findBy(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findBy(E example, int start, int max, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, int start, int max, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override List<E> findAll(); @SuppressWarnings("unchecked") @Override List<E> findAll(int start, int max); @Override Long count(); @Override Long count(E example, SingularAttribute<E, ?>... attributes); @Override Long countLike(E example, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override PK getPrimaryKey(E entity); @Override @RequiresTransaction void remove(E entity); @Override @RequiresTransaction void removeAndFlush(E entity); @Override @RequiresTransaction void attachAndRemove(E entity); @Override @RequiresTransaction void flush(); EntityManager entityManager(); CriteriaQuery<E> criteriaQuery(); TypedQuery<E> typedQuery(String qlString); @SuppressWarnings("unchecked") Class<E> entityClass(); String tableName(); String entityName(); }
@Test public void shouldRegisterPlugin() throws Exception { PluginReqisterQuery pluginReqisterQuery = new PluginReqisterQuery(); pluginReqisterQuery.setReturnCommands(true); pluginReqisterQuery.setReturnUpdatedCommands(true); pluginReqisterQuery.setReturnNotifications(true); PluginUpdate pluginUpdate = new PluginUpdate(); given(webSocketKafkaProxyConfig.getProxyPluginConnect()).willReturn(PROXY_PLUGIN_ENDPOINT); given(httpRestHelper.post(any(), any(), any(), any())).willReturn(createJwtTokenVO(ACCESS_TOKEN, REFRESH_TOKEN)); doAnswer(invocation -> { Object[] args = invocation.getArguments(); Request request = (Request)args[0]; ResponseConsumer responseConsumer = (ResponseConsumer)args[1]; responseConsumer.accept(Response.newBuilder() .withBody(request.getBody()) .buildSuccess()); return null; }).when(rpcClient).call(any(), any()); JsonObject actual = (JsonObject) pluginRegisterService.register(1L, pluginReqisterQuery, pluginUpdate, AUTHORIZATION).join().getEntity(); assertEquals(actual.get(ACCESS_TOKEN).getAsString(), ACCESS_TOKEN); assertEquals(actual.get(REFRESH_TOKEN).getAsString(), REFRESH_TOKEN); assertEquals(actual.get(PROXY_PLUGIN_ENDPOINT).getAsString(), PROXY_PLUGIN_ENDPOINT); verify(rpcClient, times(0)).call(any(), any()); }
public CompletableFuture<Response> register(Long userId, PluginReqisterQuery pluginReqisterQuery, PluginUpdate pluginUpdate, String authorization) { validateSubscription(pluginReqisterQuery); checkAuthServiceAvailable(); return persistPlugin(pluginUpdate, pluginReqisterQuery.constructFilterString(), userId).thenApply(pluginVO -> { JwtTokenVO jwtTokenVO = createPluginTokens(pluginVO.getTopicName(), authorization); JsonObject response = createTokenResponse(pluginVO.getTopicName(), jwtTokenVO); return ResponseFactory.response(CREATED, response, PLUGIN_SUBMITTED); }); }
PluginRegisterService { public CompletableFuture<Response> register(Long userId, PluginReqisterQuery pluginReqisterQuery, PluginUpdate pluginUpdate, String authorization) { validateSubscription(pluginReqisterQuery); checkAuthServiceAvailable(); return persistPlugin(pluginUpdate, pluginReqisterQuery.constructFilterString(), userId).thenApply(pluginVO -> { JwtTokenVO jwtTokenVO = createPluginTokens(pluginVO.getTopicName(), authorization); JsonObject response = createTokenResponse(pluginVO.getTopicName(), jwtTokenVO); return ResponseFactory.response(CREATED, response, PLUGIN_SUBMITTED); }); } }
PluginRegisterService { public CompletableFuture<Response> register(Long userId, PluginReqisterQuery pluginReqisterQuery, PluginUpdate pluginUpdate, String authorization) { validateSubscription(pluginReqisterQuery); checkAuthServiceAvailable(); return persistPlugin(pluginUpdate, pluginReqisterQuery.constructFilterString(), userId).thenApply(pluginVO -> { JwtTokenVO jwtTokenVO = createPluginTokens(pluginVO.getTopicName(), authorization); JsonObject response = createTokenResponse(pluginVO.getTopicName(), jwtTokenVO); return ResponseFactory.response(CREATED, response, PLUGIN_SUBMITTED); }); } @Autowired PluginRegisterService( HiveValidator hiveValidator, PluginService pluginService, FilterService filterService, RpcClient rpcClient, KafkaTopicService kafkaTopicService, LongIdGenerator idGenerator, HttpRestHelper httpRestHelper, WebSocketKafkaProxyConfig webSocketKafkaProxyConfig, Gson gson); }
PluginRegisterService { public CompletableFuture<Response> register(Long userId, PluginReqisterQuery pluginReqisterQuery, PluginUpdate pluginUpdate, String authorization) { validateSubscription(pluginReqisterQuery); checkAuthServiceAvailable(); return persistPlugin(pluginUpdate, pluginReqisterQuery.constructFilterString(), userId).thenApply(pluginVO -> { JwtTokenVO jwtTokenVO = createPluginTokens(pluginVO.getTopicName(), authorization); JsonObject response = createTokenResponse(pluginVO.getTopicName(), jwtTokenVO); return ResponseFactory.response(CREATED, response, PLUGIN_SUBMITTED); }); } @Autowired PluginRegisterService( HiveValidator hiveValidator, PluginService pluginService, FilterService filterService, RpcClient rpcClient, KafkaTopicService kafkaTopicService, LongIdGenerator idGenerator, HttpRestHelper httpRestHelper, WebSocketKafkaProxyConfig webSocketKafkaProxyConfig, Gson gson); CompletableFuture<Response> register(Long userId, PluginReqisterQuery pluginReqisterQuery, PluginUpdate pluginUpdate, String authorization); @Transactional CompletableFuture<Response> update(PluginVO existingPlugin, PluginUpdateQuery pluginUpdateQuery); @Transactional CompletableFuture<Response> delete(PluginVO existingPlugin); CompletableFuture<List<PluginVO>> list(String name, String namePattern, String topicName, Integer status, Long userId, String sortField, String sortOrderSt, Integer take, Integer skip, HivePrincipal principal); CompletableFuture<List<PluginVO>> list(ListPluginRequest listPluginRequest); CompletableFuture<EntityCountResponse> count(String name, String namePattern, String topicName, Integer status, Long userId, HivePrincipal principal); CompletableFuture<EntityCountResponse> count(CountPluginRequest countPluginRequest); }
PluginRegisterService { public CompletableFuture<Response> register(Long userId, PluginReqisterQuery pluginReqisterQuery, PluginUpdate pluginUpdate, String authorization) { validateSubscription(pluginReqisterQuery); checkAuthServiceAvailable(); return persistPlugin(pluginUpdate, pluginReqisterQuery.constructFilterString(), userId).thenApply(pluginVO -> { JwtTokenVO jwtTokenVO = createPluginTokens(pluginVO.getTopicName(), authorization); JsonObject response = createTokenResponse(pluginVO.getTopicName(), jwtTokenVO); return ResponseFactory.response(CREATED, response, PLUGIN_SUBMITTED); }); } @Autowired PluginRegisterService( HiveValidator hiveValidator, PluginService pluginService, FilterService filterService, RpcClient rpcClient, KafkaTopicService kafkaTopicService, LongIdGenerator idGenerator, HttpRestHelper httpRestHelper, WebSocketKafkaProxyConfig webSocketKafkaProxyConfig, Gson gson); CompletableFuture<Response> register(Long userId, PluginReqisterQuery pluginReqisterQuery, PluginUpdate pluginUpdate, String authorization); @Transactional CompletableFuture<Response> update(PluginVO existingPlugin, PluginUpdateQuery pluginUpdateQuery); @Transactional CompletableFuture<Response> delete(PluginVO existingPlugin); CompletableFuture<List<PluginVO>> list(String name, String namePattern, String topicName, Integer status, Long userId, String sortField, String sortOrderSt, Integer take, Integer skip, HivePrincipal principal); CompletableFuture<List<PluginVO>> list(ListPluginRequest listPluginRequest); CompletableFuture<EntityCountResponse> count(String name, String namePattern, String topicName, Integer status, Long userId, HivePrincipal principal); CompletableFuture<EntityCountResponse> count(CountPluginRequest countPluginRequest); }
@Test public void findingInvalidFieldsReturnsInvalidOnes() { assertThat(formController.findInvalidFields()).containsExactly(INVALID_FIELD); }
protected List<FormFieldController> findInvalidFields() { return subscribedFields.values().stream().filter(not(FormFieldController::isValid)).collect(Collectors.toList()); }
FormController implements FxmlController { protected List<FormFieldController> findInvalidFields() { return subscribedFields.values().stream().filter(not(FormFieldController::isValid)).collect(Collectors.toList()); } }
FormController implements FxmlController { protected List<FormFieldController> findInvalidFields() { return subscribedFields.values().stream().filter(not(FormFieldController::isValid)).collect(Collectors.toList()); } }
FormController implements FxmlController { protected List<FormFieldController> findInvalidFields() { return subscribedFields.values().stream().filter(not(FormFieldController::isValid)).collect(Collectors.toList()); } void subscribeToField(FormFieldController formField); void unsubscribeToField(FormFieldController formField); T getField(String formFieldName); abstract void submit(); }
FormController implements FxmlController { protected List<FormFieldController> findInvalidFields() { return subscribedFields.values().stream().filter(not(FormFieldController::isValid)).collect(Collectors.toList()); } void subscribeToField(FormFieldController formField); void unsubscribeToField(FormFieldController formField); T getField(String formFieldName); abstract void submit(); }
@Test public void stageOf() throws ExecutionException, InterruptedException { final Pane newPane = new Pane(); Stages.stageOf(stageTitle, newPane) .thenAccept(stage -> { assertThat(stage.getScene().getRoot()).isEqualTo(newPane); assertThat(stage.getTitle()).isEqualTo(stageTitle); }) .toCompletableFuture().get(); }
public static CompletionStage<Stage> stageOf(final String title, final Pane rootPane) { return FxAsync.computeOnFxThread( Tuple.of(title, rootPane), titleAndPane -> { final Stage stage = new Stage(StageStyle.DECORATED); stage.setTitle(title); stage.setScene(new Scene(rootPane)); return stage; } ); }
Stages { public static CompletionStage<Stage> stageOf(final String title, final Pane rootPane) { return FxAsync.computeOnFxThread( Tuple.of(title, rootPane), titleAndPane -> { final Stage stage = new Stage(StageStyle.DECORATED); stage.setTitle(title); stage.setScene(new Scene(rootPane)); return stage; } ); } }
Stages { public static CompletionStage<Stage> stageOf(final String title, final Pane rootPane) { return FxAsync.computeOnFxThread( Tuple.of(title, rootPane), titleAndPane -> { final Stage stage = new Stage(StageStyle.DECORATED); stage.setTitle(title); stage.setScene(new Scene(rootPane)); return stage; } ); } private Stages(); }
Stages { public static CompletionStage<Stage> stageOf(final String title, final Pane rootPane) { return FxAsync.computeOnFxThread( Tuple.of(title, rootPane), titleAndPane -> { final Stage stage = new Stage(StageStyle.DECORATED); stage.setTitle(title); stage.setScene(new Scene(rootPane)); return stage; } ); } private Stages(); static CompletionStage<Stage> stageOf(final String title, final Pane rootPane); static CompletionStage<Stage> scheduleDisplaying(final Stage stage); static CompletionStage<Stage> scheduleDisplaying(final CompletionStage<Stage> stageCreationResult); static CompletionStage<Stage> scheduleHiding(final Stage stage); static CompletionStage<Stage> scheduleHiding(final CompletionStage<Stage> stageCreationResult); static CompletionStage<Stage> setStylesheet(final Stage stage, final String stylesheet); static CompletionStage<Stage> setStylesheet(final CompletionStage<Stage> stageCreationResult, final String stylesheet); static CompletionStage<Stage> setStylesheet(final Stage stage, final FxmlStylesheet stylesheet); static CompletionStage<Stage> setStylesheet(final CompletionStage<Stage> stageCreationResult, final FxmlStylesheet stylesheet); }
Stages { public static CompletionStage<Stage> stageOf(final String title, final Pane rootPane) { return FxAsync.computeOnFxThread( Tuple.of(title, rootPane), titleAndPane -> { final Stage stage = new Stage(StageStyle.DECORATED); stage.setTitle(title); stage.setScene(new Scene(rootPane)); return stage; } ); } private Stages(); static CompletionStage<Stage> stageOf(final String title, final Pane rootPane); static CompletionStage<Stage> scheduleDisplaying(final Stage stage); static CompletionStage<Stage> scheduleDisplaying(final CompletionStage<Stage> stageCreationResult); static CompletionStage<Stage> scheduleHiding(final Stage stage); static CompletionStage<Stage> scheduleHiding(final CompletionStage<Stage> stageCreationResult); static CompletionStage<Stage> setStylesheet(final Stage stage, final String stylesheet); static CompletionStage<Stage> setStylesheet(final CompletionStage<Stage> stageCreationResult, final String stylesheet); static CompletionStage<Stage> setStylesheet(final Stage stage, final FxmlStylesheet stylesheet); static CompletionStage<Stage> setStylesheet(final CompletionStage<Stage> stageCreationResult, final FxmlStylesheet stylesheet); }
@Test public void scheduleDisplaying() throws ExecutionException, InterruptedException { Stages.scheduleDisplaying(testStage) .thenAccept(stage -> assertThat(testStage.isShowing()).isTrue()) .toCompletableFuture().get(); }
public static CompletionStage<Stage> scheduleDisplaying(final Stage stage) { LOG.debug( "Requested displaying of stage {} with title : \"{}\"", stage, stage.getTitle() ); return FxAsync.doOnFxThread( stage, Stage::show ); }
Stages { public static CompletionStage<Stage> scheduleDisplaying(final Stage stage) { LOG.debug( "Requested displaying of stage {} with title : \"{}\"", stage, stage.getTitle() ); return FxAsync.doOnFxThread( stage, Stage::show ); } }
Stages { public static CompletionStage<Stage> scheduleDisplaying(final Stage stage) { LOG.debug( "Requested displaying of stage {} with title : \"{}\"", stage, stage.getTitle() ); return FxAsync.doOnFxThread( stage, Stage::show ); } private Stages(); }
Stages { public static CompletionStage<Stage> scheduleDisplaying(final Stage stage) { LOG.debug( "Requested displaying of stage {} with title : \"{}\"", stage, stage.getTitle() ); return FxAsync.doOnFxThread( stage, Stage::show ); } private Stages(); static CompletionStage<Stage> stageOf(final String title, final Pane rootPane); static CompletionStage<Stage> scheduleDisplaying(final Stage stage); static CompletionStage<Stage> scheduleDisplaying(final CompletionStage<Stage> stageCreationResult); static CompletionStage<Stage> scheduleHiding(final Stage stage); static CompletionStage<Stage> scheduleHiding(final CompletionStage<Stage> stageCreationResult); static CompletionStage<Stage> setStylesheet(final Stage stage, final String stylesheet); static CompletionStage<Stage> setStylesheet(final CompletionStage<Stage> stageCreationResult, final String stylesheet); static CompletionStage<Stage> setStylesheet(final Stage stage, final FxmlStylesheet stylesheet); static CompletionStage<Stage> setStylesheet(final CompletionStage<Stage> stageCreationResult, final FxmlStylesheet stylesheet); }
Stages { public static CompletionStage<Stage> scheduleDisplaying(final Stage stage) { LOG.debug( "Requested displaying of stage {} with title : \"{}\"", stage, stage.getTitle() ); return FxAsync.doOnFxThread( stage, Stage::show ); } private Stages(); static CompletionStage<Stage> stageOf(final String title, final Pane rootPane); static CompletionStage<Stage> scheduleDisplaying(final Stage stage); static CompletionStage<Stage> scheduleDisplaying(final CompletionStage<Stage> stageCreationResult); static CompletionStage<Stage> scheduleHiding(final Stage stage); static CompletionStage<Stage> scheduleHiding(final CompletionStage<Stage> stageCreationResult); static CompletionStage<Stage> setStylesheet(final Stage stage, final String stylesheet); static CompletionStage<Stage> setStylesheet(final CompletionStage<Stage> stageCreationResult, final String stylesheet); static CompletionStage<Stage> setStylesheet(final Stage stage, final FxmlStylesheet stylesheet); static CompletionStage<Stage> setStylesheet(final CompletionStage<Stage> stageCreationResult, final FxmlStylesheet stylesheet); }
@Test public void scheduleHiding() throws ExecutionException, InterruptedException { Stages.scheduleHiding(testStage) .thenAccept(stage -> assertThat(testStage.isShowing()).isFalse()) .toCompletableFuture().get(); }
public static CompletionStage<Stage> scheduleHiding(final Stage stage) { LOG.debug( "Requested hiding of stage {} with title : \"{}\"", stage, stage.getTitle() ); return FxAsync.doOnFxThread( stage, Stage::hide ); }
Stages { public static CompletionStage<Stage> scheduleHiding(final Stage stage) { LOG.debug( "Requested hiding of stage {} with title : \"{}\"", stage, stage.getTitle() ); return FxAsync.doOnFxThread( stage, Stage::hide ); } }
Stages { public static CompletionStage<Stage> scheduleHiding(final Stage stage) { LOG.debug( "Requested hiding of stage {} with title : \"{}\"", stage, stage.getTitle() ); return FxAsync.doOnFxThread( stage, Stage::hide ); } private Stages(); }
Stages { public static CompletionStage<Stage> scheduleHiding(final Stage stage) { LOG.debug( "Requested hiding of stage {} with title : \"{}\"", stage, stage.getTitle() ); return FxAsync.doOnFxThread( stage, Stage::hide ); } private Stages(); static CompletionStage<Stage> stageOf(final String title, final Pane rootPane); static CompletionStage<Stage> scheduleDisplaying(final Stage stage); static CompletionStage<Stage> scheduleDisplaying(final CompletionStage<Stage> stageCreationResult); static CompletionStage<Stage> scheduleHiding(final Stage stage); static CompletionStage<Stage> scheduleHiding(final CompletionStage<Stage> stageCreationResult); static CompletionStage<Stage> setStylesheet(final Stage stage, final String stylesheet); static CompletionStage<Stage> setStylesheet(final CompletionStage<Stage> stageCreationResult, final String stylesheet); static CompletionStage<Stage> setStylesheet(final Stage stage, final FxmlStylesheet stylesheet); static CompletionStage<Stage> setStylesheet(final CompletionStage<Stage> stageCreationResult, final FxmlStylesheet stylesheet); }
Stages { public static CompletionStage<Stage> scheduleHiding(final Stage stage) { LOG.debug( "Requested hiding of stage {} with title : \"{}\"", stage, stage.getTitle() ); return FxAsync.doOnFxThread( stage, Stage::hide ); } private Stages(); static CompletionStage<Stage> stageOf(final String title, final Pane rootPane); static CompletionStage<Stage> scheduleDisplaying(final Stage stage); static CompletionStage<Stage> scheduleDisplaying(final CompletionStage<Stage> stageCreationResult); static CompletionStage<Stage> scheduleHiding(final Stage stage); static CompletionStage<Stage> scheduleHiding(final CompletionStage<Stage> stageCreationResult); static CompletionStage<Stage> setStylesheet(final Stage stage, final String stylesheet); static CompletionStage<Stage> setStylesheet(final CompletionStage<Stage> stageCreationResult, final String stylesheet); static CompletionStage<Stage> setStylesheet(final Stage stage, final FxmlStylesheet stylesheet); static CompletionStage<Stage> setStylesheet(final CompletionStage<Stage> stageCreationResult, final FxmlStylesheet stylesheet); }
@Test public void setStylesheet() throws ExecutionException, InterruptedException { final CompletionStage<Stage> setStyleAsyncOp = Stages.setStylesheet(testStage, TEST_STYLE); final Stage stage = setStyleAsyncOp.toCompletableFuture().get(); final ObservableList<String> stylesheets = stage.getScene().getStylesheets(); assertThat(stylesheets).hasSize(1); assertThat(stylesheets).containsExactly(TEST_STYLE.getExternalForm()); }
public static CompletionStage<Stage> setStylesheet(final Stage stage, final String stylesheet) { LOG.info( "Setting stylesheet {} for stage {}({})", stylesheet, stage.toString(), stage.getTitle() ); return FxAsync.doOnFxThread( stage, theStage -> { final Scene stageScene = theStage.getScene(); stageScene.getStylesheets().clear(); stageScene.getStylesheets().add(stylesheet); } ); }
Stages { public static CompletionStage<Stage> setStylesheet(final Stage stage, final String stylesheet) { LOG.info( "Setting stylesheet {} for stage {}({})", stylesheet, stage.toString(), stage.getTitle() ); return FxAsync.doOnFxThread( stage, theStage -> { final Scene stageScene = theStage.getScene(); stageScene.getStylesheets().clear(); stageScene.getStylesheets().add(stylesheet); } ); } }
Stages { public static CompletionStage<Stage> setStylesheet(final Stage stage, final String stylesheet) { LOG.info( "Setting stylesheet {} for stage {}({})", stylesheet, stage.toString(), stage.getTitle() ); return FxAsync.doOnFxThread( stage, theStage -> { final Scene stageScene = theStage.getScene(); stageScene.getStylesheets().clear(); stageScene.getStylesheets().add(stylesheet); } ); } private Stages(); }
Stages { public static CompletionStage<Stage> setStylesheet(final Stage stage, final String stylesheet) { LOG.info( "Setting stylesheet {} for stage {}({})", stylesheet, stage.toString(), stage.getTitle() ); return FxAsync.doOnFxThread( stage, theStage -> { final Scene stageScene = theStage.getScene(); stageScene.getStylesheets().clear(); stageScene.getStylesheets().add(stylesheet); } ); } private Stages(); static CompletionStage<Stage> stageOf(final String title, final Pane rootPane); static CompletionStage<Stage> scheduleDisplaying(final Stage stage); static CompletionStage<Stage> scheduleDisplaying(final CompletionStage<Stage> stageCreationResult); static CompletionStage<Stage> scheduleHiding(final Stage stage); static CompletionStage<Stage> scheduleHiding(final CompletionStage<Stage> stageCreationResult); static CompletionStage<Stage> setStylesheet(final Stage stage, final String stylesheet); static CompletionStage<Stage> setStylesheet(final CompletionStage<Stage> stageCreationResult, final String stylesheet); static CompletionStage<Stage> setStylesheet(final Stage stage, final FxmlStylesheet stylesheet); static CompletionStage<Stage> setStylesheet(final CompletionStage<Stage> stageCreationResult, final FxmlStylesheet stylesheet); }
Stages { public static CompletionStage<Stage> setStylesheet(final Stage stage, final String stylesheet) { LOG.info( "Setting stylesheet {} for stage {}({})", stylesheet, stage.toString(), stage.getTitle() ); return FxAsync.doOnFxThread( stage, theStage -> { final Scene stageScene = theStage.getScene(); stageScene.getStylesheets().clear(); stageScene.getStylesheets().add(stylesheet); } ); } private Stages(); static CompletionStage<Stage> stageOf(final String title, final Pane rootPane); static CompletionStage<Stage> scheduleDisplaying(final Stage stage); static CompletionStage<Stage> scheduleDisplaying(final CompletionStage<Stage> stageCreationResult); static CompletionStage<Stage> scheduleHiding(final Stage stage); static CompletionStage<Stage> scheduleHiding(final CompletionStage<Stage> stageCreationResult); static CompletionStage<Stage> setStylesheet(final Stage stage, final String stylesheet); static CompletionStage<Stage> setStylesheet(final CompletionStage<Stage> stageCreationResult, final String stylesheet); static CompletionStage<Stage> setStylesheet(final Stage stage, final FxmlStylesheet stylesheet); static CompletionStage<Stage> setStylesheet(final CompletionStage<Stage> stageCreationResult, final FxmlStylesheet stylesheet); }
@Test public void setStylesheetPostAsync() throws ExecutionException, InterruptedException { Try.of(() -> testStage) .map(Stages::scheduleDisplaying) .map(cs -> Stages.setStylesheet(cs, TEST_STYLE)) .get() .toCompletableFuture() .get(); await().until(() -> testStage.getScene().getStylesheets().contains(TEST_STYLE.getExternalForm())); assertThat(testStage.getScene().getStylesheets()).containsExactly(TEST_STYLE.getExternalForm()); }
public static CompletionStage<Stage> setStylesheet(final Stage stage, final String stylesheet) { LOG.info( "Setting stylesheet {} for stage {}({})", stylesheet, stage.toString(), stage.getTitle() ); return FxAsync.doOnFxThread( stage, theStage -> { final Scene stageScene = theStage.getScene(); stageScene.getStylesheets().clear(); stageScene.getStylesheets().add(stylesheet); } ); }
Stages { public static CompletionStage<Stage> setStylesheet(final Stage stage, final String stylesheet) { LOG.info( "Setting stylesheet {} for stage {}({})", stylesheet, stage.toString(), stage.getTitle() ); return FxAsync.doOnFxThread( stage, theStage -> { final Scene stageScene = theStage.getScene(); stageScene.getStylesheets().clear(); stageScene.getStylesheets().add(stylesheet); } ); } }
Stages { public static CompletionStage<Stage> setStylesheet(final Stage stage, final String stylesheet) { LOG.info( "Setting stylesheet {} for stage {}({})", stylesheet, stage.toString(), stage.getTitle() ); return FxAsync.doOnFxThread( stage, theStage -> { final Scene stageScene = theStage.getScene(); stageScene.getStylesheets().clear(); stageScene.getStylesheets().add(stylesheet); } ); } private Stages(); }
Stages { public static CompletionStage<Stage> setStylesheet(final Stage stage, final String stylesheet) { LOG.info( "Setting stylesheet {} for stage {}({})", stylesheet, stage.toString(), stage.getTitle() ); return FxAsync.doOnFxThread( stage, theStage -> { final Scene stageScene = theStage.getScene(); stageScene.getStylesheets().clear(); stageScene.getStylesheets().add(stylesheet); } ); } private Stages(); static CompletionStage<Stage> stageOf(final String title, final Pane rootPane); static CompletionStage<Stage> scheduleDisplaying(final Stage stage); static CompletionStage<Stage> scheduleDisplaying(final CompletionStage<Stage> stageCreationResult); static CompletionStage<Stage> scheduleHiding(final Stage stage); static CompletionStage<Stage> scheduleHiding(final CompletionStage<Stage> stageCreationResult); static CompletionStage<Stage> setStylesheet(final Stage stage, final String stylesheet); static CompletionStage<Stage> setStylesheet(final CompletionStage<Stage> stageCreationResult, final String stylesheet); static CompletionStage<Stage> setStylesheet(final Stage stage, final FxmlStylesheet stylesheet); static CompletionStage<Stage> setStylesheet(final CompletionStage<Stage> stageCreationResult, final FxmlStylesheet stylesheet); }
Stages { public static CompletionStage<Stage> setStylesheet(final Stage stage, final String stylesheet) { LOG.info( "Setting stylesheet {} for stage {}({})", stylesheet, stage.toString(), stage.getTitle() ); return FxAsync.doOnFxThread( stage, theStage -> { final Scene stageScene = theStage.getScene(); stageScene.getStylesheets().clear(); stageScene.getStylesheets().add(stylesheet); } ); } private Stages(); static CompletionStage<Stage> stageOf(final String title, final Pane rootPane); static CompletionStage<Stage> scheduleDisplaying(final Stage stage); static CompletionStage<Stage> scheduleDisplaying(final CompletionStage<Stage> stageCreationResult); static CompletionStage<Stage> scheduleHiding(final Stage stage); static CompletionStage<Stage> scheduleHiding(final CompletionStage<Stage> stageCreationResult); static CompletionStage<Stage> setStylesheet(final Stage stage, final String stylesheet); static CompletionStage<Stage> setStylesheet(final CompletionStage<Stage> stageCreationResult, final String stylesheet); static CompletionStage<Stage> setStylesheet(final Stage stage, final FxmlStylesheet stylesheet); static CompletionStage<Stage> setStylesheet(final CompletionStage<Stage> stageCreationResult, final FxmlStylesheet stylesheet); }
@Test public void setContent() { assertThat(container.getChildren()) .hasSize(1) .hasOnlyElementsOfType(Button.class); embedded = new Pane(); Panes.setContent(container, embedded) .whenCompleteAsync((res, err) -> { assertThat(err).isNull(); assertThat(res).isNotNull(); assertThat(res).isEqualTo(container); assertThat(container.getChildren()) .hasSize(1) .hasOnlyElementsOfType(embedded.getClass()); }); }
public static <T extends Pane> CompletionStage<T> setContent(final T parent, final Node content) { return FxAsync.doOnFxThread(parent, parentNode -> { parentNode.getChildren().clear(); parentNode.getChildren().add(content); }); }
Panes { public static <T extends Pane> CompletionStage<T> setContent(final T parent, final Node content) { return FxAsync.doOnFxThread(parent, parentNode -> { parentNode.getChildren().clear(); parentNode.getChildren().add(content); }); } }
Panes { public static <T extends Pane> CompletionStage<T> setContent(final T parent, final Node content) { return FxAsync.doOnFxThread(parent, parentNode -> { parentNode.getChildren().clear(); parentNode.getChildren().add(content); }); } private Panes(); }
Panes { public static <T extends Pane> CompletionStage<T> setContent(final T parent, final Node content) { return FxAsync.doOnFxThread(parent, parentNode -> { parentNode.getChildren().clear(); parentNode.getChildren().add(content); }); } private Panes(); static CompletionStage<T> setContent(final T parent, final Node content); }
Panes { public static <T extends Pane> CompletionStage<T> setContent(final T parent, final Node content) { return FxAsync.doOnFxThread(parent, parentNode -> { parentNode.getChildren().clear(); parentNode.getChildren().add(content); }); } private Panes(); static CompletionStage<T> setContent(final T parent, final Node content); }
@Test public void shouldCallDirectlyIfSetWithValue() { final Object element = new Object(); final Property<Object> called = new SimpleObjectProperty<>(null); Properties.newPropertyWithCallback(() -> new SimpleObjectProperty<>(element), called::setValue); assertThat(called.getValue()).isSameAs(element); }
public static <T, P extends ObservableValue<T>> P newPropertyWithCallback(Supplier<P> propertyFactory, Consumer<T> callback) { final P property = propertyFactory.get(); whenPropertyIsSet(property, callback); return property; }
Properties { public static <T, P extends ObservableValue<T>> P newPropertyWithCallback(Supplier<P> propertyFactory, Consumer<T> callback) { final P property = propertyFactory.get(); whenPropertyIsSet(property, callback); return property; } }
Properties { public static <T, P extends ObservableValue<T>> P newPropertyWithCallback(Supplier<P> propertyFactory, Consumer<T> callback) { final P property = propertyFactory.get(); whenPropertyIsSet(property, callback); return property; } private Properties(); }
Properties { public static <T, P extends ObservableValue<T>> P newPropertyWithCallback(Supplier<P> propertyFactory, Consumer<T> callback) { final P property = propertyFactory.get(); whenPropertyIsSet(property, callback); return property; } private Properties(); static P newPropertyWithCallback(Supplier<P> propertyFactory, Consumer<T> callback); static void whenPropertyIsSet(P property, Consumer<T> doWhenSet); static void whenPropertyIsSet(P property, Function<A, B> adapter, Consumer<B> doWhenSet); static void bind(ObservableValue<S> from, Function<S, C> adapter, Property<C> to); static void whenPropertyIsSet(P property, Runnable doWhenSet); }
Properties { public static <T, P extends ObservableValue<T>> P newPropertyWithCallback(Supplier<P> propertyFactory, Consumer<T> callback) { final P property = propertyFactory.get(); whenPropertyIsSet(property, callback); return property; } private Properties(); static P newPropertyWithCallback(Supplier<P> propertyFactory, Consumer<T> callback); static void whenPropertyIsSet(P property, Consumer<T> doWhenSet); static void whenPropertyIsSet(P property, Function<A, B> adapter, Consumer<B> doWhenSet); static void bind(ObservableValue<S> from, Function<S, C> adapter, Property<C> to); static void whenPropertyIsSet(P property, Runnable doWhenSet); }
@Test public void shouldCallConsumerOnEverySetCall() { final Property<Integer> called = new SimpleObjectProperty<>(); final Property<Integer> property = Properties.newPropertyWithCallback(SimpleObjectProperty::new, called::setValue); assertThat(called.getValue()).isNull(); IntStream.range(0, 1000).forEach(value -> { property.setValue(value); assertThat(called.getValue()).isEqualTo(value); }); }
public static <T, P extends ObservableValue<T>> P newPropertyWithCallback(Supplier<P> propertyFactory, Consumer<T> callback) { final P property = propertyFactory.get(); whenPropertyIsSet(property, callback); return property; }
Properties { public static <T, P extends ObservableValue<T>> P newPropertyWithCallback(Supplier<P> propertyFactory, Consumer<T> callback) { final P property = propertyFactory.get(); whenPropertyIsSet(property, callback); return property; } }
Properties { public static <T, P extends ObservableValue<T>> P newPropertyWithCallback(Supplier<P> propertyFactory, Consumer<T> callback) { final P property = propertyFactory.get(); whenPropertyIsSet(property, callback); return property; } private Properties(); }
Properties { public static <T, P extends ObservableValue<T>> P newPropertyWithCallback(Supplier<P> propertyFactory, Consumer<T> callback) { final P property = propertyFactory.get(); whenPropertyIsSet(property, callback); return property; } private Properties(); static P newPropertyWithCallback(Supplier<P> propertyFactory, Consumer<T> callback); static void whenPropertyIsSet(P property, Consumer<T> doWhenSet); static void whenPropertyIsSet(P property, Function<A, B> adapter, Consumer<B> doWhenSet); static void bind(ObservableValue<S> from, Function<S, C> adapter, Property<C> to); static void whenPropertyIsSet(P property, Runnable doWhenSet); }
Properties { public static <T, P extends ObservableValue<T>> P newPropertyWithCallback(Supplier<P> propertyFactory, Consumer<T> callback) { final P property = propertyFactory.get(); whenPropertyIsSet(property, callback); return property; } private Properties(); static P newPropertyWithCallback(Supplier<P> propertyFactory, Consumer<T> callback); static void whenPropertyIsSet(P property, Consumer<T> doWhenSet); static void whenPropertyIsSet(P property, Function<A, B> adapter, Consumer<B> doWhenSet); static void bind(ObservableValue<S> from, Function<S, C> adapter, Property<C> to); static void whenPropertyIsSet(P property, Runnable doWhenSet); }
@Test public void awaitCallsDirectlyIfSet() { final Property<Object> valuedProp = new SimpleObjectProperty<>(new Object()); final Property<Object> listener = new SimpleObjectProperty<>(); whenPropertyIsSet(valuedProp, listener::setValue); assertThat(listener.getValue()).isEqualTo(valuedProp.getValue()); }
public static <T, P extends ObservableValue<T>> void whenPropertyIsSet(P property, Consumer<T> doWhenSet) { whenPropertyIsSet(property, () -> doWhenSet.accept(property.getValue())); }
Properties { public static <T, P extends ObservableValue<T>> void whenPropertyIsSet(P property, Consumer<T> doWhenSet) { whenPropertyIsSet(property, () -> doWhenSet.accept(property.getValue())); } }
Properties { public static <T, P extends ObservableValue<T>> void whenPropertyIsSet(P property, Consumer<T> doWhenSet) { whenPropertyIsSet(property, () -> doWhenSet.accept(property.getValue())); } private Properties(); }
Properties { public static <T, P extends ObservableValue<T>> void whenPropertyIsSet(P property, Consumer<T> doWhenSet) { whenPropertyIsSet(property, () -> doWhenSet.accept(property.getValue())); } private Properties(); static P newPropertyWithCallback(Supplier<P> propertyFactory, Consumer<T> callback); static void whenPropertyIsSet(P property, Consumer<T> doWhenSet); static void whenPropertyIsSet(P property, Function<A, B> adapter, Consumer<B> doWhenSet); static void bind(ObservableValue<S> from, Function<S, C> adapter, Property<C> to); static void whenPropertyIsSet(P property, Runnable doWhenSet); }
Properties { public static <T, P extends ObservableValue<T>> void whenPropertyIsSet(P property, Consumer<T> doWhenSet) { whenPropertyIsSet(property, () -> doWhenSet.accept(property.getValue())); } private Properties(); static P newPropertyWithCallback(Supplier<P> propertyFactory, Consumer<T> callback); static void whenPropertyIsSet(P property, Consumer<T> doWhenSet); static void whenPropertyIsSet(P property, Function<A, B> adapter, Consumer<B> doWhenSet); static void bind(ObservableValue<S> from, Function<S, C> adapter, Property<C> to); static void whenPropertyIsSet(P property, Runnable doWhenSet); }
@Test public void awaitCallsAwaitsSetIfNullOriginally() { final Property<Object> valuedProp = new SimpleObjectProperty<>(); final Property<Object> listener = new SimpleObjectProperty<>(); whenPropertyIsSet(valuedProp, listener::setValue); assertThat(listener.getValue()).isNull(); valuedProp.setValue(new Object()); assertThat(listener.getValue()).isEqualTo(valuedProp.getValue()); }
public static <T, P extends ObservableValue<T>> void whenPropertyIsSet(P property, Consumer<T> doWhenSet) { whenPropertyIsSet(property, () -> doWhenSet.accept(property.getValue())); }
Properties { public static <T, P extends ObservableValue<T>> void whenPropertyIsSet(P property, Consumer<T> doWhenSet) { whenPropertyIsSet(property, () -> doWhenSet.accept(property.getValue())); } }
Properties { public static <T, P extends ObservableValue<T>> void whenPropertyIsSet(P property, Consumer<T> doWhenSet) { whenPropertyIsSet(property, () -> doWhenSet.accept(property.getValue())); } private Properties(); }
Properties { public static <T, P extends ObservableValue<T>> void whenPropertyIsSet(P property, Consumer<T> doWhenSet) { whenPropertyIsSet(property, () -> doWhenSet.accept(property.getValue())); } private Properties(); static P newPropertyWithCallback(Supplier<P> propertyFactory, Consumer<T> callback); static void whenPropertyIsSet(P property, Consumer<T> doWhenSet); static void whenPropertyIsSet(P property, Function<A, B> adapter, Consumer<B> doWhenSet); static void bind(ObservableValue<S> from, Function<S, C> adapter, Property<C> to); static void whenPropertyIsSet(P property, Runnable doWhenSet); }
Properties { public static <T, P extends ObservableValue<T>> void whenPropertyIsSet(P property, Consumer<T> doWhenSet) { whenPropertyIsSet(property, () -> doWhenSet.accept(property.getValue())); } private Properties(); static P newPropertyWithCallback(Supplier<P> propertyFactory, Consumer<T> callback); static void whenPropertyIsSet(P property, Consumer<T> doWhenSet); static void whenPropertyIsSet(P property, Function<A, B> adapter, Consumer<B> doWhenSet); static void bind(ObservableValue<S> from, Function<S, C> adapter, Property<C> to); static void whenPropertyIsSet(P property, Runnable doWhenSet); }
@Test public void defaultValidationIsNoop() { final FormFieldController sampleFieldController = new FormFieldController() { @Override public void initialize() { } @Override public String getFieldName() { return "Sample"; } @Override public Object getFieldValue() { return null; } @Override public void onValid() { throw new RuntimeException("Should not be called by default!"); } @Override public void onInvalid(String reason) { throw new RuntimeException("Should not be called by default!"); } }; assertThat(sampleFieldController.validate(null)).isTrue(); }
public boolean validate(F fieldValue) { return true; }
FormFieldController implements FxmlController { public boolean validate(F fieldValue) { return true; } }
FormFieldController implements FxmlController { public boolean validate(F fieldValue) { return true; } }
FormFieldController implements FxmlController { public boolean validate(F fieldValue) { return true; } abstract String getFieldName(); abstract F getFieldValue(); boolean validate(F fieldValue); boolean isValid(); void onValid(); void onInvalid(String reason); }
FormFieldController implements FxmlController { public boolean validate(F fieldValue) { return true; } abstract String getFieldName(); abstract F getFieldValue(); boolean validate(F fieldValue); boolean isValid(); void onValid(); void onInvalid(String reason); }
@Test public void awaitShouldCallConsumerOnEverySetCall() { final Property<Integer> called = new SimpleObjectProperty<>(); final Property<Integer> property = new SimpleObjectProperty<>(); whenPropertyIsSet(property, called::setValue); assertThat(called.getValue()).isNull(); IntStream.range(0, 1000).forEach(value -> { property.setValue(value); assertThat(called.getValue()).isEqualTo(value); }); }
public static <T, P extends ObservableValue<T>> void whenPropertyIsSet(P property, Consumer<T> doWhenSet) { whenPropertyIsSet(property, () -> doWhenSet.accept(property.getValue())); }
Properties { public static <T, P extends ObservableValue<T>> void whenPropertyIsSet(P property, Consumer<T> doWhenSet) { whenPropertyIsSet(property, () -> doWhenSet.accept(property.getValue())); } }
Properties { public static <T, P extends ObservableValue<T>> void whenPropertyIsSet(P property, Consumer<T> doWhenSet) { whenPropertyIsSet(property, () -> doWhenSet.accept(property.getValue())); } private Properties(); }
Properties { public static <T, P extends ObservableValue<T>> void whenPropertyIsSet(P property, Consumer<T> doWhenSet) { whenPropertyIsSet(property, () -> doWhenSet.accept(property.getValue())); } private Properties(); static P newPropertyWithCallback(Supplier<P> propertyFactory, Consumer<T> callback); static void whenPropertyIsSet(P property, Consumer<T> doWhenSet); static void whenPropertyIsSet(P property, Function<A, B> adapter, Consumer<B> doWhenSet); static void bind(ObservableValue<S> from, Function<S, C> adapter, Property<C> to); static void whenPropertyIsSet(P property, Runnable doWhenSet); }
Properties { public static <T, P extends ObservableValue<T>> void whenPropertyIsSet(P property, Consumer<T> doWhenSet) { whenPropertyIsSet(property, () -> doWhenSet.accept(property.getValue())); } private Properties(); static P newPropertyWithCallback(Supplier<P> propertyFactory, Consumer<T> callback); static void whenPropertyIsSet(P property, Consumer<T> doWhenSet); static void whenPropertyIsSet(P property, Function<A, B> adapter, Consumer<B> doWhenSet); static void bind(ObservableValue<S> from, Function<S, C> adapter, Property<C> to); static void whenPropertyIsSet(P property, Runnable doWhenSet); }
@Test public void path_of_existing_file() { final Try<Path> fileThatExists = Resources.getResourcePath( PATH_UTIL_TESTS_FOLDER + EXISTING_FILE_NAME ); assertThat(fileThatExists.isSuccess()).isTrue(); fileThatExists.mapTry(Files::readAllLines).onSuccess( content -> assertThat(content) .hasSize(1) .containsExactly(EXISTING_FILE_CONTENT) ); }
public static Try<Path> getResourcePath(final String resourceRelativePath) { return Try.of(() -> new ClassPathResource(resourceRelativePath)) .filter(ClassPathResource::exists) .map(ClassPathResource::getPath) .map(Paths::get); }
Resources { public static Try<Path> getResourcePath(final String resourceRelativePath) { return Try.of(() -> new ClassPathResource(resourceRelativePath)) .filter(ClassPathResource::exists) .map(ClassPathResource::getPath) .map(Paths::get); } }
Resources { public static Try<Path> getResourcePath(final String resourceRelativePath) { return Try.of(() -> new ClassPathResource(resourceRelativePath)) .filter(ClassPathResource::exists) .map(ClassPathResource::getPath) .map(Paths::get); } private Resources(); }
Resources { public static Try<Path> getResourcePath(final String resourceRelativePath) { return Try.of(() -> new ClassPathResource(resourceRelativePath)) .filter(ClassPathResource::exists) .map(ClassPathResource::getPath) .map(Paths::get); } private Resources(); static Try<Path> getResourcePath(final String resourceRelativePath); static Try<URL> getResourceURL(final String resourceRelativePath); static Either<Seq<Throwable>, Seq<Path>> listFiles(Path directory); }
Resources { public static Try<Path> getResourcePath(final String resourceRelativePath) { return Try.of(() -> new ClassPathResource(resourceRelativePath)) .filter(ClassPathResource::exists) .map(ClassPathResource::getPath) .map(Paths::get); } private Resources(); static Try<Path> getResourcePath(final String resourceRelativePath); static Try<URL> getResourceURL(final String resourceRelativePath); static Either<Seq<Throwable>, Seq<Path>> listFiles(Path directory); static final PathMatchingResourcePatternResolver PATH_MATCHING_RESOURCE_RESOLVER; }
@Test public void getResourcePath_should_display_path_tried() { final Try<Path> fileThatDoesntExist = Resources.getResourcePath( PATH_UTIL_TESTS_FOLDER + NONEXISTING_FILE_NAME ); assertThat(fileThatDoesntExist.isFailure()).isTrue(); assertThat(fileThatDoesntExist.getCause().getMessage()).contains(PATH_UTIL_TESTS_FOLDER + NONEXISTING_FILE_NAME); }
public static Try<Path> getResourcePath(final String resourceRelativePath) { return Try.of(() -> new ClassPathResource(resourceRelativePath)) .filter(ClassPathResource::exists) .map(ClassPathResource::getPath) .map(Paths::get); }
Resources { public static Try<Path> getResourcePath(final String resourceRelativePath) { return Try.of(() -> new ClassPathResource(resourceRelativePath)) .filter(ClassPathResource::exists) .map(ClassPathResource::getPath) .map(Paths::get); } }
Resources { public static Try<Path> getResourcePath(final String resourceRelativePath) { return Try.of(() -> new ClassPathResource(resourceRelativePath)) .filter(ClassPathResource::exists) .map(ClassPathResource::getPath) .map(Paths::get); } private Resources(); }
Resources { public static Try<Path> getResourcePath(final String resourceRelativePath) { return Try.of(() -> new ClassPathResource(resourceRelativePath)) .filter(ClassPathResource::exists) .map(ClassPathResource::getPath) .map(Paths::get); } private Resources(); static Try<Path> getResourcePath(final String resourceRelativePath); static Try<URL> getResourceURL(final String resourceRelativePath); static Either<Seq<Throwable>, Seq<Path>> listFiles(Path directory); }
Resources { public static Try<Path> getResourcePath(final String resourceRelativePath) { return Try.of(() -> new ClassPathResource(resourceRelativePath)) .filter(ClassPathResource::exists) .map(ClassPathResource::getPath) .map(Paths::get); } private Resources(); static Try<Path> getResourcePath(final String resourceRelativePath); static Try<URL> getResourceURL(final String resourceRelativePath); static Either<Seq<Throwable>, Seq<Path>> listFiles(Path directory); static final PathMatchingResourcePatternResolver PATH_MATCHING_RESOURCE_RESOLVER; }
@Test public void getResourceURL_should_display_path_tried() { final Try<URL> fileThatDoesntExist = Resources.getResourceURL( PATH_UTIL_TESTS_FOLDER + NONEXISTING_FILE_NAME ); assertThat(fileThatDoesntExist.isFailure()).isTrue(); assertThat(fileThatDoesntExist.getCause().getMessage()).contains( PATH_UTIL_TESTS_FOLDER + NONEXISTING_FILE_NAME ); }
public static Try<URL> getResourceURL(final String resourceRelativePath) { return Try.of(() -> new ClassPathResource(resourceRelativePath)) .mapTry(ClassPathResource::getURL); }
Resources { public static Try<URL> getResourceURL(final String resourceRelativePath) { return Try.of(() -> new ClassPathResource(resourceRelativePath)) .mapTry(ClassPathResource::getURL); } }
Resources { public static Try<URL> getResourceURL(final String resourceRelativePath) { return Try.of(() -> new ClassPathResource(resourceRelativePath)) .mapTry(ClassPathResource::getURL); } private Resources(); }
Resources { public static Try<URL> getResourceURL(final String resourceRelativePath) { return Try.of(() -> new ClassPathResource(resourceRelativePath)) .mapTry(ClassPathResource::getURL); } private Resources(); static Try<Path> getResourcePath(final String resourceRelativePath); static Try<URL> getResourceURL(final String resourceRelativePath); static Either<Seq<Throwable>, Seq<Path>> listFiles(Path directory); }
Resources { public static Try<URL> getResourceURL(final String resourceRelativePath) { return Try.of(() -> new ClassPathResource(resourceRelativePath)) .mapTry(ClassPathResource::getURL); } private Resources(); static Try<Path> getResourcePath(final String resourceRelativePath); static Try<URL> getResourceURL(final String resourceRelativePath); static Either<Seq<Throwable>, Seq<Path>> listFiles(Path directory); static final PathMatchingResourcePatternResolver PATH_MATCHING_RESOURCE_RESOLVER; }
@Test public void asPane() { final Label errLabel = (Label) this.ERR_PANE.getChildren().filtered(node -> node instanceof Label).get(0); assertThat(errLabel.getText()).isEqualTo(this.EXCEPTION.getMessage()); }
public Pane asPane() { return this.asPane(this.exception.getMessage()); }
ExceptionHandler { public Pane asPane() { return this.asPane(this.exception.getMessage()); } }
ExceptionHandler { public Pane asPane() { return this.asPane(this.exception.getMessage()); } ExceptionHandler(final Throwable exception); }
ExceptionHandler { public Pane asPane() { return this.asPane(this.exception.getMessage()); } ExceptionHandler(final Throwable exception); Pane asPane(); Pane asPane(final String userReadableError); static Pane fromThrowable(final Throwable throwable); static CompletionStage<Stage> displayExceptionPane( final String title, final String readable, final Throwable exception ); }
ExceptionHandler { public Pane asPane() { return this.asPane(this.exception.getMessage()); } ExceptionHandler(final Throwable exception); Pane asPane(); Pane asPane(final String userReadableError); static Pane fromThrowable(final Throwable throwable); static CompletionStage<Stage> displayExceptionPane( final String title, final String readable, final Throwable exception ); }
@Test public void displayExceptionPane() throws ExecutionException, InterruptedException, TimeoutException { final CompletionStage<Stage> asyncDisplayedStage = ExceptionHandler.displayExceptionPane( this.EXCEPTION_TEXT, this.EXCEPTION_TEXT_READABLE, this.EXCEPTION ); final Stage errStage = asyncDisplayedStage.toCompletableFuture().get(5, TimeUnit.SECONDS); assertThat(errStage.isShowing()).isTrue(); }
public static CompletionStage<Stage> displayExceptionPane( final String title, final String readable, final Throwable exception ) { final Pane exceptionPane = new ExceptionHandler(exception).asPane(readable); final CompletionStage<Stage> exceptionStage = Stages.stageOf(title, exceptionPane); return exceptionStage.thenCompose(Stages::scheduleDisplaying); }
ExceptionHandler { public static CompletionStage<Stage> displayExceptionPane( final String title, final String readable, final Throwable exception ) { final Pane exceptionPane = new ExceptionHandler(exception).asPane(readable); final CompletionStage<Stage> exceptionStage = Stages.stageOf(title, exceptionPane); return exceptionStage.thenCompose(Stages::scheduleDisplaying); } }
ExceptionHandler { public static CompletionStage<Stage> displayExceptionPane( final String title, final String readable, final Throwable exception ) { final Pane exceptionPane = new ExceptionHandler(exception).asPane(readable); final CompletionStage<Stage> exceptionStage = Stages.stageOf(title, exceptionPane); return exceptionStage.thenCompose(Stages::scheduleDisplaying); } ExceptionHandler(final Throwable exception); }
ExceptionHandler { public static CompletionStage<Stage> displayExceptionPane( final String title, final String readable, final Throwable exception ) { final Pane exceptionPane = new ExceptionHandler(exception).asPane(readable); final CompletionStage<Stage> exceptionStage = Stages.stageOf(title, exceptionPane); return exceptionStage.thenCompose(Stages::scheduleDisplaying); } ExceptionHandler(final Throwable exception); Pane asPane(); Pane asPane(final String userReadableError); static Pane fromThrowable(final Throwable throwable); static CompletionStage<Stage> displayExceptionPane( final String title, final String readable, final Throwable exception ); }
ExceptionHandler { public static CompletionStage<Stage> displayExceptionPane( final String title, final String readable, final Throwable exception ) { final Pane exceptionPane = new ExceptionHandler(exception).asPane(readable); final CompletionStage<Stage> exceptionStage = Stages.stageOf(title, exceptionPane); return exceptionStage.thenCompose(Stages::scheduleDisplaying); } ExceptionHandler(final Throwable exception); Pane asPane(); Pane asPane(final String userReadableError); static Pane fromThrowable(final Throwable throwable); static CompletionStage<Stage> displayExceptionPane( final String title, final String readable, final Throwable exception ); }
@Test public void updateItem() { final AtomicBoolean initialized = new AtomicBoolean(false); final BooleanProperty readProp = new SimpleBooleanProperty(false); final AtomicReference<String> value = new AtomicReference<>(""); final Pane pane = new Pane(); final ComponentCellFxmlController<String> clvcc = new ComponentCellFxmlController<>() { @Override public void updateWithValue(String newValue) { value.set(newValue); } @Override public void selectedProperty(final BooleanExpression selected) { readProp.bind(selected); } @Override public void initialize() { if (initialized.get()) { throw new IllegalStateException("Double init!"); } initialized.set(true); } }; final TestListCell testListViewCell = new TestListCell(pane, clvcc); testListViewCell.updateItem("TEST", false); await().until(() -> value.get().equals("TEST")); testListViewCell.updateItem("TEST2", false); await().until(() -> value.get().equals("TEST2")); testListViewCell.updateItem(null, true); await().until(() -> value.get() == null); }
@Override protected void updateItem(final T item, final boolean empty) { super.updateItem(item, empty); if (item == null || empty) { setGraphic(null); setVisible(false); setManaged(false); } else { setVisible(true); setManaged(true); } Platform.runLater(() -> { cellController.updateWithValue(item); cellController.selectedProperty(selectedProperty()); if (getGraphic() == null) { setGraphic(cellNode); } }); }
ComponentListCell extends ListCell<T> { @Override protected void updateItem(final T item, final boolean empty) { super.updateItem(item, empty); if (item == null || empty) { setGraphic(null); setVisible(false); setManaged(false); } else { setVisible(true); setManaged(true); } Platform.runLater(() -> { cellController.updateWithValue(item); cellController.selectedProperty(selectedProperty()); if (getGraphic() == null) { setGraphic(cellNode); } }); } }
ComponentListCell extends ListCell<T> { @Override protected void updateItem(final T item, final boolean empty) { super.updateItem(item, empty); if (item == null || empty) { setGraphic(null); setVisible(false); setManaged(false); } else { setVisible(true); setManaged(true); } Platform.runLater(() -> { cellController.updateWithValue(item); cellController.selectedProperty(selectedProperty()); if (getGraphic() == null) { setGraphic(cellNode); } }); } ComponentListCell(final EasyFxml easyFxml, final FxmlComponent cellNode); @SuppressWarnings("unchecked") ComponentListCell(final FxmlLoadResult<Pane, ComponentCellFxmlController> loadResult); ComponentListCell(final Pane cellNode, final ComponentCellFxmlController<T> controller); }
ComponentListCell extends ListCell<T> { @Override protected void updateItem(final T item, final boolean empty) { super.updateItem(item, empty); if (item == null || empty) { setGraphic(null); setVisible(false); setManaged(false); } else { setVisible(true); setManaged(true); } Platform.runLater(() -> { cellController.updateWithValue(item); cellController.selectedProperty(selectedProperty()); if (getGraphic() == null) { setGraphic(cellNode); } }); } ComponentListCell(final EasyFxml easyFxml, final FxmlComponent cellNode); @SuppressWarnings("unchecked") ComponentListCell(final FxmlLoadResult<Pane, ComponentCellFxmlController> loadResult); ComponentListCell(final Pane cellNode, final ComponentCellFxmlController<T> controller); }
ComponentListCell extends ListCell<T> { @Override protected void updateItem(final T item, final boolean empty) { super.updateItem(item, empty); if (item == null || empty) { setGraphic(null); setVisible(false); setManaged(false); } else { setVisible(true); setManaged(true); } Platform.runLater(() -> { cellController.updateWithValue(item); cellController.selectedProperty(selectedProperty()); if (getGraphic() == null) { setGraphic(cellNode); } }); } ComponentListCell(final EasyFxml easyFxml, final FxmlComponent cellNode); @SuppressWarnings("unchecked") ComponentListCell(final FxmlLoadResult<Pane, ComponentCellFxmlController> loadResult); ComponentListCell(final Pane cellNode, final ComponentCellFxmlController<T> controller); }
@Test public void openUrl_good_url() { workaroundOpenJfxHavingAwfulBrowserSupport(() -> browserSupport.openUrl("https: }
public Try<Void> openUrl(final String url) { return Try.run(() -> hostServices.showDocument(url)) .onFailure(cause -> onException(cause, url)); }
BrowserSupport { public Try<Void> openUrl(final String url) { return Try.run(() -> hostServices.showDocument(url)) .onFailure(cause -> onException(cause, url)); } }
BrowserSupport { public Try<Void> openUrl(final String url) { return Try.run(() -> hostServices.showDocument(url)) .onFailure(cause -> onException(cause, url)); } @Autowired BrowserSupport(HostServices hostServices); }
BrowserSupport { public Try<Void> openUrl(final String url) { return Try.run(() -> hostServices.showDocument(url)) .onFailure(cause -> onException(cause, url)); } @Autowired BrowserSupport(HostServices hostServices); Try<Void> openUrl(final String url); Try<Void> openUrl(final URL url); }
BrowserSupport { public Try<Void> openUrl(final String url) { return Try.run(() -> hostServices.showDocument(url)) .onFailure(cause -> onException(cause, url)); } @Autowired BrowserSupport(HostServices hostServices); Try<Void> openUrl(final String url); Try<Void> openUrl(final URL url); }
@Test public void openUrl_bad_url() { workaroundOpenJfxHavingAwfulBrowserSupport(() -> { Try<Void> invalidUrlOpening = browserSupport.openUrl("not_a_url"); assertThat(invalidUrlOpening.isFailure()).isFalse(); }); }
public Try<Void> openUrl(final String url) { return Try.run(() -> hostServices.showDocument(url)) .onFailure(cause -> onException(cause, url)); }
BrowserSupport { public Try<Void> openUrl(final String url) { return Try.run(() -> hostServices.showDocument(url)) .onFailure(cause -> onException(cause, url)); } }
BrowserSupport { public Try<Void> openUrl(final String url) { return Try.run(() -> hostServices.showDocument(url)) .onFailure(cause -> onException(cause, url)); } @Autowired BrowserSupport(HostServices hostServices); }
BrowserSupport { public Try<Void> openUrl(final String url) { return Try.run(() -> hostServices.showDocument(url)) .onFailure(cause -> onException(cause, url)); } @Autowired BrowserSupport(HostServices hostServices); Try<Void> openUrl(final String url); Try<Void> openUrl(final URL url); }
BrowserSupport { public Try<Void> openUrl(final String url) { return Try.run(() -> hostServices.showDocument(url)) .onFailure(cause -> onException(cause, url)); } @Autowired BrowserSupport(HostServices hostServices); Try<Void> openUrl(final String url); Try<Void> openUrl(final URL url); }
@Test public void browse_ioe() { workaroundOpenJfxHavingAwfulBrowserSupport(() -> { Try<Void> nullUrlOpening = browserSupport.openUrl((URL) null); assertThat(nullUrlOpening.isFailure()).isTrue(); assertThat(nullUrlOpening.getCause()).isInstanceOf(NullPointerException.class); }); }
public Try<Void> openUrl(final String url) { return Try.run(() -> hostServices.showDocument(url)) .onFailure(cause -> onException(cause, url)); }
BrowserSupport { public Try<Void> openUrl(final String url) { return Try.run(() -> hostServices.showDocument(url)) .onFailure(cause -> onException(cause, url)); } }
BrowserSupport { public Try<Void> openUrl(final String url) { return Try.run(() -> hostServices.showDocument(url)) .onFailure(cause -> onException(cause, url)); } @Autowired BrowserSupport(HostServices hostServices); }
BrowserSupport { public Try<Void> openUrl(final String url) { return Try.run(() -> hostServices.showDocument(url)) .onFailure(cause -> onException(cause, url)); } @Autowired BrowserSupport(HostServices hostServices); Try<Void> openUrl(final String url); Try<Void> openUrl(final URL url); }
BrowserSupport { public Try<Void> openUrl(final String url) { return Try.run(() -> hostServices.showDocument(url)) .onFailure(cause -> onException(cause, url)); } @Autowired BrowserSupport(HostServices hostServices); Try<Void> openUrl(final String url); Try<Void> openUrl(final URL url); }
@Test public void validatesOnEveryPropertyChangeByDefault() { sampleFieldController.initialize(); assertThat(validationCount.get()).isEqualTo(0); sampleProp.setValue("new value"); assertThat(validationCount.get()).isEqualTo(1); }
@Override public void initialize() { validateValueOnChange(); }
StringFormFieldController extends FormFieldController<String> { @Override public void initialize() { validateValueOnChange(); } }
StringFormFieldController extends FormFieldController<String> { @Override public void initialize() { validateValueOnChange(); } }
StringFormFieldController extends FormFieldController<String> { @Override public void initialize() { validateValueOnChange(); } @Override void initialize(); abstract ObservableValue<String> getObservableValue(); @Override String getFieldValue(); }
StringFormFieldController extends FormFieldController<String> { @Override public void initialize() { validateValueOnChange(); } @Override void initialize(); abstract ObservableValue<String> getObservableValue(); @Override String getFieldValue(); }
@Test public void getNode() { assertThat(fxmlLoadResult.getNode().get()).isEqualTo(TEST_NODE); }
public Try<NODE> getNode() { return node; }
FxmlLoadResult implements Tuple { public Try<NODE> getNode() { return node; } }
FxmlLoadResult implements Tuple { public Try<NODE> getNode() { return node; } FxmlLoadResult(Try<NODE> node, Try<CONTROLLER> controller); }
FxmlLoadResult implements Tuple { public Try<NODE> getNode() { return node; } FxmlLoadResult(Try<NODE> node, Try<CONTROLLER> controller); FxmlLoadResult<NODE, CONTROLLER> afterNodeLoaded(final Consumer<NODE> onNodeLoaded); FxmlLoadResult<NODE, CONTROLLER> afterControllerLoaded(final Consumer<CONTROLLER> onControllerLoaded); Try<NODE> getNode(); Try<CONTROLLER> getController(); Try<Pane> orExceptionPane(); Pane getNodeOrExceptionPane(); @Override int arity(); @Override Seq<?> toSeq(); }
FxmlLoadResult implements Tuple { public Try<NODE> getNode() { return node; } FxmlLoadResult(Try<NODE> node, Try<CONTROLLER> controller); FxmlLoadResult<NODE, CONTROLLER> afterNodeLoaded(final Consumer<NODE> onNodeLoaded); FxmlLoadResult<NODE, CONTROLLER> afterControllerLoaded(final Consumer<CONTROLLER> onControllerLoaded); Try<NODE> getNode(); Try<CONTROLLER> getController(); Try<Pane> orExceptionPane(); Pane getNodeOrExceptionPane(); @Override int arity(); @Override Seq<?> toSeq(); }
@Test public void orExceptionPane() { final FxmlLoadResult<Node, FxmlController> loadResult = new FxmlLoadResult<>( Try.failure(new RuntimeException("TEST")), Try.failure(new RuntimeException("TEST")) ); assertThat(loadResult.orExceptionPane().isSuccess()).isTrue(); }
public Try<Pane> orExceptionPane() { return ((Try<Pane>) getNode()).recover(ExceptionHandler::fromThrowable); }
FxmlLoadResult implements Tuple { public Try<Pane> orExceptionPane() { return ((Try<Pane>) getNode()).recover(ExceptionHandler::fromThrowable); } }
FxmlLoadResult implements Tuple { public Try<Pane> orExceptionPane() { return ((Try<Pane>) getNode()).recover(ExceptionHandler::fromThrowable); } FxmlLoadResult(Try<NODE> node, Try<CONTROLLER> controller); }
FxmlLoadResult implements Tuple { public Try<Pane> orExceptionPane() { return ((Try<Pane>) getNode()).recover(ExceptionHandler::fromThrowable); } FxmlLoadResult(Try<NODE> node, Try<CONTROLLER> controller); FxmlLoadResult<NODE, CONTROLLER> afterNodeLoaded(final Consumer<NODE> onNodeLoaded); FxmlLoadResult<NODE, CONTROLLER> afterControllerLoaded(final Consumer<CONTROLLER> onControllerLoaded); Try<NODE> getNode(); Try<CONTROLLER> getController(); Try<Pane> orExceptionPane(); Pane getNodeOrExceptionPane(); @Override int arity(); @Override Seq<?> toSeq(); }
FxmlLoadResult implements Tuple { public Try<Pane> orExceptionPane() { return ((Try<Pane>) getNode()).recover(ExceptionHandler::fromThrowable); } FxmlLoadResult(Try<NODE> node, Try<CONTROLLER> controller); FxmlLoadResult<NODE, CONTROLLER> afterNodeLoaded(final Consumer<NODE> onNodeLoaded); FxmlLoadResult<NODE, CONTROLLER> afterControllerLoaded(final Consumer<CONTROLLER> onControllerLoaded); Try<NODE> getNode(); Try<CONTROLLER> getController(); Try<Pane> orExceptionPane(); Pane getNodeOrExceptionPane(); @Override int arity(); @Override Seq<?> toSeq(); }
@Test public void getController() { assertThat(fxmlLoadResult.getController().get()).isEqualTo(TEST_CONTROLLER); }
public Try<CONTROLLER> getController() { return controller; }
FxmlLoadResult implements Tuple { public Try<CONTROLLER> getController() { return controller; } }
FxmlLoadResult implements Tuple { public Try<CONTROLLER> getController() { return controller; } FxmlLoadResult(Try<NODE> node, Try<CONTROLLER> controller); }
FxmlLoadResult implements Tuple { public Try<CONTROLLER> getController() { return controller; } FxmlLoadResult(Try<NODE> node, Try<CONTROLLER> controller); FxmlLoadResult<NODE, CONTROLLER> afterNodeLoaded(final Consumer<NODE> onNodeLoaded); FxmlLoadResult<NODE, CONTROLLER> afterControllerLoaded(final Consumer<CONTROLLER> onControllerLoaded); Try<NODE> getNode(); Try<CONTROLLER> getController(); Try<Pane> orExceptionPane(); Pane getNodeOrExceptionPane(); @Override int arity(); @Override Seq<?> toSeq(); }
FxmlLoadResult implements Tuple { public Try<CONTROLLER> getController() { return controller; } FxmlLoadResult(Try<NODE> node, Try<CONTROLLER> controller); FxmlLoadResult<NODE, CONTROLLER> afterNodeLoaded(final Consumer<NODE> onNodeLoaded); FxmlLoadResult<NODE, CONTROLLER> afterControllerLoaded(final Consumer<CONTROLLER> onControllerLoaded); Try<NODE> getNode(); Try<CONTROLLER> getController(); Try<Pane> orExceptionPane(); Pane getNodeOrExceptionPane(); @Override int arity(); @Override Seq<?> toSeq(); }
@Test public void arity() { assertThat(fxmlLoadResult.arity()).isEqualTo(2); }
@Override public int arity() { return 2; }
FxmlLoadResult implements Tuple { @Override public int arity() { return 2; } }
FxmlLoadResult implements Tuple { @Override public int arity() { return 2; } FxmlLoadResult(Try<NODE> node, Try<CONTROLLER> controller); }
FxmlLoadResult implements Tuple { @Override public int arity() { return 2; } FxmlLoadResult(Try<NODE> node, Try<CONTROLLER> controller); FxmlLoadResult<NODE, CONTROLLER> afterNodeLoaded(final Consumer<NODE> onNodeLoaded); FxmlLoadResult<NODE, CONTROLLER> afterControllerLoaded(final Consumer<CONTROLLER> onControllerLoaded); Try<NODE> getNode(); Try<CONTROLLER> getController(); Try<Pane> orExceptionPane(); Pane getNodeOrExceptionPane(); @Override int arity(); @Override Seq<?> toSeq(); }
FxmlLoadResult implements Tuple { @Override public int arity() { return 2; } FxmlLoadResult(Try<NODE> node, Try<CONTROLLER> controller); FxmlLoadResult<NODE, CONTROLLER> afterNodeLoaded(final Consumer<NODE> onNodeLoaded); FxmlLoadResult<NODE, CONTROLLER> afterControllerLoaded(final Consumer<CONTROLLER> onControllerLoaded); Try<NODE> getNode(); Try<CONTROLLER> getController(); Try<Pane> orExceptionPane(); Pane getNodeOrExceptionPane(); @Override int arity(); @Override Seq<?> toSeq(); }
@Test public void toSeq() { assertThat( fxmlLoadResult.toSeq() .map(Try.class::cast) .map(Try::get) .toJavaList() ).containsExactlyInAnyOrder(TEST_NODE, TEST_CONTROLLER); }
@Override public Seq<?> toSeq() { return List.of(node, controller); }
FxmlLoadResult implements Tuple { @Override public Seq<?> toSeq() { return List.of(node, controller); } }
FxmlLoadResult implements Tuple { @Override public Seq<?> toSeq() { return List.of(node, controller); } FxmlLoadResult(Try<NODE> node, Try<CONTROLLER> controller); }
FxmlLoadResult implements Tuple { @Override public Seq<?> toSeq() { return List.of(node, controller); } FxmlLoadResult(Try<NODE> node, Try<CONTROLLER> controller); FxmlLoadResult<NODE, CONTROLLER> afterNodeLoaded(final Consumer<NODE> onNodeLoaded); FxmlLoadResult<NODE, CONTROLLER> afterControllerLoaded(final Consumer<CONTROLLER> onControllerLoaded); Try<NODE> getNode(); Try<CONTROLLER> getController(); Try<Pane> orExceptionPane(); Pane getNodeOrExceptionPane(); @Override int arity(); @Override Seq<?> toSeq(); }
FxmlLoadResult implements Tuple { @Override public Seq<?> toSeq() { return List.of(node, controller); } FxmlLoadResult(Try<NODE> node, Try<CONTROLLER> controller); FxmlLoadResult<NODE, CONTROLLER> afterNodeLoaded(final Consumer<NODE> onNodeLoaded); FxmlLoadResult<NODE, CONTROLLER> afterControllerLoaded(final Consumer<CONTROLLER> onControllerLoaded); Try<NODE> getNode(); Try<CONTROLLER> getController(); Try<Pane> orExceptionPane(); Pane getNodeOrExceptionPane(); @Override int arity(); @Override Seq<?> toSeq(); }
@Test public void onSuccess() { new FxmlLoader(context).onSuccess(null); assertThat(succ).isEqualTo(0); assertThat(fail).isEqualTo(0); fxmlLoader.onSuccess(null); assertThat(succ).isEqualTo(1); assertThat(fail).isEqualTo(0); }
public void onSuccess(final Node loadResult) { this.onSuccess.accept(loadResult); }
FxmlLoader extends FXMLLoader { public void onSuccess(final Node loadResult) { this.onSuccess.accept(loadResult); } }
FxmlLoader extends FXMLLoader { public void onSuccess(final Node loadResult) { this.onSuccess.accept(loadResult); } @Autowired FxmlLoader(ApplicationContext context); }
FxmlLoader extends FXMLLoader { public void onSuccess(final Node loadResult) { this.onSuccess.accept(loadResult); } @Autowired FxmlLoader(ApplicationContext context); void setOnSuccess(final Consumer<Node> onSuccess); void onSuccess(final Node loadResult); void setOnFailure(final Consumer<Throwable> onFailure); void onFailure(final Throwable cause); @Override boolean equals(Object o); @Override int hashCode(); }
FxmlLoader extends FXMLLoader { public void onSuccess(final Node loadResult) { this.onSuccess.accept(loadResult); } @Autowired FxmlLoader(ApplicationContext context); void setOnSuccess(final Consumer<Node> onSuccess); void onSuccess(final Node loadResult); void setOnFailure(final Consumer<Throwable> onFailure); void onFailure(final Throwable cause); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void onFailure() { new FxmlLoader(context).onFailure(null); assertThat(succ).isEqualTo(0); assertThat(fail).isEqualTo(0); fxmlLoader.onFailure(null); assertThat(succ).isEqualTo(0); assertThat(fail).isEqualTo(1); }
public void onFailure(final Throwable cause) { this.onFailure.accept(cause); }
FxmlLoader extends FXMLLoader { public void onFailure(final Throwable cause) { this.onFailure.accept(cause); } }
FxmlLoader extends FXMLLoader { public void onFailure(final Throwable cause) { this.onFailure.accept(cause); } @Autowired FxmlLoader(ApplicationContext context); }
FxmlLoader extends FXMLLoader { public void onFailure(final Throwable cause) { this.onFailure.accept(cause); } @Autowired FxmlLoader(ApplicationContext context); void setOnSuccess(final Consumer<Node> onSuccess); void onSuccess(final Node loadResult); void setOnFailure(final Consumer<Throwable> onFailure); void onFailure(final Throwable cause); @Override boolean equals(Object o); @Override int hashCode(); }
FxmlLoader extends FXMLLoader { public void onFailure(final Throwable cause) { this.onFailure.accept(cause); } @Autowired FxmlLoader(ApplicationContext context); void setOnSuccess(final Consumer<Node> onSuccess); void onSuccess(final Node loadResult); void setOnFailure(final Consumer<Throwable> onFailure); void onFailure(final Throwable cause); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void loadAsPaneSingle() throws InterruptedException, ExecutionException, TimeoutException { Pane testPane = this.assertSuccessAndGet(this.easyFxml.load(paneWithButtonComponent).getNode()); assertThat(testPane.getChildren()).hasSize(1); assertThat(testPane.getChildren().get(0).getClass()).isEqualTo(Button.class); this.assertControllerBoundToTestPane( testPane, this.controllerManager.getSingle(paneWithButtonComponent) ); }
@Override public FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component) { return this.load(component, Pane.class, FxmlController.class); }
DefaultEasyFxml implements EasyFxml { @Override public FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component) { return this.load(component, Pane.class, FxmlController.class); } }
DefaultEasyFxml implements EasyFxml { @Override public FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component) { return this.load(component, Pane.class, FxmlController.class); } @Autowired protected DefaultEasyFxml( final ApplicationContext context, final ControllerManager controllerManager, EasyFxmlProperties easyFxmlProperties ); }
DefaultEasyFxml implements EasyFxml { @Override public FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component) { return this.load(component, Pane.class, FxmlController.class); } @Autowired protected DefaultEasyFxml( final ApplicationContext context, final ControllerManager controllerManager, EasyFxmlProperties easyFxmlProperties ); @Override FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component); @Override FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component, final Selector selector); @Override FxmlLoadResult<NODE, CONTROLLER> load( final FxmlComponent component, final Class<? extends NODE> componentClass, final Class<? extends CONTROLLER> controllerClass ); @Override FxmlLoadResult<NODE, CONTROLLER> load( final FxmlComponent component, final Class<? extends NODE> nodeClass, final Class<? extends CONTROLLER> controllerClass, final Selector selector ); }
DefaultEasyFxml implements EasyFxml { @Override public FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component) { return this.load(component, Pane.class, FxmlController.class); } @Autowired protected DefaultEasyFxml( final ApplicationContext context, final ControllerManager controllerManager, EasyFxmlProperties easyFxmlProperties ); @Override FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component); @Override FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component, final Selector selector); @Override FxmlLoadResult<NODE, CONTROLLER> load( final FxmlComponent component, final Class<? extends NODE> componentClass, final Class<? extends CONTROLLER> controllerClass ); @Override FxmlLoadResult<NODE, CONTROLLER> load( final FxmlComponent component, final Class<? extends NODE> nodeClass, final Class<? extends CONTROLLER> controllerClass, final Selector selector ); }
@Test public void loadAsPaneMultiple() throws InterruptedException, ExecutionException, TimeoutException { Object selector = new Object(); Pane testPane = this.assertSuccessAndGet(this.easyFxml.load(paneWithButtonComponent, new Selector(selector)).getNode()); this.assertControllerBoundToTestPane( testPane, this.controllerManager.getMultiple(paneWithButtonComponent, new Selector(selector)) ); assertThat(testPane.getChildren()).hasSize(1); assertThat(testPane.getChildren().get(0).getClass()).isEqualTo(Button.class); }
@Override public FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component) { return this.load(component, Pane.class, FxmlController.class); }
DefaultEasyFxml implements EasyFxml { @Override public FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component) { return this.load(component, Pane.class, FxmlController.class); } }
DefaultEasyFxml implements EasyFxml { @Override public FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component) { return this.load(component, Pane.class, FxmlController.class); } @Autowired protected DefaultEasyFxml( final ApplicationContext context, final ControllerManager controllerManager, EasyFxmlProperties easyFxmlProperties ); }
DefaultEasyFxml implements EasyFxml { @Override public FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component) { return this.load(component, Pane.class, FxmlController.class); } @Autowired protected DefaultEasyFxml( final ApplicationContext context, final ControllerManager controllerManager, EasyFxmlProperties easyFxmlProperties ); @Override FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component); @Override FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component, final Selector selector); @Override FxmlLoadResult<NODE, CONTROLLER> load( final FxmlComponent component, final Class<? extends NODE> componentClass, final Class<? extends CONTROLLER> controllerClass ); @Override FxmlLoadResult<NODE, CONTROLLER> load( final FxmlComponent component, final Class<? extends NODE> nodeClass, final Class<? extends CONTROLLER> controllerClass, final Selector selector ); }
DefaultEasyFxml implements EasyFxml { @Override public FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component) { return this.load(component, Pane.class, FxmlController.class); } @Autowired protected DefaultEasyFxml( final ApplicationContext context, final ControllerManager controllerManager, EasyFxmlProperties easyFxmlProperties ); @Override FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component); @Override FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component, final Selector selector); @Override FxmlLoadResult<NODE, CONTROLLER> load( final FxmlComponent component, final Class<? extends NODE> componentClass, final Class<? extends CONTROLLER> controllerClass ); @Override FxmlLoadResult<NODE, CONTROLLER> load( final FxmlComponent component, final Class<? extends NODE> nodeClass, final Class<? extends CONTROLLER> controllerClass, final Selector selector ); }
@Test public void loadWithTypeSuccess() throws InterruptedException, ExecutionException, TimeoutException { Pane testPane = this.assertSuccessAndGet(this.easyFxml.load( paneWithButtonComponent, Pane.class, FxmlController.class ).getNode()); this.assertControllerBoundToTestPane( testPane, this.controllerManager.getSingle(paneWithButtonComponent) ); }
@Override public FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component) { return this.load(component, Pane.class, FxmlController.class); }
DefaultEasyFxml implements EasyFxml { @Override public FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component) { return this.load(component, Pane.class, FxmlController.class); } }
DefaultEasyFxml implements EasyFxml { @Override public FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component) { return this.load(component, Pane.class, FxmlController.class); } @Autowired protected DefaultEasyFxml( final ApplicationContext context, final ControllerManager controllerManager, EasyFxmlProperties easyFxmlProperties ); }
DefaultEasyFxml implements EasyFxml { @Override public FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component) { return this.load(component, Pane.class, FxmlController.class); } @Autowired protected DefaultEasyFxml( final ApplicationContext context, final ControllerManager controllerManager, EasyFxmlProperties easyFxmlProperties ); @Override FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component); @Override FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component, final Selector selector); @Override FxmlLoadResult<NODE, CONTROLLER> load( final FxmlComponent component, final Class<? extends NODE> componentClass, final Class<? extends CONTROLLER> controllerClass ); @Override FxmlLoadResult<NODE, CONTROLLER> load( final FxmlComponent component, final Class<? extends NODE> nodeClass, final Class<? extends CONTROLLER> controllerClass, final Selector selector ); }
DefaultEasyFxml implements EasyFxml { @Override public FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component) { return this.load(component, Pane.class, FxmlController.class); } @Autowired protected DefaultEasyFxml( final ApplicationContext context, final ControllerManager controllerManager, EasyFxmlProperties easyFxmlProperties ); @Override FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component); @Override FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component, final Selector selector); @Override FxmlLoadResult<NODE, CONTROLLER> load( final FxmlComponent component, final Class<? extends NODE> componentClass, final Class<? extends CONTROLLER> controllerClass ); @Override FxmlLoadResult<NODE, CONTROLLER> load( final FxmlComponent component, final Class<? extends NODE> nodeClass, final Class<? extends CONTROLLER> controllerClass, final Selector selector ); }
@Test public void isNullOrBlankMatches() { Stream.of(null, "", "\t \n ").forEach(nullOrBlank -> { sampleProp.setValue(nullOrBlank); assertThat(sampleFieldController.isNullOrBlank()).isTrue(); }); sampleProp.setValue("Non null nor empty/blank string"); assertThat(sampleFieldController.isNullOrBlank()).isFalse(); }
protected boolean isNullOrBlank() { final String fieldValue = getFieldValue(); return fieldValue == null || fieldValue.isBlank(); }
StringFormFieldController extends FormFieldController<String> { protected boolean isNullOrBlank() { final String fieldValue = getFieldValue(); return fieldValue == null || fieldValue.isBlank(); } }
StringFormFieldController extends FormFieldController<String> { protected boolean isNullOrBlank() { final String fieldValue = getFieldValue(); return fieldValue == null || fieldValue.isBlank(); } }
StringFormFieldController extends FormFieldController<String> { protected boolean isNullOrBlank() { final String fieldValue = getFieldValue(); return fieldValue == null || fieldValue.isBlank(); } @Override void initialize(); abstract ObservableValue<String> getObservableValue(); @Override String getFieldValue(); }
StringFormFieldController extends FormFieldController<String> { protected boolean isNullOrBlank() { final String fieldValue = getFieldValue(); return fieldValue == null || fieldValue.isBlank(); } @Override void initialize(); abstract ObservableValue<String> getObservableValue(); @Override String getFieldValue(); }
@Test public void loadWithTypeSingleInvalidClassFailure() { this.assertPaneFailedLoadingAndDidNotRegister( () -> this.easyFxml.load(buttonComponent, Pane.class, FxmlController.class).getNode(), this.controllerManager.getSingle(buttonComponent), ClassCastException.class ); }
@Override public FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component) { return this.load(component, Pane.class, FxmlController.class); }
DefaultEasyFxml implements EasyFxml { @Override public FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component) { return this.load(component, Pane.class, FxmlController.class); } }
DefaultEasyFxml implements EasyFxml { @Override public FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component) { return this.load(component, Pane.class, FxmlController.class); } @Autowired protected DefaultEasyFxml( final ApplicationContext context, final ControllerManager controllerManager, EasyFxmlProperties easyFxmlProperties ); }
DefaultEasyFxml implements EasyFxml { @Override public FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component) { return this.load(component, Pane.class, FxmlController.class); } @Autowired protected DefaultEasyFxml( final ApplicationContext context, final ControllerManager controllerManager, EasyFxmlProperties easyFxmlProperties ); @Override FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component); @Override FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component, final Selector selector); @Override FxmlLoadResult<NODE, CONTROLLER> load( final FxmlComponent component, final Class<? extends NODE> componentClass, final Class<? extends CONTROLLER> controllerClass ); @Override FxmlLoadResult<NODE, CONTROLLER> load( final FxmlComponent component, final Class<? extends NODE> nodeClass, final Class<? extends CONTROLLER> controllerClass, final Selector selector ); }
DefaultEasyFxml implements EasyFxml { @Override public FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component) { return this.load(component, Pane.class, FxmlController.class); } @Autowired protected DefaultEasyFxml( final ApplicationContext context, final ControllerManager controllerManager, EasyFxmlProperties easyFxmlProperties ); @Override FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component); @Override FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component, final Selector selector); @Override FxmlLoadResult<NODE, CONTROLLER> load( final FxmlComponent component, final Class<? extends NODE> componentClass, final Class<? extends CONTROLLER> controllerClass ); @Override FxmlLoadResult<NODE, CONTROLLER> load( final FxmlComponent component, final Class<? extends NODE> nodeClass, final Class<? extends CONTROLLER> controllerClass, final Selector selector ); }
@Test public void loadWithTypeSingleInvalidFileFailure() { this.assertPaneFailedLoadingAndDidNotRegister( () -> this.easyFxml.load(invalidComponent).getNode(), this.controllerManager.getSingle(invalidComponent), LoadException.class ); }
@Override public FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component) { return this.load(component, Pane.class, FxmlController.class); }
DefaultEasyFxml implements EasyFxml { @Override public FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component) { return this.load(component, Pane.class, FxmlController.class); } }
DefaultEasyFxml implements EasyFxml { @Override public FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component) { return this.load(component, Pane.class, FxmlController.class); } @Autowired protected DefaultEasyFxml( final ApplicationContext context, final ControllerManager controllerManager, EasyFxmlProperties easyFxmlProperties ); }
DefaultEasyFxml implements EasyFxml { @Override public FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component) { return this.load(component, Pane.class, FxmlController.class); } @Autowired protected DefaultEasyFxml( final ApplicationContext context, final ControllerManager controllerManager, EasyFxmlProperties easyFxmlProperties ); @Override FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component); @Override FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component, final Selector selector); @Override FxmlLoadResult<NODE, CONTROLLER> load( final FxmlComponent component, final Class<? extends NODE> componentClass, final Class<? extends CONTROLLER> controllerClass ); @Override FxmlLoadResult<NODE, CONTROLLER> load( final FxmlComponent component, final Class<? extends NODE> nodeClass, final Class<? extends CONTROLLER> controllerClass, final Selector selector ); }
DefaultEasyFxml implements EasyFxml { @Override public FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component) { return this.load(component, Pane.class, FxmlController.class); } @Autowired protected DefaultEasyFxml( final ApplicationContext context, final ControllerManager controllerManager, EasyFxmlProperties easyFxmlProperties ); @Override FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component); @Override FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component, final Selector selector); @Override FxmlLoadResult<NODE, CONTROLLER> load( final FxmlComponent component, final Class<? extends NODE> componentClass, final Class<? extends CONTROLLER> controllerClass ); @Override FxmlLoadResult<NODE, CONTROLLER> load( final FxmlComponent component, final Class<? extends NODE> nodeClass, final Class<? extends CONTROLLER> controllerClass, final Selector selector ); }
@Test public void loadWithTypeMultipleInvalidClassFailure() { Object selector = new Object(); this.assertPaneFailedLoadingAndDidNotRegister( () -> this.easyFxml.load(buttonComponent, Pane.class, NoControllerClass.class, new Selector(selector)).getNode(), this.controllerManager.getMultiple(buttonComponent, new Selector(selector)), ClassCastException.class ); }
@Override public FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component) { return this.load(component, Pane.class, FxmlController.class); }
DefaultEasyFxml implements EasyFxml { @Override public FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component) { return this.load(component, Pane.class, FxmlController.class); } }
DefaultEasyFxml implements EasyFxml { @Override public FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component) { return this.load(component, Pane.class, FxmlController.class); } @Autowired protected DefaultEasyFxml( final ApplicationContext context, final ControllerManager controllerManager, EasyFxmlProperties easyFxmlProperties ); }
DefaultEasyFxml implements EasyFxml { @Override public FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component) { return this.load(component, Pane.class, FxmlController.class); } @Autowired protected DefaultEasyFxml( final ApplicationContext context, final ControllerManager controllerManager, EasyFxmlProperties easyFxmlProperties ); @Override FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component); @Override FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component, final Selector selector); @Override FxmlLoadResult<NODE, CONTROLLER> load( final FxmlComponent component, final Class<? extends NODE> componentClass, final Class<? extends CONTROLLER> controllerClass ); @Override FxmlLoadResult<NODE, CONTROLLER> load( final FxmlComponent component, final Class<? extends NODE> nodeClass, final Class<? extends CONTROLLER> controllerClass, final Selector selector ); }
DefaultEasyFxml implements EasyFxml { @Override public FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component) { return this.load(component, Pane.class, FxmlController.class); } @Autowired protected DefaultEasyFxml( final ApplicationContext context, final ControllerManager controllerManager, EasyFxmlProperties easyFxmlProperties ); @Override FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component); @Override FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component, final Selector selector); @Override FxmlLoadResult<NODE, CONTROLLER> load( final FxmlComponent component, final Class<? extends NODE> componentClass, final Class<? extends CONTROLLER> controllerClass ); @Override FxmlLoadResult<NODE, CONTROLLER> load( final FxmlComponent component, final Class<? extends NODE> nodeClass, final Class<? extends CONTROLLER> controllerClass, final Selector selector ); }
@Test public void loadWithTypeMultipleInvalidFileFailure() { Object selector = new Object(); this.assertPaneFailedLoadingAndDidNotRegister( () -> this.easyFxml.load(invalidComponent, new Selector(selector)).getNode(), this.controllerManager.getMultiple(invalidComponent, new Selector(selector)), LoadException.class ); }
@Override public FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component) { return this.load(component, Pane.class, FxmlController.class); }
DefaultEasyFxml implements EasyFxml { @Override public FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component) { return this.load(component, Pane.class, FxmlController.class); } }
DefaultEasyFxml implements EasyFxml { @Override public FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component) { return this.load(component, Pane.class, FxmlController.class); } @Autowired protected DefaultEasyFxml( final ApplicationContext context, final ControllerManager controllerManager, EasyFxmlProperties easyFxmlProperties ); }
DefaultEasyFxml implements EasyFxml { @Override public FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component) { return this.load(component, Pane.class, FxmlController.class); } @Autowired protected DefaultEasyFxml( final ApplicationContext context, final ControllerManager controllerManager, EasyFxmlProperties easyFxmlProperties ); @Override FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component); @Override FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component, final Selector selector); @Override FxmlLoadResult<NODE, CONTROLLER> load( final FxmlComponent component, final Class<? extends NODE> componentClass, final Class<? extends CONTROLLER> controllerClass ); @Override FxmlLoadResult<NODE, CONTROLLER> load( final FxmlComponent component, final Class<? extends NODE> nodeClass, final Class<? extends CONTROLLER> controllerClass, final Selector selector ); }
DefaultEasyFxml implements EasyFxml { @Override public FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component) { return this.load(component, Pane.class, FxmlController.class); } @Autowired protected DefaultEasyFxml( final ApplicationContext context, final ControllerManager controllerManager, EasyFxmlProperties easyFxmlProperties ); @Override FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component); @Override FxmlLoadResult<Pane, FxmlController> load(final FxmlComponent component, final Selector selector); @Override FxmlLoadResult<NODE, CONTROLLER> load( final FxmlComponent component, final Class<? extends NODE> componentClass, final Class<? extends CONTROLLER> controllerClass ); @Override FxmlLoadResult<NODE, CONTROLLER> load( final FxmlComponent component, final Class<? extends NODE> nodeClass, final Class<? extends CONTROLLER> controllerClass, final Selector selector ); }
@Test public void registerSingle() { this.instanceManager.registerSingle(PARENT, ACTUAL_1); assertThat(this.instanceManager.getSingle(PARENT).get()).isEqualTo(ACTUAL_1); }
public V registerSingle(final K parent, final V instance) { return this.singletons.put(parent, instance); }
AbstractInstanceManager { public V registerSingle(final K parent, final V instance) { return this.singletons.put(parent, instance); } }
AbstractInstanceManager { public V registerSingle(final K parent, final V instance) { return this.singletons.put(parent, instance); } }
AbstractInstanceManager { public V registerSingle(final K parent, final V instance) { return this.singletons.put(parent, instance); } V registerSingle(final K parent, final V instance); V registerMultiple( final K parent, final Selector selector, final V instance ); Option<V> getMultiple(final K parent, final Selector selector); List<V> getAll(final K parent); List<V> getMultiples(final K parent); Option<V> getSingle(final K parent); }
AbstractInstanceManager { public V registerSingle(final K parent, final V instance) { return this.singletons.put(parent, instance); } V registerSingle(final K parent, final V instance); V registerMultiple( final K parent, final Selector selector, final V instance ); Option<V> getMultiple(final K parent, final Selector selector); List<V> getAll(final K parent); List<V> getMultiples(final K parent); Option<V> getSingle(final K parent); }
@Test public void registerMultiple() { this.instanceManager.registerMultiple(PARENT, SEL_1, ACTUAL_1); this.instanceManager.registerMultiple(PARENT, SEL_2, ACTUAL_2); assertThat(this.instanceManager.getMultiple(PARENT, SEL_1).get()).isEqualTo(ACTUAL_1); assertThat(this.instanceManager.getMultiple(PARENT, SEL_2).get()).isEqualTo(ACTUAL_2); }
public V registerMultiple( final K parent, final Selector selector, final V instance ) { if (!this.prototypes.containsKey(parent)) { this.prototypes.put(parent, new ConcurrentHashMap<>()); } return this.prototypes.get(parent).put(selector, instance); }
AbstractInstanceManager { public V registerMultiple( final K parent, final Selector selector, final V instance ) { if (!this.prototypes.containsKey(parent)) { this.prototypes.put(parent, new ConcurrentHashMap<>()); } return this.prototypes.get(parent).put(selector, instance); } }
AbstractInstanceManager { public V registerMultiple( final K parent, final Selector selector, final V instance ) { if (!this.prototypes.containsKey(parent)) { this.prototypes.put(parent, new ConcurrentHashMap<>()); } return this.prototypes.get(parent).put(selector, instance); } }
AbstractInstanceManager { public V registerMultiple( final K parent, final Selector selector, final V instance ) { if (!this.prototypes.containsKey(parent)) { this.prototypes.put(parent, new ConcurrentHashMap<>()); } return this.prototypes.get(parent).put(selector, instance); } V registerSingle(final K parent, final V instance); V registerMultiple( final K parent, final Selector selector, final V instance ); Option<V> getMultiple(final K parent, final Selector selector); List<V> getAll(final K parent); List<V> getMultiples(final K parent); Option<V> getSingle(final K parent); }
AbstractInstanceManager { public V registerMultiple( final K parent, final Selector selector, final V instance ) { if (!this.prototypes.containsKey(parent)) { this.prototypes.put(parent, new ConcurrentHashMap<>()); } return this.prototypes.get(parent).put(selector, instance); } V registerSingle(final K parent, final V instance); V registerMultiple( final K parent, final Selector selector, final V instance ); Option<V> getMultiple(final K parent, final Selector selector); List<V> getAll(final K parent); List<V> getMultiples(final K parent); Option<V> getSingle(final K parent); }
@Test public void getAll() { this.instanceManager.registerSingle(PARENT, ACTUAL_1); this.instanceManager.registerSingle(PARENT, ACTUAL_2); this.instanceManager.registerMultiple(PARENT, SEL_1, ACTUAL_1); this.instanceManager.registerMultiple(PARENT, SEL_2, ACTUAL_2); final List<String> all = this.instanceManager.getAll(PARENT); assertThat(all).containsExactlyInAnyOrder( ACTUAL_1, ACTUAL_2, ACTUAL_2 ); }
public List<V> getAll(final K parent) { final List<V> all = this.getMultiples(parent); this.getSingle(parent).peek(all::add); return all; }
AbstractInstanceManager { public List<V> getAll(final K parent) { final List<V> all = this.getMultiples(parent); this.getSingle(parent).peek(all::add); return all; } }
AbstractInstanceManager { public List<V> getAll(final K parent) { final List<V> all = this.getMultiples(parent); this.getSingle(parent).peek(all::add); return all; } }
AbstractInstanceManager { public List<V> getAll(final K parent) { final List<V> all = this.getMultiples(parent); this.getSingle(parent).peek(all::add); return all; } V registerSingle(final K parent, final V instance); V registerMultiple( final K parent, final Selector selector, final V instance ); Option<V> getMultiple(final K parent, final Selector selector); List<V> getAll(final K parent); List<V> getMultiples(final K parent); Option<V> getSingle(final K parent); }
AbstractInstanceManager { public List<V> getAll(final K parent) { final List<V> all = this.getMultiples(parent); this.getSingle(parent).peek(all::add); return all; } V registerSingle(final K parent, final V instance); V registerMultiple( final K parent, final Selector selector, final V instance ); Option<V> getMultiple(final K parent, final Selector selector); List<V> getAll(final K parent); List<V> getMultiples(final K parent); Option<V> getSingle(final K parent); }
@Test public void getMultiples() { this.instanceManager.registerMultiple(PARENT, SEL_1, ACTUAL_1); this.instanceManager.registerMultiple(PARENT, SEL_2, ACTUAL_2); assertThat(this.instanceManager.getMultiples(PARENT)).containsExactlyInAnyOrder(ACTUAL_1, ACTUAL_2); }
public List<V> getMultiples(final K parent) { return new ArrayList<>(Option.of(this.prototypes.get(parent)) .map(Map::values) .getOrElse(Collections.emptyList())); }
AbstractInstanceManager { public List<V> getMultiples(final K parent) { return new ArrayList<>(Option.of(this.prototypes.get(parent)) .map(Map::values) .getOrElse(Collections.emptyList())); } }
AbstractInstanceManager { public List<V> getMultiples(final K parent) { return new ArrayList<>(Option.of(this.prototypes.get(parent)) .map(Map::values) .getOrElse(Collections.emptyList())); } }
AbstractInstanceManager { public List<V> getMultiples(final K parent) { return new ArrayList<>(Option.of(this.prototypes.get(parent)) .map(Map::values) .getOrElse(Collections.emptyList())); } V registerSingle(final K parent, final V instance); V registerMultiple( final K parent, final Selector selector, final V instance ); Option<V> getMultiple(final K parent, final Selector selector); List<V> getAll(final K parent); List<V> getMultiples(final K parent); Option<V> getSingle(final K parent); }
AbstractInstanceManager { public List<V> getMultiples(final K parent) { return new ArrayList<>(Option.of(this.prototypes.get(parent)) .map(Map::values) .getOrElse(Collections.emptyList())); } V registerSingle(final K parent, final V instance); V registerMultiple( final K parent, final Selector selector, final V instance ); Option<V> getMultiple(final K parent, final Selector selector); List<V> getAll(final K parent); List<V> getMultiples(final K parent); Option<V> getSingle(final K parent); }
@Test public void start() throws Exception { TestFxApplication.main(); }
@Override public void start(final Stage primaryStage) { this.springContext.getBean(FxUiManager.class).startGui(primaryStage); }
FxApplication extends Application { @Override public void start(final Stage primaryStage) { this.springContext.getBean(FxUiManager.class).startGui(primaryStage); } }
FxApplication extends Application { @Override public void start(final Stage primaryStage) { this.springContext.getBean(FxUiManager.class).startGui(primaryStage); } }
FxApplication extends Application { @Override public void start(final Stage primaryStage) { this.springContext.getBean(FxUiManager.class).startGui(primaryStage); } @Override void init(); @Override void start(final Stage primaryStage); @Override void stop(); }
FxApplication extends Application { @Override public void start(final Stage primaryStage) { this.springContext.getBean(FxUiManager.class).startGui(primaryStage); } @Override void init(); @Override void start(final Stage primaryStage); @Override void stop(); }
@Test public void startGui() { Platform.runLater(() -> testFxUiManager.startGui(stage)); }
public void startGui(final Stage mainStage) { try { onStageCreated(mainStage); final Scene mainScene = getScene(mainComponent()); onSceneCreated(mainScene); mainStage.setScene(mainScene); mainStage.setTitle(title()); Option.ofOptional(getStylesheet()) .filter(style -> !FxmlStylesheets.DEFAULT_JAVAFX_STYLE.equals(style)) .peek(stylesheet -> this.setTheme(stylesheet, mainStage)); mainStage.show(); } catch (Throwable t) { throw new RuntimeException("There was a failure during start-up of the application.", t); } }
FxUiManager { public void startGui(final Stage mainStage) { try { onStageCreated(mainStage); final Scene mainScene = getScene(mainComponent()); onSceneCreated(mainScene); mainStage.setScene(mainScene); mainStage.setTitle(title()); Option.ofOptional(getStylesheet()) .filter(style -> !FxmlStylesheets.DEFAULT_JAVAFX_STYLE.equals(style)) .peek(stylesheet -> this.setTheme(stylesheet, mainStage)); mainStage.show(); } catch (Throwable t) { throw new RuntimeException("There was a failure during start-up of the application.", t); } } }
FxUiManager { public void startGui(final Stage mainStage) { try { onStageCreated(mainStage); final Scene mainScene = getScene(mainComponent()); onSceneCreated(mainScene); mainStage.setScene(mainScene); mainStage.setTitle(title()); Option.ofOptional(getStylesheet()) .filter(style -> !FxmlStylesheets.DEFAULT_JAVAFX_STYLE.equals(style)) .peek(stylesheet -> this.setTheme(stylesheet, mainStage)); mainStage.show(); } catch (Throwable t) { throw new RuntimeException("There was a failure during start-up of the application.", t); } } }
FxUiManager { public void startGui(final Stage mainStage) { try { onStageCreated(mainStage); final Scene mainScene = getScene(mainComponent()); onSceneCreated(mainScene); mainStage.setScene(mainScene); mainStage.setTitle(title()); Option.ofOptional(getStylesheet()) .filter(style -> !FxmlStylesheets.DEFAULT_JAVAFX_STYLE.equals(style)) .peek(stylesheet -> this.setTheme(stylesheet, mainStage)); mainStage.show(); } catch (Throwable t) { throw new RuntimeException("There was a failure during start-up of the application.", t); } } void startGui(final Stage mainStage); @Autowired void setEasyFxml(EasyFxml easyFxml); }
FxUiManager { public void startGui(final Stage mainStage) { try { onStageCreated(mainStage); final Scene mainScene = getScene(mainComponent()); onSceneCreated(mainScene); mainStage.setScene(mainScene); mainStage.setTitle(title()); Option.ofOptional(getStylesheet()) .filter(style -> !FxmlStylesheets.DEFAULT_JAVAFX_STYLE.equals(style)) .peek(stylesheet -> this.setTheme(stylesheet, mainStage)); mainStage.show(); } catch (Throwable t) { throw new RuntimeException("There was a failure during start-up of the application.", t); } } void startGui(final Stage mainStage); @Autowired void setEasyFxml(EasyFxml easyFxml); }
@Test public void doOnFxThread() throws ExecutionException, InterruptedException { FxAsync.doOnFxThread( fxThread, expected -> assertThat(Thread.currentThread()).isEqualTo(expected) ).toCompletableFuture().get(); }
public static <T> CompletionStage<T> doOnFxThread(final T element, final Consumer<T> action) { return CompletableFuture.supplyAsync(() -> { action.accept(element); return element; }, Platform::runLater); }
FxAsync { public static <T> CompletionStage<T> doOnFxThread(final T element, final Consumer<T> action) { return CompletableFuture.supplyAsync(() -> { action.accept(element); return element; }, Platform::runLater); } }
FxAsync { public static <T> CompletionStage<T> doOnFxThread(final T element, final Consumer<T> action) { return CompletableFuture.supplyAsync(() -> { action.accept(element); return element; }, Platform::runLater); } private FxAsync(); }
FxAsync { public static <T> CompletionStage<T> doOnFxThread(final T element, final Consumer<T> action) { return CompletableFuture.supplyAsync(() -> { action.accept(element); return element; }, Platform::runLater); } private FxAsync(); static CompletionStage<T> doOnFxThread(final T element, final Consumer<T> action); static CompletionStage<U> computeOnFxThread(final T element, final Function<T, U> compute); }
FxAsync { public static <T> CompletionStage<T> doOnFxThread(final T element, final Consumer<T> action) { return CompletableFuture.supplyAsync(() -> { action.accept(element); return element; }, Platform::runLater); } private FxAsync(); static CompletionStage<T> doOnFxThread(final T element, final Consumer<T> action); static CompletionStage<U> computeOnFxThread(final T element, final Function<T, U> compute); }
@Test public void computeOnFxThread() throws ExecutionException, InterruptedException { FxAsync.computeOnFxThread( fxThread, expected -> assertThat(Thread.currentThread()).isEqualTo(expected) ).toCompletableFuture().get(); }
public static <T, U> CompletionStage<U> computeOnFxThread(final T element, final Function<T, U> compute) { return CompletableFuture.supplyAsync(() -> compute.apply(element), Platform::runLater); }
FxAsync { public static <T, U> CompletionStage<U> computeOnFxThread(final T element, final Function<T, U> compute) { return CompletableFuture.supplyAsync(() -> compute.apply(element), Platform::runLater); } }
FxAsync { public static <T, U> CompletionStage<U> computeOnFxThread(final T element, final Function<T, U> compute) { return CompletableFuture.supplyAsync(() -> compute.apply(element), Platform::runLater); } private FxAsync(); }
FxAsync { public static <T, U> CompletionStage<U> computeOnFxThread(final T element, final Function<T, U> compute) { return CompletableFuture.supplyAsync(() -> compute.apply(element), Platform::runLater); } private FxAsync(); static CompletionStage<T> doOnFxThread(final T element, final Consumer<T> action); static CompletionStage<U> computeOnFxThread(final T element, final Function<T, U> compute); }
FxAsync { public static <T, U> CompletionStage<U> computeOnFxThread(final T element, final Function<T, U> compute) { return CompletableFuture.supplyAsync(() -> compute.apply(element), Platform::runLater); } private FxAsync(); static CompletionStage<T> doOnFxThread(final T element, final Consumer<T> action); static CompletionStage<U> computeOnFxThread(final T element, final Function<T, U> compute); }
@Test public void setOnClick() { final AtomicBoolean success = new AtomicBoolean(false); final Button testButton = new Button("TEST_BUTTON"); Buttons.setOnClick(testButton, () -> success.set(true)); withNodes(testButton) .startWhen(() -> point(testButton).query() != null) .willDo(() -> clickOn(testButton, PRIMARY)) .andAwaitFor(success::get); assertThat(success).isTrue(); }
public static void setOnClick(final Button button, final Runnable action) { button.setOnAction(e -> Platform.runLater(action)); }
Buttons { public static void setOnClick(final Button button, final Runnable action) { button.setOnAction(e -> Platform.runLater(action)); } }
Buttons { public static void setOnClick(final Button button, final Runnable action) { button.setOnAction(e -> Platform.runLater(action)); } private Buttons(); }
Buttons { public static void setOnClick(final Button button, final Runnable action) { button.setOnAction(e -> Platform.runLater(action)); } private Buttons(); static void setOnClick(final Button button, final Runnable action); static void setOnClickWithNode(final Button button, final Node node, final Consumer<Node> action); }
Buttons { public static void setOnClick(final Button button, final Runnable action) { button.setOnAction(e -> Platform.runLater(action)); } private Buttons(); static void setOnClick(final Button button, final Runnable action); static void setOnClickWithNode(final Button button, final Node node, final Consumer<Node> action); }
@Test public void setOnClickWithNode() { final Button testButton = new Button("Test button"); final Label testLabel = new Label("Test label"); Buttons.setOnClickWithNode(testButton, testLabel, label -> label.setVisible(false)); withNodes(testButton, testLabel) .startWhen(() -> point(testButton).query() != null) .willDo(() -> clickOn(testButton, PRIMARY)) .andAwaitFor(() -> !testLabel.isVisible()); assertThat(testLabel.isVisible()).isFalse(); }
public static void setOnClickWithNode(final Button button, final Node node, final Consumer<Node> action) { setOnClick(button, () -> action.accept(node)); }
Buttons { public static void setOnClickWithNode(final Button button, final Node node, final Consumer<Node> action) { setOnClick(button, () -> action.accept(node)); } }
Buttons { public static void setOnClickWithNode(final Button button, final Node node, final Consumer<Node> action) { setOnClick(button, () -> action.accept(node)); } private Buttons(); }
Buttons { public static void setOnClickWithNode(final Button button, final Node node, final Consumer<Node> action) { setOnClick(button, () -> action.accept(node)); } private Buttons(); static void setOnClick(final Button button, final Runnable action); static void setOnClickWithNode(final Button button, final Node node, final Consumer<Node> action); }
Buttons { public static void setOnClickWithNode(final Button button, final Node node, final Consumer<Node> action) { setOnClick(button, () -> action.accept(node)); } private Buttons(); static void setOnClick(final Button button, final Runnable action); static void setOnClickWithNode(final Button button, final Node node, final Consumer<Node> action); }
@Test public void centerNode() { Nodes.centerNode(this.testButton, MARGIN); }
public static void centerNode(final Node node, final Double marginSize) { AnchorPane.setTopAnchor(node, marginSize); AnchorPane.setBottomAnchor(node, marginSize); AnchorPane.setLeftAnchor(node, marginSize); AnchorPane.setRightAnchor(node, marginSize); }
Nodes { public static void centerNode(final Node node, final Double marginSize) { AnchorPane.setTopAnchor(node, marginSize); AnchorPane.setBottomAnchor(node, marginSize); AnchorPane.setLeftAnchor(node, marginSize); AnchorPane.setRightAnchor(node, marginSize); } }
Nodes { public static void centerNode(final Node node, final Double marginSize) { AnchorPane.setTopAnchor(node, marginSize); AnchorPane.setBottomAnchor(node, marginSize); AnchorPane.setLeftAnchor(node, marginSize); AnchorPane.setRightAnchor(node, marginSize); } private Nodes(); }
Nodes { public static void centerNode(final Node node, final Double marginSize) { AnchorPane.setTopAnchor(node, marginSize); AnchorPane.setBottomAnchor(node, marginSize); AnchorPane.setLeftAnchor(node, marginSize); AnchorPane.setRightAnchor(node, marginSize); } private Nodes(); static void centerNode(final Node node, final Double marginSize); static void hideAndResizeParentIf( final Node node, final ObservableValue<? extends Boolean> condition ); static void autoresizeContainerOn( final Node node, final ObservableValue<?> observableValue ); static void bindContentBiasCalculationTo( final Node node, final ObservableValue<? extends Boolean> observableValue ); }
Nodes { public static void centerNode(final Node node, final Double marginSize) { AnchorPane.setTopAnchor(node, marginSize); AnchorPane.setBottomAnchor(node, marginSize); AnchorPane.setLeftAnchor(node, marginSize); AnchorPane.setRightAnchor(node, marginSize); } private Nodes(); static void centerNode(final Node node, final Double marginSize); static void hideAndResizeParentIf( final Node node, final ObservableValue<? extends Boolean> condition ); static void autoresizeContainerOn( final Node node, final ObservableValue<?> observableValue ); static void bindContentBiasCalculationTo( final Node node, final ObservableValue<? extends Boolean> observableValue ); }
@Test public void testAutosizeHelpers() { final BooleanProperty shouldDisplay = new SimpleBooleanProperty(true); final Button testButton = new Button(); Nodes.hideAndResizeParentIf(testButton, shouldDisplay); assertThat(testButton.isManaged()).isTrue(); assertThat(testButton.isVisible()).isTrue(); shouldDisplay.setValue(false); assertThat(testButton.isManaged()).isFalse(); assertThat(testButton.isVisible()).isFalse(); }
public static void hideAndResizeParentIf( final Node node, final ObservableValue<? extends Boolean> condition ) { autoresizeContainerOn(node, condition); bindContentBiasCalculationTo(node, condition); }
Nodes { public static void hideAndResizeParentIf( final Node node, final ObservableValue<? extends Boolean> condition ) { autoresizeContainerOn(node, condition); bindContentBiasCalculationTo(node, condition); } }
Nodes { public static void hideAndResizeParentIf( final Node node, final ObservableValue<? extends Boolean> condition ) { autoresizeContainerOn(node, condition); bindContentBiasCalculationTo(node, condition); } private Nodes(); }
Nodes { public static void hideAndResizeParentIf( final Node node, final ObservableValue<? extends Boolean> condition ) { autoresizeContainerOn(node, condition); bindContentBiasCalculationTo(node, condition); } private Nodes(); static void centerNode(final Node node, final Double marginSize); static void hideAndResizeParentIf( final Node node, final ObservableValue<? extends Boolean> condition ); static void autoresizeContainerOn( final Node node, final ObservableValue<?> observableValue ); static void bindContentBiasCalculationTo( final Node node, final ObservableValue<? extends Boolean> observableValue ); }
Nodes { public static void hideAndResizeParentIf( final Node node, final ObservableValue<? extends Boolean> condition ) { autoresizeContainerOn(node, condition); bindContentBiasCalculationTo(node, condition); } private Nodes(); static void centerNode(final Node node, final Double marginSize); static void hideAndResizeParentIf( final Node node, final ObservableValue<? extends Boolean> condition ); static void autoresizeContainerOn( final Node node, final ObservableValue<?> observableValue ); static void bindContentBiasCalculationTo( final Node node, final ObservableValue<? extends Boolean> observableValue ); }
@Test public void workflowscript_missing_required_againt_at_line_1_comma_column1__is_recognized_as_error() { String line = "WorkflowScript: 1: Missing required section \"agent\" @ line 1, column 1."; JenkinsLinterError error = builderToTest.build(line); assertNotNull(error); assertEquals(1,error.getLine()); assertEquals(1,error.getColumn()); assertEquals(line,error.getMessage()); }
public JenkinsLinterError build(String line) { if (line==null){ return null; } Matcher matcher = ERROR_PATTERN.matcher(line); if (! matcher.find()){ return null; } JenkinsLinterError error = new JenkinsLinterError(); error.message=line; error.line = Integer.valueOf(matcher.group(1)); error.column = Integer.valueOf(matcher.group(2)); return error; }
JenkinsLinterErrorBuilder { public JenkinsLinterError build(String line) { if (line==null){ return null; } Matcher matcher = ERROR_PATTERN.matcher(line); if (! matcher.find()){ return null; } JenkinsLinterError error = new JenkinsLinterError(); error.message=line; error.line = Integer.valueOf(matcher.group(1)); error.column = Integer.valueOf(matcher.group(2)); return error; } }
JenkinsLinterErrorBuilder { public JenkinsLinterError build(String line) { if (line==null){ return null; } Matcher matcher = ERROR_PATTERN.matcher(line); if (! matcher.find()){ return null; } JenkinsLinterError error = new JenkinsLinterError(); error.message=line; error.line = Integer.valueOf(matcher.group(1)); error.column = Integer.valueOf(matcher.group(2)); return error; } }
JenkinsLinterErrorBuilder { public JenkinsLinterError build(String line) { if (line==null){ return null; } Matcher matcher = ERROR_PATTERN.matcher(line); if (! matcher.find()){ return null; } JenkinsLinterError error = new JenkinsLinterError(); error.message=line; error.line = Integer.valueOf(matcher.group(1)); error.column = Integer.valueOf(matcher.group(2)); return error; } JenkinsLinterError build(String line); }
JenkinsLinterErrorBuilder { public JenkinsLinterError build(String line) { if (line==null){ return null; } Matcher matcher = ERROR_PATTERN.matcher(line); if (! matcher.find()){ return null; } JenkinsLinterError error = new JenkinsLinterError(); error.message=line; error.line = Integer.valueOf(matcher.group(1)); error.column = Integer.valueOf(matcher.group(2)); return error; } JenkinsLinterError build(String line); }
@Test public void commands_hidden_expected_output_done() { String expected = "[java, -Dhttp.proxyPassword=******, -Dhttps.proxyPassword=******, -jar, thePath, -s, http: String[] commands = commandToTest.createCommands(configuration, parameter, true); List<String> list = Arrays.asList(commands); assertEquals(expected, list.toString()); }
protected String[] createCommands(JenkinsCLIConfiguration configuration, P parameter, boolean hidePasswords) { return createExecutionStrings(configuration, hidePasswords); }
AbstractJenkinsCLICommand implements JenkinsCLICommand<T, P> { protected String[] createCommands(JenkinsCLIConfiguration configuration, P parameter, boolean hidePasswords) { return createExecutionStrings(configuration, hidePasswords); } }
AbstractJenkinsCLICommand implements JenkinsCLICommand<T, P> { protected String[] createCommands(JenkinsCLIConfiguration configuration, P parameter, boolean hidePasswords) { return createExecutionStrings(configuration, hidePasswords); } }
AbstractJenkinsCLICommand implements JenkinsCLICommand<T, P> { protected String[] createCommands(JenkinsCLIConfiguration configuration, P parameter, boolean hidePasswords) { return createExecutionStrings(configuration, hidePasswords); } final T execute(JenkinsCLIConfiguration configuration, P parameter); }
AbstractJenkinsCLICommand implements JenkinsCLICommand<T, P> { protected String[] createCommands(JenkinsCLIConfiguration configuration, P parameter, boolean hidePasswords) { return createExecutionStrings(configuration, hidePasswords); } final T execute(JenkinsCLIConfiguration configuration, P parameter); }
@Test public void commands_hidden_contains_no_http_proxy_passwords() throws Exception { String[] commands = commandToTest.createCommands(configuration, parameter, true); List<String> list = Arrays.asList(commands); assertFalse(list.contains(DHTTP_PROXY_PASSWORD_MYSECRET1)); assertFalse(list.contains(DHTTPS_PROXY_PASSWORD_MYSECRET2)); }
protected String[] createCommands(JenkinsCLIConfiguration configuration, P parameter, boolean hidePasswords) { return createExecutionStrings(configuration, hidePasswords); }
AbstractJenkinsCLICommand implements JenkinsCLICommand<T, P> { protected String[] createCommands(JenkinsCLIConfiguration configuration, P parameter, boolean hidePasswords) { return createExecutionStrings(configuration, hidePasswords); } }
AbstractJenkinsCLICommand implements JenkinsCLICommand<T, P> { protected String[] createCommands(JenkinsCLIConfiguration configuration, P parameter, boolean hidePasswords) { return createExecutionStrings(configuration, hidePasswords); } }
AbstractJenkinsCLICommand implements JenkinsCLICommand<T, P> { protected String[] createCommands(JenkinsCLIConfiguration configuration, P parameter, boolean hidePasswords) { return createExecutionStrings(configuration, hidePasswords); } final T execute(JenkinsCLIConfiguration configuration, P parameter); }
AbstractJenkinsCLICommand implements JenkinsCLICommand<T, P> { protected String[] createCommands(JenkinsCLIConfiguration configuration, P parameter, boolean hidePasswords) { return createExecutionStrings(configuration, hidePasswords); } final T execute(JenkinsCLIConfiguration configuration, P parameter); }
@Test public void commands_NOT_hidden_contains_http_proxy_passwords() throws Exception { String[] commands = commandToTest.createCommands(configuration, parameter, false); List<String> list = Arrays.asList(commands); assertTrue(list.contains(DHTTP_PROXY_PASSWORD_MYSECRET1)); assertTrue(list.contains(DHTTPS_PROXY_PASSWORD_MYSECRET2)); }
protected String[] createCommands(JenkinsCLIConfiguration configuration, P parameter, boolean hidePasswords) { return createExecutionStrings(configuration, hidePasswords); }
AbstractJenkinsCLICommand implements JenkinsCLICommand<T, P> { protected String[] createCommands(JenkinsCLIConfiguration configuration, P parameter, boolean hidePasswords) { return createExecutionStrings(configuration, hidePasswords); } }
AbstractJenkinsCLICommand implements JenkinsCLICommand<T, P> { protected String[] createCommands(JenkinsCLIConfiguration configuration, P parameter, boolean hidePasswords) { return createExecutionStrings(configuration, hidePasswords); } }
AbstractJenkinsCLICommand implements JenkinsCLICommand<T, P> { protected String[] createCommands(JenkinsCLIConfiguration configuration, P parameter, boolean hidePasswords) { return createExecutionStrings(configuration, hidePasswords); } final T execute(JenkinsCLIConfiguration configuration, P parameter); }
AbstractJenkinsCLICommand implements JenkinsCLICommand<T, P> { protected String[] createCommands(JenkinsCLIConfiguration configuration, P parameter, boolean hidePasswords) { return createExecutionStrings(configuration, hidePasswords); } final T execute(JenkinsCLIConfiguration configuration, P parameter); }
@Test public void command_auth_no_proxy_set() throws Exception { String[] commands = commandToTest.createCommands(configuration, parameter, true); List<String> list = Arrays.asList(commands); System.out.println(list); }
protected String[] createCommands(JenkinsCLIConfiguration configuration, P parameter, boolean hidePasswords) { return createExecutionStrings(configuration, hidePasswords); }
AbstractJenkinsCLICommand implements JenkinsCLICommand<T, P> { protected String[] createCommands(JenkinsCLIConfiguration configuration, P parameter, boolean hidePasswords) { return createExecutionStrings(configuration, hidePasswords); } }
AbstractJenkinsCLICommand implements JenkinsCLICommand<T, P> { protected String[] createCommands(JenkinsCLIConfiguration configuration, P parameter, boolean hidePasswords) { return createExecutionStrings(configuration, hidePasswords); } }
AbstractJenkinsCLICommand implements JenkinsCLICommand<T, P> { protected String[] createCommands(JenkinsCLIConfiguration configuration, P parameter, boolean hidePasswords) { return createExecutionStrings(configuration, hidePasswords); } final T execute(JenkinsCLIConfiguration configuration, P parameter); }
AbstractJenkinsCLICommand implements JenkinsCLICommand<T, P> { protected String[] createCommands(JenkinsCLIConfiguration configuration, P parameter, boolean hidePasswords) { return createExecutionStrings(configuration, hidePasswords); } final T execute(JenkinsCLIConfiguration configuration, P parameter); }
@Test public void system_provider_returns_null_for_JENKINS_URL___then_fallback_url_with_localhost_is_returned() { when(mockedSystemAdapter.getEnv("JENKINS_URL")).thenReturn(null); assertEquals("http: }
public String getDefaultJenkinsURL() { String jenkinsURL = getJENKINS_URL(); if (jenkinsURL != null && jenkinsURL.trim().length() > 0) { return jenkinsURL; } return getLocalhostURL(); }
JenkinsDefaultURLProvider { public String getDefaultJenkinsURL() { String jenkinsURL = getJENKINS_URL(); if (jenkinsURL != null && jenkinsURL.trim().length() > 0) { return jenkinsURL; } return getLocalhostURL(); } }
JenkinsDefaultURLProvider { public String getDefaultJenkinsURL() { String jenkinsURL = getJENKINS_URL(); if (jenkinsURL != null && jenkinsURL.trim().length() > 0) { return jenkinsURL; } return getLocalhostURL(); } }
JenkinsDefaultURLProvider { public String getDefaultJenkinsURL() { String jenkinsURL = getJENKINS_URL(); if (jenkinsURL != null && jenkinsURL.trim().length() > 0) { return jenkinsURL; } return getLocalhostURL(); } String getDefaultJenkinsURL(); String createDefaultURLDescription(); }
JenkinsDefaultURLProvider { public String getDefaultJenkinsURL() { String jenkinsURL = getJENKINS_URL(); if (jenkinsURL != null && jenkinsURL.trim().length() > 0) { return jenkinsURL; } return getLocalhostURL(); } String getDefaultJenkinsURL(); String createDefaultURLDescription(); }
@Test public void system_provider_returns_empty_string_for_JENKINS_URL___then_fallback_url_with_localhost_is_returned() { when(mockedSystemAdapter.getEnv("JENKINS_URL")).thenReturn(""); assertEquals("http: }
public String getDefaultJenkinsURL() { String jenkinsURL = getJENKINS_URL(); if (jenkinsURL != null && jenkinsURL.trim().length() > 0) { return jenkinsURL; } return getLocalhostURL(); }
JenkinsDefaultURLProvider { public String getDefaultJenkinsURL() { String jenkinsURL = getJENKINS_URL(); if (jenkinsURL != null && jenkinsURL.trim().length() > 0) { return jenkinsURL; } return getLocalhostURL(); } }
JenkinsDefaultURLProvider { public String getDefaultJenkinsURL() { String jenkinsURL = getJENKINS_URL(); if (jenkinsURL != null && jenkinsURL.trim().length() > 0) { return jenkinsURL; } return getLocalhostURL(); } }
JenkinsDefaultURLProvider { public String getDefaultJenkinsURL() { String jenkinsURL = getJENKINS_URL(); if (jenkinsURL != null && jenkinsURL.trim().length() > 0) { return jenkinsURL; } return getLocalhostURL(); } String getDefaultJenkinsURL(); String createDefaultURLDescription(); }
JenkinsDefaultURLProvider { public String getDefaultJenkinsURL() { String jenkinsURL = getJENKINS_URL(); if (jenkinsURL != null && jenkinsURL.trim().length() > 0) { return jenkinsURL; } return getLocalhostURL(); } String getDefaultJenkinsURL(); String createDefaultURLDescription(); }
@Test public void system_provider_returns_blubber_for_JENKINS_URL___then_blubber_is_returned() { when(mockedSystemAdapter.getEnv("JENKINS_URL")).thenReturn("blubber"); assertEquals("blubber", providerToTest.getDefaultJenkinsURL()); }
public String getDefaultJenkinsURL() { String jenkinsURL = getJENKINS_URL(); if (jenkinsURL != null && jenkinsURL.trim().length() > 0) { return jenkinsURL; } return getLocalhostURL(); }
JenkinsDefaultURLProvider { public String getDefaultJenkinsURL() { String jenkinsURL = getJENKINS_URL(); if (jenkinsURL != null && jenkinsURL.trim().length() > 0) { return jenkinsURL; } return getLocalhostURL(); } }
JenkinsDefaultURLProvider { public String getDefaultJenkinsURL() { String jenkinsURL = getJENKINS_URL(); if (jenkinsURL != null && jenkinsURL.trim().length() > 0) { return jenkinsURL; } return getLocalhostURL(); } }
JenkinsDefaultURLProvider { public String getDefaultJenkinsURL() { String jenkinsURL = getJENKINS_URL(); if (jenkinsURL != null && jenkinsURL.trim().length() > 0) { return jenkinsURL; } return getLocalhostURL(); } String getDefaultJenkinsURL(); String createDefaultURLDescription(); }
JenkinsDefaultURLProvider { public String getDefaultJenkinsURL() { String jenkinsURL = getJENKINS_URL(); if (jenkinsURL != null && jenkinsURL.trim().length() > 0) { return jenkinsURL; } return getLocalhostURL(); } String getDefaultJenkinsURL(); String createDefaultURLDescription(); }
@Test public void system_provider_returns_null_for_JENKINS_URL___then_description_about_missing_JENKINS_URL_and_usage_of_localhost_is_returned() { when(mockedSystemAdapter.getEnv("JENKINS_URL")).thenReturn(null); assertEquals("No JENKINS_URL env defined, so using http: }
public String createDefaultURLDescription() { String jenkinsURL = getJENKINS_URL(); if (jenkinsURL != null) { return "JENKINS_URL defined as " + jenkinsURL + ". Using this as default value"; } return "No JENKINS_URL env defined, so using " + getLocalhostURL() + " as default value"; }
JenkinsDefaultURLProvider { public String createDefaultURLDescription() { String jenkinsURL = getJENKINS_URL(); if (jenkinsURL != null) { return "JENKINS_URL defined as " + jenkinsURL + ". Using this as default value"; } return "No JENKINS_URL env defined, so using " + getLocalhostURL() + " as default value"; } }
JenkinsDefaultURLProvider { public String createDefaultURLDescription() { String jenkinsURL = getJENKINS_URL(); if (jenkinsURL != null) { return "JENKINS_URL defined as " + jenkinsURL + ". Using this as default value"; } return "No JENKINS_URL env defined, so using " + getLocalhostURL() + " as default value"; } }
JenkinsDefaultURLProvider { public String createDefaultURLDescription() { String jenkinsURL = getJENKINS_URL(); if (jenkinsURL != null) { return "JENKINS_URL defined as " + jenkinsURL + ". Using this as default value"; } return "No JENKINS_URL env defined, so using " + getLocalhostURL() + " as default value"; } String getDefaultJenkinsURL(); String createDefaultURLDescription(); }
JenkinsDefaultURLProvider { public String createDefaultURLDescription() { String jenkinsURL = getJENKINS_URL(); if (jenkinsURL != null) { return "JENKINS_URL defined as " + jenkinsURL + ". Using this as default value"; } return "No JENKINS_URL env defined, so using " + getLocalhostURL() + " as default value"; } String getDefaultJenkinsURL(); String createDefaultURLDescription(); }
@Test public void system_provider_returns_blubber_for_JENKINS_URL___then_description_JENKINS_URLthen_blubber_is_returned() { when(mockedSystemAdapter.getEnv("JENKINS_URL")).thenReturn("blubber"); assertEquals("JENKINS_URL defined as blubber. Using this as default value", providerToTest.createDefaultURLDescription()); }
public String createDefaultURLDescription() { String jenkinsURL = getJENKINS_URL(); if (jenkinsURL != null) { return "JENKINS_URL defined as " + jenkinsURL + ". Using this as default value"; } return "No JENKINS_URL env defined, so using " + getLocalhostURL() + " as default value"; }
JenkinsDefaultURLProvider { public String createDefaultURLDescription() { String jenkinsURL = getJENKINS_URL(); if (jenkinsURL != null) { return "JENKINS_URL defined as " + jenkinsURL + ". Using this as default value"; } return "No JENKINS_URL env defined, so using " + getLocalhostURL() + " as default value"; } }
JenkinsDefaultURLProvider { public String createDefaultURLDescription() { String jenkinsURL = getJENKINS_URL(); if (jenkinsURL != null) { return "JENKINS_URL defined as " + jenkinsURL + ". Using this as default value"; } return "No JENKINS_URL env defined, so using " + getLocalhostURL() + " as default value"; } }
JenkinsDefaultURLProvider { public String createDefaultURLDescription() { String jenkinsURL = getJENKINS_URL(); if (jenkinsURL != null) { return "JENKINS_URL defined as " + jenkinsURL + ". Using this as default value"; } return "No JENKINS_URL env defined, so using " + getLocalhostURL() + " as default value"; } String getDefaultJenkinsURL(); String createDefaultURLDescription(); }
JenkinsDefaultURLProvider { public String createDefaultURLDescription() { String jenkinsURL = getJENKINS_URL(); if (jenkinsURL != null) { return "JENKINS_URL defined as " + jenkinsURL + ". Using this as default value"; } return "No JENKINS_URL env defined, so using " + getLocalhostURL() + " as default value"; } String getDefaultJenkinsURL(); String createDefaultURLDescription(); }
@Test public void an_empty_source_will_result_in_pipeline() { Set<ProposalProvider> result = completion.calculate(source0, 0); assertFalse(result.isEmpty()); assertEquals(1,result.size()); ProposalProvider provider = result.iterator().next(); assertTrue(provider.getLabel().equals("pipeline")); List<String> template = provider.getCodeTemplate(); assertEquals(3, template.size()); Iterator<String> it = template.iterator(); assertEquals(it.next(), "pipeline {"); assertEquals(it.next(), " "+SourceCodeBuilder.CURSOR_TAG); assertEquals(it.next(), "}"); }
@Override public Set<ProposalProvider> calculate(String source, int offset) { if (source.trim().length()==0){ return Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); } String parentAsText = ""; JenkinsModelBuilder builder = new JenkinsModelBuilder(new ByteArrayInputStream(source.getBytes())); BuildContext builderContext = new BuildContext(); Item item = null; try { Model model = builder.build(builderContext); item = model.getParentItemOf(offset); } catch (ModelBuilderException e) { EclipseUtil.logError("Cannot build proposal model", e, JenkinsEditorActivator.getDefault()); return Collections.emptySet(); } if (item.isRoot()){ Set<ProposalProvider> set = Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); return set; } parentAsText=item.getIdentifier(); List<Node> foundParents = model.findByKeyword(parentAsText); if (foundParents.isEmpty()){ return Collections.emptySet(); } return fetchChildrenProposalsForParents(source, offset, foundParents); }
JenkinsWordCompletion extends AbstractWordCodeCompletition { @Override public Set<ProposalProvider> calculate(String source, int offset) { if (source.trim().length()==0){ return Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); } String parentAsText = ""; JenkinsModelBuilder builder = new JenkinsModelBuilder(new ByteArrayInputStream(source.getBytes())); BuildContext builderContext = new BuildContext(); Item item = null; try { Model model = builder.build(builderContext); item = model.getParentItemOf(offset); } catch (ModelBuilderException e) { EclipseUtil.logError("Cannot build proposal model", e, JenkinsEditorActivator.getDefault()); return Collections.emptySet(); } if (item.isRoot()){ Set<ProposalProvider> set = Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); return set; } parentAsText=item.getIdentifier(); List<Node> foundParents = model.findByKeyword(parentAsText); if (foundParents.isEmpty()){ return Collections.emptySet(); } return fetchChildrenProposalsForParents(source, offset, foundParents); } }
JenkinsWordCompletion extends AbstractWordCodeCompletition { @Override public Set<ProposalProvider> calculate(String source, int offset) { if (source.trim().length()==0){ return Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); } String parentAsText = ""; JenkinsModelBuilder builder = new JenkinsModelBuilder(new ByteArrayInputStream(source.getBytes())); BuildContext builderContext = new BuildContext(); Item item = null; try { Model model = builder.build(builderContext); item = model.getParentItemOf(offset); } catch (ModelBuilderException e) { EclipseUtil.logError("Cannot build proposal model", e, JenkinsEditorActivator.getDefault()); return Collections.emptySet(); } if (item.isRoot()){ Set<ProposalProvider> set = Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); return set; } parentAsText=item.getIdentifier(); List<Node> foundParents = model.findByKeyword(parentAsText); if (foundParents.isEmpty()){ return Collections.emptySet(); } return fetchChildrenProposalsForParents(source, offset, foundParents); } JenkinsWordCompletion(); }
JenkinsWordCompletion extends AbstractWordCodeCompletition { @Override public Set<ProposalProvider> calculate(String source, int offset) { if (source.trim().length()==0){ return Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); } String parentAsText = ""; JenkinsModelBuilder builder = new JenkinsModelBuilder(new ByteArrayInputStream(source.getBytes())); BuildContext builderContext = new BuildContext(); Item item = null; try { Model model = builder.build(builderContext); item = model.getParentItemOf(offset); } catch (ModelBuilderException e) { EclipseUtil.logError("Cannot build proposal model", e, JenkinsEditorActivator.getDefault()); return Collections.emptySet(); } if (item.isRoot()){ Set<ProposalProvider> set = Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); return set; } parentAsText=item.getIdentifier(); List<Node> foundParents = model.findByKeyword(parentAsText); if (foundParents.isEmpty()){ return Collections.emptySet(); } return fetchChildrenProposalsForParents(source, offset, foundParents); } JenkinsWordCompletion(); @Override Set<ProposalProvider> calculate(String source, int offset); @Override void reset(); }
JenkinsWordCompletion extends AbstractWordCodeCompletition { @Override public Set<ProposalProvider> calculate(String source, int offset) { if (source.trim().length()==0){ return Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); } String parentAsText = ""; JenkinsModelBuilder builder = new JenkinsModelBuilder(new ByteArrayInputStream(source.getBytes())); BuildContext builderContext = new BuildContext(); Item item = null; try { Model model = builder.build(builderContext); item = model.getParentItemOf(offset); } catch (ModelBuilderException e) { EclipseUtil.logError("Cannot build proposal model", e, JenkinsEditorActivator.getDefault()); return Collections.emptySet(); } if (item.isRoot()){ Set<ProposalProvider> set = Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); return set; } parentAsText=item.getIdentifier(); List<Node> foundParents = model.findByKeyword(parentAsText); if (foundParents.isEmpty()){ return Collections.emptySet(); } return fetchChildrenProposalsForParents(source, offset, foundParents); } JenkinsWordCompletion(); @Override Set<ProposalProvider> calculate(String source, int offset); @Override void reset(); }
@Test public void workflowscript_no_stages_specified_at_line_3_comma_column2__is_recognized_as_error() { String line = "WorkflowScript: 2: No stages specified @ line 3, column 2."; JenkinsLinterError error = builderToTest.build(line); assertNotNull(error); assertEquals(3,error.getLine()); assertEquals(2,error.getColumn()); assertEquals(line,error.getMessage()); }
public JenkinsLinterError build(String line) { if (line==null){ return null; } Matcher matcher = ERROR_PATTERN.matcher(line); if (! matcher.find()){ return null; } JenkinsLinterError error = new JenkinsLinterError(); error.message=line; error.line = Integer.valueOf(matcher.group(1)); error.column = Integer.valueOf(matcher.group(2)); return error; }
JenkinsLinterErrorBuilder { public JenkinsLinterError build(String line) { if (line==null){ return null; } Matcher matcher = ERROR_PATTERN.matcher(line); if (! matcher.find()){ return null; } JenkinsLinterError error = new JenkinsLinterError(); error.message=line; error.line = Integer.valueOf(matcher.group(1)); error.column = Integer.valueOf(matcher.group(2)); return error; } }
JenkinsLinterErrorBuilder { public JenkinsLinterError build(String line) { if (line==null){ return null; } Matcher matcher = ERROR_PATTERN.matcher(line); if (! matcher.find()){ return null; } JenkinsLinterError error = new JenkinsLinterError(); error.message=line; error.line = Integer.valueOf(matcher.group(1)); error.column = Integer.valueOf(matcher.group(2)); return error; } }
JenkinsLinterErrorBuilder { public JenkinsLinterError build(String line) { if (line==null){ return null; } Matcher matcher = ERROR_PATTERN.matcher(line); if (! matcher.find()){ return null; } JenkinsLinterError error = new JenkinsLinterError(); error.message=line; error.line = Integer.valueOf(matcher.group(1)); error.column = Integer.valueOf(matcher.group(2)); return error; } JenkinsLinterError build(String line); }
JenkinsLinterErrorBuilder { public JenkinsLinterError build(String line) { if (line==null){ return null; } Matcher matcher = ERROR_PATTERN.matcher(line); if (! matcher.find()){ return null; } JenkinsLinterError error = new JenkinsLinterError(); error.message=line; error.line = Integer.valueOf(matcher.group(1)); error.column = Integer.valueOf(matcher.group(2)); return error; } JenkinsLinterError build(String line); }
@Test public void an_pip_source_will_result_in_pipeline() { Set<ProposalProvider> result = completion.calculate("pip", 0); assertFalse(result.isEmpty()); assertEquals(1,result.size()); ProposalProvider provider = result.iterator().next(); assertTrue(provider.getLabel().equals("pipeline")); List<String> template = provider.getCodeTemplate(); assertEquals(3, template.size()); Iterator<String> it = template.iterator(); assertEquals(it.next(), "pipeline {"); assertEquals(it.next(), " "+SourceCodeBuilder.CURSOR_TAG); assertEquals(it.next(), "}"); }
@Override public Set<ProposalProvider> calculate(String source, int offset) { if (source.trim().length()==0){ return Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); } String parentAsText = ""; JenkinsModelBuilder builder = new JenkinsModelBuilder(new ByteArrayInputStream(source.getBytes())); BuildContext builderContext = new BuildContext(); Item item = null; try { Model model = builder.build(builderContext); item = model.getParentItemOf(offset); } catch (ModelBuilderException e) { EclipseUtil.logError("Cannot build proposal model", e, JenkinsEditorActivator.getDefault()); return Collections.emptySet(); } if (item.isRoot()){ Set<ProposalProvider> set = Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); return set; } parentAsText=item.getIdentifier(); List<Node> foundParents = model.findByKeyword(parentAsText); if (foundParents.isEmpty()){ return Collections.emptySet(); } return fetchChildrenProposalsForParents(source, offset, foundParents); }
JenkinsWordCompletion extends AbstractWordCodeCompletition { @Override public Set<ProposalProvider> calculate(String source, int offset) { if (source.trim().length()==0){ return Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); } String parentAsText = ""; JenkinsModelBuilder builder = new JenkinsModelBuilder(new ByteArrayInputStream(source.getBytes())); BuildContext builderContext = new BuildContext(); Item item = null; try { Model model = builder.build(builderContext); item = model.getParentItemOf(offset); } catch (ModelBuilderException e) { EclipseUtil.logError("Cannot build proposal model", e, JenkinsEditorActivator.getDefault()); return Collections.emptySet(); } if (item.isRoot()){ Set<ProposalProvider> set = Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); return set; } parentAsText=item.getIdentifier(); List<Node> foundParents = model.findByKeyword(parentAsText); if (foundParents.isEmpty()){ return Collections.emptySet(); } return fetchChildrenProposalsForParents(source, offset, foundParents); } }
JenkinsWordCompletion extends AbstractWordCodeCompletition { @Override public Set<ProposalProvider> calculate(String source, int offset) { if (source.trim().length()==0){ return Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); } String parentAsText = ""; JenkinsModelBuilder builder = new JenkinsModelBuilder(new ByteArrayInputStream(source.getBytes())); BuildContext builderContext = new BuildContext(); Item item = null; try { Model model = builder.build(builderContext); item = model.getParentItemOf(offset); } catch (ModelBuilderException e) { EclipseUtil.logError("Cannot build proposal model", e, JenkinsEditorActivator.getDefault()); return Collections.emptySet(); } if (item.isRoot()){ Set<ProposalProvider> set = Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); return set; } parentAsText=item.getIdentifier(); List<Node> foundParents = model.findByKeyword(parentAsText); if (foundParents.isEmpty()){ return Collections.emptySet(); } return fetchChildrenProposalsForParents(source, offset, foundParents); } JenkinsWordCompletion(); }
JenkinsWordCompletion extends AbstractWordCodeCompletition { @Override public Set<ProposalProvider> calculate(String source, int offset) { if (source.trim().length()==0){ return Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); } String parentAsText = ""; JenkinsModelBuilder builder = new JenkinsModelBuilder(new ByteArrayInputStream(source.getBytes())); BuildContext builderContext = new BuildContext(); Item item = null; try { Model model = builder.build(builderContext); item = model.getParentItemOf(offset); } catch (ModelBuilderException e) { EclipseUtil.logError("Cannot build proposal model", e, JenkinsEditorActivator.getDefault()); return Collections.emptySet(); } if (item.isRoot()){ Set<ProposalProvider> set = Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); return set; } parentAsText=item.getIdentifier(); List<Node> foundParents = model.findByKeyword(parentAsText); if (foundParents.isEmpty()){ return Collections.emptySet(); } return fetchChildrenProposalsForParents(source, offset, foundParents); } JenkinsWordCompletion(); @Override Set<ProposalProvider> calculate(String source, int offset); @Override void reset(); }
JenkinsWordCompletion extends AbstractWordCodeCompletition { @Override public Set<ProposalProvider> calculate(String source, int offset) { if (source.trim().length()==0){ return Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); } String parentAsText = ""; JenkinsModelBuilder builder = new JenkinsModelBuilder(new ByteArrayInputStream(source.getBytes())); BuildContext builderContext = new BuildContext(); Item item = null; try { Model model = builder.build(builderContext); item = model.getParentItemOf(offset); } catch (ModelBuilderException e) { EclipseUtil.logError("Cannot build proposal model", e, JenkinsEditorActivator.getDefault()); return Collections.emptySet(); } if (item.isRoot()){ Set<ProposalProvider> set = Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); return set; } parentAsText=item.getIdentifier(); List<Node> foundParents = model.findByKeyword(parentAsText); if (foundParents.isEmpty()){ return Collections.emptySet(); } return fetchChildrenProposalsForParents(source, offset, foundParents); } JenkinsWordCompletion(); @Override Set<ProposalProvider> calculate(String source, int offset); @Override void reset(); }
@Test public void after_pipeline_agent_is_suggested() { Set<ProposalProvider> result = completion.calculate(source1, source1_pipeline_block_index); assertLabelFound("agent",result); }
@Override public Set<ProposalProvider> calculate(String source, int offset) { if (source.trim().length()==0){ return Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); } String parentAsText = ""; JenkinsModelBuilder builder = new JenkinsModelBuilder(new ByteArrayInputStream(source.getBytes())); BuildContext builderContext = new BuildContext(); Item item = null; try { Model model = builder.build(builderContext); item = model.getParentItemOf(offset); } catch (ModelBuilderException e) { EclipseUtil.logError("Cannot build proposal model", e, JenkinsEditorActivator.getDefault()); return Collections.emptySet(); } if (item.isRoot()){ Set<ProposalProvider> set = Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); return set; } parentAsText=item.getIdentifier(); List<Node> foundParents = model.findByKeyword(parentAsText); if (foundParents.isEmpty()){ return Collections.emptySet(); } return fetchChildrenProposalsForParents(source, offset, foundParents); }
JenkinsWordCompletion extends AbstractWordCodeCompletition { @Override public Set<ProposalProvider> calculate(String source, int offset) { if (source.trim().length()==0){ return Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); } String parentAsText = ""; JenkinsModelBuilder builder = new JenkinsModelBuilder(new ByteArrayInputStream(source.getBytes())); BuildContext builderContext = new BuildContext(); Item item = null; try { Model model = builder.build(builderContext); item = model.getParentItemOf(offset); } catch (ModelBuilderException e) { EclipseUtil.logError("Cannot build proposal model", e, JenkinsEditorActivator.getDefault()); return Collections.emptySet(); } if (item.isRoot()){ Set<ProposalProvider> set = Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); return set; } parentAsText=item.getIdentifier(); List<Node> foundParents = model.findByKeyword(parentAsText); if (foundParents.isEmpty()){ return Collections.emptySet(); } return fetchChildrenProposalsForParents(source, offset, foundParents); } }
JenkinsWordCompletion extends AbstractWordCodeCompletition { @Override public Set<ProposalProvider> calculate(String source, int offset) { if (source.trim().length()==0){ return Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); } String parentAsText = ""; JenkinsModelBuilder builder = new JenkinsModelBuilder(new ByteArrayInputStream(source.getBytes())); BuildContext builderContext = new BuildContext(); Item item = null; try { Model model = builder.build(builderContext); item = model.getParentItemOf(offset); } catch (ModelBuilderException e) { EclipseUtil.logError("Cannot build proposal model", e, JenkinsEditorActivator.getDefault()); return Collections.emptySet(); } if (item.isRoot()){ Set<ProposalProvider> set = Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); return set; } parentAsText=item.getIdentifier(); List<Node> foundParents = model.findByKeyword(parentAsText); if (foundParents.isEmpty()){ return Collections.emptySet(); } return fetchChildrenProposalsForParents(source, offset, foundParents); } JenkinsWordCompletion(); }
JenkinsWordCompletion extends AbstractWordCodeCompletition { @Override public Set<ProposalProvider> calculate(String source, int offset) { if (source.trim().length()==0){ return Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); } String parentAsText = ""; JenkinsModelBuilder builder = new JenkinsModelBuilder(new ByteArrayInputStream(source.getBytes())); BuildContext builderContext = new BuildContext(); Item item = null; try { Model model = builder.build(builderContext); item = model.getParentItemOf(offset); } catch (ModelBuilderException e) { EclipseUtil.logError("Cannot build proposal model", e, JenkinsEditorActivator.getDefault()); return Collections.emptySet(); } if (item.isRoot()){ Set<ProposalProvider> set = Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); return set; } parentAsText=item.getIdentifier(); List<Node> foundParents = model.findByKeyword(parentAsText); if (foundParents.isEmpty()){ return Collections.emptySet(); } return fetchChildrenProposalsForParents(source, offset, foundParents); } JenkinsWordCompletion(); @Override Set<ProposalProvider> calculate(String source, int offset); @Override void reset(); }
JenkinsWordCompletion extends AbstractWordCodeCompletition { @Override public Set<ProposalProvider> calculate(String source, int offset) { if (source.trim().length()==0){ return Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); } String parentAsText = ""; JenkinsModelBuilder builder = new JenkinsModelBuilder(new ByteArrayInputStream(source.getBytes())); BuildContext builderContext = new BuildContext(); Item item = null; try { Model model = builder.build(builderContext); item = model.getParentItemOf(offset); } catch (ModelBuilderException e) { EclipseUtil.logError("Cannot build proposal model", e, JenkinsEditorActivator.getDefault()); return Collections.emptySet(); } if (item.isRoot()){ Set<ProposalProvider> set = Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); return set; } parentAsText=item.getIdentifier(); List<Node> foundParents = model.findByKeyword(parentAsText); if (foundParents.isEmpty()){ return Collections.emptySet(); } return fetchChildrenProposalsForParents(source, offset, foundParents); } JenkinsWordCompletion(); @Override Set<ProposalProvider> calculate(String source, int offset); @Override void reset(); }
@Test public void after_pipeline_stage_is_suggested() { Set<ProposalProvider> result = completion.calculate(source1, source1_pipeline_block_index); assertLabelFound("stages",result); }
@Override public Set<ProposalProvider> calculate(String source, int offset) { if (source.trim().length()==0){ return Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); } String parentAsText = ""; JenkinsModelBuilder builder = new JenkinsModelBuilder(new ByteArrayInputStream(source.getBytes())); BuildContext builderContext = new BuildContext(); Item item = null; try { Model model = builder.build(builderContext); item = model.getParentItemOf(offset); } catch (ModelBuilderException e) { EclipseUtil.logError("Cannot build proposal model", e, JenkinsEditorActivator.getDefault()); return Collections.emptySet(); } if (item.isRoot()){ Set<ProposalProvider> set = Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); return set; } parentAsText=item.getIdentifier(); List<Node> foundParents = model.findByKeyword(parentAsText); if (foundParents.isEmpty()){ return Collections.emptySet(); } return fetchChildrenProposalsForParents(source, offset, foundParents); }
JenkinsWordCompletion extends AbstractWordCodeCompletition { @Override public Set<ProposalProvider> calculate(String source, int offset) { if (source.trim().length()==0){ return Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); } String parentAsText = ""; JenkinsModelBuilder builder = new JenkinsModelBuilder(new ByteArrayInputStream(source.getBytes())); BuildContext builderContext = new BuildContext(); Item item = null; try { Model model = builder.build(builderContext); item = model.getParentItemOf(offset); } catch (ModelBuilderException e) { EclipseUtil.logError("Cannot build proposal model", e, JenkinsEditorActivator.getDefault()); return Collections.emptySet(); } if (item.isRoot()){ Set<ProposalProvider> set = Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); return set; } parentAsText=item.getIdentifier(); List<Node> foundParents = model.findByKeyword(parentAsText); if (foundParents.isEmpty()){ return Collections.emptySet(); } return fetchChildrenProposalsForParents(source, offset, foundParents); } }
JenkinsWordCompletion extends AbstractWordCodeCompletition { @Override public Set<ProposalProvider> calculate(String source, int offset) { if (source.trim().length()==0){ return Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); } String parentAsText = ""; JenkinsModelBuilder builder = new JenkinsModelBuilder(new ByteArrayInputStream(source.getBytes())); BuildContext builderContext = new BuildContext(); Item item = null; try { Model model = builder.build(builderContext); item = model.getParentItemOf(offset); } catch (ModelBuilderException e) { EclipseUtil.logError("Cannot build proposal model", e, JenkinsEditorActivator.getDefault()); return Collections.emptySet(); } if (item.isRoot()){ Set<ProposalProvider> set = Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); return set; } parentAsText=item.getIdentifier(); List<Node> foundParents = model.findByKeyword(parentAsText); if (foundParents.isEmpty()){ return Collections.emptySet(); } return fetchChildrenProposalsForParents(source, offset, foundParents); } JenkinsWordCompletion(); }
JenkinsWordCompletion extends AbstractWordCodeCompletition { @Override public Set<ProposalProvider> calculate(String source, int offset) { if (source.trim().length()==0){ return Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); } String parentAsText = ""; JenkinsModelBuilder builder = new JenkinsModelBuilder(new ByteArrayInputStream(source.getBytes())); BuildContext builderContext = new BuildContext(); Item item = null; try { Model model = builder.build(builderContext); item = model.getParentItemOf(offset); } catch (ModelBuilderException e) { EclipseUtil.logError("Cannot build proposal model", e, JenkinsEditorActivator.getDefault()); return Collections.emptySet(); } if (item.isRoot()){ Set<ProposalProvider> set = Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); return set; } parentAsText=item.getIdentifier(); List<Node> foundParents = model.findByKeyword(parentAsText); if (foundParents.isEmpty()){ return Collections.emptySet(); } return fetchChildrenProposalsForParents(source, offset, foundParents); } JenkinsWordCompletion(); @Override Set<ProposalProvider> calculate(String source, int offset); @Override void reset(); }
JenkinsWordCompletion extends AbstractWordCodeCompletition { @Override public Set<ProposalProvider> calculate(String source, int offset) { if (source.trim().length()==0){ return Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); } String parentAsText = ""; JenkinsModelBuilder builder = new JenkinsModelBuilder(new ByteArrayInputStream(source.getBytes())); BuildContext builderContext = new BuildContext(); Item item = null; try { Model model = builder.build(builderContext); item = model.getParentItemOf(offset); } catch (ModelBuilderException e) { EclipseUtil.logError("Cannot build proposal model", e, JenkinsEditorActivator.getDefault()); return Collections.emptySet(); } if (item.isRoot()){ Set<ProposalProvider> set = Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); return set; } parentAsText=item.getIdentifier(); List<Node> foundParents = model.findByKeyword(parentAsText); if (foundParents.isEmpty()){ return Collections.emptySet(); } return fetchChildrenProposalsForParents(source, offset, foundParents); } JenkinsWordCompletion(); @Override Set<ProposalProvider> calculate(String source, int offset); @Override void reset(); }
@Test public void after_pipeline_pipeline_is_NOT_suggested() { Set<ProposalProvider> result = completion.calculate(source1, source1_pipeline_block_index); assertNOLabelFound("pipeline",result); }
@Override public Set<ProposalProvider> calculate(String source, int offset) { if (source.trim().length()==0){ return Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); } String parentAsText = ""; JenkinsModelBuilder builder = new JenkinsModelBuilder(new ByteArrayInputStream(source.getBytes())); BuildContext builderContext = new BuildContext(); Item item = null; try { Model model = builder.build(builderContext); item = model.getParentItemOf(offset); } catch (ModelBuilderException e) { EclipseUtil.logError("Cannot build proposal model", e, JenkinsEditorActivator.getDefault()); return Collections.emptySet(); } if (item.isRoot()){ Set<ProposalProvider> set = Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); return set; } parentAsText=item.getIdentifier(); List<Node> foundParents = model.findByKeyword(parentAsText); if (foundParents.isEmpty()){ return Collections.emptySet(); } return fetchChildrenProposalsForParents(source, offset, foundParents); }
JenkinsWordCompletion extends AbstractWordCodeCompletition { @Override public Set<ProposalProvider> calculate(String source, int offset) { if (source.trim().length()==0){ return Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); } String parentAsText = ""; JenkinsModelBuilder builder = new JenkinsModelBuilder(new ByteArrayInputStream(source.getBytes())); BuildContext builderContext = new BuildContext(); Item item = null; try { Model model = builder.build(builderContext); item = model.getParentItemOf(offset); } catch (ModelBuilderException e) { EclipseUtil.logError("Cannot build proposal model", e, JenkinsEditorActivator.getDefault()); return Collections.emptySet(); } if (item.isRoot()){ Set<ProposalProvider> set = Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); return set; } parentAsText=item.getIdentifier(); List<Node> foundParents = model.findByKeyword(parentAsText); if (foundParents.isEmpty()){ return Collections.emptySet(); } return fetchChildrenProposalsForParents(source, offset, foundParents); } }
JenkinsWordCompletion extends AbstractWordCodeCompletition { @Override public Set<ProposalProvider> calculate(String source, int offset) { if (source.trim().length()==0){ return Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); } String parentAsText = ""; JenkinsModelBuilder builder = new JenkinsModelBuilder(new ByteArrayInputStream(source.getBytes())); BuildContext builderContext = new BuildContext(); Item item = null; try { Model model = builder.build(builderContext); item = model.getParentItemOf(offset); } catch (ModelBuilderException e) { EclipseUtil.logError("Cannot build proposal model", e, JenkinsEditorActivator.getDefault()); return Collections.emptySet(); } if (item.isRoot()){ Set<ProposalProvider> set = Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); return set; } parentAsText=item.getIdentifier(); List<Node> foundParents = model.findByKeyword(parentAsText); if (foundParents.isEmpty()){ return Collections.emptySet(); } return fetchChildrenProposalsForParents(source, offset, foundParents); } JenkinsWordCompletion(); }
JenkinsWordCompletion extends AbstractWordCodeCompletition { @Override public Set<ProposalProvider> calculate(String source, int offset) { if (source.trim().length()==0){ return Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); } String parentAsText = ""; JenkinsModelBuilder builder = new JenkinsModelBuilder(new ByteArrayInputStream(source.getBytes())); BuildContext builderContext = new BuildContext(); Item item = null; try { Model model = builder.build(builderContext); item = model.getParentItemOf(offset); } catch (ModelBuilderException e) { EclipseUtil.logError("Cannot build proposal model", e, JenkinsEditorActivator.getDefault()); return Collections.emptySet(); } if (item.isRoot()){ Set<ProposalProvider> set = Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); return set; } parentAsText=item.getIdentifier(); List<Node> foundParents = model.findByKeyword(parentAsText); if (foundParents.isEmpty()){ return Collections.emptySet(); } return fetchChildrenProposalsForParents(source, offset, foundParents); } JenkinsWordCompletion(); @Override Set<ProposalProvider> calculate(String source, int offset); @Override void reset(); }
JenkinsWordCompletion extends AbstractWordCodeCompletition { @Override public Set<ProposalProvider> calculate(String source, int offset) { if (source.trim().length()==0){ return Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); } String parentAsText = ""; JenkinsModelBuilder builder = new JenkinsModelBuilder(new ByteArrayInputStream(source.getBytes())); BuildContext builderContext = new BuildContext(); Item item = null; try { Model model = builder.build(builderContext); item = model.getParentItemOf(offset); } catch (ModelBuilderException e) { EclipseUtil.logError("Cannot build proposal model", e, JenkinsEditorActivator.getDefault()); return Collections.emptySet(); } if (item.isRoot()){ Set<ProposalProvider> set = Collections.singleton(new JenkinsDSLTypeProposalProvider(JenkinsDefaultClosureKeyWords.PIPELINE)); return set; } parentAsText=item.getIdentifier(); List<Node> foundParents = model.findByKeyword(parentAsText); if (foundParents.isEmpty()){ return Collections.emptySet(); } return fetchChildrenProposalsForParents(source, offset, foundParents); } JenkinsWordCompletion(); @Override Set<ProposalProvider> calculate(String source, int offset); @Override void reset(); }
@Test public void workflowscript_no_stages_specified_at_line_3000_comma_column22__is_recognized_as_error() { String line = "WorkflowScript: 2: No stages specified @ line 3000, column 22."; JenkinsLinterError error = builderToTest.build(line); assertNotNull(error); assertEquals(3000,error.getLine()); assertEquals(22,error.getColumn()); assertEquals(line,error.getMessage()); }
public JenkinsLinterError build(String line) { if (line==null){ return null; } Matcher matcher = ERROR_PATTERN.matcher(line); if (! matcher.find()){ return null; } JenkinsLinterError error = new JenkinsLinterError(); error.message=line; error.line = Integer.valueOf(matcher.group(1)); error.column = Integer.valueOf(matcher.group(2)); return error; }
JenkinsLinterErrorBuilder { public JenkinsLinterError build(String line) { if (line==null){ return null; } Matcher matcher = ERROR_PATTERN.matcher(line); if (! matcher.find()){ return null; } JenkinsLinterError error = new JenkinsLinterError(); error.message=line; error.line = Integer.valueOf(matcher.group(1)); error.column = Integer.valueOf(matcher.group(2)); return error; } }
JenkinsLinterErrorBuilder { public JenkinsLinterError build(String line) { if (line==null){ return null; } Matcher matcher = ERROR_PATTERN.matcher(line); if (! matcher.find()){ return null; } JenkinsLinterError error = new JenkinsLinterError(); error.message=line; error.line = Integer.valueOf(matcher.group(1)); error.column = Integer.valueOf(matcher.group(2)); return error; } }
JenkinsLinterErrorBuilder { public JenkinsLinterError build(String line) { if (line==null){ return null; } Matcher matcher = ERROR_PATTERN.matcher(line); if (! matcher.find()){ return null; } JenkinsLinterError error = new JenkinsLinterError(); error.message=line; error.line = Integer.valueOf(matcher.group(1)); error.column = Integer.valueOf(matcher.group(2)); return error; } JenkinsLinterError build(String line); }
JenkinsLinterErrorBuilder { public JenkinsLinterError build(String line) { if (line==null){ return null; } Matcher matcher = ERROR_PATTERN.matcher(line); if (! matcher.find()){ return null; } JenkinsLinterError error = new JenkinsLinterError(); error.message=line; error.line = Integer.valueOf(matcher.group(1)); error.column = Integer.valueOf(matcher.group(2)); return error; } JenkinsLinterError build(String line); }
@Test public void errors_encountered_validating_jenkinsfile_is_not_an_error_itself() { String line = "Errors encountered validating Jenkinsfile:"; JenkinsLinterError error = builderToTest.build(line); assertNull(error); }
public JenkinsLinterError build(String line) { if (line==null){ return null; } Matcher matcher = ERROR_PATTERN.matcher(line); if (! matcher.find()){ return null; } JenkinsLinterError error = new JenkinsLinterError(); error.message=line; error.line = Integer.valueOf(matcher.group(1)); error.column = Integer.valueOf(matcher.group(2)); return error; }
JenkinsLinterErrorBuilder { public JenkinsLinterError build(String line) { if (line==null){ return null; } Matcher matcher = ERROR_PATTERN.matcher(line); if (! matcher.find()){ return null; } JenkinsLinterError error = new JenkinsLinterError(); error.message=line; error.line = Integer.valueOf(matcher.group(1)); error.column = Integer.valueOf(matcher.group(2)); return error; } }
JenkinsLinterErrorBuilder { public JenkinsLinterError build(String line) { if (line==null){ return null; } Matcher matcher = ERROR_PATTERN.matcher(line); if (! matcher.find()){ return null; } JenkinsLinterError error = new JenkinsLinterError(); error.message=line; error.line = Integer.valueOf(matcher.group(1)); error.column = Integer.valueOf(matcher.group(2)); return error; } }
JenkinsLinterErrorBuilder { public JenkinsLinterError build(String line) { if (line==null){ return null; } Matcher matcher = ERROR_PATTERN.matcher(line); if (! matcher.find()){ return null; } JenkinsLinterError error = new JenkinsLinterError(); error.message=line; error.line = Integer.valueOf(matcher.group(1)); error.column = Integer.valueOf(matcher.group(2)); return error; } JenkinsLinterError build(String line); }
JenkinsLinterErrorBuilder { public JenkinsLinterError build(String line) { if (line==null){ return null; } Matcher matcher = ERROR_PATTERN.matcher(line); if (! matcher.find()){ return null; } JenkinsLinterError error = new JenkinsLinterError(); error.message=line; error.line = Integer.valueOf(matcher.group(1)); error.column = Integer.valueOf(matcher.group(2)); return error; } JenkinsLinterError build(String line); }
@Test public void infotext_about_pipeline_code_is_not_a_error() { String line = " pipeline{"; JenkinsLinterError error = builderToTest.build(line); assertNull(error); }
public JenkinsLinterError build(String line) { if (line==null){ return null; } Matcher matcher = ERROR_PATTERN.matcher(line); if (! matcher.find()){ return null; } JenkinsLinterError error = new JenkinsLinterError(); error.message=line; error.line = Integer.valueOf(matcher.group(1)); error.column = Integer.valueOf(matcher.group(2)); return error; }
JenkinsLinterErrorBuilder { public JenkinsLinterError build(String line) { if (line==null){ return null; } Matcher matcher = ERROR_PATTERN.matcher(line); if (! matcher.find()){ return null; } JenkinsLinterError error = new JenkinsLinterError(); error.message=line; error.line = Integer.valueOf(matcher.group(1)); error.column = Integer.valueOf(matcher.group(2)); return error; } }
JenkinsLinterErrorBuilder { public JenkinsLinterError build(String line) { if (line==null){ return null; } Matcher matcher = ERROR_PATTERN.matcher(line); if (! matcher.find()){ return null; } JenkinsLinterError error = new JenkinsLinterError(); error.message=line; error.line = Integer.valueOf(matcher.group(1)); error.column = Integer.valueOf(matcher.group(2)); return error; } }
JenkinsLinterErrorBuilder { public JenkinsLinterError build(String line) { if (line==null){ return null; } Matcher matcher = ERROR_PATTERN.matcher(line); if (! matcher.find()){ return null; } JenkinsLinterError error = new JenkinsLinterError(); error.message=line; error.line = Integer.valueOf(matcher.group(1)); error.column = Integer.valueOf(matcher.group(2)); return error; } JenkinsLinterError build(String line); }
JenkinsLinterErrorBuilder { public JenkinsLinterError build(String line) { if (line==null){ return null; } Matcher matcher = ERROR_PATTERN.matcher(line); if (! matcher.find()){ return null; } JenkinsLinterError error = new JenkinsLinterError(); error.message=line; error.line = Integer.valueOf(matcher.group(1)); error.column = Integer.valueOf(matcher.group(2)); return error; } JenkinsLinterError build(String line); }
@Test public void prefix_key_value_returned_as_system_property_entry() { assertEquals("-Dprefix.key=value",builderToTest.build("prefix", "key", "value")); }
public String build(String type, String key, String value){ StringBuilder sb = new StringBuilder(); sb.append("-D"); sb.append(type); sb.append('.'); sb.append(key); sb.append('='); sb.append(value); return sb.toString(); }
SystemPropertyListBuilder { public String build(String type, String key, String value){ StringBuilder sb = new StringBuilder(); sb.append("-D"); sb.append(type); sb.append('.'); sb.append(key); sb.append('='); sb.append(value); return sb.toString(); } }
SystemPropertyListBuilder { public String build(String type, String key, String value){ StringBuilder sb = new StringBuilder(); sb.append("-D"); sb.append(type); sb.append('.'); sb.append(key); sb.append('='); sb.append(value); return sb.toString(); } }
SystemPropertyListBuilder { public String build(String type, String key, String value){ StringBuilder sb = new StringBuilder(); sb.append("-D"); sb.append(type); sb.append('.'); sb.append(key); sb.append('='); sb.append(value); return sb.toString(); } String build(String type, String key, String value); }
SystemPropertyListBuilder { public String build(String type, String key, String value){ StringBuilder sb = new StringBuilder(); sb.append("-D"); sb.append(type); sb.append('.'); sb.append(key); sb.append('='); sb.append(value); return sb.toString(); } String build(String type, String key, String value); }
@Test public void null_key_value_returned_as_system_property_entry() { assertEquals("-Dnull.key=value",builderToTest.build(null, "key", "value")); }
public String build(String type, String key, String value){ StringBuilder sb = new StringBuilder(); sb.append("-D"); sb.append(type); sb.append('.'); sb.append(key); sb.append('='); sb.append(value); return sb.toString(); }
SystemPropertyListBuilder { public String build(String type, String key, String value){ StringBuilder sb = new StringBuilder(); sb.append("-D"); sb.append(type); sb.append('.'); sb.append(key); sb.append('='); sb.append(value); return sb.toString(); } }
SystemPropertyListBuilder { public String build(String type, String key, String value){ StringBuilder sb = new StringBuilder(); sb.append("-D"); sb.append(type); sb.append('.'); sb.append(key); sb.append('='); sb.append(value); return sb.toString(); } }
SystemPropertyListBuilder { public String build(String type, String key, String value){ StringBuilder sb = new StringBuilder(); sb.append("-D"); sb.append(type); sb.append('.'); sb.append(key); sb.append('='); sb.append(value); return sb.toString(); } String build(String type, String key, String value); }
SystemPropertyListBuilder { public String build(String type, String key, String value){ StringBuilder sb = new StringBuilder(); sb.append("-D"); sb.append(type); sb.append('.'); sb.append(key); sb.append('='); sb.append(value); return sb.toString(); } String build(String type, String key, String value); }
@Test public void prefix_null_value_returned_as_system_property_entry() { assertEquals("-Dprefix.null=value",builderToTest.build("prefix", null, "value")); }
public String build(String type, String key, String value){ StringBuilder sb = new StringBuilder(); sb.append("-D"); sb.append(type); sb.append('.'); sb.append(key); sb.append('='); sb.append(value); return sb.toString(); }
SystemPropertyListBuilder { public String build(String type, String key, String value){ StringBuilder sb = new StringBuilder(); sb.append("-D"); sb.append(type); sb.append('.'); sb.append(key); sb.append('='); sb.append(value); return sb.toString(); } }
SystemPropertyListBuilder { public String build(String type, String key, String value){ StringBuilder sb = new StringBuilder(); sb.append("-D"); sb.append(type); sb.append('.'); sb.append(key); sb.append('='); sb.append(value); return sb.toString(); } }
SystemPropertyListBuilder { public String build(String type, String key, String value){ StringBuilder sb = new StringBuilder(); sb.append("-D"); sb.append(type); sb.append('.'); sb.append(key); sb.append('='); sb.append(value); return sb.toString(); } String build(String type, String key, String value); }
SystemPropertyListBuilder { public String build(String type, String key, String value){ StringBuilder sb = new StringBuilder(); sb.append("-D"); sb.append(type); sb.append('.'); sb.append(key); sb.append('='); sb.append(value); return sb.toString(); } String build(String type, String key, String value); }
@Test public void prefix_key_null_returned_as_system_property_entry() { assertEquals("-Dprefix.key=null",builderToTest.build("prefix", "key",null)); }
public String build(String type, String key, String value){ StringBuilder sb = new StringBuilder(); sb.append("-D"); sb.append(type); sb.append('.'); sb.append(key); sb.append('='); sb.append(value); return sb.toString(); }
SystemPropertyListBuilder { public String build(String type, String key, String value){ StringBuilder sb = new StringBuilder(); sb.append("-D"); sb.append(type); sb.append('.'); sb.append(key); sb.append('='); sb.append(value); return sb.toString(); } }
SystemPropertyListBuilder { public String build(String type, String key, String value){ StringBuilder sb = new StringBuilder(); sb.append("-D"); sb.append(type); sb.append('.'); sb.append(key); sb.append('='); sb.append(value); return sb.toString(); } }
SystemPropertyListBuilder { public String build(String type, String key, String value){ StringBuilder sb = new StringBuilder(); sb.append("-D"); sb.append(type); sb.append('.'); sb.append(key); sb.append('='); sb.append(value); return sb.toString(); } String build(String type, String key, String value); }
SystemPropertyListBuilder { public String build(String type, String key, String value){ StringBuilder sb = new StringBuilder(); sb.append("-D"); sb.append(type); sb.append('.'); sb.append(key); sb.append('='); sb.append(value); return sb.toString(); } String build(String type, String key, String value); }
@Test public void commands_NOT_hidden_expected_output_done() { String expected = "[java, -Dhttp.proxyPassword=mysecret1, -Dhttps.proxyPassword=mysecret2, -jar, thePath, -s, http: String[] commands = commandToTest.createCommands(configuration, parameter, false); List<String> list = Arrays.asList(commands); assertEquals(expected, list.toString()); }
protected String[] createCommands(JenkinsCLIConfiguration configuration, P parameter, boolean hidePasswords) { return createExecutionStrings(configuration, hidePasswords); }
AbstractJenkinsCLICommand implements JenkinsCLICommand<T, P> { protected String[] createCommands(JenkinsCLIConfiguration configuration, P parameter, boolean hidePasswords) { return createExecutionStrings(configuration, hidePasswords); } }
AbstractJenkinsCLICommand implements JenkinsCLICommand<T, P> { protected String[] createCommands(JenkinsCLIConfiguration configuration, P parameter, boolean hidePasswords) { return createExecutionStrings(configuration, hidePasswords); } }
AbstractJenkinsCLICommand implements JenkinsCLICommand<T, P> { protected String[] createCommands(JenkinsCLIConfiguration configuration, P parameter, boolean hidePasswords) { return createExecutionStrings(configuration, hidePasswords); } final T execute(JenkinsCLIConfiguration configuration, P parameter); }
AbstractJenkinsCLICommand implements JenkinsCLICommand<T, P> { protected String[] createCommands(JenkinsCLIConfiguration configuration, P parameter, boolean hidePasswords) { return createExecutionStrings(configuration, hidePasswords); } final T execute(JenkinsCLIConfiguration configuration, P parameter); }
@Test public void testFetchByYear_2010() { log.info("*** BEGIN Test ***"); Integer year = 2010; SeasonAnalytics seasonAnalytics = classUnderTest.fetchByYear(year); assertNotNull(seasonAnalytics); log.info("*** END Test ***"); }
@Override public SeasonAnalytics fetchByYear(Integer year) { SeasonAnalytics ret = null; String sql = "SELECT * FROM " + TABLE_NAME + " WHERE year = ?"; Object[] args = { year }; List<SeasonAnalytics> results = getJdbcTemplate().query(sql, args, new SeasonAnalyticsRowMapper()); if (results.size() > 0) { if (results.size() > 1) { log.warn("Expected 1 result from query, instead got " + results.size() + "!"); } ret = results.get(0); } else { log.warn("Requested year (" + year + ") does not exist in the DB!"); } return ret; }
SeasonAnalyticsJdbcDao extends JdbcDaoSupport implements SeasonAnalyticsDao { @Override public SeasonAnalytics fetchByYear(Integer year) { SeasonAnalytics ret = null; String sql = "SELECT * FROM " + TABLE_NAME + " WHERE year = ?"; Object[] args = { year }; List<SeasonAnalytics> results = getJdbcTemplate().query(sql, args, new SeasonAnalyticsRowMapper()); if (results.size() > 0) { if (results.size() > 1) { log.warn("Expected 1 result from query, instead got " + results.size() + "!"); } ret = results.get(0); } else { log.warn("Requested year (" + year + ") does not exist in the DB!"); } return ret; } }
SeasonAnalyticsJdbcDao extends JdbcDaoSupport implements SeasonAnalyticsDao { @Override public SeasonAnalytics fetchByYear(Integer year) { SeasonAnalytics ret = null; String sql = "SELECT * FROM " + TABLE_NAME + " WHERE year = ?"; Object[] args = { year }; List<SeasonAnalytics> results = getJdbcTemplate().query(sql, args, new SeasonAnalyticsRowMapper()); if (results.size() > 0) { if (results.size() > 1) { log.warn("Expected 1 result from query, instead got " + results.size() + "!"); } ret = results.get(0); } else { log.warn("Requested year (" + year + ") does not exist in the DB!"); } return ret; } SeasonAnalyticsJdbcDao(DataSource dataSource); }
SeasonAnalyticsJdbcDao extends JdbcDaoSupport implements SeasonAnalyticsDao { @Override public SeasonAnalytics fetchByYear(Integer year) { SeasonAnalytics ret = null; String sql = "SELECT * FROM " + TABLE_NAME + " WHERE year = ?"; Object[] args = { year }; List<SeasonAnalytics> results = getJdbcTemplate().query(sql, args, new SeasonAnalyticsRowMapper()); if (results.size() > 0) { if (results.size() > 1) { log.warn("Expected 1 result from query, instead got " + results.size() + "!"); } ret = results.get(0); } else { log.warn("Requested year (" + year + ") does not exist in the DB!"); } return ret; } SeasonAnalyticsJdbcDao(DataSource dataSource); @Override SeasonAnalytics fetchByYear(Integer year); }
SeasonAnalyticsJdbcDao extends JdbcDaoSupport implements SeasonAnalyticsDao { @Override public SeasonAnalytics fetchByYear(Integer year) { SeasonAnalytics ret = null; String sql = "SELECT * FROM " + TABLE_NAME + " WHERE year = ?"; Object[] args = { year }; List<SeasonAnalytics> results = getJdbcTemplate().query(sql, args, new SeasonAnalyticsRowMapper()); if (results.size() > 0) { if (results.size() > 1) { log.warn("Expected 1 result from query, instead got " + results.size() + "!"); } ret = results.get(0); } else { log.warn("Requested year (" + year + ") does not exist in the DB!"); } return ret; } SeasonAnalyticsJdbcDao(DataSource dataSource); @Override SeasonAnalytics fetchByYear(Integer year); }
@Test public void testFetchAllByYear_2013() { log.info("*** BEGIN Test ***"); Integer year = 2013; List<SeasonData> results = classUnderTest.fetchAllByYear(year); assertEquals(68, results.size()); log.info("*** END Test ***"); }
@Override public List<SeasonData> fetchAllByYear(Integer year) { List<SeasonData> ret = null; String sql = "SELECT t.* FROM " + TABLE_NAME + " t WHERE t.year = ?"; Object[] args = { year }; ret = getJdbcTemplate().query(sql, args, new SeasonDataRowMapper()); return ret; }
SeasonDataJdbcDao extends JdbcDaoSupport implements SeasonDataDao { @Override public List<SeasonData> fetchAllByYear(Integer year) { List<SeasonData> ret = null; String sql = "SELECT t.* FROM " + TABLE_NAME + " t WHERE t.year = ?"; Object[] args = { year }; ret = getJdbcTemplate().query(sql, args, new SeasonDataRowMapper()); return ret; } }
SeasonDataJdbcDao extends JdbcDaoSupport implements SeasonDataDao { @Override public List<SeasonData> fetchAllByYear(Integer year) { List<SeasonData> ret = null; String sql = "SELECT t.* FROM " + TABLE_NAME + " t WHERE t.year = ?"; Object[] args = { year }; ret = getJdbcTemplate().query(sql, args, new SeasonDataRowMapper()); return ret; } SeasonDataJdbcDao(DataSource dataSource); }
SeasonDataJdbcDao extends JdbcDaoSupport implements SeasonDataDao { @Override public List<SeasonData> fetchAllByYear(Integer year) { List<SeasonData> ret = null; String sql = "SELECT t.* FROM " + TABLE_NAME + " t WHERE t.year = ?"; Object[] args = { year }; ret = getJdbcTemplate().query(sql, args, new SeasonDataRowMapper()); return ret; } SeasonDataJdbcDao(DataSource dataSource); @Override List<SeasonData> fetchAllByYear(Integer year); @Override SeasonData fetchByYearAndTeamName(Integer year, String teamName); }
SeasonDataJdbcDao extends JdbcDaoSupport implements SeasonDataDao { @Override public List<SeasonData> fetchAllByYear(Integer year) { List<SeasonData> ret = null; String sql = "SELECT t.* FROM " + TABLE_NAME + " t WHERE t.year = ?"; Object[] args = { year }; ret = getJdbcTemplate().query(sql, args, new SeasonDataRowMapper()); return ret; } SeasonDataJdbcDao(DataSource dataSource); @Override List<SeasonData> fetchAllByYear(Integer year); @Override SeasonData fetchByYearAndTeamName(Integer year, String teamName); }
@Test public void testFetchAllByYear_2014() { log.info("*** BEGIN Test ***"); Integer year = 2014; List<SeasonData> results = classUnderTest.fetchAllByYear(year); assertEquals(68, results.size()); log.info("*** END Test ***"); }
@Override public List<SeasonData> fetchAllByYear(Integer year) { List<SeasonData> ret = null; String sql = "SELECT t.* FROM " + TABLE_NAME + " t WHERE t.year = ?"; Object[] args = { year }; ret = getJdbcTemplate().query(sql, args, new SeasonDataRowMapper()); return ret; }
SeasonDataJdbcDao extends JdbcDaoSupport implements SeasonDataDao { @Override public List<SeasonData> fetchAllByYear(Integer year) { List<SeasonData> ret = null; String sql = "SELECT t.* FROM " + TABLE_NAME + " t WHERE t.year = ?"; Object[] args = { year }; ret = getJdbcTemplate().query(sql, args, new SeasonDataRowMapper()); return ret; } }
SeasonDataJdbcDao extends JdbcDaoSupport implements SeasonDataDao { @Override public List<SeasonData> fetchAllByYear(Integer year) { List<SeasonData> ret = null; String sql = "SELECT t.* FROM " + TABLE_NAME + " t WHERE t.year = ?"; Object[] args = { year }; ret = getJdbcTemplate().query(sql, args, new SeasonDataRowMapper()); return ret; } SeasonDataJdbcDao(DataSource dataSource); }
SeasonDataJdbcDao extends JdbcDaoSupport implements SeasonDataDao { @Override public List<SeasonData> fetchAllByYear(Integer year) { List<SeasonData> ret = null; String sql = "SELECT t.* FROM " + TABLE_NAME + " t WHERE t.year = ?"; Object[] args = { year }; ret = getJdbcTemplate().query(sql, args, new SeasonDataRowMapper()); return ret; } SeasonDataJdbcDao(DataSource dataSource); @Override List<SeasonData> fetchAllByYear(Integer year); @Override SeasonData fetchByYearAndTeamName(Integer year, String teamName); }
SeasonDataJdbcDao extends JdbcDaoSupport implements SeasonDataDao { @Override public List<SeasonData> fetchAllByYear(Integer year) { List<SeasonData> ret = null; String sql = "SELECT t.* FROM " + TABLE_NAME + " t WHERE t.year = ?"; Object[] args = { year }; ret = getJdbcTemplate().query(sql, args, new SeasonDataRowMapper()); return ret; } SeasonDataJdbcDao(DataSource dataSource); @Override List<SeasonData> fetchAllByYear(Integer year); @Override SeasonData fetchByYearAndTeamName(Integer year, String teamName); }