target
stringlengths 20
113k
| src_fm
stringlengths 11
86.3k
| src_fm_fc
stringlengths 21
86.4k
| src_fm_fc_co
stringlengths 30
86.4k
| src_fm_fc_ms
stringlengths 42
86.8k
| src_fm_fc_ms_ff
stringlengths 43
86.8k
|
---|---|---|---|---|---|
@Test public void checkForwardIsLazy() { impl.isLazy(); Mockito.verify(mapAttr, Mockito.times(1)).isLazy(); }
|
@Override public boolean isLazy() { return mapAttr.isLazy(); }
|
MetaMapAttribute extends MetaAttribute { @Override public boolean isLazy() { return mapAttr.isLazy(); } }
|
MetaMapAttribute extends MetaAttribute { @Override public boolean isLazy() { return mapAttr.isLazy(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); }
|
MetaMapAttribute extends MetaAttribute { @Override public boolean isLazy() { return mapAttr.isLazy(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }
|
MetaMapAttribute extends MetaAttribute { @Override public boolean isLazy() { return mapAttr.isLazy(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }
|
@Test public void checkForwardIsDerived() { impl.isDerived(); Mockito.verify(mapAttr, Mockito.times(1)).isDerived(); }
|
@Override public boolean isDerived() { return mapAttr.isDerived(); }
|
MetaMapAttribute extends MetaAttribute { @Override public boolean isDerived() { return mapAttr.isDerived(); } }
|
MetaMapAttribute extends MetaAttribute { @Override public boolean isDerived() { return mapAttr.isDerived(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); }
|
MetaMapAttribute extends MetaAttribute { @Override public boolean isDerived() { return mapAttr.isDerived(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }
|
MetaMapAttribute extends MetaAttribute { @Override public boolean isDerived() { return mapAttr.isDerived(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }
|
@Test(expected = UnsupportedOperationException.class) public void checkGetAnnotationsNotSupported() { impl.getAnnotations(); }
|
@Override public Collection<Annotation> getAnnotations() { throw new UnsupportedOperationException(); }
|
MetaMapAttribute extends MetaAttribute { @Override public Collection<Annotation> getAnnotations() { throw new UnsupportedOperationException(); } }
|
MetaMapAttribute extends MetaAttribute { @Override public Collection<Annotation> getAnnotations() { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); }
|
MetaMapAttribute extends MetaAttribute { @Override public Collection<Annotation> getAnnotations() { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }
|
MetaMapAttribute extends MetaAttribute { @Override public Collection<Annotation> getAnnotations() { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }
|
@Test(expected = UnsupportedOperationException.class) public void checkGetAnnotationNotSupported() { impl.getAnnotation(null); }
|
@Override public <T extends Annotation> T getAnnotation(Class<T> clazz) { throw new UnsupportedOperationException(); }
|
MetaMapAttribute extends MetaAttribute { @Override public <T extends Annotation> T getAnnotation(Class<T> clazz) { throw new UnsupportedOperationException(); } }
|
MetaMapAttribute extends MetaAttribute { @Override public <T extends Annotation> T getAnnotation(Class<T> clazz) { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); }
|
MetaMapAttribute extends MetaAttribute { @Override public <T extends Annotation> T getAnnotation(Class<T> clazz) { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }
|
MetaMapAttribute extends MetaAttribute { @Override public <T extends Annotation> T getAnnotation(Class<T> clazz) { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }
|
@Test(expected = UnsupportedOperationException.class) public void checkSetOppositeAttributeNotSupported() { impl.setOppositeAttribute(null); }
|
public void setOppositeAttribute(MetaAttribute oppositeAttr) { throw new UnsupportedOperationException(); }
|
MetaMapAttribute extends MetaAttribute { public void setOppositeAttribute(MetaAttribute oppositeAttr) { throw new UnsupportedOperationException(); } }
|
MetaMapAttribute extends MetaAttribute { public void setOppositeAttribute(MetaAttribute oppositeAttr) { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); }
|
MetaMapAttribute extends MetaAttribute { public void setOppositeAttribute(MetaAttribute oppositeAttr) { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }
|
MetaMapAttribute extends MetaAttribute { public void setOppositeAttribute(MetaAttribute oppositeAttr) { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }
|
@Test public void checkForwardIsAssociation() { impl.isAssociation(); Mockito.verify(mapAttr, Mockito.times(1)).isAssociation(); }
|
@Override public boolean isAssociation() { return mapAttr.isAssociation(); }
|
MetaMapAttribute extends MetaAttribute { @Override public boolean isAssociation() { return mapAttr.isAssociation(); } }
|
MetaMapAttribute extends MetaAttribute { @Override public boolean isAssociation() { return mapAttr.isAssociation(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); }
|
MetaMapAttribute extends MetaAttribute { @Override public boolean isAssociation() { return mapAttr.isAssociation(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }
|
MetaMapAttribute extends MetaAttribute { @Override public boolean isAssociation() { return mapAttr.isAssociation(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }
|
@Test(expected = UnsupportedOperationException.class) public void getVersionNotSupported() { impl.isVersion(); }
|
@Override public boolean isVersion() { throw new UnsupportedOperationException(); }
|
MetaMapAttribute extends MetaAttribute { @Override public boolean isVersion() { throw new UnsupportedOperationException(); } }
|
MetaMapAttribute extends MetaAttribute { @Override public boolean isVersion() { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); }
|
MetaMapAttribute extends MetaAttribute { @Override public boolean isVersion() { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }
|
MetaMapAttribute extends MetaAttribute { @Override public boolean isVersion() { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }
|
@Test(expected = UnsupportedOperationException.class) public void isIdNotSupported() { impl.isId(); }
|
public boolean isId() { throw new UnsupportedOperationException(); }
|
MetaMapAttribute extends MetaAttribute { public boolean isId() { throw new UnsupportedOperationException(); } }
|
MetaMapAttribute extends MetaAttribute { public boolean isId() { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); }
|
MetaMapAttribute extends MetaAttribute { public boolean isId() { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }
|
MetaMapAttribute extends MetaAttribute { public boolean isId() { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }
|
@Test(expected = UnsupportedOperationException.class) public void getOppositeAttributeNotSupported() { impl.getOppositeAttribute(); }
|
@Override public MetaAttribute getOppositeAttribute() { throw new UnsupportedOperationException(); }
|
MetaMapAttribute extends MetaAttribute { @Override public MetaAttribute getOppositeAttribute() { throw new UnsupportedOperationException(); } }
|
MetaMapAttribute extends MetaAttribute { @Override public MetaAttribute getOppositeAttribute() { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); }
|
MetaMapAttribute extends MetaAttribute { @Override public MetaAttribute getOppositeAttribute() { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }
|
MetaMapAttribute extends MetaAttribute { @Override public MetaAttribute getOppositeAttribute() { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }
|
@Test public void and() { Assert.assertEquals(ResourcePermission.DELETE, ResourcePermission.DELETE.or(ResourcePermission.DELETE)); Assert.assertEquals(ResourcePermission.GET, ResourcePermission.GET.or(ResourcePermission.GET)); Assert.assertTrue(ResourcePermission.GET.and(ResourcePermission.DELETE).isEmpty()); }
|
public ResourcePermission and(ResourcePermission other) { boolean mergePush = postAllowed && other.postAllowed; boolean mergeGet = getAllowed && other.getAllowed; boolean mergePatch = patchAllowed && other.patchAllowed; boolean mergeDelete = deleteAllowed && other.deleteAllowed; return new ResourcePermission(mergePush, mergeGet, mergePatch, mergeDelete); }
|
ResourcePermission { public ResourcePermission and(ResourcePermission other) { boolean mergePush = postAllowed && other.postAllowed; boolean mergeGet = getAllowed && other.getAllowed; boolean mergePatch = patchAllowed && other.patchAllowed; boolean mergeDelete = deleteAllowed && other.deleteAllowed; return new ResourcePermission(mergePush, mergeGet, mergePatch, mergeDelete); } }
|
ResourcePermission { public ResourcePermission and(ResourcePermission other) { boolean mergePush = postAllowed && other.postAllowed; boolean mergeGet = getAllowed && other.getAllowed; boolean mergePatch = patchAllowed && other.patchAllowed; boolean mergeDelete = deleteAllowed && other.deleteAllowed; return new ResourcePermission(mergePush, mergeGet, mergePatch, mergeDelete); } protected ResourcePermission(); private ResourcePermission(boolean post, boolean get, boolean patch, boolean delete); }
|
ResourcePermission { public ResourcePermission and(ResourcePermission other) { boolean mergePush = postAllowed && other.postAllowed; boolean mergeGet = getAllowed && other.getAllowed; boolean mergePatch = patchAllowed && other.patchAllowed; boolean mergeDelete = deleteAllowed && other.deleteAllowed; return new ResourcePermission(mergePush, mergeGet, mergePatch, mergeDelete); } protected ResourcePermission(); private ResourcePermission(boolean post, boolean get, boolean patch, boolean delete); static final ResourcePermission create(boolean push, boolean get, boolean patch, boolean delete); static ResourcePermission fromMethod(HttpMethod method); boolean isPostAllowed(); boolean isGetAllowed(); boolean isPatchAllowed(); boolean isDeleteAllowed(); @JsonIgnore boolean isEmpty(); ResourcePermission or(ResourcePermission other); ResourcePermission and(ResourcePermission other); ResourcePermission xor(ResourcePermission other); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }
|
ResourcePermission { public ResourcePermission and(ResourcePermission other) { boolean mergePush = postAllowed && other.postAllowed; boolean mergeGet = getAllowed && other.getAllowed; boolean mergePatch = patchAllowed && other.patchAllowed; boolean mergeDelete = deleteAllowed && other.deleteAllowed; return new ResourcePermission(mergePush, mergeGet, mergePatch, mergeDelete); } protected ResourcePermission(); private ResourcePermission(boolean post, boolean get, boolean patch, boolean delete); static final ResourcePermission create(boolean push, boolean get, boolean patch, boolean delete); static ResourcePermission fromMethod(HttpMethod method); boolean isPostAllowed(); boolean isGetAllowed(); boolean isPatchAllowed(); boolean isDeleteAllowed(); @JsonIgnore boolean isEmpty(); ResourcePermission or(ResourcePermission other); ResourcePermission and(ResourcePermission other); ResourcePermission xor(ResourcePermission other); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static final ResourcePermission EMPTY; static final ResourcePermission ALL; static final ResourcePermission GET; static final ResourcePermission POST; static final ResourcePermission PATCH; static final ResourcePermission DELETE; }
|
@Test(expected = UnsupportedOperationException.class) public void getValueNotSupported() { impl.getValue(null); }
|
@Override public Object getValue(Object dataObject) { throw new UnsupportedOperationException(); }
|
MetaMapAttribute extends MetaAttribute { @Override public Object getValue(Object dataObject) { throw new UnsupportedOperationException(); } }
|
MetaMapAttribute extends MetaAttribute { @Override public Object getValue(Object dataObject) { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); }
|
MetaMapAttribute extends MetaAttribute { @Override public Object getValue(Object dataObject) { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }
|
MetaMapAttribute extends MetaAttribute { @Override public Object getValue(Object dataObject) { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }
|
@Test(expected = UnsupportedOperationException.class) public void addValueNotSupported() { impl.addValue(null, null); }
|
@Override public void addValue(Object dataObject, Object value) { throw new UnsupportedOperationException(); }
|
MetaMapAttribute extends MetaAttribute { @Override public void addValue(Object dataObject, Object value) { throw new UnsupportedOperationException(); } }
|
MetaMapAttribute extends MetaAttribute { @Override public void addValue(Object dataObject, Object value) { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); }
|
MetaMapAttribute extends MetaAttribute { @Override public void addValue(Object dataObject, Object value) { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }
|
MetaMapAttribute extends MetaAttribute { @Override public void addValue(Object dataObject, Object value) { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }
|
@Test(expected = UnsupportedOperationException.class) public void removeValueNotSupported() { impl.removeValue(null, null); }
|
@Override public void removeValue(Object dataObject, Object value) { throw new UnsupportedOperationException(); }
|
MetaMapAttribute extends MetaAttribute { @Override public void removeValue(Object dataObject, Object value) { throw new UnsupportedOperationException(); } }
|
MetaMapAttribute extends MetaAttribute { @Override public void removeValue(Object dataObject, Object value) { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); }
|
MetaMapAttribute extends MetaAttribute { @Override public void removeValue(Object dataObject, Object value) { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }
|
MetaMapAttribute extends MetaAttribute { @Override public void removeValue(Object dataObject, Object value) { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }
|
@Test(expected = UnsupportedOperationException.class) public void setValueNotSupported() { impl.setValue(null, null); }
|
@Override public void setValue(Object dataObject, Object value) { throw new UnsupportedOperationException(); }
|
MetaMapAttribute extends MetaAttribute { @Override public void setValue(Object dataObject, Object value) { throw new UnsupportedOperationException(); } }
|
MetaMapAttribute extends MetaAttribute { @Override public void setValue(Object dataObject, Object value) { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); }
|
MetaMapAttribute extends MetaAttribute { @Override public void setValue(Object dataObject, Object value) { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }
|
MetaMapAttribute extends MetaAttribute { @Override public void setValue(Object dataObject, Object value) { throw new UnsupportedOperationException(); } MetaMapAttribute(MetaMapType mapType, MetaAttribute mapAttr, String keyString); @Override MetaType getType(); @Override Object getValue(Object dataObject); @Override void setValue(Object dataObject, Object value); Object getKey(); MetaAttribute getMapAttribute(); @Override boolean isAssociation(); @Override boolean isDerived(); @Override void addValue(Object dataObject, Object value); @Override void removeValue(Object dataObject, Object value); @Override boolean isLazy(); @Override MetaAttribute getOppositeAttribute(); void setOppositeAttribute(MetaAttribute oppositeAttr); @Override boolean isVersion(); boolean isId(); @Override Collection<Annotation> getAnnotations(); @Override T getAnnotation(Class<T> clazz); }
|
@Test public void testToKeyStringWithNull() { MetaKey key = new MetaKey(); Assert.assertNull(key.toKeyString(null)); }
|
public String toKeyString(Object id) { if (id == null) { return null; } PreconditionUtil.assertEquals("compound primary key not supported", 1, elements.size()); MetaAttribute keyAttr = elements.get(0); MetaType keyType = keyAttr.getType(); if (keyType instanceof MetaDataObject) { MetaDataObject embType = (MetaDataObject) keyType; return toEmbeddableKeyString(embType, id); } else { return id.toString(); } }
|
MetaKey extends MetaElement { public String toKeyString(Object id) { if (id == null) { return null; } PreconditionUtil.assertEquals("compound primary key not supported", 1, elements.size()); MetaAttribute keyAttr = elements.get(0); MetaType keyType = keyAttr.getType(); if (keyType instanceof MetaDataObject) { MetaDataObject embType = (MetaDataObject) keyType; return toEmbeddableKeyString(embType, id); } else { return id.toString(); } } }
|
MetaKey extends MetaElement { public String toKeyString(Object id) { if (id == null) { return null; } PreconditionUtil.assertEquals("compound primary key not supported", 1, elements.size()); MetaAttribute keyAttr = elements.get(0); MetaType keyType = keyAttr.getType(); if (keyType instanceof MetaDataObject) { MetaDataObject embType = (MetaDataObject) keyType; return toEmbeddableKeyString(embType, id); } else { return id.toString(); } } }
|
MetaKey extends MetaElement { public String toKeyString(Object id) { if (id == null) { return null; } PreconditionUtil.assertEquals("compound primary key not supported", 1, elements.size()); MetaAttribute keyAttr = elements.get(0); MetaType keyType = keyAttr.getType(); if (keyType instanceof MetaDataObject) { MetaDataObject embType = (MetaDataObject) keyType; return toEmbeddableKeyString(embType, id); } else { return id.toString(); } } List<MetaAttribute> getElements(); void setElements(List<MetaAttribute> elements); boolean isUnique(); void setUnique(boolean unique); @JsonIgnore MetaAttribute getUniqueElement(); String toKeyString(Object id); }
|
MetaKey extends MetaElement { public String toKeyString(Object id) { if (id == null) { return null; } PreconditionUtil.assertEquals("compound primary key not supported", 1, elements.size()); MetaAttribute keyAttr = elements.get(0); MetaType keyType = keyAttr.getType(); if (keyType instanceof MetaDataObject) { MetaDataObject embType = (MetaDataObject) keyType; return toEmbeddableKeyString(embType, id); } else { return id.toString(); } } List<MetaAttribute> getElements(); void setElements(List<MetaAttribute> elements); boolean isUnique(); void setUnique(boolean unique); @JsonIgnore MetaAttribute getUniqueElement(); String toKeyString(Object id); static final String ID_ELEMENT_SEPARATOR; }
|
@Test(expected = IllegalStateException.class) public void checkDataObjectCast() { new MetaKey().asDataObject(); }
|
public MetaDataObject asDataObject() { if (!(this instanceof MetaDataObject)) { throw new IllegalStateException(getName() + " not a MetaDataObject"); } return (MetaDataObject) this; }
|
MetaElement implements Cloneable { public MetaDataObject asDataObject() { if (!(this instanceof MetaDataObject)) { throw new IllegalStateException(getName() + " not a MetaDataObject"); } return (MetaDataObject) this; } }
|
MetaElement implements Cloneable { public MetaDataObject asDataObject() { if (!(this instanceof MetaDataObject)) { throw new IllegalStateException(getName() + " not a MetaDataObject"); } return (MetaDataObject) this; } }
|
MetaElement implements Cloneable { public MetaDataObject asDataObject() { if (!(this instanceof MetaDataObject)) { throw new IllegalStateException(getName() + " not a MetaDataObject"); } return (MetaDataObject) this; } MetaElement getParent(); void setParent(MetaElement parent); List<MetaElement> getChildren(); void setChildren(List<MetaElement> children); void addChild(MetaElement child); Map<String, MetaNature> getNatures(); void setNatures(Map<String, MetaNature> natures); MetaType asType(); MetaDataObject asDataObject(); void setParent(MetaElement parent, boolean attach); @Override String toString(); final String getId(); void setId(String id); String getName(); void setName(String name); @JsonIgnore boolean hasId(); MetaElement duplicate(); }
|
MetaElement implements Cloneable { public MetaDataObject asDataObject() { if (!(this instanceof MetaDataObject)) { throw new IllegalStateException(getName() + " not a MetaDataObject"); } return (MetaDataObject) this; } MetaElement getParent(); void setParent(MetaElement parent); List<MetaElement> getChildren(); void setChildren(List<MetaElement> children); void addChild(MetaElement child); Map<String, MetaNature> getNatures(); void setNatures(Map<String, MetaNature> natures); MetaType asType(); MetaDataObject asDataObject(); void setParent(MetaElement parent, boolean attach); @Override String toString(); final String getId(); void setId(String id); String getName(); void setName(String name); @JsonIgnore boolean hasId(); MetaElement duplicate(); }
|
@Test(expected = IllegalStateException.class) public void checkTypeCast() { new MetaKey().asType(); }
|
public MetaType asType() { if (!(this instanceof MetaType)) { throw new IllegalStateException(getName() + " not a MetaEntity"); } return (MetaType) this; }
|
MetaElement implements Cloneable { public MetaType asType() { if (!(this instanceof MetaType)) { throw new IllegalStateException(getName() + " not a MetaEntity"); } return (MetaType) this; } }
|
MetaElement implements Cloneable { public MetaType asType() { if (!(this instanceof MetaType)) { throw new IllegalStateException(getName() + " not a MetaEntity"); } return (MetaType) this; } }
|
MetaElement implements Cloneable { public MetaType asType() { if (!(this instanceof MetaType)) { throw new IllegalStateException(getName() + " not a MetaEntity"); } return (MetaType) this; } MetaElement getParent(); void setParent(MetaElement parent); List<MetaElement> getChildren(); void setChildren(List<MetaElement> children); void addChild(MetaElement child); Map<String, MetaNature> getNatures(); void setNatures(Map<String, MetaNature> natures); MetaType asType(); MetaDataObject asDataObject(); void setParent(MetaElement parent, boolean attach); @Override String toString(); final String getId(); void setId(String id); String getName(); void setName(String name); @JsonIgnore boolean hasId(); MetaElement duplicate(); }
|
MetaElement implements Cloneable { public MetaType asType() { if (!(this instanceof MetaType)) { throw new IllegalStateException(getName() + " not a MetaEntity"); } return (MetaType) this; } MetaElement getParent(); void setParent(MetaElement parent); List<MetaElement> getChildren(); void setChildren(List<MetaElement> children); void addChild(MetaElement child); Map<String, MetaNature> getNatures(); void setNatures(Map<String, MetaNature> natures); MetaType asType(); MetaDataObject asDataObject(); void setParent(MetaElement parent, boolean attach); @Override String toString(); final String getId(); void setId(String id); String getName(); void setName(String name); @JsonIgnore boolean hasId(); MetaElement duplicate(); }
|
@Test public void testGetResourceType() { Assert.assertEquals(TestEntity.class, repo.getResourceClass()); }
|
@Override public Class<T> getResourceClass() { return repositoryConfig.getResourceClass(); }
|
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>,
ResourceRegistryAware { @Override public Class<T> getResourceClass() { return repositoryConfig.getResourceClass(); } }
|
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>,
ResourceRegistryAware { @Override public Class<T> getResourceClass() { return repositoryConfig.getResourceClass(); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); }
|
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>,
ResourceRegistryAware { @Override public Class<T> getResourceClass() { return repositoryConfig.getResourceClass(); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
|
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>,
ResourceRegistryAware { @Override public Class<T> getResourceClass() { return repositoryConfig.getResourceClass(); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
|
@Test public void testGetEntityType() { Assert.assertEquals(TestEntity.class, repo.getEntityClass()); }
|
public Class<?> getEntityClass() { return repositoryConfig.getEntityClass(); }
|
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>,
ResourceRegistryAware { public Class<?> getEntityClass() { return repositoryConfig.getEntityClass(); } }
|
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>,
ResourceRegistryAware { public Class<?> getEntityClass() { return repositoryConfig.getEntityClass(); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); }
|
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>,
ResourceRegistryAware { public Class<?> getEntityClass() { return repositoryConfig.getEntityClass(); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
|
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>,
ResourceRegistryAware { public Class<?> getEntityClass() { return repositoryConfig.getEntityClass(); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
|
@Test public void testFindAll() { QuerySpec querySpec = new QuerySpec(TestEntity.class); List<TestEntity> list = repo.findAll(querySpec); Assert.assertEquals(numTestEntities, list.size()); }
|
@Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); }
|
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>,
ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } }
|
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>,
ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); }
|
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>,
ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
|
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>,
ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
|
@Test public void or() { Assert.assertEquals(ResourcePermission.DELETE, ResourcePermission.DELETE.or(ResourcePermission.DELETE)); Assert.assertEquals(ResourcePermission.GET, ResourcePermission.GET.or(ResourcePermission.GET)); Assert.assertEquals(ResourcePermission.create(false, true, false, true), ResourcePermission.GET.or(ResourcePermission.DELETE)); }
|
public ResourcePermission or(ResourcePermission other) { boolean mergePush = postAllowed || other.postAllowed; boolean mergeGet = getAllowed || other.getAllowed; boolean mergePatch = patchAllowed || other.patchAllowed; boolean mergeDelete = deleteAllowed || other.deleteAllowed; return new ResourcePermission(mergePush, mergeGet, mergePatch, mergeDelete); }
|
ResourcePermission { public ResourcePermission or(ResourcePermission other) { boolean mergePush = postAllowed || other.postAllowed; boolean mergeGet = getAllowed || other.getAllowed; boolean mergePatch = patchAllowed || other.patchAllowed; boolean mergeDelete = deleteAllowed || other.deleteAllowed; return new ResourcePermission(mergePush, mergeGet, mergePatch, mergeDelete); } }
|
ResourcePermission { public ResourcePermission or(ResourcePermission other) { boolean mergePush = postAllowed || other.postAllowed; boolean mergeGet = getAllowed || other.getAllowed; boolean mergePatch = patchAllowed || other.patchAllowed; boolean mergeDelete = deleteAllowed || other.deleteAllowed; return new ResourcePermission(mergePush, mergeGet, mergePatch, mergeDelete); } protected ResourcePermission(); private ResourcePermission(boolean post, boolean get, boolean patch, boolean delete); }
|
ResourcePermission { public ResourcePermission or(ResourcePermission other) { boolean mergePush = postAllowed || other.postAllowed; boolean mergeGet = getAllowed || other.getAllowed; boolean mergePatch = patchAllowed || other.patchAllowed; boolean mergeDelete = deleteAllowed || other.deleteAllowed; return new ResourcePermission(mergePush, mergeGet, mergePatch, mergeDelete); } protected ResourcePermission(); private ResourcePermission(boolean post, boolean get, boolean patch, boolean delete); static final ResourcePermission create(boolean push, boolean get, boolean patch, boolean delete); static ResourcePermission fromMethod(HttpMethod method); boolean isPostAllowed(); boolean isGetAllowed(); boolean isPatchAllowed(); boolean isDeleteAllowed(); @JsonIgnore boolean isEmpty(); ResourcePermission or(ResourcePermission other); ResourcePermission and(ResourcePermission other); ResourcePermission xor(ResourcePermission other); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }
|
ResourcePermission { public ResourcePermission or(ResourcePermission other) { boolean mergePush = postAllowed || other.postAllowed; boolean mergeGet = getAllowed || other.getAllowed; boolean mergePatch = patchAllowed || other.patchAllowed; boolean mergeDelete = deleteAllowed || other.deleteAllowed; return new ResourcePermission(mergePush, mergeGet, mergePatch, mergeDelete); } protected ResourcePermission(); private ResourcePermission(boolean post, boolean get, boolean patch, boolean delete); static final ResourcePermission create(boolean push, boolean get, boolean patch, boolean delete); static ResourcePermission fromMethod(HttpMethod method); boolean isPostAllowed(); boolean isGetAllowed(); boolean isPatchAllowed(); boolean isDeleteAllowed(); @JsonIgnore boolean isEmpty(); ResourcePermission or(ResourcePermission other); ResourcePermission and(ResourcePermission other); ResourcePermission xor(ResourcePermission other); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static final ResourcePermission EMPTY; static final ResourcePermission ALL; static final ResourcePermission GET; static final ResourcePermission POST; static final ResourcePermission PATCH; static final ResourcePermission DELETE; }
|
@Test public void testService() { MyService myService = new MyService(); User user = new User("John", "[email protected]"); user.setDateOfBirth(LocalDate.of(1980, Month.APRIL, 20)); logger.info("Age of user {} is {}", () -> user.getName(), () -> myService.calculateUserAge(user)); }
|
public int calculateUserAge(User user) { return Period.between(user.getDateOfBirth(), LocalDate.now()).getYears(); }
|
MyService { public int calculateUserAge(User user) { return Period.between(user.getDateOfBirth(), LocalDate.now()).getYears(); } }
|
MyService { public int calculateUserAge(User user) { return Period.between(user.getDateOfBirth(), LocalDate.now()).getYears(); } }
|
MyService { public int calculateUserAge(User user) { return Period.between(user.getDateOfBirth(), LocalDate.now()).getYears(); } int calculateUserAge(User user); }
|
MyService { public int calculateUserAge(User user) { return Period.between(user.getDateOfBirth(), LocalDate.now()).getYears(); } int calculateUserAge(User user); }
|
@Test public void testParameter() { Employee employee = new Employee("[email protected]", "John", 2000); if (logger.isDebugEnabled()) { logger.debug("The bonus for employee: " + employee.getName() + " is " + employeeService.calculateBonus(employee)); } logger.debug("The bonus for employee {} is {}", employee.getName(), employeeService.calculateBonus(employee)); }
|
public double calculateBonus(Employee user) { return 0.1 * user.getSalary(); }
|
EmployeeService { public double calculateBonus(Employee user) { return 0.1 * user.getSalary(); } }
|
EmployeeService { public double calculateBonus(Employee user) { return 0.1 * user.getSalary(); } }
|
EmployeeService { public double calculateBonus(Employee user) { return 0.1 * user.getSalary(); } double calculateBonus(Employee user); }
|
EmployeeService { public double calculateBonus(Employee user) { return 0.1 * user.getSalary(); } double calculateBonus(Employee user); }
|
@Test public void testDeviceIdentifier() { Assert.assertNotNull(Castle.clientId()); }
|
public static String clientId() { return instance.identifier; }
|
Castle { public static String clientId() { return instance.identifier; } }
|
Castle { public static String clientId() { return instance.identifier; } private Castle(Application application, CastleConfiguration castleConfiguration); }
|
Castle { public static String clientId() { return instance.identifier; } private Castle(Application application, CastleConfiguration castleConfiguration); static void configure(Application application, CastleConfiguration configuration); static void configure(Application application, String publishableKey); static void configure(Application application, String publishableKey, CastleConfiguration configuration); static void configure(Application application); static void identify(String userId); static void identify(String userId, Map<String, String> traits); static String userId(); static void reset(); static void screen(String name); static void screen(Activity activity); static void secure(String signature); static boolean secureModeEnabled(); static String publishableKey(); static boolean debugLoggingEnabled(); static String baseUrl(); static String clientId(); static String userSignature(); static void userSignature(String signature); static CastleConfiguration configuration(); static void flush(); static boolean flushIfNeeded(String url); static Map<String, String> headers(String url); static CastleInterceptor castleInterceptor(); static int queueSize(); static void destroy(Application application); static String userAgent(); static io.castle.android.api.model.Context createContext(); }
|
Castle { public static String clientId() { return instance.identifier; } private Castle(Application application, CastleConfiguration castleConfiguration); static void configure(Application application, CastleConfiguration configuration); static void configure(Application application, String publishableKey); static void configure(Application application, String publishableKey, CastleConfiguration configuration); static void configure(Application application); static void identify(String userId); static void identify(String userId, Map<String, String> traits); static String userId(); static void reset(); static void screen(String name); static void screen(Activity activity); static void secure(String signature); static boolean secureModeEnabled(); static String publishableKey(); static boolean debugLoggingEnabled(); static String baseUrl(); static String clientId(); static String userSignature(); static void userSignature(String signature); static CastleConfiguration configuration(); static void flush(); static boolean flushIfNeeded(String url); static Map<String, String> headers(String url); static CastleInterceptor castleInterceptor(); static int queueSize(); static void destroy(Application application); static String userAgent(); static io.castle.android.api.model.Context createContext(); static final String clientIdHeaderName; }
|
@Test public void testflushIfNeeded() { boolean flushed = Castle.flushIfNeeded("https: Assert.assertTrue(flushed); flushed = Castle.flushIfNeeded("https: Assert.assertFalse(flushed); }
|
public static boolean flushIfNeeded(String url) { if (isUrlWhiteListed(url)) { flush(); return true; } return false; }
|
Castle { public static boolean flushIfNeeded(String url) { if (isUrlWhiteListed(url)) { flush(); return true; } return false; } }
|
Castle { public static boolean flushIfNeeded(String url) { if (isUrlWhiteListed(url)) { flush(); return true; } return false; } private Castle(Application application, CastleConfiguration castleConfiguration); }
|
Castle { public static boolean flushIfNeeded(String url) { if (isUrlWhiteListed(url)) { flush(); return true; } return false; } private Castle(Application application, CastleConfiguration castleConfiguration); static void configure(Application application, CastleConfiguration configuration); static void configure(Application application, String publishableKey); static void configure(Application application, String publishableKey, CastleConfiguration configuration); static void configure(Application application); static void identify(String userId); static void identify(String userId, Map<String, String> traits); static String userId(); static void reset(); static void screen(String name); static void screen(Activity activity); static void secure(String signature); static boolean secureModeEnabled(); static String publishableKey(); static boolean debugLoggingEnabled(); static String baseUrl(); static String clientId(); static String userSignature(); static void userSignature(String signature); static CastleConfiguration configuration(); static void flush(); static boolean flushIfNeeded(String url); static Map<String, String> headers(String url); static CastleInterceptor castleInterceptor(); static int queueSize(); static void destroy(Application application); static String userAgent(); static io.castle.android.api.model.Context createContext(); }
|
Castle { public static boolean flushIfNeeded(String url) { if (isUrlWhiteListed(url)) { flush(); return true; } return false; } private Castle(Application application, CastleConfiguration castleConfiguration); static void configure(Application application, CastleConfiguration configuration); static void configure(Application application, String publishableKey); static void configure(Application application, String publishableKey, CastleConfiguration configuration); static void configure(Application application); static void identify(String userId); static void identify(String userId, Map<String, String> traits); static String userId(); static void reset(); static void screen(String name); static void screen(Activity activity); static void secure(String signature); static boolean secureModeEnabled(); static String publishableKey(); static boolean debugLoggingEnabled(); static String baseUrl(); static String clientId(); static String userSignature(); static void userSignature(String signature); static CastleConfiguration configuration(); static void flush(); static boolean flushIfNeeded(String url); static Map<String, String> headers(String url); static CastleInterceptor castleInterceptor(); static int queueSize(); static void destroy(Application application); static String userAgent(); static io.castle.android.api.model.Context createContext(); static final String clientIdHeaderName; }
|
@Test public void testReset() { Castle.reset(); Assert.assertNull(Castle.userId()); }
|
public static void reset() { Castle.flush(); Castle.userId(null); Castle.userSignature(null); }
|
Castle { public static void reset() { Castle.flush(); Castle.userId(null); Castle.userSignature(null); } }
|
Castle { public static void reset() { Castle.flush(); Castle.userId(null); Castle.userSignature(null); } private Castle(Application application, CastleConfiguration castleConfiguration); }
|
Castle { public static void reset() { Castle.flush(); Castle.userId(null); Castle.userSignature(null); } private Castle(Application application, CastleConfiguration castleConfiguration); static void configure(Application application, CastleConfiguration configuration); static void configure(Application application, String publishableKey); static void configure(Application application, String publishableKey, CastleConfiguration configuration); static void configure(Application application); static void identify(String userId); static void identify(String userId, Map<String, String> traits); static String userId(); static void reset(); static void screen(String name); static void screen(Activity activity); static void secure(String signature); static boolean secureModeEnabled(); static String publishableKey(); static boolean debugLoggingEnabled(); static String baseUrl(); static String clientId(); static String userSignature(); static void userSignature(String signature); static CastleConfiguration configuration(); static void flush(); static boolean flushIfNeeded(String url); static Map<String, String> headers(String url); static CastleInterceptor castleInterceptor(); static int queueSize(); static void destroy(Application application); static String userAgent(); static io.castle.android.api.model.Context createContext(); }
|
Castle { public static void reset() { Castle.flush(); Castle.userId(null); Castle.userSignature(null); } private Castle(Application application, CastleConfiguration castleConfiguration); static void configure(Application application, CastleConfiguration configuration); static void configure(Application application, String publishableKey); static void configure(Application application, String publishableKey, CastleConfiguration configuration); static void configure(Application application); static void identify(String userId); static void identify(String userId, Map<String, String> traits); static String userId(); static void reset(); static void screen(String name); static void screen(Activity activity); static void secure(String signature); static boolean secureModeEnabled(); static String publishableKey(); static boolean debugLoggingEnabled(); static String baseUrl(); static String clientId(); static String userSignature(); static void userSignature(String signature); static CastleConfiguration configuration(); static void flush(); static boolean flushIfNeeded(String url); static Map<String, String> headers(String url); static CastleInterceptor castleInterceptor(); static int queueSize(); static void destroy(Application application); static String userAgent(); static io.castle.android.api.model.Context createContext(); static final String clientIdHeaderName; }
|
@Test public void testRequestInterceptor() throws IOException { Request request = new Request.Builder() .url("https: .build(); Response response = client.newCall(request).execute(); Assert.assertEquals(Castle.clientId(), response.request().header(Castle.clientIdHeaderName)); request = new Request.Builder() .url("https: .build(); response = client.newCall(request).execute(); Assert.assertEquals(null, response.request().header(Castle.clientIdHeaderName)); }
|
public static String clientId() { return instance.identifier; }
|
Castle { public static String clientId() { return instance.identifier; } }
|
Castle { public static String clientId() { return instance.identifier; } private Castle(Application application, CastleConfiguration castleConfiguration); }
|
Castle { public static String clientId() { return instance.identifier; } private Castle(Application application, CastleConfiguration castleConfiguration); static void configure(Application application, CastleConfiguration configuration); static void configure(Application application, String publishableKey); static void configure(Application application, String publishableKey, CastleConfiguration configuration); static void configure(Application application); static void identify(String userId); static void identify(String userId, Map<String, String> traits); static String userId(); static void reset(); static void screen(String name); static void screen(Activity activity); static void secure(String signature); static boolean secureModeEnabled(); static String publishableKey(); static boolean debugLoggingEnabled(); static String baseUrl(); static String clientId(); static String userSignature(); static void userSignature(String signature); static CastleConfiguration configuration(); static void flush(); static boolean flushIfNeeded(String url); static Map<String, String> headers(String url); static CastleInterceptor castleInterceptor(); static int queueSize(); static void destroy(Application application); static String userAgent(); static io.castle.android.api.model.Context createContext(); }
|
Castle { public static String clientId() { return instance.identifier; } private Castle(Application application, CastleConfiguration castleConfiguration); static void configure(Application application, CastleConfiguration configuration); static void configure(Application application, String publishableKey); static void configure(Application application, String publishableKey, CastleConfiguration configuration); static void configure(Application application); static void identify(String userId); static void identify(String userId, Map<String, String> traits); static String userId(); static void reset(); static void screen(String name); static void screen(Activity activity); static void secure(String signature); static boolean secureModeEnabled(); static String publishableKey(); static boolean debugLoggingEnabled(); static String baseUrl(); static String clientId(); static String userSignature(); static void userSignature(String signature); static CastleConfiguration configuration(); static void flush(); static boolean flushIfNeeded(String url); static Map<String, String> headers(String url); static CastleInterceptor castleInterceptor(); static int queueSize(); static void destroy(Application application); static String userAgent(); static io.castle.android.api.model.Context createContext(); static final String clientIdHeaderName; }
|
@Test public void testWhiteList() { Assert.assertFalse(Castle.isUrlWhiteListed("invalid url")); }
|
static boolean isUrlWhiteListed(String urlString) { try { URL url = new URL(urlString); String baseUrl = url.getProtocol() + ": if (Castle.configuration().baseURLWhiteList() != null && !Castle.configuration().baseURLWhiteList().isEmpty()) { if (Castle.configuration().baseURLWhiteList().contains(baseUrl)) { return true; } } } catch (MalformedURLException e) { e.printStackTrace(); } return false; }
|
Castle { static boolean isUrlWhiteListed(String urlString) { try { URL url = new URL(urlString); String baseUrl = url.getProtocol() + ": if (Castle.configuration().baseURLWhiteList() != null && !Castle.configuration().baseURLWhiteList().isEmpty()) { if (Castle.configuration().baseURLWhiteList().contains(baseUrl)) { return true; } } } catch (MalformedURLException e) { e.printStackTrace(); } return false; } }
|
Castle { static boolean isUrlWhiteListed(String urlString) { try { URL url = new URL(urlString); String baseUrl = url.getProtocol() + ": if (Castle.configuration().baseURLWhiteList() != null && !Castle.configuration().baseURLWhiteList().isEmpty()) { if (Castle.configuration().baseURLWhiteList().contains(baseUrl)) { return true; } } } catch (MalformedURLException e) { e.printStackTrace(); } return false; } private Castle(Application application, CastleConfiguration castleConfiguration); }
|
Castle { static boolean isUrlWhiteListed(String urlString) { try { URL url = new URL(urlString); String baseUrl = url.getProtocol() + ": if (Castle.configuration().baseURLWhiteList() != null && !Castle.configuration().baseURLWhiteList().isEmpty()) { if (Castle.configuration().baseURLWhiteList().contains(baseUrl)) { return true; } } } catch (MalformedURLException e) { e.printStackTrace(); } return false; } private Castle(Application application, CastleConfiguration castleConfiguration); static void configure(Application application, CastleConfiguration configuration); static void configure(Application application, String publishableKey); static void configure(Application application, String publishableKey, CastleConfiguration configuration); static void configure(Application application); static void identify(String userId); static void identify(String userId, Map<String, String> traits); static String userId(); static void reset(); static void screen(String name); static void screen(Activity activity); static void secure(String signature); static boolean secureModeEnabled(); static String publishableKey(); static boolean debugLoggingEnabled(); static String baseUrl(); static String clientId(); static String userSignature(); static void userSignature(String signature); static CastleConfiguration configuration(); static void flush(); static boolean flushIfNeeded(String url); static Map<String, String> headers(String url); static CastleInterceptor castleInterceptor(); static int queueSize(); static void destroy(Application application); static String userAgent(); static io.castle.android.api.model.Context createContext(); }
|
Castle { static boolean isUrlWhiteListed(String urlString) { try { URL url = new URL(urlString); String baseUrl = url.getProtocol() + ": if (Castle.configuration().baseURLWhiteList() != null && !Castle.configuration().baseURLWhiteList().isEmpty()) { if (Castle.configuration().baseURLWhiteList().contains(baseUrl)) { return true; } } } catch (MalformedURLException e) { e.printStackTrace(); } return false; } private Castle(Application application, CastleConfiguration castleConfiguration); static void configure(Application application, CastleConfiguration configuration); static void configure(Application application, String publishableKey); static void configure(Application application, String publishableKey, CastleConfiguration configuration); static void configure(Application application); static void identify(String userId); static void identify(String userId, Map<String, String> traits); static String userId(); static void reset(); static void screen(String name); static void screen(Activity activity); static void secure(String signature); static boolean secureModeEnabled(); static String publishableKey(); static boolean debugLoggingEnabled(); static String baseUrl(); static String clientId(); static String userSignature(); static void userSignature(String signature); static CastleConfiguration configuration(); static void flush(); static boolean flushIfNeeded(String url); static Map<String, String> headers(String url); static CastleInterceptor castleInterceptor(); static int queueSize(); static void destroy(Application application); static String userAgent(); static io.castle.android.api.model.Context createContext(); static final String clientIdHeaderName; }
|
@Test @Config(manifest = "AndroidManifest.xml") public void testUserAgent() { String regex = "[a-zA-Z0-9\\s._-]+/[0-9]+\\.[0-9]+\\.?[0-9]*(-[a-zA-Z0-9]*)? \\([a-zA-Z0-9-_.]+\\) \\([a-zA-Z0-9\\s]+; Android [0-9]+\\.?[0-9]*; Castle [0-9]+\\.[0-9]+\\.?[0-9]*(-[a-zA-Z0-9]*)?\\)"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(Castle.userAgent()); Assert.assertTrue(matcher.matches()); matcher = pattern.matcher("io.castle.android.test/1.0 (1) (Google Nexus 5x; Android 9.0; Castle 1.1.1)"); Assert.assertTrue(matcher.matches()); matcher = pattern.matcher("io.castle.android.test/1.0-SNAPSHOT (1) (Google Nexus 5x; Android 9.0; Castle 1.1.1-SNAPSHOT)"); Assert.assertTrue(matcher.matches()); String result = Utils.sanitizeHeader("[Ţŕéļļö one two]/2020.5.13837-production (13837) (motorola Moto G (4); Android 7.0; Castle 1.1.2)"); Assert.assertEquals("[ one two]/2020.5.13837-production (13837) (motorola Moto G (4); Android 7.0; Castle 1.1.2)", result); }
|
public static String userAgent() { return Utils.sanitizeHeader(String.format(Locale.US, "%s/%s (%d) (%s %s; Android %s; Castle %s)", instance.appName, instance.appVersion, instance.appBuild, Build.MANUFACTURER, Build.MODEL, Build.VERSION.RELEASE, BuildConfig.VERSION_NAME)); }
|
Castle { public static String userAgent() { return Utils.sanitizeHeader(String.format(Locale.US, "%s/%s (%d) (%s %s; Android %s; Castle %s)", instance.appName, instance.appVersion, instance.appBuild, Build.MANUFACTURER, Build.MODEL, Build.VERSION.RELEASE, BuildConfig.VERSION_NAME)); } }
|
Castle { public static String userAgent() { return Utils.sanitizeHeader(String.format(Locale.US, "%s/%s (%d) (%s %s; Android %s; Castle %s)", instance.appName, instance.appVersion, instance.appBuild, Build.MANUFACTURER, Build.MODEL, Build.VERSION.RELEASE, BuildConfig.VERSION_NAME)); } private Castle(Application application, CastleConfiguration castleConfiguration); }
|
Castle { public static String userAgent() { return Utils.sanitizeHeader(String.format(Locale.US, "%s/%s (%d) (%s %s; Android %s; Castle %s)", instance.appName, instance.appVersion, instance.appBuild, Build.MANUFACTURER, Build.MODEL, Build.VERSION.RELEASE, BuildConfig.VERSION_NAME)); } private Castle(Application application, CastleConfiguration castleConfiguration); static void configure(Application application, CastleConfiguration configuration); static void configure(Application application, String publishableKey); static void configure(Application application, String publishableKey, CastleConfiguration configuration); static void configure(Application application); static void identify(String userId); static void identify(String userId, Map<String, String> traits); static String userId(); static void reset(); static void screen(String name); static void screen(Activity activity); static void secure(String signature); static boolean secureModeEnabled(); static String publishableKey(); static boolean debugLoggingEnabled(); static String baseUrl(); static String clientId(); static String userSignature(); static void userSignature(String signature); static CastleConfiguration configuration(); static void flush(); static boolean flushIfNeeded(String url); static Map<String, String> headers(String url); static CastleInterceptor castleInterceptor(); static int queueSize(); static void destroy(Application application); static String userAgent(); static io.castle.android.api.model.Context createContext(); }
|
Castle { public static String userAgent() { return Utils.sanitizeHeader(String.format(Locale.US, "%s/%s (%d) (%s %s; Android %s; Castle %s)", instance.appName, instance.appVersion, instance.appBuild, Build.MANUFACTURER, Build.MODEL, Build.VERSION.RELEASE, BuildConfig.VERSION_NAME)); } private Castle(Application application, CastleConfiguration castleConfiguration); static void configure(Application application, CastleConfiguration configuration); static void configure(Application application, String publishableKey); static void configure(Application application, String publishableKey, CastleConfiguration configuration); static void configure(Application application); static void identify(String userId); static void identify(String userId, Map<String, String> traits); static String userId(); static void reset(); static void screen(String name); static void screen(Activity activity); static void secure(String signature); static boolean secureModeEnabled(); static String publishableKey(); static boolean debugLoggingEnabled(); static String baseUrl(); static String clientId(); static String userSignature(); static void userSignature(String signature); static CastleConfiguration configuration(); static void flush(); static boolean flushIfNeeded(String url); static Map<String, String> headers(String url); static CastleInterceptor castleInterceptor(); static int queueSize(); static void destroy(Application application); static String userAgent(); static io.castle.android.api.model.Context createContext(); static final String clientIdHeaderName; }
|
@Test public void testInvalidGrid() { Solve grid1 = new Solve(); int[][] grid = { { 4, 8, 3, 7, 6, 9, 2, 1, 5 }, { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, { 1, 2, 3, 4, 5, 6, 7, 8, 0 } }; assertEquals(0, grid1.solve(9, grid)); }
|
Solve() { }
|
Solve { Solve() { } }
|
Solve { Solve() { } Solve(); }
|
Solve { Solve() { } Solve(); int solve(int dimension, int[][] gridCopy); static int[] rc2box(int i, int j); }
|
Solve { Solve() { } Solve(); int solve(int dimension, int[][] gridCopy); static int[] rc2box(int i, int j); }
|
@Test public void testGameGrid() { Solve grid1 = new Solve(); GameGrid grid = new GameGrid(9); assertTrue(0< grid1.solve(9, grid.grid)); }
|
Solve() { }
|
Solve { Solve() { } }
|
Solve { Solve() { } Solve(); }
|
Solve { Solve() { } Solve(); int solve(int dimension, int[][] gridCopy); static int[] rc2box(int i, int j); }
|
Solve { Solve() { } Solve(); int solve(int dimension, int[][] gridCopy); static int[] rc2box(int i, int j); }
|
@Test public void find() throws Exception { this.mockMvc.perform(get("/matrix/find/42;q=11;r=22")) .andExpect(status().isOk()) .andExpect(content().string("4211")); }
|
@RequestMapping(path = "/find/{petId}", method = RequestMethod.GET) @ResponseBody public String find(@PathVariable String petId, @MatrixVariable int q) { logger.info("petId:{},q:{}",petId,q); return petId + q; }
|
MatrixController { @RequestMapping(path = "/find/{petId}", method = RequestMethod.GET) @ResponseBody public String find(@PathVariable String petId, @MatrixVariable int q) { logger.info("petId:{},q:{}",petId,q); return petId + q; } }
|
MatrixController { @RequestMapping(path = "/find/{petId}", method = RequestMethod.GET) @ResponseBody public String find(@PathVariable String petId, @MatrixVariable int q) { logger.info("petId:{},q:{}",petId,q); return petId + q; } }
|
MatrixController { @RequestMapping(path = "/find/{petId}", method = RequestMethod.GET) @ResponseBody public String find(@PathVariable String petId, @MatrixVariable int q) { logger.info("petId:{},q:{}",petId,q); return petId + q; } @RequestMapping(path = "/find/{petId}", method = RequestMethod.GET) @ResponseBody String find(@PathVariable String petId, @MatrixVariable int q); @RequestMapping(path = "/owners/{ownerId}/pets/{petId}", method = RequestMethod.GET) @ResponseBody String find1(
@MatrixVariable(name="q", pathVar="ownerId") int q1,
@MatrixVariable(name="q", pathVar="petId") int q2); }
|
MatrixController { @RequestMapping(path = "/find/{petId}", method = RequestMethod.GET) @ResponseBody public String find(@PathVariable String petId, @MatrixVariable int q) { logger.info("petId:{},q:{}",petId,q); return petId + q; } @RequestMapping(path = "/find/{petId}", method = RequestMethod.GET) @ResponseBody String find(@PathVariable String petId, @MatrixVariable int q); @RequestMapping(path = "/owners/{ownerId}/pets/{petId}", method = RequestMethod.GET) @ResponseBody String find1(
@MatrixVariable(name="q", pathVar="ownerId") int q1,
@MatrixVariable(name="q", pathVar="petId") int q2); }
|
@Test public void find1() throws Exception { this.mockMvc.perform(get("/matrix/owners/42;q=11/pets/11;q=22")) .andExpect(status().isOk()) .andExpect(content().string("33")); }
|
@RequestMapping(path = "/owners/{ownerId}/pets/{petId}", method = RequestMethod.GET) @ResponseBody public String find1( @MatrixVariable(name="q", pathVar="ownerId") int q1, @MatrixVariable(name="q", pathVar="petId") int q2) { return String.valueOf(q1+q2); }
|
MatrixController { @RequestMapping(path = "/owners/{ownerId}/pets/{petId}", method = RequestMethod.GET) @ResponseBody public String find1( @MatrixVariable(name="q", pathVar="ownerId") int q1, @MatrixVariable(name="q", pathVar="petId") int q2) { return String.valueOf(q1+q2); } }
|
MatrixController { @RequestMapping(path = "/owners/{ownerId}/pets/{petId}", method = RequestMethod.GET) @ResponseBody public String find1( @MatrixVariable(name="q", pathVar="ownerId") int q1, @MatrixVariable(name="q", pathVar="petId") int q2) { return String.valueOf(q1+q2); } }
|
MatrixController { @RequestMapping(path = "/owners/{ownerId}/pets/{petId}", method = RequestMethod.GET) @ResponseBody public String find1( @MatrixVariable(name="q", pathVar="ownerId") int q1, @MatrixVariable(name="q", pathVar="petId") int q2) { return String.valueOf(q1+q2); } @RequestMapping(path = "/find/{petId}", method = RequestMethod.GET) @ResponseBody String find(@PathVariable String petId, @MatrixVariable int q); @RequestMapping(path = "/owners/{ownerId}/pets/{petId}", method = RequestMethod.GET) @ResponseBody String find1(
@MatrixVariable(name="q", pathVar="ownerId") int q1,
@MatrixVariable(name="q", pathVar="petId") int q2); }
|
MatrixController { @RequestMapping(path = "/owners/{ownerId}/pets/{petId}", method = RequestMethod.GET) @ResponseBody public String find1( @MatrixVariable(name="q", pathVar="ownerId") int q1, @MatrixVariable(name="q", pathVar="petId") int q2) { return String.valueOf(q1+q2); } @RequestMapping(path = "/find/{petId}", method = RequestMethod.GET) @ResponseBody String find(@PathVariable String petId, @MatrixVariable int q); @RequestMapping(path = "/owners/{ownerId}/pets/{petId}", method = RequestMethod.GET) @ResponseBody String find1(
@MatrixVariable(name="q", pathVar="ownerId") int q1,
@MatrixVariable(name="q", pathVar="petId") int q2); }
|
@Test public void getUser() throws Exception { logger.info("JsonControllerTest getUser is running"); this.mockMvc.perform(get("/json/get").accept(MediaType.parseMediaType("application/json;charset=UTF-8"))) .andExpect(status().isOk()).andExpect(content().contentType("application/json;charset=UTF-8")) .andExpect(jsonPath("$.name").value("李四")); }
|
@RequestMapping(path = "/get",method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody public User get(){ return new User(20,"李四","F"); }
|
JsonController { @RequestMapping(path = "/get",method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody public User get(){ return new User(20,"李四","F"); } }
|
JsonController { @RequestMapping(path = "/get",method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody public User get(){ return new User(20,"李四","F"); } }
|
JsonController { @RequestMapping(path = "/get",method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody public User get(){ return new User(20,"李四","F"); } @RequestMapping(path = "/get",method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User get(); @RequestMapping(path = "/post/{name}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User post(@PathVariable String name, Model model); }
|
JsonController { @RequestMapping(path = "/get",method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody public User get(){ return new User(20,"李四","F"); } @RequestMapping(path = "/get",method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User get(); @RequestMapping(path = "/post/{name}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User post(@PathVariable String name, Model model); }
|
@Test public void postUser() throws Exception { logger.info("JsonControllerTest postUser is running"); this.mockMvc.perform(post("/json/post/haha").accept(MediaType.parseMediaType("application/json;charset=UTF-8"))) .andExpect(status().isOk()).andExpect(content().contentType("application/json;charset=UTF-8")) .andExpect(jsonPath("$.name").value("haha")); }
|
@RequestMapping(path = "/post/{name}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody public User post(@PathVariable String name, Model model){ logger.info("name : {}",name); return new User(20,name,"男"); }
|
JsonController { @RequestMapping(path = "/post/{name}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody public User post(@PathVariable String name, Model model){ logger.info("name : {}",name); return new User(20,name,"男"); } }
|
JsonController { @RequestMapping(path = "/post/{name}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody public User post(@PathVariable String name, Model model){ logger.info("name : {}",name); return new User(20,name,"男"); } }
|
JsonController { @RequestMapping(path = "/post/{name}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody public User post(@PathVariable String name, Model model){ logger.info("name : {}",name); return new User(20,name,"男"); } @RequestMapping(path = "/get",method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User get(); @RequestMapping(path = "/post/{name}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User post(@PathVariable String name, Model model); }
|
JsonController { @RequestMapping(path = "/post/{name}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody public User post(@PathVariable String name, Model model){ logger.info("name : {}",name); return new User(20,name,"男"); } @RequestMapping(path = "/get",method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User get(); @RequestMapping(path = "/post/{name}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User post(@PathVariable String name, Model model); }
|
@Test public void getUser() throws Exception { logger.info("XmlControllerTest getUser is running"); this.mockMvc.perform(get("/xml/get")).andExpect(status().isOk()).andExpect(content().contentType ("application/xml")).andExpect(xpath("/user/name", new HashMap<String, String>()).string("张三")); }
|
@RequestMapping(path = "/get",method = RequestMethod.GET,produces = MediaType.APPLICATION_XML_VALUE) @ResponseBody public User get(){ return new User(21,"张三","男"); }
|
XmlController { @RequestMapping(path = "/get",method = RequestMethod.GET,produces = MediaType.APPLICATION_XML_VALUE) @ResponseBody public User get(){ return new User(21,"张三","男"); } }
|
XmlController { @RequestMapping(path = "/get",method = RequestMethod.GET,produces = MediaType.APPLICATION_XML_VALUE) @ResponseBody public User get(){ return new User(21,"张三","男"); } }
|
XmlController { @RequestMapping(path = "/get",method = RequestMethod.GET,produces = MediaType.APPLICATION_XML_VALUE) @ResponseBody public User get(){ return new User(21,"张三","男"); } @RequestMapping(path = "/get",method = RequestMethod.GET,produces = MediaType.APPLICATION_XML_VALUE) @ResponseBody User get(); @RequestMapping(path = "/post",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody User post(@RequestBody User user); @RequestMapping(path = "/post1",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody User post1(@RequestBody User user); @RequestMapping(path = "/postHouse",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody House postHouse(@RequestBody House house); }
|
XmlController { @RequestMapping(path = "/get",method = RequestMethod.GET,produces = MediaType.APPLICATION_XML_VALUE) @ResponseBody public User get(){ return new User(21,"张三","男"); } @RequestMapping(path = "/get",method = RequestMethod.GET,produces = MediaType.APPLICATION_XML_VALUE) @ResponseBody User get(); @RequestMapping(path = "/post",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody User post(@RequestBody User user); @RequestMapping(path = "/post1",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody User post1(@RequestBody User user); @RequestMapping(path = "/postHouse",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody House postHouse(@RequestBody House house); }
|
@Test public void postUser() throws Exception { logger.info("XmlControllerTest postUser is running"); User user = new User(10, "王五", "男"); String content = JaxbUtils.toXml(user); logger.info("content:{}", content); this.mockMvc.perform(post("/xml/post").contentType(MediaType.APPLICATION_XML_VALUE).content(content)) .andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_XML_VALUE)).andExpect(xpath ("/user/sex", new HashMap<String, String>()).string("男")); }
|
@RequestMapping(path = "/post",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody public User post(@RequestBody User user){ logger.info(user.toString()); return user; }
|
XmlController { @RequestMapping(path = "/post",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody public User post(@RequestBody User user){ logger.info(user.toString()); return user; } }
|
XmlController { @RequestMapping(path = "/post",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody public User post(@RequestBody User user){ logger.info(user.toString()); return user; } }
|
XmlController { @RequestMapping(path = "/post",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody public User post(@RequestBody User user){ logger.info(user.toString()); return user; } @RequestMapping(path = "/get",method = RequestMethod.GET,produces = MediaType.APPLICATION_XML_VALUE) @ResponseBody User get(); @RequestMapping(path = "/post",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody User post(@RequestBody User user); @RequestMapping(path = "/post1",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody User post1(@RequestBody User user); @RequestMapping(path = "/postHouse",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody House postHouse(@RequestBody House house); }
|
XmlController { @RequestMapping(path = "/post",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody public User post(@RequestBody User user){ logger.info(user.toString()); return user; } @RequestMapping(path = "/get",method = RequestMethod.GET,produces = MediaType.APPLICATION_XML_VALUE) @ResponseBody User get(); @RequestMapping(path = "/post",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody User post(@RequestBody User user); @RequestMapping(path = "/post1",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody User post1(@RequestBody User user); @RequestMapping(path = "/postHouse",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody House postHouse(@RequestBody House house); }
|
@Test public void postHouse() throws Exception { logger.info("XmlControllerTest postHouse is running"); User user = new User(30, "王五", "男"); House house = new House(user,"南京"); String content = JaxbUtils.toXml(house); logger.info("content:{}", content); this.mockMvc.perform(post("/xml/postHouse").contentType(MediaType.APPLICATION_XML_VALUE).content(content)) .andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_XML_VALUE)).andExpect(xpath ("/house/user/sex", new HashMap<String, String>()).string("男")); }
|
@RequestMapping(path = "/postHouse",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody public House postHouse(@RequestBody House house){ logger.info(house.toString()); return house; }
|
XmlController { @RequestMapping(path = "/postHouse",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody public House postHouse(@RequestBody House house){ logger.info(house.toString()); return house; } }
|
XmlController { @RequestMapping(path = "/postHouse",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody public House postHouse(@RequestBody House house){ logger.info(house.toString()); return house; } }
|
XmlController { @RequestMapping(path = "/postHouse",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody public House postHouse(@RequestBody House house){ logger.info(house.toString()); return house; } @RequestMapping(path = "/get",method = RequestMethod.GET,produces = MediaType.APPLICATION_XML_VALUE) @ResponseBody User get(); @RequestMapping(path = "/post",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody User post(@RequestBody User user); @RequestMapping(path = "/post1",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody User post1(@RequestBody User user); @RequestMapping(path = "/postHouse",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody House postHouse(@RequestBody House house); }
|
XmlController { @RequestMapping(path = "/postHouse",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody public House postHouse(@RequestBody House house){ logger.info(house.toString()); return house; } @RequestMapping(path = "/get",method = RequestMethod.GET,produces = MediaType.APPLICATION_XML_VALUE) @ResponseBody User get(); @RequestMapping(path = "/post",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody User post(@RequestBody User user); @RequestMapping(path = "/post1",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody User post1(@RequestBody User user); @RequestMapping(path = "/postHouse",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody House postHouse(@RequestBody House house); }
|
@Test public void postTest() throws Exception { User user = new User(50, "王五", "男"); String content = JSON.toJSONString(user); logger.info("content:{}", content); this.mockMvc.perform(post("/valid/post").contentType(MediaType.APPLICATION_JSON_UTF8_VALUE).content(content)) .andExpect(content().string("4211")); }
|
@RequestMapping(path = "/post",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody public User post(@RequestBody @Valid User user){ return user; }
|
ValidController { @RequestMapping(path = "/post",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody public User post(@RequestBody @Valid User user){ return user; } }
|
ValidController { @RequestMapping(path = "/post",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody public User post(@RequestBody @Valid User user){ return user; } }
|
ValidController { @RequestMapping(path = "/post",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody public User post(@RequestBody @Valid User user){ return user; } @RequestMapping(path = "/post",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User post(@RequestBody @Valid User user); }
|
ValidController { @RequestMapping(path = "/post",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody public User post(@RequestBody @Valid User user){ return user; } @RequestMapping(path = "/post",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User post(@RequestBody @Valid User user); }
|
@Test public void validateId(){ assertTrue(ModelRef.validateId("com.mycompany.Test")); assertTrue(ModelRef.validateId("Test_v1")); assertTrue(ModelRef.validateId("Test_v1.0")); assertFalse(ModelRef.validateId(".")); assertFalse(ModelRef.validateId("-Test")); }
|
static public boolean validateId(String id){ return (id != null) && (id).matches(REGEX_ID); }
|
ModelRef { static public boolean validateId(String id){ return (id != null) && (id).matches(REGEX_ID); } }
|
ModelRef { static public boolean validateId(String id){ return (id != null) && (id).matches(REGEX_ID); } ModelRef(ModelRef modelRef); ModelRef(Principal owner, String id); }
|
ModelRef { static public boolean validateId(String id){ return (id != null) && (id).matches(REGEX_ID); } ModelRef(ModelRef modelRef); ModelRef(Principal owner, String id); @Override int hashCode(); @Override boolean equals(Object object); Principal getOwner(); String getId(); static boolean validateId(String id); }
|
ModelRef { static public boolean validateId(String id){ return (id != null) && (id).matches(REGEX_ID); } ModelRef(ModelRef modelRef); ModelRef(Principal owner, String id); @Override int hashCode(); @Override boolean equals(Object object); Principal getOwner(); String getId(); static boolean validateId(String id); static final String PATH_VALUE_ID; }
|
@Test public void getFormat() throws IOException { CsvPreference first; CsvPreference second; String csv = "1\tone\n" + "2\ttwo\n" + "3\tthree"; try(BufferedReader reader = new BufferedReader(new StringReader(csv))){ first = CsvUtil.getFormat(reader); second = CsvUtil.getFormat(reader); } assertNotSame(first.getEncoder(), second.getEncoder()); }
|
static public CsvPreference getFormat(String delimiterChar, String quoteChar){ char delimiter = ','; char quote = '\"'; if(delimiterChar != null){ delimiterChar = decodeDelimiter(delimiterChar); if(delimiterChar.length() != 1){ throw new IllegalArgumentException("Invalid CSV delimiter character: \"" + delimiterChar + "\""); } delimiter = delimiterChar.charAt(0); } if(quoteChar != null){ quoteChar = decodeQuote(quoteChar); if(quoteChar.length() != 1){ throw new IllegalArgumentException("Invalid CSV quote character: \"" + quoteChar + "\""); } quote = quoteChar.charAt(0); } CsvPreference format = createFormat(delimiter, quote); return format; }
|
CsvUtil { static public CsvPreference getFormat(String delimiterChar, String quoteChar){ char delimiter = ','; char quote = '\"'; if(delimiterChar != null){ delimiterChar = decodeDelimiter(delimiterChar); if(delimiterChar.length() != 1){ throw new IllegalArgumentException("Invalid CSV delimiter character: \"" + delimiterChar + "\""); } delimiter = delimiterChar.charAt(0); } if(quoteChar != null){ quoteChar = decodeQuote(quoteChar); if(quoteChar.length() != 1){ throw new IllegalArgumentException("Invalid CSV quote character: \"" + quoteChar + "\""); } quote = quoteChar.charAt(0); } CsvPreference format = createFormat(delimiter, quote); return format; } }
|
CsvUtil { static public CsvPreference getFormat(String delimiterChar, String quoteChar){ char delimiter = ','; char quote = '\"'; if(delimiterChar != null){ delimiterChar = decodeDelimiter(delimiterChar); if(delimiterChar.length() != 1){ throw new IllegalArgumentException("Invalid CSV delimiter character: \"" + delimiterChar + "\""); } delimiter = delimiterChar.charAt(0); } if(quoteChar != null){ quoteChar = decodeQuote(quoteChar); if(quoteChar.length() != 1){ throw new IllegalArgumentException("Invalid CSV quote character: \"" + quoteChar + "\""); } quote = quoteChar.charAt(0); } CsvPreference format = createFormat(delimiter, quote); return format; } private CsvUtil(); }
|
CsvUtil { static public CsvPreference getFormat(String delimiterChar, String quoteChar){ char delimiter = ','; char quote = '\"'; if(delimiterChar != null){ delimiterChar = decodeDelimiter(delimiterChar); if(delimiterChar.length() != 1){ throw new IllegalArgumentException("Invalid CSV delimiter character: \"" + delimiterChar + "\""); } delimiter = delimiterChar.charAt(0); } if(quoteChar != null){ quoteChar = decodeQuote(quoteChar); if(quoteChar.length() != 1){ throw new IllegalArgumentException("Invalid CSV quote character: \"" + quoteChar + "\""); } quote = quoteChar.charAt(0); } CsvPreference format = createFormat(delimiter, quote); return format; } private CsvUtil(); static CsvPreference getFormat(String delimiterChar, String quoteChar); static CsvPreference getFormat(BufferedReader reader); static CsvPreference createFormat(char delimiterChar, char quoteChar); static TableEvaluationRequest readTable(BufferedReader reader, CsvPreference format); static void writeTable(TableEvaluationResponse tableResponse, BufferedWriter writer, CsvPreference format); }
|
CsvUtil { static public CsvPreference getFormat(String delimiterChar, String quoteChar){ char delimiter = ','; char quote = '\"'; if(delimiterChar != null){ delimiterChar = decodeDelimiter(delimiterChar); if(delimiterChar.length() != 1){ throw new IllegalArgumentException("Invalid CSV delimiter character: \"" + delimiterChar + "\""); } delimiter = delimiterChar.charAt(0); } if(quoteChar != null){ quoteChar = decodeQuote(quoteChar); if(quoteChar.length() != 1){ throw new IllegalArgumentException("Invalid CSV quote character: \"" + quoteChar + "\""); } quote = quoteChar.charAt(0); } CsvPreference format = createFormat(delimiter, quote); return format; } private CsvUtil(); static CsvPreference getFormat(String delimiterChar, String quoteChar); static CsvPreference getFormat(BufferedReader reader); static CsvPreference createFormat(char delimiterChar, char quoteChar); static TableEvaluationRequest readTable(BufferedReader reader, CsvPreference format); static void writeTable(TableEvaluationResponse tableResponse, BufferedWriter writer, CsvPreference format); }
|
@Test public void toResponse(){ assertEquals("Not Found", getMessage(new NotFoundException())); assertEquals("Resource \"id\" not found", getMessage(new NotFoundException("Resource \"id\" not found"))); assertEquals("Bad Request", getMessage(new BadRequestException(new IllegalArgumentException()))); assertEquals("Bad \"id\" value", getMessage(new BadRequestException(new IllegalArgumentException("Bad \"id\" value")))); assertEquals("Bad Request", getMessage(new BadRequestException(new UnmarshalException(new IOException())))); assertEquals("Resource \"id\" is incomplete", getMessage(new BadRequestException(new UnmarshalException(new EOFException("Resource \"id\" is incomplete"))))); UnmarshalException selfRefException = new UnmarshalException((Throwable)null); selfRefException.setLinkedException(new UnmarshalException(selfRefException)); assertEquals("Bad Request", getMessage(new BadRequestException(selfRefException))); }
|
@Override public Response toResponse(WebApplicationException exception){ Response response = exception.getResponse(); Throwable throwable = exception; Map<Throwable, Throwable> throwableMap = new IdentityHashMap<>(); while(true){ Throwable cause = throwable.getCause(); throwableMap.put(throwable, cause); if((cause == null) || throwableMap.containsKey(cause)){ break; } throwable = cause; } String message = throwable.getMessage(); if((message == null) || ("").equals(message)){ Response.Status status = (Response.Status)response.getStatusInfo(); message = status.getReasonPhrase(); } if(message.startsWith("HTTP ")){ message = message.replaceFirst("^HTTP (\\d)+ ", ""); } SimpleResponse entity = new SimpleResponse(); entity.setMessage(message); return (Response.fromResponse(response).entity(entity).type(MediaType.APPLICATION_JSON)).build(); }
|
WebApplicationExceptionMapper implements ExceptionMapper<WebApplicationException> { @Override public Response toResponse(WebApplicationException exception){ Response response = exception.getResponse(); Throwable throwable = exception; Map<Throwable, Throwable> throwableMap = new IdentityHashMap<>(); while(true){ Throwable cause = throwable.getCause(); throwableMap.put(throwable, cause); if((cause == null) || throwableMap.containsKey(cause)){ break; } throwable = cause; } String message = throwable.getMessage(); if((message == null) || ("").equals(message)){ Response.Status status = (Response.Status)response.getStatusInfo(); message = status.getReasonPhrase(); } if(message.startsWith("HTTP ")){ message = message.replaceFirst("^HTTP (\\d)+ ", ""); } SimpleResponse entity = new SimpleResponse(); entity.setMessage(message); return (Response.fromResponse(response).entity(entity).type(MediaType.APPLICATION_JSON)).build(); } }
|
WebApplicationExceptionMapper implements ExceptionMapper<WebApplicationException> { @Override public Response toResponse(WebApplicationException exception){ Response response = exception.getResponse(); Throwable throwable = exception; Map<Throwable, Throwable> throwableMap = new IdentityHashMap<>(); while(true){ Throwable cause = throwable.getCause(); throwableMap.put(throwable, cause); if((cause == null) || throwableMap.containsKey(cause)){ break; } throwable = cause; } String message = throwable.getMessage(); if((message == null) || ("").equals(message)){ Response.Status status = (Response.Status)response.getStatusInfo(); message = status.getReasonPhrase(); } if(message.startsWith("HTTP ")){ message = message.replaceFirst("^HTTP (\\d)+ ", ""); } SimpleResponse entity = new SimpleResponse(); entity.setMessage(message); return (Response.fromResponse(response).entity(entity).type(MediaType.APPLICATION_JSON)).build(); } }
|
WebApplicationExceptionMapper implements ExceptionMapper<WebApplicationException> { @Override public Response toResponse(WebApplicationException exception){ Response response = exception.getResponse(); Throwable throwable = exception; Map<Throwable, Throwable> throwableMap = new IdentityHashMap<>(); while(true){ Throwable cause = throwable.getCause(); throwableMap.put(throwable, cause); if((cause == null) || throwableMap.containsKey(cause)){ break; } throwable = cause; } String message = throwable.getMessage(); if((message == null) || ("").equals(message)){ Response.Status status = (Response.Status)response.getStatusInfo(); message = status.getReasonPhrase(); } if(message.startsWith("HTTP ")){ message = message.replaceFirst("^HTTP (\\d)+ ", ""); } SimpleResponse entity = new SimpleResponse(); entity.setMessage(message); return (Response.fromResponse(response).entity(entity).type(MediaType.APPLICATION_JSON)).build(); } @Override Response toResponse(WebApplicationException exception); }
|
WebApplicationExceptionMapper implements ExceptionMapper<WebApplicationException> { @Override public Response toResponse(WebApplicationException exception){ Response response = exception.getResponse(); Throwable throwable = exception; Map<Throwable, Throwable> throwableMap = new IdentityHashMap<>(); while(true){ Throwable cause = throwable.getCause(); throwableMap.put(throwable, cause); if((cause == null) || throwableMap.containsKey(cause)){ break; } throwable = cause; } String message = throwable.getMessage(); if((message == null) || ("").equals(message)){ Response.Status status = (Response.Status)response.getStatusInfo(); message = status.getReasonPhrase(); } if(message.startsWith("HTTP ")){ message = message.replaceFirst("^HTTP (\\d)+ ", ""); } SimpleResponse entity = new SimpleResponse(); entity.setMessage(message); return (Response.fromResponse(response).entity(entity).type(MediaType.APPLICATION_JSON)).build(); } @Override Response toResponse(WebApplicationException exception); }
|
@Test(expected = MyException.class) public void shouldInterceptInvocationException() throws Exception { final Throwable[] thrown = new Throwable[1]; final MyException decoratedException = new MyException(); foo = Decorating.proxy(new MethodMissingImpl(), Foo.class).visiting(new Decorator<Foo>() { private static final long serialVersionUID = 1L; @Override public Exception decorateInvocationException(Foo proxy, Method method, Object[] args, Exception cause) { thrown[0] = cause; return decoratedException; } }).build(); foo.getSomething("value"); fail("Mock should have thrown exception"); }
|
public static <T> DecoratingWith<T> proxy(final Class<T> type) { return new DecoratingWith<T>(new Decorating<T, T>((T)null, type)); }
|
Decorating { public static <T> DecoratingWith<T> proxy(final Class<T> type) { return new DecoratingWith<T>(new Decorating<T, T>((T)null, type)); } }
|
Decorating { public static <T> DecoratingWith<T> proxy(final Class<T> type) { return new DecoratingWith<T>(new Decorating<T, T>((T)null, type)); } private Decorating(final U delegate, final Class<T>primaryType, final Class<?>... types); }
|
Decorating { public static <T> DecoratingWith<T> proxy(final Class<T> type) { return new DecoratingWith<T>(new Decorating<T, T>((T)null, type)); } private Decorating(final U delegate, final Class<T>primaryType, final Class<?>... types); static DecoratingWith<T> proxy(final Class<T> type); static DecoratingWith<T> proxy(final Class<T> primaryType, final Class<?> ... types); static DecoratingVisitor<U, U> proxy(final U delegate); static DecoratingVisitor<U, T> proxy(final U delegate, final Class<T> type); static DecoratingVisitor<U, T> proxy(final U delegate, final Class<T> primaryType, final Class<?> ... types); }
|
Decorating { public static <T> DecoratingWith<T> proxy(final Class<T> type) { return new DecoratingWith<T>(new Decorating<T, T>((T)null, type)); } private Decorating(final U delegate, final Class<T>primaryType, final Class<?>... types); static DecoratingWith<T> proxy(final Class<T> type); static DecoratingWith<T> proxy(final Class<T> primaryType, final Class<?> ... types); static DecoratingVisitor<U, U> proxy(final U delegate); static DecoratingVisitor<U, T> proxy(final U delegate, final Class<T> type); static DecoratingVisitor<U, T> proxy(final U delegate, final Class<T> primaryType, final Class<?> ... types); }
|
@Test public void callWithArgumentsIsDelegated() throws Exception { Foo fooMock = mock(Foo.class); Foo foo = Privileging.proxy(Foo.class).with(fooMock).executedBy(new DirectExecutor()).build(getFactory()); foo.call(42, "Arthur"); verify(fooMock).call(42, "Arthur"); }
|
public static <T> PrivilegingWith<T> proxy(Class<T> type) { return new PrivilegingWith<T>(new Privileging<T>(type)); }
|
Privileging { public static <T> PrivilegingWith<T> proxy(Class<T> type) { return new PrivilegingWith<T>(new Privileging<T>(type)); } }
|
Privileging { public static <T> PrivilegingWith<T> proxy(Class<T> type) { return new PrivilegingWith<T>(new Privileging<T>(type)); } private Privileging(Class<T> type); }
|
Privileging { public static <T> PrivilegingWith<T> proxy(Class<T> type) { return new PrivilegingWith<T>(new Privileging<T>(type)); } private Privileging(Class<T> type); static PrivilegingWith<T> proxy(Class<T> type); static PrivilegingExecutedByOrBuild<T> proxy(T target); }
|
Privileging { public static <T> PrivilegingWith<T> proxy(Class<T> type) { return new PrivilegingWith<T>(new Privileging<T>(type)); } private Privileging(Class<T> type); static PrivilegingWith<T> proxy(Class<T> type); static PrivilegingExecutedByOrBuild<T> proxy(T target); }
|
@Test public void callWillReturnValue() throws Exception { Foo fooMock = mock(Foo.class); when(fooMock.call("Arthur")).thenReturn(42); Foo foo = Privileging.proxy(Foo.class).with(fooMock).executedBy(new DirectExecutor()).build(getFactory()); assertEquals(42, foo.call("Arthur")); verify(fooMock).call("Arthur"); }
|
public static <T> PrivilegingWith<T> proxy(Class<T> type) { return new PrivilegingWith<T>(new Privileging<T>(type)); }
|
Privileging { public static <T> PrivilegingWith<T> proxy(Class<T> type) { return new PrivilegingWith<T>(new Privileging<T>(type)); } }
|
Privileging { public static <T> PrivilegingWith<T> proxy(Class<T> type) { return new PrivilegingWith<T>(new Privileging<T>(type)); } private Privileging(Class<T> type); }
|
Privileging { public static <T> PrivilegingWith<T> proxy(Class<T> type) { return new PrivilegingWith<T>(new Privileging<T>(type)); } private Privileging(Class<T> type); static PrivilegingWith<T> proxy(Class<T> type); static PrivilegingExecutedByOrBuild<T> proxy(T target); }
|
Privileging { public static <T> PrivilegingWith<T> proxy(Class<T> type) { return new PrivilegingWith<T>(new Privileging<T>(type)); } private Privileging(Class<T> type); static PrivilegingWith<T> proxy(Class<T> type); static PrivilegingExecutedByOrBuild<T> proxy(T target); }
|
@Test(expected=NoSuchElementException.class) public void callWillThrowCheckedException() throws Exception { Foo fooMock = mock(Foo.class); when(fooMock.call("Arthur")).thenThrow(new NoSuchElementException("JUnit")); Foo foo = Privileging.proxy(Foo.class).with(fooMock).executedBy(new DirectExecutor()).build(getFactory()); foo.call("Arthur"); }
|
public static <T> PrivilegingWith<T> proxy(Class<T> type) { return new PrivilegingWith<T>(new Privileging<T>(type)); }
|
Privileging { public static <T> PrivilegingWith<T> proxy(Class<T> type) { return new PrivilegingWith<T>(new Privileging<T>(type)); } }
|
Privileging { public static <T> PrivilegingWith<T> proxy(Class<T> type) { return new PrivilegingWith<T>(new Privileging<T>(type)); } private Privileging(Class<T> type); }
|
Privileging { public static <T> PrivilegingWith<T> proxy(Class<T> type) { return new PrivilegingWith<T>(new Privileging<T>(type)); } private Privileging(Class<T> type); static PrivilegingWith<T> proxy(Class<T> type); static PrivilegingExecutedByOrBuild<T> proxy(T target); }
|
Privileging { public static <T> PrivilegingWith<T> proxy(Class<T> type) { return new PrivilegingWith<T>(new Privileging<T>(type)); } private Privileging(Class<T> type); static PrivilegingWith<T> proxy(Class<T> type); static PrivilegingExecutedByOrBuild<T> proxy(T target); }
|
@Test(expected=ArithmeticException.class) public void callWillThrowRuntimeException() throws Exception { Foo fooMock = mock(Foo.class); when(fooMock.call("Arthur")).thenThrow(new ArithmeticException("JUnit")); Foo foo = Privileging.proxy(Foo.class).with(fooMock).executedBy(new DirectExecutor()).build(getFactory()); foo.call("Arthur"); }
|
public static <T> PrivilegingWith<T> proxy(Class<T> type) { return new PrivilegingWith<T>(new Privileging<T>(type)); }
|
Privileging { public static <T> PrivilegingWith<T> proxy(Class<T> type) { return new PrivilegingWith<T>(new Privileging<T>(type)); } }
|
Privileging { public static <T> PrivilegingWith<T> proxy(Class<T> type) { return new PrivilegingWith<T>(new Privileging<T>(type)); } private Privileging(Class<T> type); }
|
Privileging { public static <T> PrivilegingWith<T> proxy(Class<T> type) { return new PrivilegingWith<T>(new Privileging<T>(type)); } private Privileging(Class<T> type); static PrivilegingWith<T> proxy(Class<T> type); static PrivilegingExecutedByOrBuild<T> proxy(T target); }
|
Privileging { public static <T> PrivilegingWith<T> proxy(Class<T> type) { return new PrivilegingWith<T>(new Privileging<T>(type)); } private Privileging(Class<T> type); static PrivilegingWith<T> proxy(Class<T> type); static PrivilegingExecutedByOrBuild<T> proxy(T target); }
|
@Test public void callWillCallToString() throws Exception { Foo fooMock = mock(Foo.class); when(fooMock.toString()).thenReturn("Arthur"); Foo foo = Privileging.proxy(Foo.class).with(fooMock).executedBy(new DirectExecutor()).build(getFactory()); assertEquals("Arthur", foo.toString()); }
|
public static <T> PrivilegingWith<T> proxy(Class<T> type) { return new PrivilegingWith<T>(new Privileging<T>(type)); }
|
Privileging { public static <T> PrivilegingWith<T> proxy(Class<T> type) { return new PrivilegingWith<T>(new Privileging<T>(type)); } }
|
Privileging { public static <T> PrivilegingWith<T> proxy(Class<T> type) { return new PrivilegingWith<T>(new Privileging<T>(type)); } private Privileging(Class<T> type); }
|
Privileging { public static <T> PrivilegingWith<T> proxy(Class<T> type) { return new PrivilegingWith<T>(new Privileging<T>(type)); } private Privileging(Class<T> type); static PrivilegingWith<T> proxy(Class<T> type); static PrivilegingExecutedByOrBuild<T> proxy(T target); }
|
Privileging { public static <T> PrivilegingWith<T> proxy(Class<T> type) { return new PrivilegingWith<T>(new Privileging<T>(type)); } private Privileging(Class<T> type); static PrivilegingWith<T> proxy(Class<T> type); static PrivilegingExecutedByOrBuild<T> proxy(T target); }
|
@Test public void shouldFailoverToNextOnSpecialException() { FailsOnNthCall first = new FailsOnNthCallImpl(1); FailsOnNthCall second = new FailsOnNthCallImpl(1); FailsOnNthCall failover = Failover.proxy(FailsOnNthCall.class) .with(first, second) .excepting(RuntimeException.class) .build(getFactory()); assertEquals(0, first.dunIt()); assertEquals(0, second.dunIt()); failover.doIt(); assertEquals(1, first.dunIt()); assertEquals(0, second.dunIt()); failover.doIt(); assertEquals(1, first.dunIt()); assertEquals(1, second.dunIt()); }
|
public static <T> FailoverWithOrExceptingOrBuild<T> proxy(Class<T> type) { return new FailoverWithOrExceptingOrBuild<T>(new Failover<T>(type)); }
|
Failover { public static <T> FailoverWithOrExceptingOrBuild<T> proxy(Class<T> type) { return new FailoverWithOrExceptingOrBuild<T>(new Failover<T>(type)); } }
|
Failover { public static <T> FailoverWithOrExceptingOrBuild<T> proxy(Class<T> type) { return new FailoverWithOrExceptingOrBuild<T>(new Failover<T>(type)); } private Failover(Class<T> primaryType, Class<?>... types); }
|
Failover { public static <T> FailoverWithOrExceptingOrBuild<T> proxy(Class<T> type) { return new FailoverWithOrExceptingOrBuild<T>(new Failover<T>(type)); } private Failover(Class<T> primaryType, Class<?>... types); static FailoverWithOrExceptingOrBuild<T> proxy(Class<T> type); static FailoverWithOrExceptingOrBuild<T> proxy(final Class<T> primaryType, final Class<?> ... types); static FailoverExceptingOrBuild<T> proxy(final T... delegates); }
|
Failover { public static <T> FailoverWithOrExceptingOrBuild<T> proxy(Class<T> type) { return new FailoverWithOrExceptingOrBuild<T>(new Failover<T>(type)); } private Failover(Class<T> primaryType, Class<?>... types); static FailoverWithOrExceptingOrBuild<T> proxy(Class<T> type); static FailoverWithOrExceptingOrBuild<T> proxy(final Class<T> primaryType, final Class<?> ... types); static FailoverExceptingOrBuild<T> proxy(final T... delegates); }
|
@Test public void serializeWithJDK() throws IOException, ClassNotFoundException { final FailsOnNthCall failover = Failover.proxy(FailsOnNthCall.class) .with(new FailsOnNthCallImpl(1), new FailsOnNthCallImpl(1)) .excepting(RuntimeException.class) .build(getFactory()); failover.doIt(); useSerializedProxy(serializeWithJDK(failover)); }
|
public static <T> FailoverWithOrExceptingOrBuild<T> proxy(Class<T> type) { return new FailoverWithOrExceptingOrBuild<T>(new Failover<T>(type)); }
|
Failover { public static <T> FailoverWithOrExceptingOrBuild<T> proxy(Class<T> type) { return new FailoverWithOrExceptingOrBuild<T>(new Failover<T>(type)); } }
|
Failover { public static <T> FailoverWithOrExceptingOrBuild<T> proxy(Class<T> type) { return new FailoverWithOrExceptingOrBuild<T>(new Failover<T>(type)); } private Failover(Class<T> primaryType, Class<?>... types); }
|
Failover { public static <T> FailoverWithOrExceptingOrBuild<T> proxy(Class<T> type) { return new FailoverWithOrExceptingOrBuild<T>(new Failover<T>(type)); } private Failover(Class<T> primaryType, Class<?>... types); static FailoverWithOrExceptingOrBuild<T> proxy(Class<T> type); static FailoverWithOrExceptingOrBuild<T> proxy(final Class<T> primaryType, final Class<?> ... types); static FailoverExceptingOrBuild<T> proxy(final T... delegates); }
|
Failover { public static <T> FailoverWithOrExceptingOrBuild<T> proxy(Class<T> type) { return new FailoverWithOrExceptingOrBuild<T>(new Failover<T>(type)); } private Failover(Class<T> primaryType, Class<?>... types); static FailoverWithOrExceptingOrBuild<T> proxy(Class<T> type); static FailoverWithOrExceptingOrBuild<T> proxy(final Class<T> primaryType, final Class<?> ... types); static FailoverExceptingOrBuild<T> proxy(final T... delegates); }
|
@Test public void serializeWithXStream() { final FailsOnNthCall failover = Failover.proxy(FailsOnNthCall.class) .with(new FailsOnNthCallImpl(1), new FailsOnNthCallImpl(1)) .excepting(RuntimeException.class) .build(getFactory()); failover.doIt(); useSerializedProxy(serializeWithXStream(failover)); }
|
public static <T> FailoverWithOrExceptingOrBuild<T> proxy(Class<T> type) { return new FailoverWithOrExceptingOrBuild<T>(new Failover<T>(type)); }
|
Failover { public static <T> FailoverWithOrExceptingOrBuild<T> proxy(Class<T> type) { return new FailoverWithOrExceptingOrBuild<T>(new Failover<T>(type)); } }
|
Failover { public static <T> FailoverWithOrExceptingOrBuild<T> proxy(Class<T> type) { return new FailoverWithOrExceptingOrBuild<T>(new Failover<T>(type)); } private Failover(Class<T> primaryType, Class<?>... types); }
|
Failover { public static <T> FailoverWithOrExceptingOrBuild<T> proxy(Class<T> type) { return new FailoverWithOrExceptingOrBuild<T>(new Failover<T>(type)); } private Failover(Class<T> primaryType, Class<?>... types); static FailoverWithOrExceptingOrBuild<T> proxy(Class<T> type); static FailoverWithOrExceptingOrBuild<T> proxy(final Class<T> primaryType, final Class<?> ... types); static FailoverExceptingOrBuild<T> proxy(final T... delegates); }
|
Failover { public static <T> FailoverWithOrExceptingOrBuild<T> proxy(Class<T> type) { return new FailoverWithOrExceptingOrBuild<T>(new Failover<T>(type)); } private Failover(Class<T> primaryType, Class<?>... types); static FailoverWithOrExceptingOrBuild<T> proxy(Class<T> type); static FailoverWithOrExceptingOrBuild<T> proxy(final Class<T> primaryType, final Class<?> ... types); static FailoverExceptingOrBuild<T> proxy(final T... delegates); }
|
@Test public void serializeWithXStreamInPureReflectionMode() { final FailsOnNthCall failover = Failover.proxy(FailsOnNthCall.class) .with(new FailsOnNthCallImpl(1), new FailsOnNthCallImpl(1)) .excepting(RuntimeException.class) .build(getFactory()); failover.doIt(); useSerializedProxy(serializeWithXStreamAndPureReflection(failover)); }
|
public static <T> FailoverWithOrExceptingOrBuild<T> proxy(Class<T> type) { return new FailoverWithOrExceptingOrBuild<T>(new Failover<T>(type)); }
|
Failover { public static <T> FailoverWithOrExceptingOrBuild<T> proxy(Class<T> type) { return new FailoverWithOrExceptingOrBuild<T>(new Failover<T>(type)); } }
|
Failover { public static <T> FailoverWithOrExceptingOrBuild<T> proxy(Class<T> type) { return new FailoverWithOrExceptingOrBuild<T>(new Failover<T>(type)); } private Failover(Class<T> primaryType, Class<?>... types); }
|
Failover { public static <T> FailoverWithOrExceptingOrBuild<T> proxy(Class<T> type) { return new FailoverWithOrExceptingOrBuild<T>(new Failover<T>(type)); } private Failover(Class<T> primaryType, Class<?>... types); static FailoverWithOrExceptingOrBuild<T> proxy(Class<T> type); static FailoverWithOrExceptingOrBuild<T> proxy(final Class<T> primaryType, final Class<?> ... types); static FailoverExceptingOrBuild<T> proxy(final T... delegates); }
|
Failover { public static <T> FailoverWithOrExceptingOrBuild<T> proxy(Class<T> type) { return new FailoverWithOrExceptingOrBuild<T>(new Failover<T>(type)); } private Failover(Class<T> primaryType, Class<?>... types); static FailoverWithOrExceptingOrBuild<T> proxy(Class<T> type); static FailoverWithOrExceptingOrBuild<T> proxy(final Class<T> primaryType, final Class<?> ... types); static FailoverExceptingOrBuild<T> proxy(final T... delegates); }
|
@Test public void shouldSupportIndirectRecursion() { Faculty fac = new Faculty() { public int calc(int i, Faculty fac) { return i == 1 ? 1 : i * fac.calc(i - 1, fac); } }; Faculty proxy = Delegating.proxy(Faculty.class).with(fac).build(getFactory()); assertEquals(120, fac.calc(5, fac)); assertEquals(120, proxy.calc(5, proxy)); }
|
public static <T> DelegatingWith<T> proxy(Class<T> type) { return new DelegatingWith<T>(new Delegating<T>(type)); }
|
Delegating { public static <T> DelegatingWith<T> proxy(Class<T> type) { return new DelegatingWith<T>(new Delegating<T>(type)); } }
|
Delegating { public static <T> DelegatingWith<T> proxy(Class<T> type) { return new DelegatingWith<T>(new Delegating<T>(type)); } private Delegating(Class<T> type); }
|
Delegating { public static <T> DelegatingWith<T> proxy(Class<T> type) { return new DelegatingWith<T>(new Delegating<T>(type)); } private Delegating(Class<T> type); static DelegatingWith<T> proxy(Class<T> type); }
|
Delegating { public static <T> DelegatingWith<T> proxy(Class<T> type) { return new DelegatingWith<T>(new Delegating<T>(type)); } private Delegating(Class<T> type); static DelegatingWith<T> proxy(Class<T> type); }
|
@Test public void serializeWithJDK() throws IOException, ClassNotFoundException { useSerializedProxy(serializeWithJDK( Decorating.proxy(CharSequence.class).with("Test").visiting(new AssertingDecorator()).build(getFactory()))); }
|
public static <T> DecoratingWith<T> proxy(final Class<T> type) { return new DecoratingWith<T>(new Decorating<T, T>((T)null, type)); }
|
Decorating { public static <T> DecoratingWith<T> proxy(final Class<T> type) { return new DecoratingWith<T>(new Decorating<T, T>((T)null, type)); } }
|
Decorating { public static <T> DecoratingWith<T> proxy(final Class<T> type) { return new DecoratingWith<T>(new Decorating<T, T>((T)null, type)); } private Decorating(final U delegate, final Class<T>primaryType, final Class<?>... types); }
|
Decorating { public static <T> DecoratingWith<T> proxy(final Class<T> type) { return new DecoratingWith<T>(new Decorating<T, T>((T)null, type)); } private Decorating(final U delegate, final Class<T>primaryType, final Class<?>... types); static DecoratingWith<T> proxy(final Class<T> type); static DecoratingWith<T> proxy(final Class<T> primaryType, final Class<?> ... types); static DecoratingVisitor<U, U> proxy(final U delegate); static DecoratingVisitor<U, T> proxy(final U delegate, final Class<T> type); static DecoratingVisitor<U, T> proxy(final U delegate, final Class<T> primaryType, final Class<?> ... types); }
|
Decorating { public static <T> DecoratingWith<T> proxy(final Class<T> type) { return new DecoratingWith<T>(new Decorating<T, T>((T)null, type)); } private Decorating(final U delegate, final Class<T>primaryType, final Class<?>... types); static DecoratingWith<T> proxy(final Class<T> type); static DecoratingWith<T> proxy(final Class<T> primaryType, final Class<?> ... types); static DecoratingVisitor<U, U> proxy(final U delegate); static DecoratingVisitor<U, T> proxy(final U delegate, final Class<T> type); static DecoratingVisitor<U, T> proxy(final U delegate, final Class<T> primaryType, final Class<?> ... types); }
|
@Test public void shouldEchoMethodNameAndArgs() throws Exception { Writer out = new StringWriter(); Simple foo = Echoing.proxy(Simple.class).to(new PrintWriter(out)).build(getFactory()); foo.doSomething(); assertContains("Simple.doSomething()", out); }
|
public static <T> EchoingWithOrTo<T> proxy(final Class<T> type) { return new EchoingWithOrTo<T>(new Echoing<T>(type)); }
|
Echoing { public static <T> EchoingWithOrTo<T> proxy(final Class<T> type) { return new EchoingWithOrTo<T>(new Echoing<T>(type)); } }
|
Echoing { public static <T> EchoingWithOrTo<T> proxy(final Class<T> type) { return new EchoingWithOrTo<T>(new Echoing<T>(type)); } private Echoing(final Class<T> type); }
|
Echoing { public static <T> EchoingWithOrTo<T> proxy(final Class<T> type) { return new EchoingWithOrTo<T>(new Echoing<T>(type)); } private Echoing(final Class<T> type); static EchoingWithOrTo<T> proxy(final Class<T> type); }
|
Echoing { public static <T> EchoingWithOrTo<T> proxy(final Class<T> type) { return new EchoingWithOrTo<T>(new Echoing<T>(type)); } private Echoing(final Class<T> type); static EchoingWithOrTo<T> proxy(final Class<T> type); }
|
@Test public void shouldDelegateCalls() throws Exception { Writer out = new StringWriter(); Simple foo = Echoing.proxy(Simple.class).with(simpleMock).to(new PrintWriter(out)).build(getFactory()); foo.doSomething(); verify(simpleMock).doSomething(); }
|
public static <T> EchoingWithOrTo<T> proxy(final Class<T> type) { return new EchoingWithOrTo<T>(new Echoing<T>(type)); }
|
Echoing { public static <T> EchoingWithOrTo<T> proxy(final Class<T> type) { return new EchoingWithOrTo<T>(new Echoing<T>(type)); } }
|
Echoing { public static <T> EchoingWithOrTo<T> proxy(final Class<T> type) { return new EchoingWithOrTo<T>(new Echoing<T>(type)); } private Echoing(final Class<T> type); }
|
Echoing { public static <T> EchoingWithOrTo<T> proxy(final Class<T> type) { return new EchoingWithOrTo<T>(new Echoing<T>(type)); } private Echoing(final Class<T> type); static EchoingWithOrTo<T> proxy(final Class<T> type); }
|
Echoing { public static <T> EchoingWithOrTo<T> proxy(final Class<T> type) { return new EchoingWithOrTo<T>(new Echoing<T>(type)); } private Echoing(final Class<T> type); static EchoingWithOrTo<T> proxy(final Class<T> type); }
|
@Test public void shouldRecursivelyReturnEchoProxiesForInterfaces() throws Exception { Inner innerMock = mock(Inner.class); Outer outerMock = mock(Outer.class); StringWriter out = new StringWriter(); Outer outer = Echoing.proxy(Outer.class).with(outerMock).to(new PrintWriter(out)).build(getFactory()); when(outerMock.getInner()).thenReturn(innerMock); when(innerMock.getName()).thenReturn("inner"); String result = outer.getInner().getName(); assertEquals("inner", result); assertContains("Outer.getInner()", out); assertContains("Inner.getName()", out); verify(outerMock).getInner(); verify(innerMock).getName(); }
|
public static <T> EchoingWithOrTo<T> proxy(final Class<T> type) { return new EchoingWithOrTo<T>(new Echoing<T>(type)); }
|
Echoing { public static <T> EchoingWithOrTo<T> proxy(final Class<T> type) { return new EchoingWithOrTo<T>(new Echoing<T>(type)); } }
|
Echoing { public static <T> EchoingWithOrTo<T> proxy(final Class<T> type) { return new EchoingWithOrTo<T>(new Echoing<T>(type)); } private Echoing(final Class<T> type); }
|
Echoing { public static <T> EchoingWithOrTo<T> proxy(final Class<T> type) { return new EchoingWithOrTo<T>(new Echoing<T>(type)); } private Echoing(final Class<T> type); static EchoingWithOrTo<T> proxy(final Class<T> type); }
|
Echoing { public static <T> EchoingWithOrTo<T> proxy(final Class<T> type) { return new EchoingWithOrTo<T>(new Echoing<T>(type)); } private Echoing(final Class<T> type); static EchoingWithOrTo<T> proxy(final Class<T> type); }
|
@Test public void shouldRecursivelyReturnEchoProxiesEvenForMissingImplementations() throws Exception { StringWriter out = new StringWriter(); Outer outer = Echoing.proxy(Outer.class).to(new PrintWriter(out)).build(getFactory()); outer.getInner().getName(); assertContains("Outer.getInner()", out); assertContains("Inner.getName()", out); }
|
public static <T> EchoingWithOrTo<T> proxy(final Class<T> type) { return new EchoingWithOrTo<T>(new Echoing<T>(type)); }
|
Echoing { public static <T> EchoingWithOrTo<T> proxy(final Class<T> type) { return new EchoingWithOrTo<T>(new Echoing<T>(type)); } }
|
Echoing { public static <T> EchoingWithOrTo<T> proxy(final Class<T> type) { return new EchoingWithOrTo<T>(new Echoing<T>(type)); } private Echoing(final Class<T> type); }
|
Echoing { public static <T> EchoingWithOrTo<T> proxy(final Class<T> type) { return new EchoingWithOrTo<T>(new Echoing<T>(type)); } private Echoing(final Class<T> type); static EchoingWithOrTo<T> proxy(final Class<T> type); }
|
Echoing { public static <T> EchoingWithOrTo<T> proxy(final Class<T> type) { return new EchoingWithOrTo<T>(new Echoing<T>(type)); } private Echoing(final Class<T> type); static EchoingWithOrTo<T> proxy(final Class<T> type); }
|
@Test public void shouldDenyProxyGenerationForFinalClasses() throws Exception { ProxyFactory factory = new CglibProxyFactory(); assertFalse(factory.canProxy(String.class)); }
|
public boolean canProxy(final Class<?> type) { return !Modifier.isFinal(type.getModifiers()); }
|
CglibProxyFactory extends AbstractProxyFactory { public boolean canProxy(final Class<?> type) { return !Modifier.isFinal(type.getModifiers()); } }
|
CglibProxyFactory extends AbstractProxyFactory { public boolean canProxy(final Class<?> type) { return !Modifier.isFinal(type.getModifiers()); } CglibProxyFactory(); CglibProxyFactory(boolean interceptDuringConstruction); }
|
CglibProxyFactory extends AbstractProxyFactory { public boolean canProxy(final Class<?> type) { return !Modifier.isFinal(type.getModifiers()); } CglibProxyFactory(); CglibProxyFactory(boolean interceptDuringConstruction); T createProxy(final Invoker invoker, final Class<?>... types); boolean canProxy(final Class<?> type); boolean isProxyClass(final Class<?> type); }
|
CglibProxyFactory extends AbstractProxyFactory { public boolean canProxy(final Class<?> type) { return !Modifier.isFinal(type.getModifiers()); } CglibProxyFactory(); CglibProxyFactory(boolean interceptDuringConstruction); T createProxy(final Invoker invoker, final Class<?>... types); boolean canProxy(final Class<?> type); boolean isProxyClass(final Class<?> type); }
|
@Test public void mostCommonSuperclassForClassesWithACommonBaseClass() { assertEquals(Writer.class, ReflectionUtils.getMostCommonSuperclass(new StringWriter(), new OutputStreamWriter(System.out))); assertEquals(Writer.class, ReflectionUtils.getMostCommonSuperclass(new OutputStreamWriter(System.out), new StringWriter())); }
|
public static Class<?> getMostCommonSuperclass(Object... objects) { Class<?> type = null; boolean found = false; if (objects != null && objects.length > 0) { while (!found) { for (Object object : objects) { found = true; if (object != null) { final Class<?> currenttype = object.getClass(); if (type == null) { type = currenttype; } if (!type.isAssignableFrom(currenttype)) { if (currenttype.isAssignableFrom(type)) { type = currenttype; } else { type = type.getSuperclass(); found = false; break; } } } } } } if (type == null) { type = Object.class; } return type; }
|
ReflectionUtils { public static Class<?> getMostCommonSuperclass(Object... objects) { Class<?> type = null; boolean found = false; if (objects != null && objects.length > 0) { while (!found) { for (Object object : objects) { found = true; if (object != null) { final Class<?> currenttype = object.getClass(); if (type == null) { type = currenttype; } if (!type.isAssignableFrom(currenttype)) { if (currenttype.isAssignableFrom(type)) { type = currenttype; } else { type = type.getSuperclass(); found = false; break; } } } } } } if (type == null) { type = Object.class; } return type; } }
|
ReflectionUtils { public static Class<?> getMostCommonSuperclass(Object... objects) { Class<?> type = null; boolean found = false; if (objects != null && objects.length > 0) { while (!found) { for (Object object : objects) { found = true; if (object != null) { final Class<?> currenttype = object.getClass(); if (type == null) { type = currenttype; } if (!type.isAssignableFrom(currenttype)) { if (currenttype.isAssignableFrom(type)) { type = currenttype; } else { type = type.getSuperclass(); found = false; break; } } } } } } if (type == null) { type = Object.class; } return type; } private ReflectionUtils(); }
|
ReflectionUtils { public static Class<?> getMostCommonSuperclass(Object... objects) { Class<?> type = null; boolean found = false; if (objects != null && objects.length > 0) { while (!found) { for (Object object : objects) { found = true; if (object != null) { final Class<?> currenttype = object.getClass(); if (type == null) { type = currenttype; } if (!type.isAssignableFrom(currenttype)) { if (currenttype.isAssignableFrom(type)) { type = currenttype; } else { type = type.getSuperclass(); found = false; break; } } } } } } if (type == null) { type = Object.class; } return type; } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); }
|
ReflectionUtils { public static Class<?> getMostCommonSuperclass(Object... objects) { Class<?> type = null; boolean found = false; if (objects != null && objects.length > 0) { while (!found) { for (Object object : objects) { found = true; if (object != null) { final Class<?> currenttype = object.getClass(); if (type == null) { type = currenttype; } if (!type.isAssignableFrom(currenttype)) { if (currenttype.isAssignableFrom(type)) { type = currenttype; } else { type = type.getSuperclass(); found = false; break; } } } } } } if (type == null) { type = Object.class; } return type; } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); static final Method equals; static final Method hashCode; static final Method toString; }
|
@Test public void mostCommonSuperclassForClassesAreInSameHierarchy() { assertEquals(OutputStreamWriter.class, ReflectionUtils.getMostCommonSuperclass(new FileWriter(FileDescriptor.out), new OutputStreamWriter(System.out))); assertEquals(OutputStreamWriter.class, ReflectionUtils.getMostCommonSuperclass(new OutputStreamWriter(System.out), new FileWriter(FileDescriptor.out))); }
|
public static Class<?> getMostCommonSuperclass(Object... objects) { Class<?> type = null; boolean found = false; if (objects != null && objects.length > 0) { while (!found) { for (Object object : objects) { found = true; if (object != null) { final Class<?> currenttype = object.getClass(); if (type == null) { type = currenttype; } if (!type.isAssignableFrom(currenttype)) { if (currenttype.isAssignableFrom(type)) { type = currenttype; } else { type = type.getSuperclass(); found = false; break; } } } } } } if (type == null) { type = Object.class; } return type; }
|
ReflectionUtils { public static Class<?> getMostCommonSuperclass(Object... objects) { Class<?> type = null; boolean found = false; if (objects != null && objects.length > 0) { while (!found) { for (Object object : objects) { found = true; if (object != null) { final Class<?> currenttype = object.getClass(); if (type == null) { type = currenttype; } if (!type.isAssignableFrom(currenttype)) { if (currenttype.isAssignableFrom(type)) { type = currenttype; } else { type = type.getSuperclass(); found = false; break; } } } } } } if (type == null) { type = Object.class; } return type; } }
|
ReflectionUtils { public static Class<?> getMostCommonSuperclass(Object... objects) { Class<?> type = null; boolean found = false; if (objects != null && objects.length > 0) { while (!found) { for (Object object : objects) { found = true; if (object != null) { final Class<?> currenttype = object.getClass(); if (type == null) { type = currenttype; } if (!type.isAssignableFrom(currenttype)) { if (currenttype.isAssignableFrom(type)) { type = currenttype; } else { type = type.getSuperclass(); found = false; break; } } } } } } if (type == null) { type = Object.class; } return type; } private ReflectionUtils(); }
|
ReflectionUtils { public static Class<?> getMostCommonSuperclass(Object... objects) { Class<?> type = null; boolean found = false; if (objects != null && objects.length > 0) { while (!found) { for (Object object : objects) { found = true; if (object != null) { final Class<?> currenttype = object.getClass(); if (type == null) { type = currenttype; } if (!type.isAssignableFrom(currenttype)) { if (currenttype.isAssignableFrom(type)) { type = currenttype; } else { type = type.getSuperclass(); found = false; break; } } } } } } if (type == null) { type = Object.class; } return type; } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); }
|
ReflectionUtils { public static Class<?> getMostCommonSuperclass(Object... objects) { Class<?> type = null; boolean found = false; if (objects != null && objects.length > 0) { while (!found) { for (Object object : objects) { found = true; if (object != null) { final Class<?> currenttype = object.getClass(); if (type == null) { type = currenttype; } if (!type.isAssignableFrom(currenttype)) { if (currenttype.isAssignableFrom(type)) { type = currenttype; } else { type = type.getSuperclass(); found = false; break; } } } } } } if (type == null) { type = Object.class; } return type; } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); static final Method equals; static final Method hashCode; static final Method toString; }
|
@Test public void mostCommonSuperclassForClassesInSameOrDifferentHierarchy() { assertEquals(Writer.class, ReflectionUtils.getMostCommonSuperclass(new FileWriter(FileDescriptor.out), new StringWriter(), new OutputStreamWriter(System.out))); assertEquals(Writer.class, ReflectionUtils.getMostCommonSuperclass(new FileWriter(FileDescriptor.out), new OutputStreamWriter(System.out), new StringWriter())); assertEquals(Writer.class, ReflectionUtils.getMostCommonSuperclass(new StringWriter(), new FileWriter(FileDescriptor.out), new OutputStreamWriter(System.out))); assertEquals(Writer.class, ReflectionUtils.getMostCommonSuperclass(new OutputStreamWriter(System.out), new FileWriter(FileDescriptor.out), new StringWriter())); assertEquals(Writer.class, ReflectionUtils.getMostCommonSuperclass(new StringWriter(), new OutputStreamWriter(System.out), new FileWriter(FileDescriptor.out))); assertEquals(Writer.class, ReflectionUtils.getMostCommonSuperclass(new OutputStreamWriter(System.out), new StringWriter(), new FileWriter(FileDescriptor.out))); }
|
public static Class<?> getMostCommonSuperclass(Object... objects) { Class<?> type = null; boolean found = false; if (objects != null && objects.length > 0) { while (!found) { for (Object object : objects) { found = true; if (object != null) { final Class<?> currenttype = object.getClass(); if (type == null) { type = currenttype; } if (!type.isAssignableFrom(currenttype)) { if (currenttype.isAssignableFrom(type)) { type = currenttype; } else { type = type.getSuperclass(); found = false; break; } } } } } } if (type == null) { type = Object.class; } return type; }
|
ReflectionUtils { public static Class<?> getMostCommonSuperclass(Object... objects) { Class<?> type = null; boolean found = false; if (objects != null && objects.length > 0) { while (!found) { for (Object object : objects) { found = true; if (object != null) { final Class<?> currenttype = object.getClass(); if (type == null) { type = currenttype; } if (!type.isAssignableFrom(currenttype)) { if (currenttype.isAssignableFrom(type)) { type = currenttype; } else { type = type.getSuperclass(); found = false; break; } } } } } } if (type == null) { type = Object.class; } return type; } }
|
ReflectionUtils { public static Class<?> getMostCommonSuperclass(Object... objects) { Class<?> type = null; boolean found = false; if (objects != null && objects.length > 0) { while (!found) { for (Object object : objects) { found = true; if (object != null) { final Class<?> currenttype = object.getClass(); if (type == null) { type = currenttype; } if (!type.isAssignableFrom(currenttype)) { if (currenttype.isAssignableFrom(type)) { type = currenttype; } else { type = type.getSuperclass(); found = false; break; } } } } } } if (type == null) { type = Object.class; } return type; } private ReflectionUtils(); }
|
ReflectionUtils { public static Class<?> getMostCommonSuperclass(Object... objects) { Class<?> type = null; boolean found = false; if (objects != null && objects.length > 0) { while (!found) { for (Object object : objects) { found = true; if (object != null) { final Class<?> currenttype = object.getClass(); if (type == null) { type = currenttype; } if (!type.isAssignableFrom(currenttype)) { if (currenttype.isAssignableFrom(type)) { type = currenttype; } else { type = type.getSuperclass(); found = false; break; } } } } } } if (type == null) { type = Object.class; } return type; } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); }
|
ReflectionUtils { public static Class<?> getMostCommonSuperclass(Object... objects) { Class<?> type = null; boolean found = false; if (objects != null && objects.length > 0) { while (!found) { for (Object object : objects) { found = true; if (object != null) { final Class<?> currenttype = object.getClass(); if (type == null) { type = currenttype; } if (!type.isAssignableFrom(currenttype)) { if (currenttype.isAssignableFrom(type)) { type = currenttype; } else { type = type.getSuperclass(); found = false; break; } } } } } } if (type == null) { type = Object.class; } return type; } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); static final Method equals; static final Method hashCode; static final Method toString; }
|
@Test public void mostCommonSuperclassForUnmatchingObjects() { assertEquals(Object.class, ReflectionUtils.getMostCommonSuperclass(1, new OutputStreamWriter(System.out))); assertEquals(Object.class, ReflectionUtils.getMostCommonSuperclass(new OutputStreamWriter(System.out), 1)); }
|
public static Class<?> getMostCommonSuperclass(Object... objects) { Class<?> type = null; boolean found = false; if (objects != null && objects.length > 0) { while (!found) { for (Object object : objects) { found = true; if (object != null) { final Class<?> currenttype = object.getClass(); if (type == null) { type = currenttype; } if (!type.isAssignableFrom(currenttype)) { if (currenttype.isAssignableFrom(type)) { type = currenttype; } else { type = type.getSuperclass(); found = false; break; } } } } } } if (type == null) { type = Object.class; } return type; }
|
ReflectionUtils { public static Class<?> getMostCommonSuperclass(Object... objects) { Class<?> type = null; boolean found = false; if (objects != null && objects.length > 0) { while (!found) { for (Object object : objects) { found = true; if (object != null) { final Class<?> currenttype = object.getClass(); if (type == null) { type = currenttype; } if (!type.isAssignableFrom(currenttype)) { if (currenttype.isAssignableFrom(type)) { type = currenttype; } else { type = type.getSuperclass(); found = false; break; } } } } } } if (type == null) { type = Object.class; } return type; } }
|
ReflectionUtils { public static Class<?> getMostCommonSuperclass(Object... objects) { Class<?> type = null; boolean found = false; if (objects != null && objects.length > 0) { while (!found) { for (Object object : objects) { found = true; if (object != null) { final Class<?> currenttype = object.getClass(); if (type == null) { type = currenttype; } if (!type.isAssignableFrom(currenttype)) { if (currenttype.isAssignableFrom(type)) { type = currenttype; } else { type = type.getSuperclass(); found = false; break; } } } } } } if (type == null) { type = Object.class; } return type; } private ReflectionUtils(); }
|
ReflectionUtils { public static Class<?> getMostCommonSuperclass(Object... objects) { Class<?> type = null; boolean found = false; if (objects != null && objects.length > 0) { while (!found) { for (Object object : objects) { found = true; if (object != null) { final Class<?> currenttype = object.getClass(); if (type == null) { type = currenttype; } if (!type.isAssignableFrom(currenttype)) { if (currenttype.isAssignableFrom(type)) { type = currenttype; } else { type = type.getSuperclass(); found = false; break; } } } } } } if (type == null) { type = Object.class; } return type; } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); }
|
ReflectionUtils { public static Class<?> getMostCommonSuperclass(Object... objects) { Class<?> type = null; boolean found = false; if (objects != null && objects.length > 0) { while (!found) { for (Object object : objects) { found = true; if (object != null) { final Class<?> currenttype = object.getClass(); if (type == null) { type = currenttype; } if (!type.isAssignableFrom(currenttype)) { if (currenttype.isAssignableFrom(type)) { type = currenttype; } else { type = type.getSuperclass(); found = false; break; } } } } } } if (type == null) { type = Object.class; } return type; } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); static final Method equals; static final Method hashCode; static final Method toString; }
|
@Test public void mostCommonSuperclassForEmptyArray() { assertEquals(Object.class, ReflectionUtils.getMostCommonSuperclass()); }
|
public static Class<?> getMostCommonSuperclass(Object... objects) { Class<?> type = null; boolean found = false; if (objects != null && objects.length > 0) { while (!found) { for (Object object : objects) { found = true; if (object != null) { final Class<?> currenttype = object.getClass(); if (type == null) { type = currenttype; } if (!type.isAssignableFrom(currenttype)) { if (currenttype.isAssignableFrom(type)) { type = currenttype; } else { type = type.getSuperclass(); found = false; break; } } } } } } if (type == null) { type = Object.class; } return type; }
|
ReflectionUtils { public static Class<?> getMostCommonSuperclass(Object... objects) { Class<?> type = null; boolean found = false; if (objects != null && objects.length > 0) { while (!found) { for (Object object : objects) { found = true; if (object != null) { final Class<?> currenttype = object.getClass(); if (type == null) { type = currenttype; } if (!type.isAssignableFrom(currenttype)) { if (currenttype.isAssignableFrom(type)) { type = currenttype; } else { type = type.getSuperclass(); found = false; break; } } } } } } if (type == null) { type = Object.class; } return type; } }
|
ReflectionUtils { public static Class<?> getMostCommonSuperclass(Object... objects) { Class<?> type = null; boolean found = false; if (objects != null && objects.length > 0) { while (!found) { for (Object object : objects) { found = true; if (object != null) { final Class<?> currenttype = object.getClass(); if (type == null) { type = currenttype; } if (!type.isAssignableFrom(currenttype)) { if (currenttype.isAssignableFrom(type)) { type = currenttype; } else { type = type.getSuperclass(); found = false; break; } } } } } } if (type == null) { type = Object.class; } return type; } private ReflectionUtils(); }
|
ReflectionUtils { public static Class<?> getMostCommonSuperclass(Object... objects) { Class<?> type = null; boolean found = false; if (objects != null && objects.length > 0) { while (!found) { for (Object object : objects) { found = true; if (object != null) { final Class<?> currenttype = object.getClass(); if (type == null) { type = currenttype; } if (!type.isAssignableFrom(currenttype)) { if (currenttype.isAssignableFrom(type)) { type = currenttype; } else { type = type.getSuperclass(); found = false; break; } } } } } } if (type == null) { type = Object.class; } return type; } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); }
|
ReflectionUtils { public static Class<?> getMostCommonSuperclass(Object... objects) { Class<?> type = null; boolean found = false; if (objects != null && objects.length > 0) { while (!found) { for (Object object : objects) { found = true; if (object != null) { final Class<?> currenttype = object.getClass(); if (type == null) { type = currenttype; } if (!type.isAssignableFrom(currenttype)) { if (currenttype.isAssignableFrom(type)) { type = currenttype; } else { type = type.getSuperclass(); found = false; break; } } } } } } if (type == null) { type = Object.class; } return type; } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); static final Method equals; static final Method hashCode; static final Method toString; }
|
@Test public void serializeWithXStream() { useSerializedProxy(serializeWithXStream( Decorating.proxy(CharSequence.class).with("Test").visiting(new AssertingDecorator()).build(getFactory()))); }
|
public static <T> DecoratingWith<T> proxy(final Class<T> type) { return new DecoratingWith<T>(new Decorating<T, T>((T)null, type)); }
|
Decorating { public static <T> DecoratingWith<T> proxy(final Class<T> type) { return new DecoratingWith<T>(new Decorating<T, T>((T)null, type)); } }
|
Decorating { public static <T> DecoratingWith<T> proxy(final Class<T> type) { return new DecoratingWith<T>(new Decorating<T, T>((T)null, type)); } private Decorating(final U delegate, final Class<T>primaryType, final Class<?>... types); }
|
Decorating { public static <T> DecoratingWith<T> proxy(final Class<T> type) { return new DecoratingWith<T>(new Decorating<T, T>((T)null, type)); } private Decorating(final U delegate, final Class<T>primaryType, final Class<?>... types); static DecoratingWith<T> proxy(final Class<T> type); static DecoratingWith<T> proxy(final Class<T> primaryType, final Class<?> ... types); static DecoratingVisitor<U, U> proxy(final U delegate); static DecoratingVisitor<U, T> proxy(final U delegate, final Class<T> type); static DecoratingVisitor<U, T> proxy(final U delegate, final Class<T> primaryType, final Class<?> ... types); }
|
Decorating { public static <T> DecoratingWith<T> proxy(final Class<T> type) { return new DecoratingWith<T>(new Decorating<T, T>((T)null, type)); } private Decorating(final U delegate, final Class<T>primaryType, final Class<?>... types); static DecoratingWith<T> proxy(final Class<T> type); static DecoratingWith<T> proxy(final Class<T> primaryType, final Class<?> ... types); static DecoratingVisitor<U, U> proxy(final U delegate); static DecoratingVisitor<U, T> proxy(final U delegate, final Class<T> type); static DecoratingVisitor<U, T> proxy(final U delegate, final Class<T> primaryType, final Class<?> ... types); }
|
@Test public void mostCommonSuperclassForNullElements() { assertEquals(Object.class, ReflectionUtils.getMostCommonSuperclass(null, null)); }
|
public static Class<?> getMostCommonSuperclass(Object... objects) { Class<?> type = null; boolean found = false; if (objects != null && objects.length > 0) { while (!found) { for (Object object : objects) { found = true; if (object != null) { final Class<?> currenttype = object.getClass(); if (type == null) { type = currenttype; } if (!type.isAssignableFrom(currenttype)) { if (currenttype.isAssignableFrom(type)) { type = currenttype; } else { type = type.getSuperclass(); found = false; break; } } } } } } if (type == null) { type = Object.class; } return type; }
|
ReflectionUtils { public static Class<?> getMostCommonSuperclass(Object... objects) { Class<?> type = null; boolean found = false; if (objects != null && objects.length > 0) { while (!found) { for (Object object : objects) { found = true; if (object != null) { final Class<?> currenttype = object.getClass(); if (type == null) { type = currenttype; } if (!type.isAssignableFrom(currenttype)) { if (currenttype.isAssignableFrom(type)) { type = currenttype; } else { type = type.getSuperclass(); found = false; break; } } } } } } if (type == null) { type = Object.class; } return type; } }
|
ReflectionUtils { public static Class<?> getMostCommonSuperclass(Object... objects) { Class<?> type = null; boolean found = false; if (objects != null && objects.length > 0) { while (!found) { for (Object object : objects) { found = true; if (object != null) { final Class<?> currenttype = object.getClass(); if (type == null) { type = currenttype; } if (!type.isAssignableFrom(currenttype)) { if (currenttype.isAssignableFrom(type)) { type = currenttype; } else { type = type.getSuperclass(); found = false; break; } } } } } } if (type == null) { type = Object.class; } return type; } private ReflectionUtils(); }
|
ReflectionUtils { public static Class<?> getMostCommonSuperclass(Object... objects) { Class<?> type = null; boolean found = false; if (objects != null && objects.length > 0) { while (!found) { for (Object object : objects) { found = true; if (object != null) { final Class<?> currenttype = object.getClass(); if (type == null) { type = currenttype; } if (!type.isAssignableFrom(currenttype)) { if (currenttype.isAssignableFrom(type)) { type = currenttype; } else { type = type.getSuperclass(); found = false; break; } } } } } } if (type == null) { type = Object.class; } return type; } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); }
|
ReflectionUtils { public static Class<?> getMostCommonSuperclass(Object... objects) { Class<?> type = null; boolean found = false; if (objects != null && objects.length > 0) { while (!found) { for (Object object : objects) { found = true; if (object != null) { final Class<?> currenttype = object.getClass(); if (type == null) { type = currenttype; } if (!type.isAssignableFrom(currenttype)) { if (currenttype.isAssignableFrom(type)) { type = currenttype; } else { type = type.getSuperclass(); found = false; break; } } } } } } if (type == null) { type = Object.class; } return type; } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); static final Method equals; static final Method hashCode; static final Method toString; }
|
@Test public void mostCommonSuperclassForCollections() { assertEquals(AbstractList.class, ReflectionUtils.getMostCommonSuperclass(new LinkedList<Object>(), new Vector<Object>())); }
|
public static Class<?> getMostCommonSuperclass(Object... objects) { Class<?> type = null; boolean found = false; if (objects != null && objects.length > 0) { while (!found) { for (Object object : objects) { found = true; if (object != null) { final Class<?> currenttype = object.getClass(); if (type == null) { type = currenttype; } if (!type.isAssignableFrom(currenttype)) { if (currenttype.isAssignableFrom(type)) { type = currenttype; } else { type = type.getSuperclass(); found = false; break; } } } } } } if (type == null) { type = Object.class; } return type; }
|
ReflectionUtils { public static Class<?> getMostCommonSuperclass(Object... objects) { Class<?> type = null; boolean found = false; if (objects != null && objects.length > 0) { while (!found) { for (Object object : objects) { found = true; if (object != null) { final Class<?> currenttype = object.getClass(); if (type == null) { type = currenttype; } if (!type.isAssignableFrom(currenttype)) { if (currenttype.isAssignableFrom(type)) { type = currenttype; } else { type = type.getSuperclass(); found = false; break; } } } } } } if (type == null) { type = Object.class; } return type; } }
|
ReflectionUtils { public static Class<?> getMostCommonSuperclass(Object... objects) { Class<?> type = null; boolean found = false; if (objects != null && objects.length > 0) { while (!found) { for (Object object : objects) { found = true; if (object != null) { final Class<?> currenttype = object.getClass(); if (type == null) { type = currenttype; } if (!type.isAssignableFrom(currenttype)) { if (currenttype.isAssignableFrom(type)) { type = currenttype; } else { type = type.getSuperclass(); found = false; break; } } } } } } if (type == null) { type = Object.class; } return type; } private ReflectionUtils(); }
|
ReflectionUtils { public static Class<?> getMostCommonSuperclass(Object... objects) { Class<?> type = null; boolean found = false; if (objects != null && objects.length > 0) { while (!found) { for (Object object : objects) { found = true; if (object != null) { final Class<?> currenttype = object.getClass(); if (type == null) { type = currenttype; } if (!type.isAssignableFrom(currenttype)) { if (currenttype.isAssignableFrom(type)) { type = currenttype; } else { type = type.getSuperclass(); found = false; break; } } } } } } if (type == null) { type = Object.class; } return type; } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); }
|
ReflectionUtils { public static Class<?> getMostCommonSuperclass(Object... objects) { Class<?> type = null; boolean found = false; if (objects != null && objects.length > 0) { while (!found) { for (Object object : objects) { found = true; if (object != null) { final Class<?> currenttype = object.getClass(); if (type == null) { type = currenttype; } if (!type.isAssignableFrom(currenttype)) { if (currenttype.isAssignableFrom(type)) { type = currenttype; } else { type = type.getSuperclass(); found = false; break; } } } } } } if (type == null) { type = Object.class; } return type; } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); static final Method equals; static final Method hashCode; static final Method toString; }
|
@Test public void allInterfacesOfListShouldBeFound() { Set<Class<?>> interfaces = ReflectionUtils.getAllInterfaces(BeanContextServices.class); assertTrue(interfaces.contains(BeanContextServices.class)); assertTrue(interfaces.contains(BeanContext.class)); assertTrue(interfaces.contains(Collection.class)); assertTrue(interfaces.contains(BeanContextServicesListener.class)); assertTrue(interfaces.contains(EventListener.class)); }
|
public static Set<Class<?>> getAllInterfaces(Object... objects) { final Set<Class<?>> interfaces = new HashSet<Class<?>>(); for (Object object : objects) { if (object != null) { getInterfaces(object.getClass(), interfaces); } } interfaces.remove(InvokerReference.class); return interfaces; }
|
ReflectionUtils { public static Set<Class<?>> getAllInterfaces(Object... objects) { final Set<Class<?>> interfaces = new HashSet<Class<?>>(); for (Object object : objects) { if (object != null) { getInterfaces(object.getClass(), interfaces); } } interfaces.remove(InvokerReference.class); return interfaces; } }
|
ReflectionUtils { public static Set<Class<?>> getAllInterfaces(Object... objects) { final Set<Class<?>> interfaces = new HashSet<Class<?>>(); for (Object object : objects) { if (object != null) { getInterfaces(object.getClass(), interfaces); } } interfaces.remove(InvokerReference.class); return interfaces; } private ReflectionUtils(); }
|
ReflectionUtils { public static Set<Class<?>> getAllInterfaces(Object... objects) { final Set<Class<?>> interfaces = new HashSet<Class<?>>(); for (Object object : objects) { if (object != null) { getInterfaces(object.getClass(), interfaces); } } interfaces.remove(InvokerReference.class); return interfaces; } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); }
|
ReflectionUtils { public static Set<Class<?>> getAllInterfaces(Object... objects) { final Set<Class<?>> interfaces = new HashSet<Class<?>>(); for (Object object : objects) { if (object != null) { getInterfaces(object.getClass(), interfaces); } } interfaces.remove(InvokerReference.class); return interfaces; } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); static final Method equals; static final Method hashCode; static final Method toString; }
|
@Test public void matchingMethodIsFound() throws Exception { Method appendChar = ReflectionUtils.getMatchingMethod(StringBuffer.class, "append", new Object[]{'c'}); Method appendCharArray = ReflectionUtils.getMatchingMethod( StringBuffer.class, "append", new Object[]{new char[]{'c'}}); Method appendShort = ReflectionUtils.getMatchingMethod(StringBuffer.class, "append", new Object[]{(short) 0}); Method appendObject = ReflectionUtils.getMatchingMethod(StringBuffer.class, "append", new Object[]{this}); Method appendObject2 = ReflectionUtils.getMatchingMethod( StringBuffer.class, "append", new Object[]{new Exception()}); assertNotNull(appendChar); assertNotNull(appendCharArray); assertNotNull(appendShort); assertNotNull(appendObject); assertNotNull(appendObject2); assertNotSame(appendChar, appendCharArray); assertNotSame(appendObject, appendChar); assertNotSame(appendObject, appendCharArray); assertNotSame(appendObject, appendShort); assertTrue(appendObject.equals(appendObject2)); }
|
public static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args) throws NoSuchMethodException { final Object[] newArgs = args == null ? new Object[0] : args; final Method[] methods = type.getMethods(); final Set<Method> possibleMethods = new HashSet<Method>(); Method method = null; for (int i = 0; method == null && i < methods.length; i++) { if (methodName.equals(methods[i].getName())) { final Class<?>[] argTypes = methods[i].getParameterTypes(); if (argTypes.length == newArgs.length) { boolean exact = true; Method possibleMethod = methods[i]; for (int j = 0; possibleMethod != null && j < argTypes.length; j++) { final Class<?> newArgType = newArgs[j] != null ? newArgs[j].getClass() : Object.class; if ((argTypes[j].equals(byte.class) && newArgType.equals(Byte.class)) || (argTypes[j].equals(char.class) && newArgType.equals(Character.class)) || (argTypes[j].equals(short.class) && newArgType.equals(Short.class)) || (argTypes[j].equals(int.class) && newArgType.equals(Integer.class)) || (argTypes[j].equals(long.class) && newArgType.equals(Long.class)) || (argTypes[j].equals(float.class) && newArgType.equals(Float.class)) || (argTypes[j].equals(double.class) && newArgType.equals(Double.class)) || (argTypes[j].equals(boolean.class) && newArgType.equals(Boolean.class))) { exact = true; } else if (!argTypes[j].isAssignableFrom(newArgType)) { possibleMethod = null; exact = false; } else if (!argTypes[j].isPrimitive()) { if (!argTypes[j].equals(newArgType)) { exact = false; } } } if (exact) { method = possibleMethod; } else if (possibleMethod != null) { possibleMethods.add(possibleMethod); } } } } if (method == null && possibleMethods.size() > 0) { method = possibleMethods.iterator().next(); } if (method == null) { final StringBuilder name = new StringBuilder(type.getName()); name.append('.'); name.append(methodName); name.append('('); for (int i = 0; i < newArgs.length; i++) { if (i != 0) { name.append(", "); } name.append(newArgs[i].getClass().getName()); } name.append(')'); throw new NoSuchMethodException(name.toString()); } return method; }
|
ReflectionUtils { public static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args) throws NoSuchMethodException { final Object[] newArgs = args == null ? new Object[0] : args; final Method[] methods = type.getMethods(); final Set<Method> possibleMethods = new HashSet<Method>(); Method method = null; for (int i = 0; method == null && i < methods.length; i++) { if (methodName.equals(methods[i].getName())) { final Class<?>[] argTypes = methods[i].getParameterTypes(); if (argTypes.length == newArgs.length) { boolean exact = true; Method possibleMethod = methods[i]; for (int j = 0; possibleMethod != null && j < argTypes.length; j++) { final Class<?> newArgType = newArgs[j] != null ? newArgs[j].getClass() : Object.class; if ((argTypes[j].equals(byte.class) && newArgType.equals(Byte.class)) || (argTypes[j].equals(char.class) && newArgType.equals(Character.class)) || (argTypes[j].equals(short.class) && newArgType.equals(Short.class)) || (argTypes[j].equals(int.class) && newArgType.equals(Integer.class)) || (argTypes[j].equals(long.class) && newArgType.equals(Long.class)) || (argTypes[j].equals(float.class) && newArgType.equals(Float.class)) || (argTypes[j].equals(double.class) && newArgType.equals(Double.class)) || (argTypes[j].equals(boolean.class) && newArgType.equals(Boolean.class))) { exact = true; } else if (!argTypes[j].isAssignableFrom(newArgType)) { possibleMethod = null; exact = false; } else if (!argTypes[j].isPrimitive()) { if (!argTypes[j].equals(newArgType)) { exact = false; } } } if (exact) { method = possibleMethod; } else if (possibleMethod != null) { possibleMethods.add(possibleMethod); } } } } if (method == null && possibleMethods.size() > 0) { method = possibleMethods.iterator().next(); } if (method == null) { final StringBuilder name = new StringBuilder(type.getName()); name.append('.'); name.append(methodName); name.append('('); for (int i = 0; i < newArgs.length; i++) { if (i != 0) { name.append(", "); } name.append(newArgs[i].getClass().getName()); } name.append(')'); throw new NoSuchMethodException(name.toString()); } return method; } }
|
ReflectionUtils { public static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args) throws NoSuchMethodException { final Object[] newArgs = args == null ? new Object[0] : args; final Method[] methods = type.getMethods(); final Set<Method> possibleMethods = new HashSet<Method>(); Method method = null; for (int i = 0; method == null && i < methods.length; i++) { if (methodName.equals(methods[i].getName())) { final Class<?>[] argTypes = methods[i].getParameterTypes(); if (argTypes.length == newArgs.length) { boolean exact = true; Method possibleMethod = methods[i]; for (int j = 0; possibleMethod != null && j < argTypes.length; j++) { final Class<?> newArgType = newArgs[j] != null ? newArgs[j].getClass() : Object.class; if ((argTypes[j].equals(byte.class) && newArgType.equals(Byte.class)) || (argTypes[j].equals(char.class) && newArgType.equals(Character.class)) || (argTypes[j].equals(short.class) && newArgType.equals(Short.class)) || (argTypes[j].equals(int.class) && newArgType.equals(Integer.class)) || (argTypes[j].equals(long.class) && newArgType.equals(Long.class)) || (argTypes[j].equals(float.class) && newArgType.equals(Float.class)) || (argTypes[j].equals(double.class) && newArgType.equals(Double.class)) || (argTypes[j].equals(boolean.class) && newArgType.equals(Boolean.class))) { exact = true; } else if (!argTypes[j].isAssignableFrom(newArgType)) { possibleMethod = null; exact = false; } else if (!argTypes[j].isPrimitive()) { if (!argTypes[j].equals(newArgType)) { exact = false; } } } if (exact) { method = possibleMethod; } else if (possibleMethod != null) { possibleMethods.add(possibleMethod); } } } } if (method == null && possibleMethods.size() > 0) { method = possibleMethods.iterator().next(); } if (method == null) { final StringBuilder name = new StringBuilder(type.getName()); name.append('.'); name.append(methodName); name.append('('); for (int i = 0; i < newArgs.length; i++) { if (i != 0) { name.append(", "); } name.append(newArgs[i].getClass().getName()); } name.append(')'); throw new NoSuchMethodException(name.toString()); } return method; } private ReflectionUtils(); }
|
ReflectionUtils { public static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args) throws NoSuchMethodException { final Object[] newArgs = args == null ? new Object[0] : args; final Method[] methods = type.getMethods(); final Set<Method> possibleMethods = new HashSet<Method>(); Method method = null; for (int i = 0; method == null && i < methods.length; i++) { if (methodName.equals(methods[i].getName())) { final Class<?>[] argTypes = methods[i].getParameterTypes(); if (argTypes.length == newArgs.length) { boolean exact = true; Method possibleMethod = methods[i]; for (int j = 0; possibleMethod != null && j < argTypes.length; j++) { final Class<?> newArgType = newArgs[j] != null ? newArgs[j].getClass() : Object.class; if ((argTypes[j].equals(byte.class) && newArgType.equals(Byte.class)) || (argTypes[j].equals(char.class) && newArgType.equals(Character.class)) || (argTypes[j].equals(short.class) && newArgType.equals(Short.class)) || (argTypes[j].equals(int.class) && newArgType.equals(Integer.class)) || (argTypes[j].equals(long.class) && newArgType.equals(Long.class)) || (argTypes[j].equals(float.class) && newArgType.equals(Float.class)) || (argTypes[j].equals(double.class) && newArgType.equals(Double.class)) || (argTypes[j].equals(boolean.class) && newArgType.equals(Boolean.class))) { exact = true; } else if (!argTypes[j].isAssignableFrom(newArgType)) { possibleMethod = null; exact = false; } else if (!argTypes[j].isPrimitive()) { if (!argTypes[j].equals(newArgType)) { exact = false; } } } if (exact) { method = possibleMethod; } else if (possibleMethod != null) { possibleMethods.add(possibleMethod); } } } } if (method == null && possibleMethods.size() > 0) { method = possibleMethods.iterator().next(); } if (method == null) { final StringBuilder name = new StringBuilder(type.getName()); name.append('.'); name.append(methodName); name.append('('); for (int i = 0; i < newArgs.length; i++) { if (i != 0) { name.append(", "); } name.append(newArgs[i].getClass().getName()); } name.append(')'); throw new NoSuchMethodException(name.toString()); } return method; } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); }
|
ReflectionUtils { public static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args) throws NoSuchMethodException { final Object[] newArgs = args == null ? new Object[0] : args; final Method[] methods = type.getMethods(); final Set<Method> possibleMethods = new HashSet<Method>(); Method method = null; for (int i = 0; method == null && i < methods.length; i++) { if (methodName.equals(methods[i].getName())) { final Class<?>[] argTypes = methods[i].getParameterTypes(); if (argTypes.length == newArgs.length) { boolean exact = true; Method possibleMethod = methods[i]; for (int j = 0; possibleMethod != null && j < argTypes.length; j++) { final Class<?> newArgType = newArgs[j] != null ? newArgs[j].getClass() : Object.class; if ((argTypes[j].equals(byte.class) && newArgType.equals(Byte.class)) || (argTypes[j].equals(char.class) && newArgType.equals(Character.class)) || (argTypes[j].equals(short.class) && newArgType.equals(Short.class)) || (argTypes[j].equals(int.class) && newArgType.equals(Integer.class)) || (argTypes[j].equals(long.class) && newArgType.equals(Long.class)) || (argTypes[j].equals(float.class) && newArgType.equals(Float.class)) || (argTypes[j].equals(double.class) && newArgType.equals(Double.class)) || (argTypes[j].equals(boolean.class) && newArgType.equals(Boolean.class))) { exact = true; } else if (!argTypes[j].isAssignableFrom(newArgType)) { possibleMethod = null; exact = false; } else if (!argTypes[j].isPrimitive()) { if (!argTypes[j].equals(newArgType)) { exact = false; } } } if (exact) { method = possibleMethod; } else if (possibleMethod != null) { possibleMethods.add(possibleMethod); } } } } if (method == null && possibleMethods.size() > 0) { method = possibleMethods.iterator().next(); } if (method == null) { final StringBuilder name = new StringBuilder(type.getName()); name.append('.'); name.append(methodName); name.append('('); for (int i = 0; i < newArgs.length; i++) { if (i != 0) { name.append(", "); } name.append(newArgs[i].getClass().getName()); } name.append(')'); throw new NoSuchMethodException(name.toString()); } return method; } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); static final Method equals; static final Method hashCode; static final Method toString; }
|
@Test public void matchingMethodArgumentCanBeNull() throws Exception { Method appendObject = ReflectionUtils.getMatchingMethod(StringBuffer.class, "append", new Object[]{null}); assertNotNull(appendObject); }
|
public static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args) throws NoSuchMethodException { final Object[] newArgs = args == null ? new Object[0] : args; final Method[] methods = type.getMethods(); final Set<Method> possibleMethods = new HashSet<Method>(); Method method = null; for (int i = 0; method == null && i < methods.length; i++) { if (methodName.equals(methods[i].getName())) { final Class<?>[] argTypes = methods[i].getParameterTypes(); if (argTypes.length == newArgs.length) { boolean exact = true; Method possibleMethod = methods[i]; for (int j = 0; possibleMethod != null && j < argTypes.length; j++) { final Class<?> newArgType = newArgs[j] != null ? newArgs[j].getClass() : Object.class; if ((argTypes[j].equals(byte.class) && newArgType.equals(Byte.class)) || (argTypes[j].equals(char.class) && newArgType.equals(Character.class)) || (argTypes[j].equals(short.class) && newArgType.equals(Short.class)) || (argTypes[j].equals(int.class) && newArgType.equals(Integer.class)) || (argTypes[j].equals(long.class) && newArgType.equals(Long.class)) || (argTypes[j].equals(float.class) && newArgType.equals(Float.class)) || (argTypes[j].equals(double.class) && newArgType.equals(Double.class)) || (argTypes[j].equals(boolean.class) && newArgType.equals(Boolean.class))) { exact = true; } else if (!argTypes[j].isAssignableFrom(newArgType)) { possibleMethod = null; exact = false; } else if (!argTypes[j].isPrimitive()) { if (!argTypes[j].equals(newArgType)) { exact = false; } } } if (exact) { method = possibleMethod; } else if (possibleMethod != null) { possibleMethods.add(possibleMethod); } } } } if (method == null && possibleMethods.size() > 0) { method = possibleMethods.iterator().next(); } if (method == null) { final StringBuilder name = new StringBuilder(type.getName()); name.append('.'); name.append(methodName); name.append('('); for (int i = 0; i < newArgs.length; i++) { if (i != 0) { name.append(", "); } name.append(newArgs[i].getClass().getName()); } name.append(')'); throw new NoSuchMethodException(name.toString()); } return method; }
|
ReflectionUtils { public static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args) throws NoSuchMethodException { final Object[] newArgs = args == null ? new Object[0] : args; final Method[] methods = type.getMethods(); final Set<Method> possibleMethods = new HashSet<Method>(); Method method = null; for (int i = 0; method == null && i < methods.length; i++) { if (methodName.equals(methods[i].getName())) { final Class<?>[] argTypes = methods[i].getParameterTypes(); if (argTypes.length == newArgs.length) { boolean exact = true; Method possibleMethod = methods[i]; for (int j = 0; possibleMethod != null && j < argTypes.length; j++) { final Class<?> newArgType = newArgs[j] != null ? newArgs[j].getClass() : Object.class; if ((argTypes[j].equals(byte.class) && newArgType.equals(Byte.class)) || (argTypes[j].equals(char.class) && newArgType.equals(Character.class)) || (argTypes[j].equals(short.class) && newArgType.equals(Short.class)) || (argTypes[j].equals(int.class) && newArgType.equals(Integer.class)) || (argTypes[j].equals(long.class) && newArgType.equals(Long.class)) || (argTypes[j].equals(float.class) && newArgType.equals(Float.class)) || (argTypes[j].equals(double.class) && newArgType.equals(Double.class)) || (argTypes[j].equals(boolean.class) && newArgType.equals(Boolean.class))) { exact = true; } else if (!argTypes[j].isAssignableFrom(newArgType)) { possibleMethod = null; exact = false; } else if (!argTypes[j].isPrimitive()) { if (!argTypes[j].equals(newArgType)) { exact = false; } } } if (exact) { method = possibleMethod; } else if (possibleMethod != null) { possibleMethods.add(possibleMethod); } } } } if (method == null && possibleMethods.size() > 0) { method = possibleMethods.iterator().next(); } if (method == null) { final StringBuilder name = new StringBuilder(type.getName()); name.append('.'); name.append(methodName); name.append('('); for (int i = 0; i < newArgs.length; i++) { if (i != 0) { name.append(", "); } name.append(newArgs[i].getClass().getName()); } name.append(')'); throw new NoSuchMethodException(name.toString()); } return method; } }
|
ReflectionUtils { public static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args) throws NoSuchMethodException { final Object[] newArgs = args == null ? new Object[0] : args; final Method[] methods = type.getMethods(); final Set<Method> possibleMethods = new HashSet<Method>(); Method method = null; for (int i = 0; method == null && i < methods.length; i++) { if (methodName.equals(methods[i].getName())) { final Class<?>[] argTypes = methods[i].getParameterTypes(); if (argTypes.length == newArgs.length) { boolean exact = true; Method possibleMethod = methods[i]; for (int j = 0; possibleMethod != null && j < argTypes.length; j++) { final Class<?> newArgType = newArgs[j] != null ? newArgs[j].getClass() : Object.class; if ((argTypes[j].equals(byte.class) && newArgType.equals(Byte.class)) || (argTypes[j].equals(char.class) && newArgType.equals(Character.class)) || (argTypes[j].equals(short.class) && newArgType.equals(Short.class)) || (argTypes[j].equals(int.class) && newArgType.equals(Integer.class)) || (argTypes[j].equals(long.class) && newArgType.equals(Long.class)) || (argTypes[j].equals(float.class) && newArgType.equals(Float.class)) || (argTypes[j].equals(double.class) && newArgType.equals(Double.class)) || (argTypes[j].equals(boolean.class) && newArgType.equals(Boolean.class))) { exact = true; } else if (!argTypes[j].isAssignableFrom(newArgType)) { possibleMethod = null; exact = false; } else if (!argTypes[j].isPrimitive()) { if (!argTypes[j].equals(newArgType)) { exact = false; } } } if (exact) { method = possibleMethod; } else if (possibleMethod != null) { possibleMethods.add(possibleMethod); } } } } if (method == null && possibleMethods.size() > 0) { method = possibleMethods.iterator().next(); } if (method == null) { final StringBuilder name = new StringBuilder(type.getName()); name.append('.'); name.append(methodName); name.append('('); for (int i = 0; i < newArgs.length; i++) { if (i != 0) { name.append(", "); } name.append(newArgs[i].getClass().getName()); } name.append(')'); throw new NoSuchMethodException(name.toString()); } return method; } private ReflectionUtils(); }
|
ReflectionUtils { public static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args) throws NoSuchMethodException { final Object[] newArgs = args == null ? new Object[0] : args; final Method[] methods = type.getMethods(); final Set<Method> possibleMethods = new HashSet<Method>(); Method method = null; for (int i = 0; method == null && i < methods.length; i++) { if (methodName.equals(methods[i].getName())) { final Class<?>[] argTypes = methods[i].getParameterTypes(); if (argTypes.length == newArgs.length) { boolean exact = true; Method possibleMethod = methods[i]; for (int j = 0; possibleMethod != null && j < argTypes.length; j++) { final Class<?> newArgType = newArgs[j] != null ? newArgs[j].getClass() : Object.class; if ((argTypes[j].equals(byte.class) && newArgType.equals(Byte.class)) || (argTypes[j].equals(char.class) && newArgType.equals(Character.class)) || (argTypes[j].equals(short.class) && newArgType.equals(Short.class)) || (argTypes[j].equals(int.class) && newArgType.equals(Integer.class)) || (argTypes[j].equals(long.class) && newArgType.equals(Long.class)) || (argTypes[j].equals(float.class) && newArgType.equals(Float.class)) || (argTypes[j].equals(double.class) && newArgType.equals(Double.class)) || (argTypes[j].equals(boolean.class) && newArgType.equals(Boolean.class))) { exact = true; } else if (!argTypes[j].isAssignableFrom(newArgType)) { possibleMethod = null; exact = false; } else if (!argTypes[j].isPrimitive()) { if (!argTypes[j].equals(newArgType)) { exact = false; } } } if (exact) { method = possibleMethod; } else if (possibleMethod != null) { possibleMethods.add(possibleMethod); } } } } if (method == null && possibleMethods.size() > 0) { method = possibleMethods.iterator().next(); } if (method == null) { final StringBuilder name = new StringBuilder(type.getName()); name.append('.'); name.append(methodName); name.append('('); for (int i = 0; i < newArgs.length; i++) { if (i != 0) { name.append(", "); } name.append(newArgs[i].getClass().getName()); } name.append(')'); throw new NoSuchMethodException(name.toString()); } return method; } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); }
|
ReflectionUtils { public static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args) throws NoSuchMethodException { final Object[] newArgs = args == null ? new Object[0] : args; final Method[] methods = type.getMethods(); final Set<Method> possibleMethods = new HashSet<Method>(); Method method = null; for (int i = 0; method == null && i < methods.length; i++) { if (methodName.equals(methods[i].getName())) { final Class<?>[] argTypes = methods[i].getParameterTypes(); if (argTypes.length == newArgs.length) { boolean exact = true; Method possibleMethod = methods[i]; for (int j = 0; possibleMethod != null && j < argTypes.length; j++) { final Class<?> newArgType = newArgs[j] != null ? newArgs[j].getClass() : Object.class; if ((argTypes[j].equals(byte.class) && newArgType.equals(Byte.class)) || (argTypes[j].equals(char.class) && newArgType.equals(Character.class)) || (argTypes[j].equals(short.class) && newArgType.equals(Short.class)) || (argTypes[j].equals(int.class) && newArgType.equals(Integer.class)) || (argTypes[j].equals(long.class) && newArgType.equals(Long.class)) || (argTypes[j].equals(float.class) && newArgType.equals(Float.class)) || (argTypes[j].equals(double.class) && newArgType.equals(Double.class)) || (argTypes[j].equals(boolean.class) && newArgType.equals(Boolean.class))) { exact = true; } else if (!argTypes[j].isAssignableFrom(newArgType)) { possibleMethod = null; exact = false; } else if (!argTypes[j].isPrimitive()) { if (!argTypes[j].equals(newArgType)) { exact = false; } } } if (exact) { method = possibleMethod; } else if (possibleMethod != null) { possibleMethods.add(possibleMethod); } } } } if (method == null && possibleMethods.size() > 0) { method = possibleMethods.iterator().next(); } if (method == null) { final StringBuilder name = new StringBuilder(type.getName()); name.append('.'); name.append(methodName); name.append('('); for (int i = 0; i < newArgs.length; i++) { if (i != 0) { name.append(", "); } name.append(newArgs[i].getClass().getName()); } name.append(')'); throw new NoSuchMethodException(name.toString()); } return method; } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); static final Method equals; static final Method hashCode; static final Method toString; }
|
@Test public void matchingMethodArgumentsCanBeNull() throws Exception { Method method = ReflectionUtils.getMatchingMethod(StringBuffer.class, "toString", null); assertNotNull(method); }
|
public static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args) throws NoSuchMethodException { final Object[] newArgs = args == null ? new Object[0] : args; final Method[] methods = type.getMethods(); final Set<Method> possibleMethods = new HashSet<Method>(); Method method = null; for (int i = 0; method == null && i < methods.length; i++) { if (methodName.equals(methods[i].getName())) { final Class<?>[] argTypes = methods[i].getParameterTypes(); if (argTypes.length == newArgs.length) { boolean exact = true; Method possibleMethod = methods[i]; for (int j = 0; possibleMethod != null && j < argTypes.length; j++) { final Class<?> newArgType = newArgs[j] != null ? newArgs[j].getClass() : Object.class; if ((argTypes[j].equals(byte.class) && newArgType.equals(Byte.class)) || (argTypes[j].equals(char.class) && newArgType.equals(Character.class)) || (argTypes[j].equals(short.class) && newArgType.equals(Short.class)) || (argTypes[j].equals(int.class) && newArgType.equals(Integer.class)) || (argTypes[j].equals(long.class) && newArgType.equals(Long.class)) || (argTypes[j].equals(float.class) && newArgType.equals(Float.class)) || (argTypes[j].equals(double.class) && newArgType.equals(Double.class)) || (argTypes[j].equals(boolean.class) && newArgType.equals(Boolean.class))) { exact = true; } else if (!argTypes[j].isAssignableFrom(newArgType)) { possibleMethod = null; exact = false; } else if (!argTypes[j].isPrimitive()) { if (!argTypes[j].equals(newArgType)) { exact = false; } } } if (exact) { method = possibleMethod; } else if (possibleMethod != null) { possibleMethods.add(possibleMethod); } } } } if (method == null && possibleMethods.size() > 0) { method = possibleMethods.iterator().next(); } if (method == null) { final StringBuilder name = new StringBuilder(type.getName()); name.append('.'); name.append(methodName); name.append('('); for (int i = 0; i < newArgs.length; i++) { if (i != 0) { name.append(", "); } name.append(newArgs[i].getClass().getName()); } name.append(')'); throw new NoSuchMethodException(name.toString()); } return method; }
|
ReflectionUtils { public static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args) throws NoSuchMethodException { final Object[] newArgs = args == null ? new Object[0] : args; final Method[] methods = type.getMethods(); final Set<Method> possibleMethods = new HashSet<Method>(); Method method = null; for (int i = 0; method == null && i < methods.length; i++) { if (methodName.equals(methods[i].getName())) { final Class<?>[] argTypes = methods[i].getParameterTypes(); if (argTypes.length == newArgs.length) { boolean exact = true; Method possibleMethod = methods[i]; for (int j = 0; possibleMethod != null && j < argTypes.length; j++) { final Class<?> newArgType = newArgs[j] != null ? newArgs[j].getClass() : Object.class; if ((argTypes[j].equals(byte.class) && newArgType.equals(Byte.class)) || (argTypes[j].equals(char.class) && newArgType.equals(Character.class)) || (argTypes[j].equals(short.class) && newArgType.equals(Short.class)) || (argTypes[j].equals(int.class) && newArgType.equals(Integer.class)) || (argTypes[j].equals(long.class) && newArgType.equals(Long.class)) || (argTypes[j].equals(float.class) && newArgType.equals(Float.class)) || (argTypes[j].equals(double.class) && newArgType.equals(Double.class)) || (argTypes[j].equals(boolean.class) && newArgType.equals(Boolean.class))) { exact = true; } else if (!argTypes[j].isAssignableFrom(newArgType)) { possibleMethod = null; exact = false; } else if (!argTypes[j].isPrimitive()) { if (!argTypes[j].equals(newArgType)) { exact = false; } } } if (exact) { method = possibleMethod; } else if (possibleMethod != null) { possibleMethods.add(possibleMethod); } } } } if (method == null && possibleMethods.size() > 0) { method = possibleMethods.iterator().next(); } if (method == null) { final StringBuilder name = new StringBuilder(type.getName()); name.append('.'); name.append(methodName); name.append('('); for (int i = 0; i < newArgs.length; i++) { if (i != 0) { name.append(", "); } name.append(newArgs[i].getClass().getName()); } name.append(')'); throw new NoSuchMethodException(name.toString()); } return method; } }
|
ReflectionUtils { public static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args) throws NoSuchMethodException { final Object[] newArgs = args == null ? new Object[0] : args; final Method[] methods = type.getMethods(); final Set<Method> possibleMethods = new HashSet<Method>(); Method method = null; for (int i = 0; method == null && i < methods.length; i++) { if (methodName.equals(methods[i].getName())) { final Class<?>[] argTypes = methods[i].getParameterTypes(); if (argTypes.length == newArgs.length) { boolean exact = true; Method possibleMethod = methods[i]; for (int j = 0; possibleMethod != null && j < argTypes.length; j++) { final Class<?> newArgType = newArgs[j] != null ? newArgs[j].getClass() : Object.class; if ((argTypes[j].equals(byte.class) && newArgType.equals(Byte.class)) || (argTypes[j].equals(char.class) && newArgType.equals(Character.class)) || (argTypes[j].equals(short.class) && newArgType.equals(Short.class)) || (argTypes[j].equals(int.class) && newArgType.equals(Integer.class)) || (argTypes[j].equals(long.class) && newArgType.equals(Long.class)) || (argTypes[j].equals(float.class) && newArgType.equals(Float.class)) || (argTypes[j].equals(double.class) && newArgType.equals(Double.class)) || (argTypes[j].equals(boolean.class) && newArgType.equals(Boolean.class))) { exact = true; } else if (!argTypes[j].isAssignableFrom(newArgType)) { possibleMethod = null; exact = false; } else if (!argTypes[j].isPrimitive()) { if (!argTypes[j].equals(newArgType)) { exact = false; } } } if (exact) { method = possibleMethod; } else if (possibleMethod != null) { possibleMethods.add(possibleMethod); } } } } if (method == null && possibleMethods.size() > 0) { method = possibleMethods.iterator().next(); } if (method == null) { final StringBuilder name = new StringBuilder(type.getName()); name.append('.'); name.append(methodName); name.append('('); for (int i = 0; i < newArgs.length; i++) { if (i != 0) { name.append(", "); } name.append(newArgs[i].getClass().getName()); } name.append(')'); throw new NoSuchMethodException(name.toString()); } return method; } private ReflectionUtils(); }
|
ReflectionUtils { public static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args) throws NoSuchMethodException { final Object[] newArgs = args == null ? new Object[0] : args; final Method[] methods = type.getMethods(); final Set<Method> possibleMethods = new HashSet<Method>(); Method method = null; for (int i = 0; method == null && i < methods.length; i++) { if (methodName.equals(methods[i].getName())) { final Class<?>[] argTypes = methods[i].getParameterTypes(); if (argTypes.length == newArgs.length) { boolean exact = true; Method possibleMethod = methods[i]; for (int j = 0; possibleMethod != null && j < argTypes.length; j++) { final Class<?> newArgType = newArgs[j] != null ? newArgs[j].getClass() : Object.class; if ((argTypes[j].equals(byte.class) && newArgType.equals(Byte.class)) || (argTypes[j].equals(char.class) && newArgType.equals(Character.class)) || (argTypes[j].equals(short.class) && newArgType.equals(Short.class)) || (argTypes[j].equals(int.class) && newArgType.equals(Integer.class)) || (argTypes[j].equals(long.class) && newArgType.equals(Long.class)) || (argTypes[j].equals(float.class) && newArgType.equals(Float.class)) || (argTypes[j].equals(double.class) && newArgType.equals(Double.class)) || (argTypes[j].equals(boolean.class) && newArgType.equals(Boolean.class))) { exact = true; } else if (!argTypes[j].isAssignableFrom(newArgType)) { possibleMethod = null; exact = false; } else if (!argTypes[j].isPrimitive()) { if (!argTypes[j].equals(newArgType)) { exact = false; } } } if (exact) { method = possibleMethod; } else if (possibleMethod != null) { possibleMethods.add(possibleMethod); } } } } if (method == null && possibleMethods.size() > 0) { method = possibleMethods.iterator().next(); } if (method == null) { final StringBuilder name = new StringBuilder(type.getName()); name.append('.'); name.append(methodName); name.append('('); for (int i = 0; i < newArgs.length; i++) { if (i != 0) { name.append(", "); } name.append(newArgs[i].getClass().getName()); } name.append(')'); throw new NoSuchMethodException(name.toString()); } return method; } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); }
|
ReflectionUtils { public static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args) throws NoSuchMethodException { final Object[] newArgs = args == null ? new Object[0] : args; final Method[] methods = type.getMethods(); final Set<Method> possibleMethods = new HashSet<Method>(); Method method = null; for (int i = 0; method == null && i < methods.length; i++) { if (methodName.equals(methods[i].getName())) { final Class<?>[] argTypes = methods[i].getParameterTypes(); if (argTypes.length == newArgs.length) { boolean exact = true; Method possibleMethod = methods[i]; for (int j = 0; possibleMethod != null && j < argTypes.length; j++) { final Class<?> newArgType = newArgs[j] != null ? newArgs[j].getClass() : Object.class; if ((argTypes[j].equals(byte.class) && newArgType.equals(Byte.class)) || (argTypes[j].equals(char.class) && newArgType.equals(Character.class)) || (argTypes[j].equals(short.class) && newArgType.equals(Short.class)) || (argTypes[j].equals(int.class) && newArgType.equals(Integer.class)) || (argTypes[j].equals(long.class) && newArgType.equals(Long.class)) || (argTypes[j].equals(float.class) && newArgType.equals(Float.class)) || (argTypes[j].equals(double.class) && newArgType.equals(Double.class)) || (argTypes[j].equals(boolean.class) && newArgType.equals(Boolean.class))) { exact = true; } else if (!argTypes[j].isAssignableFrom(newArgType)) { possibleMethod = null; exact = false; } else if (!argTypes[j].isPrimitive()) { if (!argTypes[j].equals(newArgType)) { exact = false; } } } if (exact) { method = possibleMethod; } else if (possibleMethod != null) { possibleMethods.add(possibleMethod); } } } } if (method == null && possibleMethods.size() > 0) { method = possibleMethods.iterator().next(); } if (method == null) { final StringBuilder name = new StringBuilder(type.getName()); name.append('.'); name.append(methodName); name.append('('); for (int i = 0; i < newArgs.length; i++) { if (i != 0) { name.append(", "); } name.append(newArgs[i].getClass().getName()); } name.append(')'); throw new NoSuchMethodException(name.toString()); } return method; } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); static final Method equals; static final Method hashCode; static final Method toString; }
|
@Test public void noSuchMethodExceptionIsThrownIfNoMatchingMethodCouldBeFound() throws Exception { try { ReflectionUtils.getMatchingMethod(StringBuffer.class, "append", new Object[]{this, StringBuffer.class}); fail("Thrown " + NoSuchMethodException.class.getName() + " expected"); } catch (final NoSuchMethodException e) { assertTrue(e.getMessage().indexOf( StringBuffer.class.getName() + ".append(" + this.getClass().getName() + ", " + Class.class.getName() + ")") >= 0); } }
|
public static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args) throws NoSuchMethodException { final Object[] newArgs = args == null ? new Object[0] : args; final Method[] methods = type.getMethods(); final Set<Method> possibleMethods = new HashSet<Method>(); Method method = null; for (int i = 0; method == null && i < methods.length; i++) { if (methodName.equals(methods[i].getName())) { final Class<?>[] argTypes = methods[i].getParameterTypes(); if (argTypes.length == newArgs.length) { boolean exact = true; Method possibleMethod = methods[i]; for (int j = 0; possibleMethod != null && j < argTypes.length; j++) { final Class<?> newArgType = newArgs[j] != null ? newArgs[j].getClass() : Object.class; if ((argTypes[j].equals(byte.class) && newArgType.equals(Byte.class)) || (argTypes[j].equals(char.class) && newArgType.equals(Character.class)) || (argTypes[j].equals(short.class) && newArgType.equals(Short.class)) || (argTypes[j].equals(int.class) && newArgType.equals(Integer.class)) || (argTypes[j].equals(long.class) && newArgType.equals(Long.class)) || (argTypes[j].equals(float.class) && newArgType.equals(Float.class)) || (argTypes[j].equals(double.class) && newArgType.equals(Double.class)) || (argTypes[j].equals(boolean.class) && newArgType.equals(Boolean.class))) { exact = true; } else if (!argTypes[j].isAssignableFrom(newArgType)) { possibleMethod = null; exact = false; } else if (!argTypes[j].isPrimitive()) { if (!argTypes[j].equals(newArgType)) { exact = false; } } } if (exact) { method = possibleMethod; } else if (possibleMethod != null) { possibleMethods.add(possibleMethod); } } } } if (method == null && possibleMethods.size() > 0) { method = possibleMethods.iterator().next(); } if (method == null) { final StringBuilder name = new StringBuilder(type.getName()); name.append('.'); name.append(methodName); name.append('('); for (int i = 0; i < newArgs.length; i++) { if (i != 0) { name.append(", "); } name.append(newArgs[i].getClass().getName()); } name.append(')'); throw new NoSuchMethodException(name.toString()); } return method; }
|
ReflectionUtils { public static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args) throws NoSuchMethodException { final Object[] newArgs = args == null ? new Object[0] : args; final Method[] methods = type.getMethods(); final Set<Method> possibleMethods = new HashSet<Method>(); Method method = null; for (int i = 0; method == null && i < methods.length; i++) { if (methodName.equals(methods[i].getName())) { final Class<?>[] argTypes = methods[i].getParameterTypes(); if (argTypes.length == newArgs.length) { boolean exact = true; Method possibleMethod = methods[i]; for (int j = 0; possibleMethod != null && j < argTypes.length; j++) { final Class<?> newArgType = newArgs[j] != null ? newArgs[j].getClass() : Object.class; if ((argTypes[j].equals(byte.class) && newArgType.equals(Byte.class)) || (argTypes[j].equals(char.class) && newArgType.equals(Character.class)) || (argTypes[j].equals(short.class) && newArgType.equals(Short.class)) || (argTypes[j].equals(int.class) && newArgType.equals(Integer.class)) || (argTypes[j].equals(long.class) && newArgType.equals(Long.class)) || (argTypes[j].equals(float.class) && newArgType.equals(Float.class)) || (argTypes[j].equals(double.class) && newArgType.equals(Double.class)) || (argTypes[j].equals(boolean.class) && newArgType.equals(Boolean.class))) { exact = true; } else if (!argTypes[j].isAssignableFrom(newArgType)) { possibleMethod = null; exact = false; } else if (!argTypes[j].isPrimitive()) { if (!argTypes[j].equals(newArgType)) { exact = false; } } } if (exact) { method = possibleMethod; } else if (possibleMethod != null) { possibleMethods.add(possibleMethod); } } } } if (method == null && possibleMethods.size() > 0) { method = possibleMethods.iterator().next(); } if (method == null) { final StringBuilder name = new StringBuilder(type.getName()); name.append('.'); name.append(methodName); name.append('('); for (int i = 0; i < newArgs.length; i++) { if (i != 0) { name.append(", "); } name.append(newArgs[i].getClass().getName()); } name.append(')'); throw new NoSuchMethodException(name.toString()); } return method; } }
|
ReflectionUtils { public static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args) throws NoSuchMethodException { final Object[] newArgs = args == null ? new Object[0] : args; final Method[] methods = type.getMethods(); final Set<Method> possibleMethods = new HashSet<Method>(); Method method = null; for (int i = 0; method == null && i < methods.length; i++) { if (methodName.equals(methods[i].getName())) { final Class<?>[] argTypes = methods[i].getParameterTypes(); if (argTypes.length == newArgs.length) { boolean exact = true; Method possibleMethod = methods[i]; for (int j = 0; possibleMethod != null && j < argTypes.length; j++) { final Class<?> newArgType = newArgs[j] != null ? newArgs[j].getClass() : Object.class; if ((argTypes[j].equals(byte.class) && newArgType.equals(Byte.class)) || (argTypes[j].equals(char.class) && newArgType.equals(Character.class)) || (argTypes[j].equals(short.class) && newArgType.equals(Short.class)) || (argTypes[j].equals(int.class) && newArgType.equals(Integer.class)) || (argTypes[j].equals(long.class) && newArgType.equals(Long.class)) || (argTypes[j].equals(float.class) && newArgType.equals(Float.class)) || (argTypes[j].equals(double.class) && newArgType.equals(Double.class)) || (argTypes[j].equals(boolean.class) && newArgType.equals(Boolean.class))) { exact = true; } else if (!argTypes[j].isAssignableFrom(newArgType)) { possibleMethod = null; exact = false; } else if (!argTypes[j].isPrimitive()) { if (!argTypes[j].equals(newArgType)) { exact = false; } } } if (exact) { method = possibleMethod; } else if (possibleMethod != null) { possibleMethods.add(possibleMethod); } } } } if (method == null && possibleMethods.size() > 0) { method = possibleMethods.iterator().next(); } if (method == null) { final StringBuilder name = new StringBuilder(type.getName()); name.append('.'); name.append(methodName); name.append('('); for (int i = 0; i < newArgs.length; i++) { if (i != 0) { name.append(", "); } name.append(newArgs[i].getClass().getName()); } name.append(')'); throw new NoSuchMethodException(name.toString()); } return method; } private ReflectionUtils(); }
|
ReflectionUtils { public static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args) throws NoSuchMethodException { final Object[] newArgs = args == null ? new Object[0] : args; final Method[] methods = type.getMethods(); final Set<Method> possibleMethods = new HashSet<Method>(); Method method = null; for (int i = 0; method == null && i < methods.length; i++) { if (methodName.equals(methods[i].getName())) { final Class<?>[] argTypes = methods[i].getParameterTypes(); if (argTypes.length == newArgs.length) { boolean exact = true; Method possibleMethod = methods[i]; for (int j = 0; possibleMethod != null && j < argTypes.length; j++) { final Class<?> newArgType = newArgs[j] != null ? newArgs[j].getClass() : Object.class; if ((argTypes[j].equals(byte.class) && newArgType.equals(Byte.class)) || (argTypes[j].equals(char.class) && newArgType.equals(Character.class)) || (argTypes[j].equals(short.class) && newArgType.equals(Short.class)) || (argTypes[j].equals(int.class) && newArgType.equals(Integer.class)) || (argTypes[j].equals(long.class) && newArgType.equals(Long.class)) || (argTypes[j].equals(float.class) && newArgType.equals(Float.class)) || (argTypes[j].equals(double.class) && newArgType.equals(Double.class)) || (argTypes[j].equals(boolean.class) && newArgType.equals(Boolean.class))) { exact = true; } else if (!argTypes[j].isAssignableFrom(newArgType)) { possibleMethod = null; exact = false; } else if (!argTypes[j].isPrimitive()) { if (!argTypes[j].equals(newArgType)) { exact = false; } } } if (exact) { method = possibleMethod; } else if (possibleMethod != null) { possibleMethods.add(possibleMethod); } } } } if (method == null && possibleMethods.size() > 0) { method = possibleMethods.iterator().next(); } if (method == null) { final StringBuilder name = new StringBuilder(type.getName()); name.append('.'); name.append(methodName); name.append('('); for (int i = 0; i < newArgs.length; i++) { if (i != 0) { name.append(", "); } name.append(newArgs[i].getClass().getName()); } name.append(')'); throw new NoSuchMethodException(name.toString()); } return method; } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); }
|
ReflectionUtils { public static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args) throws NoSuchMethodException { final Object[] newArgs = args == null ? new Object[0] : args; final Method[] methods = type.getMethods(); final Set<Method> possibleMethods = new HashSet<Method>(); Method method = null; for (int i = 0; method == null && i < methods.length; i++) { if (methodName.equals(methods[i].getName())) { final Class<?>[] argTypes = methods[i].getParameterTypes(); if (argTypes.length == newArgs.length) { boolean exact = true; Method possibleMethod = methods[i]; for (int j = 0; possibleMethod != null && j < argTypes.length; j++) { final Class<?> newArgType = newArgs[j] != null ? newArgs[j].getClass() : Object.class; if ((argTypes[j].equals(byte.class) && newArgType.equals(Byte.class)) || (argTypes[j].equals(char.class) && newArgType.equals(Character.class)) || (argTypes[j].equals(short.class) && newArgType.equals(Short.class)) || (argTypes[j].equals(int.class) && newArgType.equals(Integer.class)) || (argTypes[j].equals(long.class) && newArgType.equals(Long.class)) || (argTypes[j].equals(float.class) && newArgType.equals(Float.class)) || (argTypes[j].equals(double.class) && newArgType.equals(Double.class)) || (argTypes[j].equals(boolean.class) && newArgType.equals(Boolean.class))) { exact = true; } else if (!argTypes[j].isAssignableFrom(newArgType)) { possibleMethod = null; exact = false; } else if (!argTypes[j].isPrimitive()) { if (!argTypes[j].equals(newArgType)) { exact = false; } } } if (exact) { method = possibleMethod; } else if (possibleMethod != null) { possibleMethods.add(possibleMethod); } } } } if (method == null && possibleMethods.size() > 0) { method = possibleMethods.iterator().next(); } if (method == null) { final StringBuilder name = new StringBuilder(type.getName()); name.append('.'); name.append(methodName); name.append('('); for (int i = 0; i < newArgs.length; i++) { if (i != 0) { name.append(", "); } name.append(newArgs[i].getClass().getName()); } name.append(')'); throw new NoSuchMethodException(name.toString()); } return method; } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); static final Method equals; static final Method hashCode; static final Method toString; }
|
@Test public void methodCanBeSerialized() throws IOException, ClassNotFoundException { ByteArrayOutputStream outBuffer = new ByteArrayOutputStream(); ObjectOutputStream outStream = new ObjectOutputStream(outBuffer); ReflectionUtils.writeMethod(outStream, ReflectionUtils.equals); outStream.close(); ByteArrayInputStream inBuffer = new ByteArrayInputStream(outBuffer.toByteArray()); ObjectInputStream inStream = new ObjectInputStream(inBuffer); assertSame(Object.class, inStream.readObject()); assertEquals("equals", inStream.readObject()); assertTrue(Arrays.equals(new Class[]{Object.class}, (Object[]) inStream.readObject())); inStream.close(); }
|
public static void writeMethod(final ObjectOutputStream out, final Method method) throws IOException { out.writeObject(method.getDeclaringClass()); out.writeObject(method.getName()); out.writeObject(method.getParameterTypes()); }
|
ReflectionUtils { public static void writeMethod(final ObjectOutputStream out, final Method method) throws IOException { out.writeObject(method.getDeclaringClass()); out.writeObject(method.getName()); out.writeObject(method.getParameterTypes()); } }
|
ReflectionUtils { public static void writeMethod(final ObjectOutputStream out, final Method method) throws IOException { out.writeObject(method.getDeclaringClass()); out.writeObject(method.getName()); out.writeObject(method.getParameterTypes()); } private ReflectionUtils(); }
|
ReflectionUtils { public static void writeMethod(final ObjectOutputStream out, final Method method) throws IOException { out.writeObject(method.getDeclaringClass()); out.writeObject(method.getName()); out.writeObject(method.getParameterTypes()); } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); }
|
ReflectionUtils { public static void writeMethod(final ObjectOutputStream out, final Method method) throws IOException { out.writeObject(method.getDeclaringClass()); out.writeObject(method.getName()); out.writeObject(method.getParameterTypes()); } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); static final Method equals; static final Method hashCode; static final Method toString; }
|
@Test public void methodCanBeDeserialized() throws IOException, ClassNotFoundException { ByteArrayOutputStream outBuffer = new ByteArrayOutputStream(); ObjectOutputStream outStream = new ObjectOutputStream(outBuffer); outStream.writeObject(Object.class); outStream.writeObject("equals"); outStream.writeObject(new Class[]{Object.class}); outStream.close(); ByteArrayInputStream inBuffer = new ByteArrayInputStream(outBuffer.toByteArray()); ObjectInputStream inStream = new ObjectInputStream(inBuffer); assertEquals(ReflectionUtils.equals, ReflectionUtils.readMethod(inStream)); }
|
public static Method readMethod(final ObjectInputStream in) throws IOException, ClassNotFoundException { final Class<?> type = Class.class.cast(in.readObject()); final String name = String.class.cast(in.readObject()); final Class<?>[] parameters = Class[].class.cast(in.readObject()); try { return type.getMethod(name, parameters); } catch (final NoSuchMethodException e) { throw new InvalidObjectException(e.getMessage()); } }
|
ReflectionUtils { public static Method readMethod(final ObjectInputStream in) throws IOException, ClassNotFoundException { final Class<?> type = Class.class.cast(in.readObject()); final String name = String.class.cast(in.readObject()); final Class<?>[] parameters = Class[].class.cast(in.readObject()); try { return type.getMethod(name, parameters); } catch (final NoSuchMethodException e) { throw new InvalidObjectException(e.getMessage()); } } }
|
ReflectionUtils { public static Method readMethod(final ObjectInputStream in) throws IOException, ClassNotFoundException { final Class<?> type = Class.class.cast(in.readObject()); final String name = String.class.cast(in.readObject()); final Class<?>[] parameters = Class[].class.cast(in.readObject()); try { return type.getMethod(name, parameters); } catch (final NoSuchMethodException e) { throw new InvalidObjectException(e.getMessage()); } } private ReflectionUtils(); }
|
ReflectionUtils { public static Method readMethod(final ObjectInputStream in) throws IOException, ClassNotFoundException { final Class<?> type = Class.class.cast(in.readObject()); final String name = String.class.cast(in.readObject()); final Class<?>[] parameters = Class[].class.cast(in.readObject()); try { return type.getMethod(name, parameters); } catch (final NoSuchMethodException e) { throw new InvalidObjectException(e.getMessage()); } } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); }
|
ReflectionUtils { public static Method readMethod(final ObjectInputStream in) throws IOException, ClassNotFoundException { final Class<?> type = Class.class.cast(in.readObject()); final String name = String.class.cast(in.readObject()); final Class<?>[] parameters = Class[].class.cast(in.readObject()); try { return type.getMethod(name, parameters); } catch (final NoSuchMethodException e) { throw new InvalidObjectException(e.getMessage()); } } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); static final Method equals; static final Method hashCode; static final Method toString; }
|
@Test public void unknownDeserializedMethodThrowsInvalidObjectException() throws IOException, ClassNotFoundException { ByteArrayOutputStream outBuffer = new ByteArrayOutputStream(); ObjectOutputStream outStream = new ObjectOutputStream(outBuffer); outStream.writeObject(Object.class); outStream.writeObject("equals"); outStream.writeObject(new Class[0]); outStream.close(); ByteArrayInputStream inBuffer = new ByteArrayInputStream(outBuffer.toByteArray()); ObjectInputStream inStream = new ObjectInputStream(inBuffer); try { ReflectionUtils.readMethod(inStream); fail("Thrown " + InvalidObjectException.class.getName() + " expected"); } catch (final InvalidObjectException e) { } }
|
public static Method readMethod(final ObjectInputStream in) throws IOException, ClassNotFoundException { final Class<?> type = Class.class.cast(in.readObject()); final String name = String.class.cast(in.readObject()); final Class<?>[] parameters = Class[].class.cast(in.readObject()); try { return type.getMethod(name, parameters); } catch (final NoSuchMethodException e) { throw new InvalidObjectException(e.getMessage()); } }
|
ReflectionUtils { public static Method readMethod(final ObjectInputStream in) throws IOException, ClassNotFoundException { final Class<?> type = Class.class.cast(in.readObject()); final String name = String.class.cast(in.readObject()); final Class<?>[] parameters = Class[].class.cast(in.readObject()); try { return type.getMethod(name, parameters); } catch (final NoSuchMethodException e) { throw new InvalidObjectException(e.getMessage()); } } }
|
ReflectionUtils { public static Method readMethod(final ObjectInputStream in) throws IOException, ClassNotFoundException { final Class<?> type = Class.class.cast(in.readObject()); final String name = String.class.cast(in.readObject()); final Class<?>[] parameters = Class[].class.cast(in.readObject()); try { return type.getMethod(name, parameters); } catch (final NoSuchMethodException e) { throw new InvalidObjectException(e.getMessage()); } } private ReflectionUtils(); }
|
ReflectionUtils { public static Method readMethod(final ObjectInputStream in) throws IOException, ClassNotFoundException { final Class<?> type = Class.class.cast(in.readObject()); final String name = String.class.cast(in.readObject()); final Class<?>[] parameters = Class[].class.cast(in.readObject()); try { return type.getMethod(name, parameters); } catch (final NoSuchMethodException e) { throw new InvalidObjectException(e.getMessage()); } } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); }
|
ReflectionUtils { public static Method readMethod(final ObjectInputStream in) throws IOException, ClassNotFoundException { final Class<?> type = Class.class.cast(in.readObject()); final String name = String.class.cast(in.readObject()); final Class<?>[] parameters = Class[].class.cast(in.readObject()); try { return type.getMethod(name, parameters); } catch (final NoSuchMethodException e) { throw new InvalidObjectException(e.getMessage()); } } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); static final Method equals; static final Method hashCode; static final Method toString; }
|
@Test public void serializeWithXStreamInPureReflectionMode() { useSerializedProxy(serializeWithXStreamAndPureReflection( Decorating.proxy(CharSequence.class).with("Test").visiting(new AssertingDecorator()).build(getFactory()))); }
|
public static <T> DecoratingWith<T> proxy(final Class<T> type) { return new DecoratingWith<T>(new Decorating<T, T>((T)null, type)); }
|
Decorating { public static <T> DecoratingWith<T> proxy(final Class<T> type) { return new DecoratingWith<T>(new Decorating<T, T>((T)null, type)); } }
|
Decorating { public static <T> DecoratingWith<T> proxy(final Class<T> type) { return new DecoratingWith<T>(new Decorating<T, T>((T)null, type)); } private Decorating(final U delegate, final Class<T>primaryType, final Class<?>... types); }
|
Decorating { public static <T> DecoratingWith<T> proxy(final Class<T> type) { return new DecoratingWith<T>(new Decorating<T, T>((T)null, type)); } private Decorating(final U delegate, final Class<T>primaryType, final Class<?>... types); static DecoratingWith<T> proxy(final Class<T> type); static DecoratingWith<T> proxy(final Class<T> primaryType, final Class<?> ... types); static DecoratingVisitor<U, U> proxy(final U delegate); static DecoratingVisitor<U, T> proxy(final U delegate, final Class<T> type); static DecoratingVisitor<U, T> proxy(final U delegate, final Class<T> primaryType, final Class<?> ... types); }
|
Decorating { public static <T> DecoratingWith<T> proxy(final Class<T> type) { return new DecoratingWith<T>(new Decorating<T, T>((T)null, type)); } private Decorating(final U delegate, final Class<T>primaryType, final Class<?>... types); static DecoratingWith<T> proxy(final Class<T> type); static DecoratingWith<T> proxy(final Class<T> primaryType, final Class<?> ... types); static DecoratingVisitor<U, U> proxy(final U delegate); static DecoratingVisitor<U, T> proxy(final U delegate, final Class<T> type); static DecoratingVisitor<U, T> proxy(final U delegate, final Class<T> primaryType, final Class<?> ... types); }
|
@Test public void canDeferDecorationUntilAfterProxyInstantiation() throws Exception { final Decorator<WithCallsInConstructor> nullDecorator = new Decorator<WithCallsInConstructor>() {}; final WithCallsInConstructor obj = new WithCallsInConstructor(); obj.setS("custom"); assertEquals("sanity check", "custom", obj.getS()); final WithCallsInConstructor withCallsInConstructor = Decorating.proxy(WithCallsInConstructor.class).with(obj).visiting(nullDecorator).build(new CglibProxyFactory(true)); assertEquals("This won't be expected by most users, but it is \"correct\" nonetheless", "default", withCallsInConstructor.getS()); assertEquals("And this was passed on to the underlying object too", "default", obj.getS()); final WithCallsInConstructor obj2 = new WithCallsInConstructor(); obj2.setS("custom"); assertEquals("sanity check", "custom", obj2.getS()); final WithCallsInConstructor withoutCallsInConstructor = Decorating.proxy(WithCallsInConstructor.class).with(obj2).visiting(nullDecorator).build(new CglibProxyFactory(false)); assertEquals("And this is what most users would expect - setting interceptDuringConstruction to false", "custom", withoutCallsInConstructor.getS()); assertEquals("And this was not passed on to the underlying object either", "custom", obj2.getS()); }
|
public static <T> DecoratingWith<T> proxy(final Class<T> type) { return new DecoratingWith<T>(new Decorating<T, T>((T)null, type)); }
|
Decorating { public static <T> DecoratingWith<T> proxy(final Class<T> type) { return new DecoratingWith<T>(new Decorating<T, T>((T)null, type)); } }
|
Decorating { public static <T> DecoratingWith<T> proxy(final Class<T> type) { return new DecoratingWith<T>(new Decorating<T, T>((T)null, type)); } private Decorating(final U delegate, final Class<T>primaryType, final Class<?>... types); }
|
Decorating { public static <T> DecoratingWith<T> proxy(final Class<T> type) { return new DecoratingWith<T>(new Decorating<T, T>((T)null, type)); } private Decorating(final U delegate, final Class<T>primaryType, final Class<?>... types); static DecoratingWith<T> proxy(final Class<T> type); static DecoratingWith<T> proxy(final Class<T> primaryType, final Class<?> ... types); static DecoratingVisitor<U, U> proxy(final U delegate); static DecoratingVisitor<U, T> proxy(final U delegate, final Class<T> type); static DecoratingVisitor<U, T> proxy(final U delegate, final Class<T> primaryType, final Class<?> ... types); }
|
Decorating { public static <T> DecoratingWith<T> proxy(final Class<T> type) { return new DecoratingWith<T>(new Decorating<T, T>((T)null, type)); } private Decorating(final U delegate, final Class<T>primaryType, final Class<?>... types); static DecoratingWith<T> proxy(final Class<T> type); static DecoratingWith<T> proxy(final Class<T> primaryType, final Class<?> ... types); static DecoratingVisitor<U, U> proxy(final U delegate); static DecoratingVisitor<U, T> proxy(final U delegate, final Class<T> type); static DecoratingVisitor<U, T> proxy(final U delegate, final Class<T> primaryType, final Class<?> ... types); }
|
@Test public void shouldReturnNullObjectAsIntermediateResultAndSwapWhenMethodCompletesWithCast() throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); Service slowService = new SlowService(latch); Service fastService = Future.proxy(slowService).build(getFactory()); List<String> stuff = fastService.getList(); assertTrue(stuff.isEmpty()); latch.countDown(); Thread.sleep(100); assertEquals(1, stuff.size()); assertEquals("yo", stuff.get(0)); }
|
public static <T> FutureWith<T> proxy(Class<T> primaryType) { Future<T> future = new Future<T>(new Class<?>[]{primaryType}); return new FutureWith<T>(future); }
|
Future { public static <T> FutureWith<T> proxy(Class<T> primaryType) { Future<T> future = new Future<T>(new Class<?>[]{primaryType}); return new FutureWith<T>(future); } }
|
Future { public static <T> FutureWith<T> proxy(Class<T> primaryType) { Future<T> future = new Future<T>(new Class<?>[]{primaryType}); return new FutureWith<T>(future); } private Future(Class<?>[] types); }
|
Future { public static <T> FutureWith<T> proxy(Class<T> primaryType) { Future<T> future = new Future<T>(new Class<?>[]{primaryType}); return new FutureWith<T>(future); } private Future(Class<?>[] types); static FutureWith<T> proxy(Class<T> primaryType); static FutureWith<T> proxy(Class<T> primaryType, Class<?>... types); static FutureBuild<T> proxy(T target); }
|
Future { public static <T> FutureWith<T> proxy(Class<T> primaryType) { Future<T> future = new Future<T>(new Class<?>[]{primaryType}); return new FutureWith<T>(future); } private Future(Class<?>[] types); static FutureWith<T> proxy(Class<T> primaryType); static FutureWith<T> proxy(Class<T> primaryType, Class<?>... types); static FutureBuild<T> proxy(T target); }
|
@Test public void shouldReturnNullObjectAsIntermediateResultAndSwapWhenMethodCompletesWithGenerics() throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); Service slowService = new SlowService(latch); Service fastService = Future.proxy(Service.class).with(slowService).build(getFactory()); List<String> stuff = fastService.getList(); assertTrue(stuff.isEmpty()); latch.countDown(); Thread.sleep(100); assertEquals(1, stuff.size()); assertEquals("yo", stuff.get(0)); }
|
public static <T> FutureWith<T> proxy(Class<T> primaryType) { Future<T> future = new Future<T>(new Class<?>[]{primaryType}); return new FutureWith<T>(future); }
|
Future { public static <T> FutureWith<T> proxy(Class<T> primaryType) { Future<T> future = new Future<T>(new Class<?>[]{primaryType}); return new FutureWith<T>(future); } }
|
Future { public static <T> FutureWith<T> proxy(Class<T> primaryType) { Future<T> future = new Future<T>(new Class<?>[]{primaryType}); return new FutureWith<T>(future); } private Future(Class<?>[] types); }
|
Future { public static <T> FutureWith<T> proxy(Class<T> primaryType) { Future<T> future = new Future<T>(new Class<?>[]{primaryType}); return new FutureWith<T>(future); } private Future(Class<?>[] types); static FutureWith<T> proxy(Class<T> primaryType); static FutureWith<T> proxy(Class<T> primaryType, Class<?>... types); static FutureBuild<T> proxy(T target); }
|
Future { public static <T> FutureWith<T> proxy(Class<T> primaryType) { Future<T> future = new Future<T>(new Class<?>[]{primaryType}); return new FutureWith<T>(future); } private Future(Class<?>[] types); static FutureWith<T> proxy(Class<T> primaryType); static FutureWith<T> proxy(Class<T> primaryType, Class<?>... types); static FutureBuild<T> proxy(T target); }
|
@Test public void shouldHandleVoidMethodsWithCast() { CountDownLatch latch = new CountDownLatch(1); Service slowService = new SlowService(latch); Service fastService = Future.proxy(slowService).build(getFactory()); fastService.methodReturnsVoid(); }
|
public static <T> FutureWith<T> proxy(Class<T> primaryType) { Future<T> future = new Future<T>(new Class<?>[]{primaryType}); return new FutureWith<T>(future); }
|
Future { public static <T> FutureWith<T> proxy(Class<T> primaryType) { Future<T> future = new Future<T>(new Class<?>[]{primaryType}); return new FutureWith<T>(future); } }
|
Future { public static <T> FutureWith<T> proxy(Class<T> primaryType) { Future<T> future = new Future<T>(new Class<?>[]{primaryType}); return new FutureWith<T>(future); } private Future(Class<?>[] types); }
|
Future { public static <T> FutureWith<T> proxy(Class<T> primaryType) { Future<T> future = new Future<T>(new Class<?>[]{primaryType}); return new FutureWith<T>(future); } private Future(Class<?>[] types); static FutureWith<T> proxy(Class<T> primaryType); static FutureWith<T> proxy(Class<T> primaryType, Class<?>... types); static FutureBuild<T> proxy(T target); }
|
Future { public static <T> FutureWith<T> proxy(Class<T> primaryType) { Future<T> future = new Future<T>(new Class<?>[]{primaryType}); return new FutureWith<T>(future); } private Future(Class<?>[] types); static FutureWith<T> proxy(Class<T> primaryType); static FutureWith<T> proxy(Class<T> primaryType, Class<?>... types); static FutureBuild<T> proxy(T target); }
|
@Test public void shouldHandleVoidMethodsWithGenerics() { CountDownLatch latch = new CountDownLatch(1); Service slowService = new SlowService(latch); Service fastService = Future.proxy(Service.class).with(slowService).build(getFactory()); fastService.methodReturnsVoid(); }
|
public static <T> FutureWith<T> proxy(Class<T> primaryType) { Future<T> future = new Future<T>(new Class<?>[]{primaryType}); return new FutureWith<T>(future); }
|
Future { public static <T> FutureWith<T> proxy(Class<T> primaryType) { Future<T> future = new Future<T>(new Class<?>[]{primaryType}); return new FutureWith<T>(future); } }
|
Future { public static <T> FutureWith<T> proxy(Class<T> primaryType) { Future<T> future = new Future<T>(new Class<?>[]{primaryType}); return new FutureWith<T>(future); } private Future(Class<?>[] types); }
|
Future { public static <T> FutureWith<T> proxy(Class<T> primaryType) { Future<T> future = new Future<T>(new Class<?>[]{primaryType}); return new FutureWith<T>(future); } private Future(Class<?>[] types); static FutureWith<T> proxy(Class<T> primaryType); static FutureWith<T> proxy(Class<T> primaryType, Class<?>... types); static FutureBuild<T> proxy(T target); }
|
Future { public static <T> FutureWith<T> proxy(Class<T> primaryType) { Future<T> future = new Future<T>(new Class<?>[]{primaryType}); return new FutureWith<T>(future); } private Future(Class<?>[] types); static FutureWith<T> proxy(Class<T> primaryType); static FutureWith<T> proxy(Class<T> primaryType, Class<?>... types); static FutureBuild<T> proxy(T target); }
|
@Test public void callIsDelegated() throws Exception { Foo fooMock = mock(Foo.class); Foo foo = Privileging.proxy(Foo.class).with(fooMock).executedBy(new DirectExecutor()).build(getFactory()); foo.call(); verify(fooMock).call(); }
|
public static <T> PrivilegingWith<T> proxy(Class<T> type) { return new PrivilegingWith<T>(new Privileging<T>(type)); }
|
Privileging { public static <T> PrivilegingWith<T> proxy(Class<T> type) { return new PrivilegingWith<T>(new Privileging<T>(type)); } }
|
Privileging { public static <T> PrivilegingWith<T> proxy(Class<T> type) { return new PrivilegingWith<T>(new Privileging<T>(type)); } private Privileging(Class<T> type); }
|
Privileging { public static <T> PrivilegingWith<T> proxy(Class<T> type) { return new PrivilegingWith<T>(new Privileging<T>(type)); } private Privileging(Class<T> type); static PrivilegingWith<T> proxy(Class<T> type); static PrivilegingExecutedByOrBuild<T> proxy(T target); }
|
Privileging { public static <T> PrivilegingWith<T> proxy(Class<T> type) { return new PrivilegingWith<T>(new Privileging<T>(type)); } private Privileging(Class<T> type); static PrivilegingWith<T> proxy(Class<T> type); static PrivilegingExecutedByOrBuild<T> proxy(T target); }
|
@Test public void testBlobDataIsCreated() { assertThat(restoreBlobStrategy.createRestoreData(restoreBlobData).getBlobData(), is(restoreBlobData)); }
|
@Override protected RRestoreBlobData createRestoreData(final RestoreBlobData restoreBlobData) { checkState(!isEmpty(restoreBlobData.getBlobName()), "Blob name cannot be empty"); return new RRestoreBlobData(restoreBlobData); }
|
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected RRestoreBlobData createRestoreData(final RestoreBlobData restoreBlobData) { checkState(!isEmpty(restoreBlobData.getBlobName()), "Blob name cannot be empty"); return new RRestoreBlobData(restoreBlobData); } }
|
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected RRestoreBlobData createRestoreData(final RestoreBlobData restoreBlobData) { checkState(!isEmpty(restoreBlobData.getBlobName()), "Blob name cannot be empty"); return new RRestoreBlobData(restoreBlobData); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess,
final RepositoryManager repositoryManager,
final BlobStoreManager blobStoreManager,
final DryRunPrefix dryRunPrefix); }
|
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected RRestoreBlobData createRestoreData(final RestoreBlobData restoreBlobData) { checkState(!isEmpty(restoreBlobData.getBlobName()), "Blob name cannot be empty"); return new RRestoreBlobData(restoreBlobData); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess,
final RepositoryManager repositoryManager,
final BlobStoreManager blobStoreManager,
final DryRunPrefix dryRunPrefix); }
|
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected RRestoreBlobData createRestoreData(final RestoreBlobData restoreBlobData) { checkState(!isEmpty(restoreBlobData.getBlobName()), "Blob name cannot be empty"); return new RRestoreBlobData(restoreBlobData); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess,
final RepositoryManager repositoryManager,
final BlobStoreManager blobStoreManager,
final DryRunPrefix dryRunPrefix); }
|
@Test(expected = IllegalStateException.class) public void testIfBlobDataNameIsEmptyExceptionIsThrown() { when(rRestoreBlobData.getBlobData().getBlobName()).thenReturn(""); restoreBlobStrategy.createRestoreData(restoreBlobData); }
|
@Override protected RRestoreBlobData createRestoreData(final RestoreBlobData restoreBlobData) { checkState(!isEmpty(restoreBlobData.getBlobName()), "Blob name cannot be empty"); return new RRestoreBlobData(restoreBlobData); }
|
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected RRestoreBlobData createRestoreData(final RestoreBlobData restoreBlobData) { checkState(!isEmpty(restoreBlobData.getBlobName()), "Blob name cannot be empty"); return new RRestoreBlobData(restoreBlobData); } }
|
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected RRestoreBlobData createRestoreData(final RestoreBlobData restoreBlobData) { checkState(!isEmpty(restoreBlobData.getBlobName()), "Blob name cannot be empty"); return new RRestoreBlobData(restoreBlobData); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess,
final RepositoryManager repositoryManager,
final BlobStoreManager blobStoreManager,
final DryRunPrefix dryRunPrefix); }
|
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected RRestoreBlobData createRestoreData(final RestoreBlobData restoreBlobData) { checkState(!isEmpty(restoreBlobData.getBlobName()), "Blob name cannot be empty"); return new RRestoreBlobData(restoreBlobData); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess,
final RepositoryManager repositoryManager,
final BlobStoreManager blobStoreManager,
final DryRunPrefix dryRunPrefix); }
|
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected RRestoreBlobData createRestoreData(final RestoreBlobData restoreBlobData) { checkState(!isEmpty(restoreBlobData.getBlobName()), "Blob name cannot be empty"); return new RRestoreBlobData(restoreBlobData); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess,
final RepositoryManager repositoryManager,
final BlobStoreManager blobStoreManager,
final DryRunPrefix dryRunPrefix); }
|
@Test public void testCorrectHashAlgorithmsAreSupported() { assertThat(restoreBlobStrategy.getHashAlgorithms(), containsInAnyOrder(SHA1)); }
|
@Nonnull @Override protected List<HashAlgorithm> getHashAlgorithms() { return ImmutableList.of(SHA1); }
|
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Nonnull @Override protected List<HashAlgorithm> getHashAlgorithms() { return ImmutableList.of(SHA1); } }
|
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Nonnull @Override protected List<HashAlgorithm> getHashAlgorithms() { return ImmutableList.of(SHA1); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess,
final RepositoryManager repositoryManager,
final BlobStoreManager blobStoreManager,
final DryRunPrefix dryRunPrefix); }
|
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Nonnull @Override protected List<HashAlgorithm> getHashAlgorithms() { return ImmutableList.of(SHA1); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess,
final RepositoryManager repositoryManager,
final BlobStoreManager blobStoreManager,
final DryRunPrefix dryRunPrefix); }
|
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Nonnull @Override protected List<HashAlgorithm> getHashAlgorithms() { return ImmutableList.of(SHA1); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess,
final RepositoryManager repositoryManager,
final BlobStoreManager blobStoreManager,
final DryRunPrefix dryRunPrefix); }
|
@Test public void testAppropriatePathIsReturned() { assertThat(restoreBlobStrategy.getAssetPath(rRestoreBlobData), is(ARCHIVE_PATH)); }
|
@Override protected String getAssetPath(@Nonnull final RRestoreBlobData rRestoreBlobData) { return rRestoreBlobData.getBlobData().getBlobName(); }
|
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected String getAssetPath(@Nonnull final RRestoreBlobData rRestoreBlobData) { return rRestoreBlobData.getBlobData().getBlobName(); } }
|
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected String getAssetPath(@Nonnull final RRestoreBlobData rRestoreBlobData) { return rRestoreBlobData.getBlobData().getBlobName(); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess,
final RepositoryManager repositoryManager,
final BlobStoreManager blobStoreManager,
final DryRunPrefix dryRunPrefix); }
|
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected String getAssetPath(@Nonnull final RRestoreBlobData rRestoreBlobData) { return rRestoreBlobData.getBlobData().getBlobName(); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess,
final RepositoryManager repositoryManager,
final BlobStoreManager blobStoreManager,
final DryRunPrefix dryRunPrefix); }
|
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected String getAssetPath(@Nonnull final RRestoreBlobData rRestoreBlobData) { return rRestoreBlobData.getBlobData().getBlobName(); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess,
final RepositoryManager repositoryManager,
final BlobStoreManager blobStoreManager,
final DryRunPrefix dryRunPrefix); }
|
@Test public void testPackageIsRestored() throws Exception { restoreBlobStrategy.restore(properties, blob, TEST_BLOB_STORE_NAME, false); verify(rRestoreFacet).assetExists(ARCHIVE_PATH); verify(rRestoreFacet).restore(any(AssetBlob.class), eq(ARCHIVE_PATH)); verifyNoMoreInteractions(rRestoreFacet); }
|
@Override protected boolean assetExists(@Nonnull final RRestoreBlobData rRestoreBlobData) { RRestoreFacet facet = getRestoreFacet(rRestoreBlobData); return facet.assetExists(getAssetPath(rRestoreBlobData)); }
|
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected boolean assetExists(@Nonnull final RRestoreBlobData rRestoreBlobData) { RRestoreFacet facet = getRestoreFacet(rRestoreBlobData); return facet.assetExists(getAssetPath(rRestoreBlobData)); } }
|
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected boolean assetExists(@Nonnull final RRestoreBlobData rRestoreBlobData) { RRestoreFacet facet = getRestoreFacet(rRestoreBlobData); return facet.assetExists(getAssetPath(rRestoreBlobData)); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess,
final RepositoryManager repositoryManager,
final BlobStoreManager blobStoreManager,
final DryRunPrefix dryRunPrefix); }
|
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected boolean assetExists(@Nonnull final RRestoreBlobData rRestoreBlobData) { RRestoreFacet facet = getRestoreFacet(rRestoreBlobData); return facet.assetExists(getAssetPath(rRestoreBlobData)); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess,
final RepositoryManager repositoryManager,
final BlobStoreManager blobStoreManager,
final DryRunPrefix dryRunPrefix); }
|
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected boolean assetExists(@Nonnull final RRestoreBlobData rRestoreBlobData) { RRestoreFacet facet = getRestoreFacet(rRestoreBlobData); return facet.assetExists(getAssetPath(rRestoreBlobData)); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess,
final RepositoryManager repositoryManager,
final BlobStoreManager blobStoreManager,
final DryRunPrefix dryRunPrefix); }
|
@Test public void testComponentIsRequiredForGz() { boolean expected = true; when(rRestoreFacet.componentRequired(ARCHIVE_PATH)).thenReturn(expected); assertThat(restoreBlobStrategy.componentRequired(rRestoreBlobData), is(expected)); verify(rRestoreFacet).componentRequired(ARCHIVE_PATH); verifyNoMoreInteractions(rRestoreFacet); }
|
@Override protected boolean componentRequired(final RRestoreBlobData data) { RRestoreFacet facet = getRestoreFacet(data); final String path = data.getBlobData().getBlobName(); return facet.componentRequired(path); }
|
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected boolean componentRequired(final RRestoreBlobData data) { RRestoreFacet facet = getRestoreFacet(data); final String path = data.getBlobData().getBlobName(); return facet.componentRequired(path); } }
|
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected boolean componentRequired(final RRestoreBlobData data) { RRestoreFacet facet = getRestoreFacet(data); final String path = data.getBlobData().getBlobName(); return facet.componentRequired(path); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess,
final RepositoryManager repositoryManager,
final BlobStoreManager blobStoreManager,
final DryRunPrefix dryRunPrefix); }
|
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected boolean componentRequired(final RRestoreBlobData data) { RRestoreFacet facet = getRestoreFacet(data); final String path = data.getBlobData().getBlobName(); return facet.componentRequired(path); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess,
final RepositoryManager repositoryManager,
final BlobStoreManager blobStoreManager,
final DryRunPrefix dryRunPrefix); }
|
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected boolean componentRequired(final RRestoreBlobData data) { RRestoreFacet facet = getRestoreFacet(data); final String path = data.getBlobData().getBlobName(); return facet.componentRequired(path); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess,
final RepositoryManager repositoryManager,
final BlobStoreManager blobStoreManager,
final DryRunPrefix dryRunPrefix); }
|
@Test public void testComponentQuery() throws IOException { restoreBlobStrategy.getComponentQuery(rRestoreBlobData); verify(rRestoreFacet, times(1)).getComponentQuery(anyMapOf(String.class, String.class)); }
|
@Override protected Query getComponentQuery(final RRestoreBlobData data) throws IOException { RRestoreFacet facet = getRestoreFacet(data); RestoreBlobData blobData = data.getBlobData(); Map<String, String> attributes; try (InputStream inputStream = blobData.getBlob().getInputStream()) { attributes = facet.extractComponentAttributesFromArchive(blobData.getBlobName(), inputStream); } return facet.getComponentQuery(attributes); }
|
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected Query getComponentQuery(final RRestoreBlobData data) throws IOException { RRestoreFacet facet = getRestoreFacet(data); RestoreBlobData blobData = data.getBlobData(); Map<String, String> attributes; try (InputStream inputStream = blobData.getBlob().getInputStream()) { attributes = facet.extractComponentAttributesFromArchive(blobData.getBlobName(), inputStream); } return facet.getComponentQuery(attributes); } }
|
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected Query getComponentQuery(final RRestoreBlobData data) throws IOException { RRestoreFacet facet = getRestoreFacet(data); RestoreBlobData blobData = data.getBlobData(); Map<String, String> attributes; try (InputStream inputStream = blobData.getBlob().getInputStream()) { attributes = facet.extractComponentAttributesFromArchive(blobData.getBlobName(), inputStream); } return facet.getComponentQuery(attributes); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess,
final RepositoryManager repositoryManager,
final BlobStoreManager blobStoreManager,
final DryRunPrefix dryRunPrefix); }
|
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected Query getComponentQuery(final RRestoreBlobData data) throws IOException { RRestoreFacet facet = getRestoreFacet(data); RestoreBlobData blobData = data.getBlobData(); Map<String, String> attributes; try (InputStream inputStream = blobData.getBlob().getInputStream()) { attributes = facet.extractComponentAttributesFromArchive(blobData.getBlobName(), inputStream); } return facet.getComponentQuery(attributes); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess,
final RepositoryManager repositoryManager,
final BlobStoreManager blobStoreManager,
final DryRunPrefix dryRunPrefix); }
|
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected Query getComponentQuery(final RRestoreBlobData data) throws IOException { RRestoreFacet facet = getRestoreFacet(data); RestoreBlobData blobData = data.getBlobData(); Map<String, String> attributes; try (InputStream inputStream = blobData.getBlob().getInputStream()) { attributes = facet.extractComponentAttributesFromArchive(blobData.getBlobName(), inputStream); } return facet.getComponentQuery(attributes); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess,
final RepositoryManager repositoryManager,
final BlobStoreManager blobStoreManager,
final DryRunPrefix dryRunPrefix); }
|
@Test public void test() throws Exception { String unsafe = "<a href='javascript:alert('XSS')'>часто</a> используемый в печати и вэб-дизайне"; String safe = xssSanitizerService.sanitize(unsafe); Assertions.assertEquals("часто используемый в печати и вэб-дизайне", safe); }
|
public String sanitize(String html) { return policyFactory.sanitize( html, xssHtmlChangeListener, "ip='"+ getIpAddressFromRequestContext()+"'" ); }
|
XssSanitizerService { public String sanitize(String html) { return policyFactory.sanitize( html, xssHtmlChangeListener, "ip='"+ getIpAddressFromRequestContext()+"'" ); } }
|
XssSanitizerService { public String sanitize(String html) { return policyFactory.sanitize( html, xssHtmlChangeListener, "ip='"+ getIpAddressFromRequestContext()+"'" ); } }
|
XssSanitizerService { public String sanitize(String html) { return policyFactory.sanitize( html, xssHtmlChangeListener, "ip='"+ getIpAddressFromRequestContext()+"'" ); } String sanitize(String html); }
|
XssSanitizerService { public String sanitize(String html) { return policyFactory.sanitize( html, xssHtmlChangeListener, "ip='"+ getIpAddressFromRequestContext()+"'" ); } String sanitize(String html); }
|
@Test public void testNoClosed() throws Exception { String unsafe = "<a href='javascript:alert('XSS')'>часто используемый в печати и вэб-дизайне"; String safe = xssSanitizerService.sanitize(unsafe); Assertions.assertEquals("часто используемый в печати и вэб-дизайне", safe); }
|
public String sanitize(String html) { return policyFactory.sanitize( html, xssHtmlChangeListener, "ip='"+ getIpAddressFromRequestContext()+"'" ); }
|
XssSanitizerService { public String sanitize(String html) { return policyFactory.sanitize( html, xssHtmlChangeListener, "ip='"+ getIpAddressFromRequestContext()+"'" ); } }
|
XssSanitizerService { public String sanitize(String html) { return policyFactory.sanitize( html, xssHtmlChangeListener, "ip='"+ getIpAddressFromRequestContext()+"'" ); } }
|
XssSanitizerService { public String sanitize(String html) { return policyFactory.sanitize( html, xssHtmlChangeListener, "ip='"+ getIpAddressFromRequestContext()+"'" ); } String sanitize(String html); }
|
XssSanitizerService { public String sanitize(String html) { return policyFactory.sanitize( html, xssHtmlChangeListener, "ip='"+ getIpAddressFromRequestContext()+"'" ); } String sanitize(String html); }
|
@Test public void getConfig() throws Exception { mockMvc.perform( get(Constants.Urls.API+ Constants.Urls.CONFIG) .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE) ) .andExpect(status().isOk()) .andExpect(jsonPath("$.titleTemplate").value("%s | nkonev's blog")) .andExpect(jsonPath("$.header").value("Блог Конева Никиты")) .andExpect(jsonPath("$.canShowSettings").value(false)) .andExpect(jsonPath("$.removeImageBackground").doesNotExist()) .andReturn(); }
|
@GetMapping(API+CONFIG) public SettingsDTO getConfig(@AuthenticationPrincipal UserAccountDetailsDTO userAccount){ Iterable<RuntimeSettings> runtimeSettings = runtimeSettingsRepository.findAll(); SettingsDTO settingsDTOPartial = StreamSupport.stream(runtimeSettings.spliterator(), false) .reduce( new SettingsDTO(), (settingsDTO, runtimeSettings1) -> { if (runtimeSettings1.getKey() == null) { throw new RuntimeException("Null key is not supported"); } switch (runtimeSettings1.getKey()) { case IMAGE_BACKGROUND: settingsDTO.setImageBackground(runtimeSettings1.getValue()); break; case HEADER: settingsDTO.setHeader(runtimeSettings1.getValue()); break; case SUB_HEADER: settingsDTO.setSubHeader(runtimeSettings1.getValue()); break; case TITLE_TEMPLATE: settingsDTO.setTitleTemplate(runtimeSettings1.getValue()); break; case BACKGROUND_COLOR: settingsDTO.setBackgroundColor(runtimeSettings1.getValue()); break; default: LOGGER.warn("Unknown key " + runtimeSettings1.getKey()); } return settingsDTO; }, (settingsDTO, settingsDTO2) -> { throw new UnsupportedOperationException("Parallel is not supported");} ); boolean canShowSettings = blogSecurityService.hasSettingsPermission(userAccount); settingsDTOPartial.setCanShowSettings(canShowSettings); settingsDTOPartial.setCanShowApplications(applicationConfig.isEnableApplications()); settingsDTOPartial.setAvailableRoles(Arrays.asList(UserRole.ROLE_ADMIN, UserRole.ROLE_USER)); return settingsDTOPartial; }
|
SettingsController { @GetMapping(API+CONFIG) public SettingsDTO getConfig(@AuthenticationPrincipal UserAccountDetailsDTO userAccount){ Iterable<RuntimeSettings> runtimeSettings = runtimeSettingsRepository.findAll(); SettingsDTO settingsDTOPartial = StreamSupport.stream(runtimeSettings.spliterator(), false) .reduce( new SettingsDTO(), (settingsDTO, runtimeSettings1) -> { if (runtimeSettings1.getKey() == null) { throw new RuntimeException("Null key is not supported"); } switch (runtimeSettings1.getKey()) { case IMAGE_BACKGROUND: settingsDTO.setImageBackground(runtimeSettings1.getValue()); break; case HEADER: settingsDTO.setHeader(runtimeSettings1.getValue()); break; case SUB_HEADER: settingsDTO.setSubHeader(runtimeSettings1.getValue()); break; case TITLE_TEMPLATE: settingsDTO.setTitleTemplate(runtimeSettings1.getValue()); break; case BACKGROUND_COLOR: settingsDTO.setBackgroundColor(runtimeSettings1.getValue()); break; default: LOGGER.warn("Unknown key " + runtimeSettings1.getKey()); } return settingsDTO; }, (settingsDTO, settingsDTO2) -> { throw new UnsupportedOperationException("Parallel is not supported");} ); boolean canShowSettings = blogSecurityService.hasSettingsPermission(userAccount); settingsDTOPartial.setCanShowSettings(canShowSettings); settingsDTOPartial.setCanShowApplications(applicationConfig.isEnableApplications()); settingsDTOPartial.setAvailableRoles(Arrays.asList(UserRole.ROLE_ADMIN, UserRole.ROLE_USER)); return settingsDTOPartial; } }
|
SettingsController { @GetMapping(API+CONFIG) public SettingsDTO getConfig(@AuthenticationPrincipal UserAccountDetailsDTO userAccount){ Iterable<RuntimeSettings> runtimeSettings = runtimeSettingsRepository.findAll(); SettingsDTO settingsDTOPartial = StreamSupport.stream(runtimeSettings.spliterator(), false) .reduce( new SettingsDTO(), (settingsDTO, runtimeSettings1) -> { if (runtimeSettings1.getKey() == null) { throw new RuntimeException("Null key is not supported"); } switch (runtimeSettings1.getKey()) { case IMAGE_BACKGROUND: settingsDTO.setImageBackground(runtimeSettings1.getValue()); break; case HEADER: settingsDTO.setHeader(runtimeSettings1.getValue()); break; case SUB_HEADER: settingsDTO.setSubHeader(runtimeSettings1.getValue()); break; case TITLE_TEMPLATE: settingsDTO.setTitleTemplate(runtimeSettings1.getValue()); break; case BACKGROUND_COLOR: settingsDTO.setBackgroundColor(runtimeSettings1.getValue()); break; default: LOGGER.warn("Unknown key " + runtimeSettings1.getKey()); } return settingsDTO; }, (settingsDTO, settingsDTO2) -> { throw new UnsupportedOperationException("Parallel is not supported");} ); boolean canShowSettings = blogSecurityService.hasSettingsPermission(userAccount); settingsDTOPartial.setCanShowSettings(canShowSettings); settingsDTOPartial.setCanShowApplications(applicationConfig.isEnableApplications()); settingsDTOPartial.setAvailableRoles(Arrays.asList(UserRole.ROLE_ADMIN, UserRole.ROLE_USER)); return settingsDTOPartial; } }
|
SettingsController { @GetMapping(API+CONFIG) public SettingsDTO getConfig(@AuthenticationPrincipal UserAccountDetailsDTO userAccount){ Iterable<RuntimeSettings> runtimeSettings = runtimeSettingsRepository.findAll(); SettingsDTO settingsDTOPartial = StreamSupport.stream(runtimeSettings.spliterator(), false) .reduce( new SettingsDTO(), (settingsDTO, runtimeSettings1) -> { if (runtimeSettings1.getKey() == null) { throw new RuntimeException("Null key is not supported"); } switch (runtimeSettings1.getKey()) { case IMAGE_BACKGROUND: settingsDTO.setImageBackground(runtimeSettings1.getValue()); break; case HEADER: settingsDTO.setHeader(runtimeSettings1.getValue()); break; case SUB_HEADER: settingsDTO.setSubHeader(runtimeSettings1.getValue()); break; case TITLE_TEMPLATE: settingsDTO.setTitleTemplate(runtimeSettings1.getValue()); break; case BACKGROUND_COLOR: settingsDTO.setBackgroundColor(runtimeSettings1.getValue()); break; default: LOGGER.warn("Unknown key " + runtimeSettings1.getKey()); } return settingsDTO; }, (settingsDTO, settingsDTO2) -> { throw new UnsupportedOperationException("Parallel is not supported");} ); boolean canShowSettings = blogSecurityService.hasSettingsPermission(userAccount); settingsDTOPartial.setCanShowSettings(canShowSettings); settingsDTOPartial.setCanShowApplications(applicationConfig.isEnableApplications()); settingsDTOPartial.setAvailableRoles(Arrays.asList(UserRole.ROLE_ADMIN, UserRole.ROLE_USER)); return settingsDTOPartial; } @GetMapping(API+CONFIG) SettingsDTO getConfig(@AuthenticationPrincipal UserAccountDetailsDTO userAccount); @Transactional @PostMapping(value = API+CONFIG, consumes = {"multipart/form-data"}) @PreAuthorize("@blogSecurityService.hasSettingsPermission(#userAccount)") SettingsDTO putConfig(
@AuthenticationPrincipal UserAccountDetailsDTO userAccount,
@RequestPart(value = DTO_PART) SettingsDTO dto,
@RequestPart(value = IMAGE_PART, required = false) MultipartFile imagePart
); }
|
SettingsController { @GetMapping(API+CONFIG) public SettingsDTO getConfig(@AuthenticationPrincipal UserAccountDetailsDTO userAccount){ Iterable<RuntimeSettings> runtimeSettings = runtimeSettingsRepository.findAll(); SettingsDTO settingsDTOPartial = StreamSupport.stream(runtimeSettings.spliterator(), false) .reduce( new SettingsDTO(), (settingsDTO, runtimeSettings1) -> { if (runtimeSettings1.getKey() == null) { throw new RuntimeException("Null key is not supported"); } switch (runtimeSettings1.getKey()) { case IMAGE_BACKGROUND: settingsDTO.setImageBackground(runtimeSettings1.getValue()); break; case HEADER: settingsDTO.setHeader(runtimeSettings1.getValue()); break; case SUB_HEADER: settingsDTO.setSubHeader(runtimeSettings1.getValue()); break; case TITLE_TEMPLATE: settingsDTO.setTitleTemplate(runtimeSettings1.getValue()); break; case BACKGROUND_COLOR: settingsDTO.setBackgroundColor(runtimeSettings1.getValue()); break; default: LOGGER.warn("Unknown key " + runtimeSettings1.getKey()); } return settingsDTO; }, (settingsDTO, settingsDTO2) -> { throw new UnsupportedOperationException("Parallel is not supported");} ); boolean canShowSettings = blogSecurityService.hasSettingsPermission(userAccount); settingsDTOPartial.setCanShowSettings(canShowSettings); settingsDTOPartial.setCanShowApplications(applicationConfig.isEnableApplications()); settingsDTOPartial.setAvailableRoles(Arrays.asList(UserRole.ROLE_ADMIN, UserRole.ROLE_USER)); return settingsDTOPartial; } @GetMapping(API+CONFIG) SettingsDTO getConfig(@AuthenticationPrincipal UserAccountDetailsDTO userAccount); @Transactional @PostMapping(value = API+CONFIG, consumes = {"multipart/form-data"}) @PreAuthorize("@blogSecurityService.hasSettingsPermission(#userAccount)") SettingsDTO putConfig(
@AuthenticationPrincipal UserAccountDetailsDTO userAccount,
@RequestPart(value = DTO_PART) SettingsDTO dto,
@RequestPart(value = IMAGE_PART, required = false) MultipartFile imagePart
); static final String IMAGE_PART; static final String DTO_PART; static final String IMAGE_BACKGROUND; }
|
@WithUserDetails(TestConstants.USER_ADMIN) @Test public void testFulltextSearchHostPort() throws Exception { final String newPostRendered = "<body>Post Rendered</body>"; mockServer.expect(requestTo(new StringStartsWith(true, "http: .andExpect(method(HttpMethod.GET)) .andRespond(withSuccess(newPostRendered, MediaType.TEXT_HTML)); final String newIndexRendered = "<body>Index Rendered</body>"; mockServer.expect(requestTo("http: .andExpect(method(HttpMethod.GET)) .andRespond(withSuccess(newIndexRendered, MediaType.TEXT_HTML)); UserAccountDetailsDTO userAccountDetailsDTO = (UserAccountDetailsDTO) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); postController.updatePost(userAccountDetailsDTO, new PostDTO(50L, "edited for search host port", "A new host for test www.google.com:80 with port too", "", null, null, null, false, null)); MvcResult getPostsRequest = mockMvc.perform( get(Constants.Urls.API+ Constants.Urls.POST+"?searchString=www.google.com:80") .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE) ) .andDo( mvcResult -> { LOGGER.info(mvcResult.getResponse().getContentAsString()); } ) .andExpect(status().isOk()) .andExpect(jsonPath("$.data.size()").value(1)) .andExpect(jsonPath("$.data[0].title").value("edited for search host port")) .andExpect(jsonPath("$.data[0].text").value("A new host for test <b>www.google.com:80</b> with port too")) .andReturn(); }
|
@PreAuthorize("@blogSecurityService.hasPostPermission(#postDTO, #userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).EDIT)") @PutMapping(Constants.Urls.API + Constants.Urls.POST) public PostDTOWithAuthorization updatePost( @AuthenticationPrincipal UserAccountDetailsDTO userAccount, @RequestBody @NotNull PostDTO postDTO ) { return postService.updatePost(userAccount, postDTO); }
|
PostController { @PreAuthorize("@blogSecurityService.hasPostPermission(#postDTO, #userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).EDIT)") @PutMapping(Constants.Urls.API + Constants.Urls.POST) public PostDTOWithAuthorization updatePost( @AuthenticationPrincipal UserAccountDetailsDTO userAccount, @RequestBody @NotNull PostDTO postDTO ) { return postService.updatePost(userAccount, postDTO); } }
|
PostController { @PreAuthorize("@blogSecurityService.hasPostPermission(#postDTO, #userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).EDIT)") @PutMapping(Constants.Urls.API + Constants.Urls.POST) public PostDTOWithAuthorization updatePost( @AuthenticationPrincipal UserAccountDetailsDTO userAccount, @RequestBody @NotNull PostDTO postDTO ) { return postService.updatePost(userAccount, postDTO); } }
|
PostController { @PreAuthorize("@blogSecurityService.hasPostPermission(#postDTO, #userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).EDIT)") @PutMapping(Constants.Urls.API + Constants.Urls.POST) public PostDTOWithAuthorization updatePost( @AuthenticationPrincipal UserAccountDetailsDTO userAccount, @RequestBody @NotNull PostDTO postDTO ) { return postService.updatePost(userAccount, postDTO); } @GetMapping(Constants.Urls.API + Constants.Urls.POST) Wrapper<PostDTO> getPosts(
@RequestParam(value = "page", required = false, defaultValue = "0") int page,
@RequestParam(value = "size", required = false, defaultValue = "0") int size,
@RequestParam(value = "searchString", required = false, defaultValue = "") String searchString,
@AuthenticationPrincipal UserAccountDetailsDTO userAccount // null if not authenticated
); @GetMapping(Constants.Urls.API + Constants.Urls.POST + Constants.Urls.POST_ID) PostDTOExtended getPost(
@PathVariable(Constants.PathVariables.POST_ID) long id,
@AuthenticationPrincipal UserAccountDetailsDTO userAccount // null if not authenticated
); @PreAuthorize("@blogSecurityService.hasPostPermission(#userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).READ_MY)") @GetMapping(Constants.Urls.API + Constants.Urls.POST + Constants.Urls.MY) List<PostDTO> getMyPosts(
@AuthenticationPrincipal UserAccountDetailsDTO userAccount,
@RequestParam(value = "page", required = false, defaultValue = "0") int page,
@RequestParam(value = "size", required = false, defaultValue = "0") int size,
@RequestParam(value = "searchString", required = false, defaultValue = "") String searchString // TODO implement
); @PreAuthorize("@blogSecurityService.hasPostPermission(#userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).CREATE)") @PostMapping(Constants.Urls.API + Constants.Urls.POST) PostDTOWithAuthorization addPost(
@AuthenticationPrincipal UserAccountDetailsDTO userAccount, // null if not authenticated
@RequestBody @NotNull PostDTO postDTO
); @PreAuthorize("@blogSecurityService.hasPostPermission(#postDTO, #userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).EDIT)") @PutMapping(Constants.Urls.API + Constants.Urls.POST) PostDTOWithAuthorization updatePost(
@AuthenticationPrincipal UserAccountDetailsDTO userAccount, // null if not authenticated
@RequestBody @NotNull PostDTO postDTO
); @PreAuthorize("@blogSecurityService.hasPostPermission(#postId, #userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).DELETE)") @DeleteMapping(Constants.Urls.API + Constants.Urls.POST + Constants.Urls.POST_ID) void deletePost(
@AuthenticationPrincipal UserAccountDetailsDTO userAccount, // null if not authenticated
@PathVariable(Constants.PathVariables.POST_ID) long postId
); }
|
PostController { @PreAuthorize("@blogSecurityService.hasPostPermission(#postDTO, #userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).EDIT)") @PutMapping(Constants.Urls.API + Constants.Urls.POST) public PostDTOWithAuthorization updatePost( @AuthenticationPrincipal UserAccountDetailsDTO userAccount, @RequestBody @NotNull PostDTO postDTO ) { return postService.updatePost(userAccount, postDTO); } @GetMapping(Constants.Urls.API + Constants.Urls.POST) Wrapper<PostDTO> getPosts(
@RequestParam(value = "page", required = false, defaultValue = "0") int page,
@RequestParam(value = "size", required = false, defaultValue = "0") int size,
@RequestParam(value = "searchString", required = false, defaultValue = "") String searchString,
@AuthenticationPrincipal UserAccountDetailsDTO userAccount // null if not authenticated
); @GetMapping(Constants.Urls.API + Constants.Urls.POST + Constants.Urls.POST_ID) PostDTOExtended getPost(
@PathVariable(Constants.PathVariables.POST_ID) long id,
@AuthenticationPrincipal UserAccountDetailsDTO userAccount // null if not authenticated
); @PreAuthorize("@blogSecurityService.hasPostPermission(#userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).READ_MY)") @GetMapping(Constants.Urls.API + Constants.Urls.POST + Constants.Urls.MY) List<PostDTO> getMyPosts(
@AuthenticationPrincipal UserAccountDetailsDTO userAccount,
@RequestParam(value = "page", required = false, defaultValue = "0") int page,
@RequestParam(value = "size", required = false, defaultValue = "0") int size,
@RequestParam(value = "searchString", required = false, defaultValue = "") String searchString // TODO implement
); @PreAuthorize("@blogSecurityService.hasPostPermission(#userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).CREATE)") @PostMapping(Constants.Urls.API + Constants.Urls.POST) PostDTOWithAuthorization addPost(
@AuthenticationPrincipal UserAccountDetailsDTO userAccount, // null if not authenticated
@RequestBody @NotNull PostDTO postDTO
); @PreAuthorize("@blogSecurityService.hasPostPermission(#postDTO, #userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).EDIT)") @PutMapping(Constants.Urls.API + Constants.Urls.POST) PostDTOWithAuthorization updatePost(
@AuthenticationPrincipal UserAccountDetailsDTO userAccount, // null if not authenticated
@RequestBody @NotNull PostDTO postDTO
); @PreAuthorize("@blogSecurityService.hasPostPermission(#postId, #userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).DELETE)") @DeleteMapping(Constants.Urls.API + Constants.Urls.POST + Constants.Urls.POST_ID) void deletePost(
@AuthenticationPrincipal UserAccountDetailsDTO userAccount, // null if not authenticated
@PathVariable(Constants.PathVariables.POST_ID) long postId
); }
|
@Test public void testAnonymousCannotAddPostUnit() throws Exception { Assertions.assertThrows(AuthenticationCredentialsNotFoundException.class, () -> { postController.addPost(null, PostDtoBuilder.startBuilding().build()); }); }
|
@PreAuthorize("@blogSecurityService.hasPostPermission(#userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).CREATE)") @PostMapping(Constants.Urls.API + Constants.Urls.POST) public PostDTOWithAuthorization addPost( @AuthenticationPrincipal UserAccountDetailsDTO userAccount, @RequestBody @NotNull PostDTO postDTO ) { return postService.addPost(userAccount, postDTO); }
|
PostController { @PreAuthorize("@blogSecurityService.hasPostPermission(#userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).CREATE)") @PostMapping(Constants.Urls.API + Constants.Urls.POST) public PostDTOWithAuthorization addPost( @AuthenticationPrincipal UserAccountDetailsDTO userAccount, @RequestBody @NotNull PostDTO postDTO ) { return postService.addPost(userAccount, postDTO); } }
|
PostController { @PreAuthorize("@blogSecurityService.hasPostPermission(#userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).CREATE)") @PostMapping(Constants.Urls.API + Constants.Urls.POST) public PostDTOWithAuthorization addPost( @AuthenticationPrincipal UserAccountDetailsDTO userAccount, @RequestBody @NotNull PostDTO postDTO ) { return postService.addPost(userAccount, postDTO); } }
|
PostController { @PreAuthorize("@blogSecurityService.hasPostPermission(#userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).CREATE)") @PostMapping(Constants.Urls.API + Constants.Urls.POST) public PostDTOWithAuthorization addPost( @AuthenticationPrincipal UserAccountDetailsDTO userAccount, @RequestBody @NotNull PostDTO postDTO ) { return postService.addPost(userAccount, postDTO); } @GetMapping(Constants.Urls.API + Constants.Urls.POST) Wrapper<PostDTO> getPosts(
@RequestParam(value = "page", required = false, defaultValue = "0") int page,
@RequestParam(value = "size", required = false, defaultValue = "0") int size,
@RequestParam(value = "searchString", required = false, defaultValue = "") String searchString,
@AuthenticationPrincipal UserAccountDetailsDTO userAccount // null if not authenticated
); @GetMapping(Constants.Urls.API + Constants.Urls.POST + Constants.Urls.POST_ID) PostDTOExtended getPost(
@PathVariable(Constants.PathVariables.POST_ID) long id,
@AuthenticationPrincipal UserAccountDetailsDTO userAccount // null if not authenticated
); @PreAuthorize("@blogSecurityService.hasPostPermission(#userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).READ_MY)") @GetMapping(Constants.Urls.API + Constants.Urls.POST + Constants.Urls.MY) List<PostDTO> getMyPosts(
@AuthenticationPrincipal UserAccountDetailsDTO userAccount,
@RequestParam(value = "page", required = false, defaultValue = "0") int page,
@RequestParam(value = "size", required = false, defaultValue = "0") int size,
@RequestParam(value = "searchString", required = false, defaultValue = "") String searchString // TODO implement
); @PreAuthorize("@blogSecurityService.hasPostPermission(#userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).CREATE)") @PostMapping(Constants.Urls.API + Constants.Urls.POST) PostDTOWithAuthorization addPost(
@AuthenticationPrincipal UserAccountDetailsDTO userAccount, // null if not authenticated
@RequestBody @NotNull PostDTO postDTO
); @PreAuthorize("@blogSecurityService.hasPostPermission(#postDTO, #userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).EDIT)") @PutMapping(Constants.Urls.API + Constants.Urls.POST) PostDTOWithAuthorization updatePost(
@AuthenticationPrincipal UserAccountDetailsDTO userAccount, // null if not authenticated
@RequestBody @NotNull PostDTO postDTO
); @PreAuthorize("@blogSecurityService.hasPostPermission(#postId, #userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).DELETE)") @DeleteMapping(Constants.Urls.API + Constants.Urls.POST + Constants.Urls.POST_ID) void deletePost(
@AuthenticationPrincipal UserAccountDetailsDTO userAccount, // null if not authenticated
@PathVariable(Constants.PathVariables.POST_ID) long postId
); }
|
PostController { @PreAuthorize("@blogSecurityService.hasPostPermission(#userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).CREATE)") @PostMapping(Constants.Urls.API + Constants.Urls.POST) public PostDTOWithAuthorization addPost( @AuthenticationPrincipal UserAccountDetailsDTO userAccount, @RequestBody @NotNull PostDTO postDTO ) { return postService.addPost(userAccount, postDTO); } @GetMapping(Constants.Urls.API + Constants.Urls.POST) Wrapper<PostDTO> getPosts(
@RequestParam(value = "page", required = false, defaultValue = "0") int page,
@RequestParam(value = "size", required = false, defaultValue = "0") int size,
@RequestParam(value = "searchString", required = false, defaultValue = "") String searchString,
@AuthenticationPrincipal UserAccountDetailsDTO userAccount // null if not authenticated
); @GetMapping(Constants.Urls.API + Constants.Urls.POST + Constants.Urls.POST_ID) PostDTOExtended getPost(
@PathVariable(Constants.PathVariables.POST_ID) long id,
@AuthenticationPrincipal UserAccountDetailsDTO userAccount // null if not authenticated
); @PreAuthorize("@blogSecurityService.hasPostPermission(#userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).READ_MY)") @GetMapping(Constants.Urls.API + Constants.Urls.POST + Constants.Urls.MY) List<PostDTO> getMyPosts(
@AuthenticationPrincipal UserAccountDetailsDTO userAccount,
@RequestParam(value = "page", required = false, defaultValue = "0") int page,
@RequestParam(value = "size", required = false, defaultValue = "0") int size,
@RequestParam(value = "searchString", required = false, defaultValue = "") String searchString // TODO implement
); @PreAuthorize("@blogSecurityService.hasPostPermission(#userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).CREATE)") @PostMapping(Constants.Urls.API + Constants.Urls.POST) PostDTOWithAuthorization addPost(
@AuthenticationPrincipal UserAccountDetailsDTO userAccount, // null if not authenticated
@RequestBody @NotNull PostDTO postDTO
); @PreAuthorize("@blogSecurityService.hasPostPermission(#postDTO, #userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).EDIT)") @PutMapping(Constants.Urls.API + Constants.Urls.POST) PostDTOWithAuthorization updatePost(
@AuthenticationPrincipal UserAccountDetailsDTO userAccount, // null if not authenticated
@RequestBody @NotNull PostDTO postDTO
); @PreAuthorize("@blogSecurityService.hasPostPermission(#postId, #userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).DELETE)") @DeleteMapping(Constants.Urls.API + Constants.Urls.POST + Constants.Urls.POST_ID) void deletePost(
@AuthenticationPrincipal UserAccountDetailsDTO userAccount, // null if not authenticated
@PathVariable(Constants.PathVariables.POST_ID) long postId
); }
|
@Test public void testGetYouTubeId() { String youtubeVideoId = PostConverter.getYouTubeVideoId("https: Assertions.assertEquals("eoDsxos6xhM", youtubeVideoId); }
|
public static String getYouTubeVideoId(String iframeSrcUrl) { UriComponents build = UriComponentsBuilder.fromHttpUrl(iframeSrcUrl).build(); List<String> pathSegments = build.getPathSegments(); return pathSegments.get(pathSegments.size() - 1); }
|
PostConverter { public static String getYouTubeVideoId(String iframeSrcUrl) { UriComponents build = UriComponentsBuilder.fromHttpUrl(iframeSrcUrl).build(); List<String> pathSegments = build.getPathSegments(); return pathSegments.get(pathSegments.size() - 1); } }
|
PostConverter { public static String getYouTubeVideoId(String iframeSrcUrl) { UriComponents build = UriComponentsBuilder.fromHttpUrl(iframeSrcUrl).build(); List<String> pathSegments = build.getPathSegments(); return pathSegments.get(pathSegments.size() - 1); } }
|
PostConverter { public static String getYouTubeVideoId(String iframeSrcUrl) { UriComponents build = UriComponentsBuilder.fromHttpUrl(iframeSrcUrl).build(); List<String> pathSegments = build.getPathSegments(); return pathSegments.get(pathSegments.size() - 1); } PostDTOWithAuthorization convertToDto(Post saved, UserAccountDetailsDTO userAccount); Post convertToPost(PostDTO postDTO, Post forUpdate); static String getYouTubeVideoId(String iframeSrcUrl); IndexPost toElasticsearchPost(com.github.nkonev.blog.entity.jdbc.Post jpaPost); static void cleanTags(PostDTO postDTO); static String cleanHtmlTags(String html); PostDTO convertToPostDTO(Post post); }
|
PostConverter { public static String getYouTubeVideoId(String iframeSrcUrl) { UriComponents build = UriComponentsBuilder.fromHttpUrl(iframeSrcUrl).build(); List<String> pathSegments = build.getPathSegments(); return pathSegments.get(pathSegments.size() - 1); } PostDTOWithAuthorization convertToDto(Post saved, UserAccountDetailsDTO userAccount); Post convertToPost(PostDTO postDTO, Post forUpdate); static String getYouTubeVideoId(String iframeSrcUrl); IndexPost toElasticsearchPost(com.github.nkonev.blog.entity.jdbc.Post jpaPost); static void cleanTags(PostDTO postDTO); static String cleanHtmlTags(String html); PostDTO convertToPostDTO(Post post); }
|
@Test public void shouldSetFirstImgWhenTitleImgEmpty() { PostDTO postDTO = new PostDTO(); postDTO.setText("Hello, I contains images. This is first. <img src=\"http: postDTO.setTitle("Title"); String titleImg = postConverter.getTitleImg(postDTO); Assertions.assertEquals("http: }
|
String getTitleImg(PostDTO postDTO) { String titleImg = postDTO.getTitleImg(); if (setFirstImageAsTitle && StringUtils.isEmpty(titleImg)) { try { Document document = Jsoup.parse(postDTO.getText()); Elements images = document.getElementsByTag("img"); if (!images.isEmpty()) { Element element = images.get(0); return element.attr("src"); } Elements iframes = document.getElementsByTag("iframe"); if (!iframes.isEmpty()) { Element element = iframes.get(0); String iframeSrcUrl = element.attr("src"); if (iframeSrcUrl.contains("youtube.com")) { String youtubeVideoId = getYouTubeVideoId(iframeSrcUrl); String youtubeThumbnailUrl = youtubeThumbnailUrlTemplate.replace("__VIDEO_ID__", youtubeVideoId); return imageDownloader.downloadImageAndSave(youtubeThumbnailUrl, imagePostTitleUploadController); } } } catch (RuntimeException e) { if (LOGGER.isDebugEnabled()){ LOGGER.warn("Error during parse image from content: {}", e.getMessage(), e); } else { LOGGER.warn("Error during parse image from content: {}", e.getMessage()); } return null; } } return titleImg; }
|
PostConverter { String getTitleImg(PostDTO postDTO) { String titleImg = postDTO.getTitleImg(); if (setFirstImageAsTitle && StringUtils.isEmpty(titleImg)) { try { Document document = Jsoup.parse(postDTO.getText()); Elements images = document.getElementsByTag("img"); if (!images.isEmpty()) { Element element = images.get(0); return element.attr("src"); } Elements iframes = document.getElementsByTag("iframe"); if (!iframes.isEmpty()) { Element element = iframes.get(0); String iframeSrcUrl = element.attr("src"); if (iframeSrcUrl.contains("youtube.com")) { String youtubeVideoId = getYouTubeVideoId(iframeSrcUrl); String youtubeThumbnailUrl = youtubeThumbnailUrlTemplate.replace("__VIDEO_ID__", youtubeVideoId); return imageDownloader.downloadImageAndSave(youtubeThumbnailUrl, imagePostTitleUploadController); } } } catch (RuntimeException e) { if (LOGGER.isDebugEnabled()){ LOGGER.warn("Error during parse image from content: {}", e.getMessage(), e); } else { LOGGER.warn("Error during parse image from content: {}", e.getMessage()); } return null; } } return titleImg; } }
|
PostConverter { String getTitleImg(PostDTO postDTO) { String titleImg = postDTO.getTitleImg(); if (setFirstImageAsTitle && StringUtils.isEmpty(titleImg)) { try { Document document = Jsoup.parse(postDTO.getText()); Elements images = document.getElementsByTag("img"); if (!images.isEmpty()) { Element element = images.get(0); return element.attr("src"); } Elements iframes = document.getElementsByTag("iframe"); if (!iframes.isEmpty()) { Element element = iframes.get(0); String iframeSrcUrl = element.attr("src"); if (iframeSrcUrl.contains("youtube.com")) { String youtubeVideoId = getYouTubeVideoId(iframeSrcUrl); String youtubeThumbnailUrl = youtubeThumbnailUrlTemplate.replace("__VIDEO_ID__", youtubeVideoId); return imageDownloader.downloadImageAndSave(youtubeThumbnailUrl, imagePostTitleUploadController); } } } catch (RuntimeException e) { if (LOGGER.isDebugEnabled()){ LOGGER.warn("Error during parse image from content: {}", e.getMessage(), e); } else { LOGGER.warn("Error during parse image from content: {}", e.getMessage()); } return null; } } return titleImg; } }
|
PostConverter { String getTitleImg(PostDTO postDTO) { String titleImg = postDTO.getTitleImg(); if (setFirstImageAsTitle && StringUtils.isEmpty(titleImg)) { try { Document document = Jsoup.parse(postDTO.getText()); Elements images = document.getElementsByTag("img"); if (!images.isEmpty()) { Element element = images.get(0); return element.attr("src"); } Elements iframes = document.getElementsByTag("iframe"); if (!iframes.isEmpty()) { Element element = iframes.get(0); String iframeSrcUrl = element.attr("src"); if (iframeSrcUrl.contains("youtube.com")) { String youtubeVideoId = getYouTubeVideoId(iframeSrcUrl); String youtubeThumbnailUrl = youtubeThumbnailUrlTemplate.replace("__VIDEO_ID__", youtubeVideoId); return imageDownloader.downloadImageAndSave(youtubeThumbnailUrl, imagePostTitleUploadController); } } } catch (RuntimeException e) { if (LOGGER.isDebugEnabled()){ LOGGER.warn("Error during parse image from content: {}", e.getMessage(), e); } else { LOGGER.warn("Error during parse image from content: {}", e.getMessage()); } return null; } } return titleImg; } PostDTOWithAuthorization convertToDto(Post saved, UserAccountDetailsDTO userAccount); Post convertToPost(PostDTO postDTO, Post forUpdate); static String getYouTubeVideoId(String iframeSrcUrl); IndexPost toElasticsearchPost(com.github.nkonev.blog.entity.jdbc.Post jpaPost); static void cleanTags(PostDTO postDTO); static String cleanHtmlTags(String html); PostDTO convertToPostDTO(Post post); }
|
PostConverter { String getTitleImg(PostDTO postDTO) { String titleImg = postDTO.getTitleImg(); if (setFirstImageAsTitle && StringUtils.isEmpty(titleImg)) { try { Document document = Jsoup.parse(postDTO.getText()); Elements images = document.getElementsByTag("img"); if (!images.isEmpty()) { Element element = images.get(0); return element.attr("src"); } Elements iframes = document.getElementsByTag("iframe"); if (!iframes.isEmpty()) { Element element = iframes.get(0); String iframeSrcUrl = element.attr("src"); if (iframeSrcUrl.contains("youtube.com")) { String youtubeVideoId = getYouTubeVideoId(iframeSrcUrl); String youtubeThumbnailUrl = youtubeThumbnailUrlTemplate.replace("__VIDEO_ID__", youtubeVideoId); return imageDownloader.downloadImageAndSave(youtubeThumbnailUrl, imagePostTitleUploadController); } } } catch (RuntimeException e) { if (LOGGER.isDebugEnabled()){ LOGGER.warn("Error during parse image from content: {}", e.getMessage(), e); } else { LOGGER.warn("Error during parse image from content: {}", e.getMessage()); } return null; } } return titleImg; } PostDTOWithAuthorization convertToDto(Post saved, UserAccountDetailsDTO userAccount); Post convertToPost(PostDTO postDTO, Post forUpdate); static String getYouTubeVideoId(String iframeSrcUrl); IndexPost toElasticsearchPost(com.github.nkonev.blog.entity.jdbc.Post jpaPost); static void cleanTags(PostDTO postDTO); static String cleanHtmlTags(String html); PostDTO convertToPostDTO(Post post); }
|
@Test public void shouldDownloadYoutubePreviewWhenTitleImgEmptyAndContentHasNotImages() { PostDTO postDTO = new PostDTO(); postDTO.setText("Hello, I contains youtube videos. " + " This is first. <iframe allowfullscreen=\"true\" src=\"https: " This is second. <iframe allowfullscreen=\"true\" src=\"https: postDTO.setTitle("Title"); String titleImg = postConverter.getTitleImg(postDTO); Assertions.assertNotNull(titleImg); String imageId = titleImg .replace("/api/image/post/title/", "") .replace(".png", ""); Assertions.assertFalse(StringUtils.isEmpty(imageId)); Integer integer = jdbcTemplate.queryForObject("select count(*) from images.post_title_image where id = :id\\:\\:uuid", Map.of("id", imageId), Integer.class); Assertions.assertEquals(1, integer); }
|
String getTitleImg(PostDTO postDTO) { String titleImg = postDTO.getTitleImg(); if (setFirstImageAsTitle && StringUtils.isEmpty(titleImg)) { try { Document document = Jsoup.parse(postDTO.getText()); Elements images = document.getElementsByTag("img"); if (!images.isEmpty()) { Element element = images.get(0); return element.attr("src"); } Elements iframes = document.getElementsByTag("iframe"); if (!iframes.isEmpty()) { Element element = iframes.get(0); String iframeSrcUrl = element.attr("src"); if (iframeSrcUrl.contains("youtube.com")) { String youtubeVideoId = getYouTubeVideoId(iframeSrcUrl); String youtubeThumbnailUrl = youtubeThumbnailUrlTemplate.replace("__VIDEO_ID__", youtubeVideoId); return imageDownloader.downloadImageAndSave(youtubeThumbnailUrl, imagePostTitleUploadController); } } } catch (RuntimeException e) { if (LOGGER.isDebugEnabled()){ LOGGER.warn("Error during parse image from content: {}", e.getMessage(), e); } else { LOGGER.warn("Error during parse image from content: {}", e.getMessage()); } return null; } } return titleImg; }
|
PostConverter { String getTitleImg(PostDTO postDTO) { String titleImg = postDTO.getTitleImg(); if (setFirstImageAsTitle && StringUtils.isEmpty(titleImg)) { try { Document document = Jsoup.parse(postDTO.getText()); Elements images = document.getElementsByTag("img"); if (!images.isEmpty()) { Element element = images.get(0); return element.attr("src"); } Elements iframes = document.getElementsByTag("iframe"); if (!iframes.isEmpty()) { Element element = iframes.get(0); String iframeSrcUrl = element.attr("src"); if (iframeSrcUrl.contains("youtube.com")) { String youtubeVideoId = getYouTubeVideoId(iframeSrcUrl); String youtubeThumbnailUrl = youtubeThumbnailUrlTemplate.replace("__VIDEO_ID__", youtubeVideoId); return imageDownloader.downloadImageAndSave(youtubeThumbnailUrl, imagePostTitleUploadController); } } } catch (RuntimeException e) { if (LOGGER.isDebugEnabled()){ LOGGER.warn("Error during parse image from content: {}", e.getMessage(), e); } else { LOGGER.warn("Error during parse image from content: {}", e.getMessage()); } return null; } } return titleImg; } }
|
PostConverter { String getTitleImg(PostDTO postDTO) { String titleImg = postDTO.getTitleImg(); if (setFirstImageAsTitle && StringUtils.isEmpty(titleImg)) { try { Document document = Jsoup.parse(postDTO.getText()); Elements images = document.getElementsByTag("img"); if (!images.isEmpty()) { Element element = images.get(0); return element.attr("src"); } Elements iframes = document.getElementsByTag("iframe"); if (!iframes.isEmpty()) { Element element = iframes.get(0); String iframeSrcUrl = element.attr("src"); if (iframeSrcUrl.contains("youtube.com")) { String youtubeVideoId = getYouTubeVideoId(iframeSrcUrl); String youtubeThumbnailUrl = youtubeThumbnailUrlTemplate.replace("__VIDEO_ID__", youtubeVideoId); return imageDownloader.downloadImageAndSave(youtubeThumbnailUrl, imagePostTitleUploadController); } } } catch (RuntimeException e) { if (LOGGER.isDebugEnabled()){ LOGGER.warn("Error during parse image from content: {}", e.getMessage(), e); } else { LOGGER.warn("Error during parse image from content: {}", e.getMessage()); } return null; } } return titleImg; } }
|
PostConverter { String getTitleImg(PostDTO postDTO) { String titleImg = postDTO.getTitleImg(); if (setFirstImageAsTitle && StringUtils.isEmpty(titleImg)) { try { Document document = Jsoup.parse(postDTO.getText()); Elements images = document.getElementsByTag("img"); if (!images.isEmpty()) { Element element = images.get(0); return element.attr("src"); } Elements iframes = document.getElementsByTag("iframe"); if (!iframes.isEmpty()) { Element element = iframes.get(0); String iframeSrcUrl = element.attr("src"); if (iframeSrcUrl.contains("youtube.com")) { String youtubeVideoId = getYouTubeVideoId(iframeSrcUrl); String youtubeThumbnailUrl = youtubeThumbnailUrlTemplate.replace("__VIDEO_ID__", youtubeVideoId); return imageDownloader.downloadImageAndSave(youtubeThumbnailUrl, imagePostTitleUploadController); } } } catch (RuntimeException e) { if (LOGGER.isDebugEnabled()){ LOGGER.warn("Error during parse image from content: {}", e.getMessage(), e); } else { LOGGER.warn("Error during parse image from content: {}", e.getMessage()); } return null; } } return titleImg; } PostDTOWithAuthorization convertToDto(Post saved, UserAccountDetailsDTO userAccount); Post convertToPost(PostDTO postDTO, Post forUpdate); static String getYouTubeVideoId(String iframeSrcUrl); IndexPost toElasticsearchPost(com.github.nkonev.blog.entity.jdbc.Post jpaPost); static void cleanTags(PostDTO postDTO); static String cleanHtmlTags(String html); PostDTO convertToPostDTO(Post post); }
|
PostConverter { String getTitleImg(PostDTO postDTO) { String titleImg = postDTO.getTitleImg(); if (setFirstImageAsTitle && StringUtils.isEmpty(titleImg)) { try { Document document = Jsoup.parse(postDTO.getText()); Elements images = document.getElementsByTag("img"); if (!images.isEmpty()) { Element element = images.get(0); return element.attr("src"); } Elements iframes = document.getElementsByTag("iframe"); if (!iframes.isEmpty()) { Element element = iframes.get(0); String iframeSrcUrl = element.attr("src"); if (iframeSrcUrl.contains("youtube.com")) { String youtubeVideoId = getYouTubeVideoId(iframeSrcUrl); String youtubeThumbnailUrl = youtubeThumbnailUrlTemplate.replace("__VIDEO_ID__", youtubeVideoId); return imageDownloader.downloadImageAndSave(youtubeThumbnailUrl, imagePostTitleUploadController); } } } catch (RuntimeException e) { if (LOGGER.isDebugEnabled()){ LOGGER.warn("Error during parse image from content: {}", e.getMessage(), e); } else { LOGGER.warn("Error during parse image from content: {}", e.getMessage()); } return null; } } return titleImg; } PostDTOWithAuthorization convertToDto(Post saved, UserAccountDetailsDTO userAccount); Post convertToPost(PostDTO postDTO, Post forUpdate); static String getYouTubeVideoId(String iframeSrcUrl); IndexPost toElasticsearchPost(com.github.nkonev.blog.entity.jdbc.Post jpaPost); static void cleanTags(PostDTO postDTO); static String cleanHtmlTags(String html); PostDTO convertToPostDTO(Post post); }
|
@SuppressWarnings("unchecked") @Test public void getOrCreateContextDoesNotRegisterMultipleServletContextsForSameContextModelSingleThreaded() throws Exception { final JettyServerWrapper jettyServerWrapperUnderTest = new JettyServerWrapper( serverModelMock, new QueuedThreadPool()); try { jettyServerWrapperUnderTest.start(); HttpServiceContext context = jettyServerWrapperUnderTest.getOrCreateContext(contextModelMock); context.start(); context = jettyServerWrapperUnderTest.getOrCreateContext(contextModelMock); context.start(); verify(bundleContextMock, times(1)).registerService( same(ServletContext.class), any(ServletContext.class), any(Dictionary.class)); } finally { jettyServerWrapperUnderTest.stop(); } }
|
HttpServiceContext getOrCreateContext(final Model model) { return getOrCreateContext(model.getContextModel()); }
|
JettyServerWrapper extends Server { HttpServiceContext getOrCreateContext(final Model model) { return getOrCreateContext(model.getContextModel()); } }
|
JettyServerWrapper extends Server { HttpServiceContext getOrCreateContext(final Model model) { return getOrCreateContext(model.getContextModel()); } JettyServerWrapper(ServerModel serverModel, ThreadPool threadPool); }
|
JettyServerWrapper extends Server { HttpServiceContext getOrCreateContext(final Model model) { return getOrCreateContext(model.getContextModel()); } JettyServerWrapper(ServerModel serverModel, ThreadPool threadPool); HandlerCollection getRootHandlerCollection(); void configureContext(final Map<String, Object> attributes, final Integer timeout, final String cookie,
final String domain, final String path, final String url, final Boolean cookieHttpOnly,
final Boolean sessionCookieSecure, final String workerName, final Boolean lazy, final String directory,
Integer maxAge, final Boolean showStacks); void setServerConfigDir(File serverConfigDir); File getServerConfigDir(); URL getServerConfigURL(); void setServerConfigURL(URL serverConfigURL); String getDefaultAuthMethod(); void setDefaultAuthMethod(String defaultAuthMethod); String getDefaultRealmName(); void setDefaultRealmName(String defaultRealmName); }
|
JettyServerWrapper extends Server { HttpServiceContext getOrCreateContext(final Model model) { return getOrCreateContext(model.getContextModel()); } JettyServerWrapper(ServerModel serverModel, ThreadPool threadPool); HandlerCollection getRootHandlerCollection(); void configureContext(final Map<String, Object> attributes, final Integer timeout, final String cookie,
final String domain, final String path, final String url, final Boolean cookieHttpOnly,
final Boolean sessionCookieSecure, final String workerName, final Boolean lazy, final String directory,
Integer maxAge, final Boolean showStacks); void setServerConfigDir(File serverConfigDir); File getServerConfigDir(); URL getServerConfigURL(); void setServerConfigURL(URL serverConfigURL); String getDefaultAuthMethod(); void setDefaultAuthMethod(String defaultAuthMethod); String getDefaultRealmName(); void setDefaultRealmName(String defaultRealmName); }
|
@Test public void replaceSlashes07() { assertEquals("Replaced", "/foo/bar/car/", Path.replaceSlashes("/foo }
|
static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); static String normalizeResourcePath(final String path); static String getDirectParent(URL entry); }
|
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); static String normalizeResourcePath(final String path); static String getDirectParent(URL entry); }
|
@Test public void normalizeResourcePathSlash01() { assertEquals("Normalized", "/", Path.normalizeResourcePath("/")); }
|
public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; }
|
Path { public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; } }
|
Path { public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; } private Path(); }
|
Path { public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; } private Path(); static String normalizeResourcePath(final String path); static String getDirectParent(URL entry); }
|
Path { public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; } private Path(); static String normalizeResourcePath(final String path); static String getDirectParent(URL entry); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.