method2testcases
stringlengths 118
6.63k
|
---|
### Question:
AVFile { public AVFile() { super(); if (PaasClient.storageInstance().getDefaultACL() != null) { acl = new AVACL(PaasClient.storageInstance().getDefaultACL()); } } AVFile(); @Deprecated AVFile(byte[] data); AVFile(String name, String url, Map<String, Object> metaData); protected AVFile(String name, String url, Map<String, Object> metaData, boolean external); AVFile(String name, byte[] data); protected AVFile(String name, String url); static void setUploadHeader(String key, String value); String getObjectId(); void setObjectId(String objectId); @Deprecated static void parseFileWithObjectIdInBackground(final String objectId,
final GetFileCallback<AVFile> cb); static void withObjectIdInBackground(final String objectId,
final GetFileCallback<AVFile> cb); @Deprecated static AVFile parseFileWithObjectId(String objectId); static AVFile withObjectId(String objectId); @Deprecated static AVFile parseFileWithAVObject(AVObject obj); static AVFile withAVObject(AVObject obj); @Deprecated static AVFile parseFileWithAbsoluteLocalPath(String name, String absoluteLocalFilePath); static AVFile withAbsoluteLocalPath(String name, String absoluteLocalFilePath); @Deprecated static AVFile parseFileWithFile(String name, File file); static AVFile withFile(String name, File file); HashMap<String, Object> getMetaData(); Object addMetaData(String key, Object val); Object getMetaData(String key); int getSize(); String getOwnerObjectId(); Object removeMetaData(String key); void clearMetaData(); String getName(); String getOriginalName(); void setName(String name); static String getMimeType(String url); boolean isDirty(); @Deprecated boolean isDataAvailable(); String getUrl(); String getThumbnailUrl(boolean scaleToFit, int width, int height); String getThumbnailUrl(boolean scaleToFit, int width, int height, int quality, String fmt); void setUrl(String url); void save(); synchronized void saveInBackground(final SaveCallback saveCallback,
final ProgressCallback progressCallback); void saveInBackground(SaveCallback callback); void saveInBackground(); @Deprecated @JSONField(serialize = false) byte[] getData(); @JSONField(serialize = false) InputStream getDataStream(); void getDataInBackground(final GetDataCallback dataCallback,
final ProgressCallback progressCallback); void getDataInBackground(GetDataCallback dataCallback); void getDataStreamInBackground(GetDataStreamCallback callback); void getDataStreamInBackground(final GetDataStreamCallback callback, final ProgressCallback progressCallback); void cancel(); void delete(); void deleteEventually(); void deleteEventually(DeleteCallback callback); void deleteInBackground(); void deleteInBackground(DeleteCallback callback); static String className(); Uploader getUploader(SaveCallback saveCallback, ProgressCallback progressCallback); String getBucket(); void setBucket(String bucket); AVACL getACL(); void setACL(AVACL acl); void clearCachedFile(); static void clearAllCachedFiles(); static void clearCacheMoreThanDays(int days); static String DEFAULTMIMETYPE; static final String AVFILE_ENDPOINT; }### Answer:
@Test public void testAVFile() { AVFile file = new AVFile(); Assert.assertNotNull(file); } |
### Question:
AVFile { public void setObjectId(String objectId) { this.objectId = objectId; } AVFile(); @Deprecated AVFile(byte[] data); AVFile(String name, String url, Map<String, Object> metaData); protected AVFile(String name, String url, Map<String, Object> metaData, boolean external); AVFile(String name, byte[] data); protected AVFile(String name, String url); static void setUploadHeader(String key, String value); String getObjectId(); void setObjectId(String objectId); @Deprecated static void parseFileWithObjectIdInBackground(final String objectId,
final GetFileCallback<AVFile> cb); static void withObjectIdInBackground(final String objectId,
final GetFileCallback<AVFile> cb); @Deprecated static AVFile parseFileWithObjectId(String objectId); static AVFile withObjectId(String objectId); @Deprecated static AVFile parseFileWithAVObject(AVObject obj); static AVFile withAVObject(AVObject obj); @Deprecated static AVFile parseFileWithAbsoluteLocalPath(String name, String absoluteLocalFilePath); static AVFile withAbsoluteLocalPath(String name, String absoluteLocalFilePath); @Deprecated static AVFile parseFileWithFile(String name, File file); static AVFile withFile(String name, File file); HashMap<String, Object> getMetaData(); Object addMetaData(String key, Object val); Object getMetaData(String key); int getSize(); String getOwnerObjectId(); Object removeMetaData(String key); void clearMetaData(); String getName(); String getOriginalName(); void setName(String name); static String getMimeType(String url); boolean isDirty(); @Deprecated boolean isDataAvailable(); String getUrl(); String getThumbnailUrl(boolean scaleToFit, int width, int height); String getThumbnailUrl(boolean scaleToFit, int width, int height, int quality, String fmt); void setUrl(String url); void save(); synchronized void saveInBackground(final SaveCallback saveCallback,
final ProgressCallback progressCallback); void saveInBackground(SaveCallback callback); void saveInBackground(); @Deprecated @JSONField(serialize = false) byte[] getData(); @JSONField(serialize = false) InputStream getDataStream(); void getDataInBackground(final GetDataCallback dataCallback,
final ProgressCallback progressCallback); void getDataInBackground(GetDataCallback dataCallback); void getDataStreamInBackground(GetDataStreamCallback callback); void getDataStreamInBackground(final GetDataStreamCallback callback, final ProgressCallback progressCallback); void cancel(); void delete(); void deleteEventually(); void deleteEventually(DeleteCallback callback); void deleteInBackground(); void deleteInBackground(DeleteCallback callback); static String className(); Uploader getUploader(SaveCallback saveCallback, ProgressCallback progressCallback); String getBucket(); void setBucket(String bucket); AVACL getACL(); void setACL(AVACL acl); void clearCachedFile(); static void clearAllCachedFiles(); static void clearCacheMoreThanDays(int days); static String DEFAULTMIMETYPE; static final String AVFILE_ENDPOINT; }### Answer:
@Test public void testSetObjectId() { String objectId = "testObjectId"; AVFile file = new AVFile(); file.setObjectId(objectId); Assert.assertEquals(objectId, file.getObjectId()); } |
### Question:
AVFile { public Object addMetaData(String key, Object val) { return metaData.put(key, val); } AVFile(); @Deprecated AVFile(byte[] data); AVFile(String name, String url, Map<String, Object> metaData); protected AVFile(String name, String url, Map<String, Object> metaData, boolean external); AVFile(String name, byte[] data); protected AVFile(String name, String url); static void setUploadHeader(String key, String value); String getObjectId(); void setObjectId(String objectId); @Deprecated static void parseFileWithObjectIdInBackground(final String objectId,
final GetFileCallback<AVFile> cb); static void withObjectIdInBackground(final String objectId,
final GetFileCallback<AVFile> cb); @Deprecated static AVFile parseFileWithObjectId(String objectId); static AVFile withObjectId(String objectId); @Deprecated static AVFile parseFileWithAVObject(AVObject obj); static AVFile withAVObject(AVObject obj); @Deprecated static AVFile parseFileWithAbsoluteLocalPath(String name, String absoluteLocalFilePath); static AVFile withAbsoluteLocalPath(String name, String absoluteLocalFilePath); @Deprecated static AVFile parseFileWithFile(String name, File file); static AVFile withFile(String name, File file); HashMap<String, Object> getMetaData(); Object addMetaData(String key, Object val); Object getMetaData(String key); int getSize(); String getOwnerObjectId(); Object removeMetaData(String key); void clearMetaData(); String getName(); String getOriginalName(); void setName(String name); static String getMimeType(String url); boolean isDirty(); @Deprecated boolean isDataAvailable(); String getUrl(); String getThumbnailUrl(boolean scaleToFit, int width, int height); String getThumbnailUrl(boolean scaleToFit, int width, int height, int quality, String fmt); void setUrl(String url); void save(); synchronized void saveInBackground(final SaveCallback saveCallback,
final ProgressCallback progressCallback); void saveInBackground(SaveCallback callback); void saveInBackground(); @Deprecated @JSONField(serialize = false) byte[] getData(); @JSONField(serialize = false) InputStream getDataStream(); void getDataInBackground(final GetDataCallback dataCallback,
final ProgressCallback progressCallback); void getDataInBackground(GetDataCallback dataCallback); void getDataStreamInBackground(GetDataStreamCallback callback); void getDataStreamInBackground(final GetDataStreamCallback callback, final ProgressCallback progressCallback); void cancel(); void delete(); void deleteEventually(); void deleteEventually(DeleteCallback callback); void deleteInBackground(); void deleteInBackground(DeleteCallback callback); static String className(); Uploader getUploader(SaveCallback saveCallback, ProgressCallback progressCallback); String getBucket(); void setBucket(String bucket); AVACL getACL(); void setACL(AVACL acl); void clearCachedFile(); static void clearAllCachedFiles(); static void clearCacheMoreThanDays(int days); static String DEFAULTMIMETYPE; static final String AVFILE_ENDPOINT; }### Answer:
@Test public void testAddMetaData() { AVFile file = new AVFile(); file.addMetaData("key", "value"); Assert.assertEquals(file.getMetaData("key"), "value"); } |
### Question:
AVFile { public HashMap<String, Object> getMetaData() { return metaData; } AVFile(); @Deprecated AVFile(byte[] data); AVFile(String name, String url, Map<String, Object> metaData); protected AVFile(String name, String url, Map<String, Object> metaData, boolean external); AVFile(String name, byte[] data); protected AVFile(String name, String url); static void setUploadHeader(String key, String value); String getObjectId(); void setObjectId(String objectId); @Deprecated static void parseFileWithObjectIdInBackground(final String objectId,
final GetFileCallback<AVFile> cb); static void withObjectIdInBackground(final String objectId,
final GetFileCallback<AVFile> cb); @Deprecated static AVFile parseFileWithObjectId(String objectId); static AVFile withObjectId(String objectId); @Deprecated static AVFile parseFileWithAVObject(AVObject obj); static AVFile withAVObject(AVObject obj); @Deprecated static AVFile parseFileWithAbsoluteLocalPath(String name, String absoluteLocalFilePath); static AVFile withAbsoluteLocalPath(String name, String absoluteLocalFilePath); @Deprecated static AVFile parseFileWithFile(String name, File file); static AVFile withFile(String name, File file); HashMap<String, Object> getMetaData(); Object addMetaData(String key, Object val); Object getMetaData(String key); int getSize(); String getOwnerObjectId(); Object removeMetaData(String key); void clearMetaData(); String getName(); String getOriginalName(); void setName(String name); static String getMimeType(String url); boolean isDirty(); @Deprecated boolean isDataAvailable(); String getUrl(); String getThumbnailUrl(boolean scaleToFit, int width, int height); String getThumbnailUrl(boolean scaleToFit, int width, int height, int quality, String fmt); void setUrl(String url); void save(); synchronized void saveInBackground(final SaveCallback saveCallback,
final ProgressCallback progressCallback); void saveInBackground(SaveCallback callback); void saveInBackground(); @Deprecated @JSONField(serialize = false) byte[] getData(); @JSONField(serialize = false) InputStream getDataStream(); void getDataInBackground(final GetDataCallback dataCallback,
final ProgressCallback progressCallback); void getDataInBackground(GetDataCallback dataCallback); void getDataStreamInBackground(GetDataStreamCallback callback); void getDataStreamInBackground(final GetDataStreamCallback callback, final ProgressCallback progressCallback); void cancel(); void delete(); void deleteEventually(); void deleteEventually(DeleteCallback callback); void deleteInBackground(); void deleteInBackground(DeleteCallback callback); static String className(); Uploader getUploader(SaveCallback saveCallback, ProgressCallback progressCallback); String getBucket(); void setBucket(String bucket); AVACL getACL(); void setACL(AVACL acl); void clearCachedFile(); static void clearAllCachedFiles(); static void clearCacheMoreThanDays(int days); static String DEFAULTMIMETYPE; static final String AVFILE_ENDPOINT; }### Answer:
@Test public void testGetMetaData() { AVFile file = new AVFile("name", TEST_FILE_CONTENT.getBytes()); Assert.assertNotNull(file.getMetaData()); } |
### Question:
AVFile { public int getSize() { Number size = (Number) getMetaData("size"); if (size != null) return size.intValue(); else return -1; } AVFile(); @Deprecated AVFile(byte[] data); AVFile(String name, String url, Map<String, Object> metaData); protected AVFile(String name, String url, Map<String, Object> metaData, boolean external); AVFile(String name, byte[] data); protected AVFile(String name, String url); static void setUploadHeader(String key, String value); String getObjectId(); void setObjectId(String objectId); @Deprecated static void parseFileWithObjectIdInBackground(final String objectId,
final GetFileCallback<AVFile> cb); static void withObjectIdInBackground(final String objectId,
final GetFileCallback<AVFile> cb); @Deprecated static AVFile parseFileWithObjectId(String objectId); static AVFile withObjectId(String objectId); @Deprecated static AVFile parseFileWithAVObject(AVObject obj); static AVFile withAVObject(AVObject obj); @Deprecated static AVFile parseFileWithAbsoluteLocalPath(String name, String absoluteLocalFilePath); static AVFile withAbsoluteLocalPath(String name, String absoluteLocalFilePath); @Deprecated static AVFile parseFileWithFile(String name, File file); static AVFile withFile(String name, File file); HashMap<String, Object> getMetaData(); Object addMetaData(String key, Object val); Object getMetaData(String key); int getSize(); String getOwnerObjectId(); Object removeMetaData(String key); void clearMetaData(); String getName(); String getOriginalName(); void setName(String name); static String getMimeType(String url); boolean isDirty(); @Deprecated boolean isDataAvailable(); String getUrl(); String getThumbnailUrl(boolean scaleToFit, int width, int height); String getThumbnailUrl(boolean scaleToFit, int width, int height, int quality, String fmt); void setUrl(String url); void save(); synchronized void saveInBackground(final SaveCallback saveCallback,
final ProgressCallback progressCallback); void saveInBackground(SaveCallback callback); void saveInBackground(); @Deprecated @JSONField(serialize = false) byte[] getData(); @JSONField(serialize = false) InputStream getDataStream(); void getDataInBackground(final GetDataCallback dataCallback,
final ProgressCallback progressCallback); void getDataInBackground(GetDataCallback dataCallback); void getDataStreamInBackground(GetDataStreamCallback callback); void getDataStreamInBackground(final GetDataStreamCallback callback, final ProgressCallback progressCallback); void cancel(); void delete(); void deleteEventually(); void deleteEventually(DeleteCallback callback); void deleteInBackground(); void deleteInBackground(DeleteCallback callback); static String className(); Uploader getUploader(SaveCallback saveCallback, ProgressCallback progressCallback); String getBucket(); void setBucket(String bucket); AVACL getACL(); void setACL(AVACL acl); void clearCachedFile(); static void clearAllCachedFiles(); static void clearCacheMoreThanDays(int days); static String DEFAULTMIMETYPE; static final String AVFILE_ENDPOINT; }### Answer:
@Test public void testGetSize() { AVFile file = new AVFile("name", TEST_FILE_CONTENT.getBytes()); Assert.assertEquals(file.getSize(), TEST_FILE_CONTENT.length()); } |
### Question:
SnackbarAdapter extends RecyclerView.Adapter<SnackbarAdapter.ViewHolder> { public boolean isEmpty() { return mSnackbarViews == null || mSnackbarViews.size() == 0; } @Override ViewHolder onCreateViewHolder(ViewGroup parent, int position); @Override void onBindViewHolder(ViewHolder holder, int position); @Override int getItemViewType(int position); @Override int getItemCount(); boolean isEmpty(); synchronized void addItem(SnackbarView item); synchronized void removeItem(SnackbarView view); SnackbarView getSnackbarView(int index); }### Answer:
@Test public void testZeroAdapterSize(){ Assert.assertTrue(mAdapter.isEmpty()); } |
### Question:
SnackbarAdapter extends RecyclerView.Adapter<SnackbarAdapter.ViewHolder> { @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int position) { View view = mSnackbarViews.get(position).onCreateView(parent); ViewHolder viewHolder = new ViewHolder(view); return viewHolder; } @Override ViewHolder onCreateViewHolder(ViewGroup parent, int position); @Override void onBindViewHolder(ViewHolder holder, int position); @Override int getItemViewType(int position); @Override int getItemCount(); boolean isEmpty(); synchronized void addItem(SnackbarView item); synchronized void removeItem(SnackbarView view); SnackbarView getSnackbarView(int index); }### Answer:
@Test public void testOnCreateViewHolder() throws Exception { mAdapter.addItem(viewMock); PowerMockito.whenNew(SnackbarAdapter.ViewHolder.class).withAnyArguments().thenReturn(mViewHolder); mAdapter.onCreateViewHolder(null, 0); Mockito.verify(viewMock, Mockito.times(1)).onCreateView(null); } |
### Question:
SnackbarAdapter extends RecyclerView.Adapter<SnackbarAdapter.ViewHolder> { @Override public void onBindViewHolder(ViewHolder holder, int position) { SnackbarView snackbarView = mSnackbarViews.get(position); if (snackbarView != null) { snackbarView.onBindView(); } } @Override ViewHolder onCreateViewHolder(ViewGroup parent, int position); @Override void onBindViewHolder(ViewHolder holder, int position); @Override int getItemViewType(int position); @Override int getItemCount(); boolean isEmpty(); synchronized void addItem(SnackbarView item); synchronized void removeItem(SnackbarView view); SnackbarView getSnackbarView(int index); }### Answer:
@Test public void testOnBindViewHolder() throws Exception{ mAdapter.addItem(viewMock); PowerMockito.whenNew(SnackbarAdapter.ViewHolder.class).withAnyArguments().thenReturn(mViewHolder); mAdapter.onCreateViewHolder(null, 0); mAdapter.onBindViewHolder(mViewHolder,0); Mockito.verify(viewMock, Mockito.times(1)).onBindView(); } |
### Question:
SnackbarAdapter extends RecyclerView.Adapter<SnackbarAdapter.ViewHolder> { public synchronized void addItem(SnackbarView item) { mSnackbarViews.add(item); int position = mSnackbarViews.indexOf(item); notifyItemInserted(position); } @Override ViewHolder onCreateViewHolder(ViewGroup parent, int position); @Override void onBindViewHolder(ViewHolder holder, int position); @Override int getItemViewType(int position); @Override int getItemCount(); boolean isEmpty(); synchronized void addItem(SnackbarView item); synchronized void removeItem(SnackbarView view); SnackbarView getSnackbarView(int index); }### Answer:
@Test public void testAddItem(){ mAdapter.addItem(viewMock); Assert.assertEquals(mAdapter.getItemCount(),1); } |
### Question:
SnackbarAdapter extends RecyclerView.Adapter<SnackbarAdapter.ViewHolder> { public synchronized void removeItem(SnackbarView view) { int position = mSnackbarViews.indexOf(view); if (position > -1) { mSnackbarViews.remove(position); notifyItemRemoved(position); } } @Override ViewHolder onCreateViewHolder(ViewGroup parent, int position); @Override void onBindViewHolder(ViewHolder holder, int position); @Override int getItemViewType(int position); @Override int getItemCount(); boolean isEmpty(); synchronized void addItem(SnackbarView item); synchronized void removeItem(SnackbarView view); SnackbarView getSnackbarView(int index); }### Answer:
@Test public void testRemoveItem(){ mAdapter.addItem(viewMock); Assert.assertEquals(mAdapter.getItemCount(),1); mAdapter.removeItem(viewMock); Assert.assertEquals(mAdapter.getItemCount(),0); } |
### Question:
NumberInterval { @Override public boolean equals(Object obj) { if (!(obj instanceof NumberInterval)) { return false; } NumberInterval rhs = (NumberInterval) obj; return Objects.equals(low, rhs.low) && Objects.equals(high, rhs.high); } NumberInterval(); NumberInterval(NumberIntervalBoundary low, NumberIntervalBoundary high); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); void validate(); boolean overlaps(NumberInterval rhs); boolean doesNotOverlap(NumberInterval rhs); boolean contains(Double value); NumberIntervalBoundary getLow(); void setLow(NumberIntervalBoundary low); NumberIntervalBoundary getHigh(); void setHigh(NumberIntervalBoundary high); }### Answer:
@Test public void testEqualsNotEqualToNull() { Object rhs = null; NumberInterval instance = new NumberInterval(); assertFalse(instance.equals(rhs)); }
@Test public void testEqualsNotEqualToOtherClasses() { Object rhs = new Object(); NumberInterval instance = new NumberInterval(); assertFalse(instance.equals(rhs)); }
@Test public void testEquals() { NumberInterval rhs = new NumberInterval(); rhs.setLow(new NumberIntervalBoundary(0.0)); rhs.setHigh(new NumberIntervalBoundary(10.0)); NumberInterval instance = new NumberInterval(); instance.setLow(new NumberIntervalBoundary(0.0)); instance.setHigh(new NumberIntervalBoundary(10.0)); assertTrue(instance.equals(rhs)); } |
### Question:
NumberInterval { public void validate() throws BadValueException { if (low == null) { throw new BadValueException("NumberInterval.low is required"); } if (high == null) { throw new BadValueException("NumberInterval.high is required"); } low.validate(); high.validate(); int compareLowHigh = low.compareBoundaryTo(high); if (compareLowHigh > 0) { throw new BadValueException("NumberInterval.low > NumberInterval.high"); } if (compareLowHigh == 0 && (!low.isInclusive() || !high.isInclusive())) { throw new BadValueException("NumberInterval: when low = high both ends must be inclusive"); } } NumberInterval(); NumberInterval(NumberIntervalBoundary low, NumberIntervalBoundary high); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); void validate(); boolean overlaps(NumberInterval rhs); boolean doesNotOverlap(NumberInterval rhs); boolean contains(Double value); NumberIntervalBoundary getLow(); void setLow(NumberIntervalBoundary low); NumberIntervalBoundary getHigh(); void setHigh(NumberIntervalBoundary high); }### Answer:
@Test public void testValidateLowAndHighEqual() throws Exception { NumberInterval instance = new NumberInterval( new NumberIntervalBoundary(10.0, true), new NumberIntervalBoundary(10.0, true) ); instance.validate(); }
@Test public void testValidateInfinity() throws Exception { NumberInterval instance = new NumberInterval( NumberIntervalBoundary.NEGATIVE_INFINITY, NumberIntervalBoundary.POSITIVE_INFINITY ); instance.validate(); }
@Test public void testValidateLowInfinity() throws Exception { NumberInterval instance = new NumberInterval( NumberIntervalBoundary.NEGATIVE_INFINITY, new NumberIntervalBoundary(10.0, true) ); instance.validate(); }
@Test public void testValidateHighInfinity() throws Exception { NumberInterval instance = new NumberInterval( new NumberIntervalBoundary(10.0, true), NumberIntervalBoundary.POSITIVE_INFINITY ); instance.validate(); }
@Test public void testValidate() throws Exception { NumberInterval instance = new NumberInterval( new NumberIntervalBoundary(-10.0), new NumberIntervalBoundary(10.0, false) ); instance.validate(); }
@Test(expected = BadValueException.class) public void testValidateNoBoundaries() throws Exception { NumberInterval instance = new NumberInterval(); instance.validate(); }
@Test(expected = BadValueException.class) public void testValidateNoLow() throws Exception { NumberInterval instance = new NumberInterval(null, NumberIntervalBoundary.POSITIVE_INFINITY); instance.validate(); }
@Test(expected = BadValueException.class) public void testValidateNoHigh() throws Exception { NumberInterval instance = new NumberInterval(NumberIntervalBoundary.NEGATIVE_INFINITY, null); instance.validate(); }
@Test(expected = BadValueException.class) public void testValidateHighLessThanLow() throws Exception { NumberInterval instance = new NumberInterval( new NumberIntervalBoundary(10.0), new NumberIntervalBoundary(0.0) ); instance.validate(); }
@Test(expected = BadValueException.class) public void testValidateLowAndHighEqualLowNotInclusive() throws Exception { NumberInterval instance = new NumberInterval( new NumberIntervalBoundary(10.0), new NumberIntervalBoundary(10.0, true) ); instance.validate(); }
@Test(expected = BadValueException.class) public void testValidateLowAndHighEqualHighNotInclusive() throws Exception { NumberInterval instance = new NumberInterval( new NumberIntervalBoundary(10.0, true), new NumberIntervalBoundary(10.0, false) ); instance.validate(); } |
### Question:
NumberInterval { public boolean overlaps(NumberInterval rhs) { return !doesNotOverlap(rhs); } NumberInterval(); NumberInterval(NumberIntervalBoundary low, NumberIntervalBoundary high); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); void validate(); boolean overlaps(NumberInterval rhs); boolean doesNotOverlap(NumberInterval rhs); boolean contains(Double value); NumberIntervalBoundary getLow(); void setLow(NumberIntervalBoundary low); NumberIntervalBoundary getHigh(); void setHigh(NumberIntervalBoundary high); }### Answer:
@Test public void testOverlaps() { NumberInterval lhs; NumberInterval rhs; lhs = new NumberInterval( new NumberIntervalBoundary(-10.0), new NumberIntervalBoundary(10.0) ); testOverlapCommon(lhs); rhs = new NumberInterval( NumberIntervalBoundary.NEGATIVE_INFINITY, new NumberIntervalBoundary(-10.0, true) ); assertDontOverlap(lhs, rhs); rhs = new NumberInterval( new NumberIntervalBoundary(10.0, true), NumberIntervalBoundary.POSITIVE_INFINITY ); assertDontOverlap(lhs, rhs); lhs = new NumberInterval( new NumberIntervalBoundary(-10.0, true), new NumberIntervalBoundary(10.0) ); testOverlapCommon(lhs); rhs = new NumberInterval( NumberIntervalBoundary.NEGATIVE_INFINITY, new NumberIntervalBoundary(-10.0, true) ); assertOverlap(lhs, rhs); rhs = new NumberInterval( new NumberIntervalBoundary(10.0, true), NumberIntervalBoundary.POSITIVE_INFINITY ); assertDontOverlap(lhs, rhs); lhs = new NumberInterval( new NumberIntervalBoundary(-10.0), new NumberIntervalBoundary(10.0, true) ); testOverlapCommon(lhs); rhs = new NumberInterval( NumberIntervalBoundary.NEGATIVE_INFINITY, new NumberIntervalBoundary(-10.0, true) ); assertDontOverlap(lhs, rhs); rhs = new NumberInterval( new NumberIntervalBoundary(10.0, true), NumberIntervalBoundary.POSITIVE_INFINITY ); assertOverlap(lhs, rhs); lhs = new NumberInterval( new NumberIntervalBoundary(-10.0, true), new NumberIntervalBoundary(10.0, true) ); testOverlapCommon(lhs); rhs = new NumberInterval( NumberIntervalBoundary.NEGATIVE_INFINITY, new NumberIntervalBoundary(-10.0, true) ); assertOverlap(lhs, rhs); rhs = new NumberInterval( new NumberIntervalBoundary(10.0, true), NumberIntervalBoundary.POSITIVE_INFINITY ); assertOverlap(lhs, rhs); } |
### Question:
NumberAttributeDomainDto extends AttributeDomainDto { @Override public void validate() throws BadValueException { if (intervals == null) { return; } for (NumberInterval interval : intervals) { interval.validate(); } int size = intervals.size(); int count = 0; for (NumberInterval interval : intervals) { validateNoOverlap(interval, intervals.subList(++count, size)); } } NumberAttributeDomainDto(); NumberAttributeDomainDto(List<NumberInterval> intervals); @Override boolean equals(Object obj); @Override int hashCode(); @Override AttributeType getType(); @Override void accept(AttributeDomainDtoVisitor visitor); @Override void validate(); List<NumberInterval> getIntervals(); void setIntervals(List<NumberInterval> intervals); }### Answer:
@Test public void testValidateNoIntervals() throws Exception { NumberAttributeDomainDto instance = new NumberAttributeDomainDto(); instance.validate(); }
@Test public void testValidateEmptyIntervals() throws Exception { NumberAttributeDomainDto instance = new NumberAttributeDomainDto(Arrays.asList()); instance.validate(); }
@Test(expected = BadValueException.class) public void testValidateBadInterval() throws Exception { NumberAttributeDomainDto instance = new NumberAttributeDomainDto(Arrays.asList( new NumberInterval() )); instance.validate(); }
@Test public void testValidateSingle() throws Exception { NumberAttributeDomainDto instance = new NumberAttributeDomainDto(Arrays.asList( new NumberInterval( NumberIntervalBoundary.NEGATIVE_INFINITY, NumberIntervalBoundary.POSITIVE_INFINITY ) )); instance.validate(); }
@Test(expected = BadValueException.class) public void testValidateOverlap() throws Exception { NumberAttributeDomainDto instance = new NumberAttributeDomainDto(Arrays.asList( new NumberInterval( NumberIntervalBoundary.NEGATIVE_INFINITY, NumberIntervalBoundary.POSITIVE_INFINITY ), new NumberInterval( new NumberIntervalBoundary(10.0, true), new NumberIntervalBoundary(10.0, true) ) )); instance.validate(); }
@Test(expected = BadValueException.class) public void testValidateOverlapSwapped() throws Exception { NumberAttributeDomainDto instance = new NumberAttributeDomainDto(Arrays.asList( new NumberInterval( new NumberIntervalBoundary(10.0, true), new NumberIntervalBoundary(10.0, true) ), new NumberInterval( NumberIntervalBoundary.NEGATIVE_INFINITY, NumberIntervalBoundary.POSITIVE_INFINITY ) )); instance.validate(); }
@Test public void testValidateTwo() throws Exception { NumberAttributeDomainDto instance = new NumberAttributeDomainDto(Arrays.asList( new NumberInterval( new NumberIntervalBoundary(10.0, true), new NumberIntervalBoundary(10.0, true) ), new NumberInterval( new NumberIntervalBoundary(10.0, false), new NumberIntervalBoundary(20.0, true) ) )); instance.validate(); }
@Test public void testValidateTwoSwapped() throws Exception { NumberAttributeDomainDto instance = new NumberAttributeDomainDto(Arrays.asList( new NumberInterval( new NumberIntervalBoundary(10.0, false), new NumberIntervalBoundary(20.0, true) ), new NumberInterval( new NumberIntervalBoundary(10.0, true), new NumberIntervalBoundary(10.0, true) ) )); instance.validate(); } |
### Question:
StringAttributeDomainDto extends AttributeDomainDto { @Override public void validate() throws BadValueException { if (regex == null) { return; } try { Pattern.compile(regex); } catch (PatternSyntaxException ex) { throw new BadValueException("Invalid regex: " + ex.getMessage(), ex); } } StringAttributeDomainDto(); StringAttributeDomainDto(String regex); @Override AttributeType getType(); @Override void accept(AttributeDomainDtoVisitor visitor); @Override void validate(); String getRegex(); void setRegex(String regex); }### Answer:
@Test public void testValidateNoRegex() throws BadValueException { StringAttributeDomainDto instance = new StringAttributeDomainDto(); instance.validate(); }
@Test public void testValidateEmptyRegex() throws BadValueException { StringAttributeDomainDto instance = new StringAttributeDomainDto(""); instance.validate(); }
@Test(expected = PatternSyntaxException.class) public void testValidateBadRegex() throws BadValueException, Throwable { StringAttributeDomainDto instance = new StringAttributeDomainDto("["); try { instance.validate(); } catch (BadValueException ex) { if (ex.getCause() instanceof PatternSyntaxException) { throw ex.getCause(); } throw ex; } }
@Test public void testValidateRegex() throws BadValueException { StringAttributeDomainDto instance = new StringAttributeDomainDto("prefix-[0-9]+"); instance.validate(); } |
### Question:
NumberIntervalBoundary { @Override public boolean equals(Object obj) { if (!(obj instanceof NumberIntervalBoundary)) { return false; } NumberIntervalBoundary rhs = (NumberIntervalBoundary) obj; return Objects.equals(boundary, rhs.boundary) && (isInclusive() == rhs.isInclusive()); } NumberIntervalBoundary(); NumberIntervalBoundary(Double boundary); NumberIntervalBoundary(Double boundary, Boolean inclusive); @Override boolean equals(Object obj); @Override int hashCode(); int compareBoundaryTo(NumberIntervalBoundary rhs); void validate(); Double getBoundary(); void setBoundary(Double boundary); @JsonIgnore boolean isInclusive(); Boolean getInclusive(); void setInclusive(Boolean inclusive); static NumberIntervalBoundary POSITIVE_INFINITY; static NumberIntervalBoundary NEGATIVE_INFINITY; }### Answer:
@Test public void testNotEqualToNull() { Object rhs = null; NumberIntervalBoundary instance = new NumberIntervalBoundary(); assertFalse(instance.equals(rhs)); }
@Test public void testNotEqualToOtherClasses() { Object rhs = new Object(); NumberIntervalBoundary instance = new NumberIntervalBoundary(); assertFalse(instance.equals(rhs)); }
@Test public void testNotEqualToDifferentBoundarySameInclusion() { NumberIntervalBoundary rhs = new NumberIntervalBoundary(10.0); NumberIntervalBoundary instance = new NumberIntervalBoundary(11.0); assertFalse(instance.equals(rhs)); }
@Test public void testNotEqualToSameBoundaryDifferentInclusion() { NumberIntervalBoundary rhs = new NumberIntervalBoundary(10.0, true); NumberIntervalBoundary instance = new NumberIntervalBoundary(10.0, false); assertFalse(instance.equals(rhs)); }
@Test public void testNotEqualToDifferentBoundaryDifferentInclusion() { NumberIntervalBoundary rhs = new NumberIntervalBoundary(10.0, true); NumberIntervalBoundary instance = new NumberIntervalBoundary(12.0, null); assertFalse(instance.equals(rhs)); }
@Test public void testEquals() { NumberIntervalBoundary rhs = new NumberIntervalBoundary(10.0, true); NumberIntervalBoundary instance = new NumberIntervalBoundary(10.0, true); assertTrue(instance.equals(rhs)); } |
### Question:
NumberIntervalBoundary { @Override public int hashCode() { return Objects.hash(this.boundary, isInclusive() ? Boolean.TRUE : Boolean.FALSE); } NumberIntervalBoundary(); NumberIntervalBoundary(Double boundary); NumberIntervalBoundary(Double boundary, Boolean inclusive); @Override boolean equals(Object obj); @Override int hashCode(); int compareBoundaryTo(NumberIntervalBoundary rhs); void validate(); Double getBoundary(); void setBoundary(Double boundary); @JsonIgnore boolean isInclusive(); Boolean getInclusive(); void setInclusive(Boolean inclusive); static NumberIntervalBoundary POSITIVE_INFINITY; static NumberIntervalBoundary NEGATIVE_INFINITY; }### Answer:
@Test public void testHashCodeForEqualInstances() { int lhs = new NumberIntervalBoundary(1.1, Boolean.FALSE).hashCode(); int rhs = new NumberIntervalBoundary(1.1, Boolean.FALSE).hashCode(); assertEquals(lhs, rhs); } |
### Question:
NumberIntervalBoundary { @JsonIgnore public boolean isInclusive() { return inclusive != null && inclusive; } NumberIntervalBoundary(); NumberIntervalBoundary(Double boundary); NumberIntervalBoundary(Double boundary, Boolean inclusive); @Override boolean equals(Object obj); @Override int hashCode(); int compareBoundaryTo(NumberIntervalBoundary rhs); void validate(); Double getBoundary(); void setBoundary(Double boundary); @JsonIgnore boolean isInclusive(); Boolean getInclusive(); void setInclusive(Boolean inclusive); static NumberIntervalBoundary POSITIVE_INFINITY; static NumberIntervalBoundary NEGATIVE_INFINITY; }### Answer:
@Test public void testNotIsInclusiveByDefault() { NumberIntervalBoundary instance = new NumberIntervalBoundary(); assertFalse(instance.isInclusive()); }
@Test public void testNotIsInclusiveWhenConstructedWithFalse() { NumberIntervalBoundary instance = new NumberIntervalBoundary(0.0, false); assertFalse(instance.isInclusive()); }
@Test public void testNotIsInclusiveWhenConstructedWithNull() { NumberIntervalBoundary instance = new NumberIntervalBoundary(0.0, null); assertFalse(instance.isInclusive()); }
@Test public void testIsInclusiveWhenConstructedWithTrue() { NumberIntervalBoundary instance = new NumberIntervalBoundary(0.0, true); assertTrue(instance.isInclusive()); } |
### Question:
NumberIntervalBoundary { public int compareBoundaryTo(NumberIntervalBoundary rhs) { return boundary.compareTo(rhs.getBoundary()); } NumberIntervalBoundary(); NumberIntervalBoundary(Double boundary); NumberIntervalBoundary(Double boundary, Boolean inclusive); @Override boolean equals(Object obj); @Override int hashCode(); int compareBoundaryTo(NumberIntervalBoundary rhs); void validate(); Double getBoundary(); void setBoundary(Double boundary); @JsonIgnore boolean isInclusive(); Boolean getInclusive(); void setInclusive(Boolean inclusive); static NumberIntervalBoundary POSITIVE_INFINITY; static NumberIntervalBoundary NEGATIVE_INFINITY; }### Answer:
@Test public void testCompareBoundaryTo() { NumberIntervalBoundary instance = new NumberIntervalBoundary(0.0); assertThat(instance.compareBoundaryTo(new NumberIntervalBoundary(0.0)), comparesEqualTo(0)); assertThat(instance.compareBoundaryTo(new NumberIntervalBoundary(-5.0)), greaterThan(0)); assertThat(instance.compareBoundaryTo(NumberIntervalBoundary.NEGATIVE_INFINITY), greaterThan(0)); assertThat(instance.compareBoundaryTo(new NumberIntervalBoundary(5.0)), lessThan(0)); assertThat(instance.compareBoundaryTo(NumberIntervalBoundary.POSITIVE_INFINITY), lessThan(0)); } |
### Question:
NumberInterval { @Override public String toString() { return lowToString() + ", " + highToString(); } NumberInterval(); NumberInterval(NumberIntervalBoundary low, NumberIntervalBoundary high); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); void validate(); boolean overlaps(NumberInterval rhs); boolean doesNotOverlap(NumberInterval rhs); boolean contains(Double value); NumberIntervalBoundary getLow(); void setLow(NumberIntervalBoundary low); NumberIntervalBoundary getHigh(); void setHigh(NumberIntervalBoundary high); }### Answer:
@Test public void testToString() { NumberInterval instance; instance = new NumberInterval(); assertEquals("null, null", instance.toString()); instance = new NumberInterval( NumberIntervalBoundary.NEGATIVE_INFINITY, NumberIntervalBoundary.POSITIVE_INFINITY); assertEquals("(-Infinity, Infinity)", instance.toString()); instance = new NumberInterval( new NumberIntervalBoundary(0.0, true), new NumberIntervalBoundary(10.3, false)); assertEquals("[0.0, 10.3)", instance.toString()); instance = new NumberInterval( new NumberIntervalBoundary(0.0, null), new NumberIntervalBoundary(10.3, true)); assertEquals("(0.0, 10.3]", instance.toString()); } |
### Question:
NumberIntervalBoundary { public void validate() throws BadValueException { if (boundary == null) { throw new BadValueException("NumberIntervalBoundary.boundary is required"); } } NumberIntervalBoundary(); NumberIntervalBoundary(Double boundary); NumberIntervalBoundary(Double boundary, Boolean inclusive); @Override boolean equals(Object obj); @Override int hashCode(); int compareBoundaryTo(NumberIntervalBoundary rhs); void validate(); Double getBoundary(); void setBoundary(Double boundary); @JsonIgnore boolean isInclusive(); Boolean getInclusive(); void setInclusive(Boolean inclusive); static NumberIntervalBoundary POSITIVE_INFINITY; static NumberIntervalBoundary NEGATIVE_INFINITY; }### Answer:
@Test public void testValidateValid() throws Exception { NumberIntervalBoundary instance = new NumberIntervalBoundary(0.0); instance.validate(); }
@Test(expected = BadValueException.class) public void testValidateInvalid() throws Exception { NumberIntervalBoundary instance = new NumberIntervalBoundary(); instance.validate(); } |
### Question:
ThreadPoolKiller { public static void shutdown(ExecutorService threadPool, String name) { shutdown(threadPool, name, DEFAULT_WAIT_DOWN_SECONDS); } static void shutdown(ExecutorService threadPool, String name); static void shutdown(ExecutorService threadPool, String name, long waitSeconds); static final long DEFAULT_WAIT_DOWN_SECONDS; }### Answer:
@Test public void testCleanShutdown() throws InterruptedException { final int wait = 1; ExecutorService threadPool = mock(ExecutorService.class); when(threadPool.awaitTermination(wait, TimeUnit.SECONDS)).thenReturn(true); ThreadPoolKiller.shutdown(threadPool, "TestPool", wait); verify(threadPool).shutdown(); verify(threadPool).awaitTermination(wait, TimeUnit.SECONDS); }
@Test public void testForcedShutdown() throws InterruptedException { final int wait = 1; ExecutorService threadPool = mock(ExecutorService.class); when(threadPool.awaitTermination(wait, TimeUnit.SECONDS)).thenReturn(false).thenReturn(true); ThreadPoolKiller.shutdown(threadPool, "TestPool", wait); verify(threadPool).shutdown(); verify(threadPool, times(2)).awaitTermination(wait, TimeUnit.SECONDS); verify(threadPool).shutdownNow(); verifyNoMoreInteractions(threadPool); }
@Test public void testForcedShutdownTimesOut() throws InterruptedException { final int wait = 1; ExecutorService threadPool = mock(ExecutorService.class); when(threadPool.awaitTermination(wait, TimeUnit.SECONDS)).thenReturn(false).thenReturn(false); ThreadPoolKiller.shutdown(threadPool, "TestPool", wait); verify(threadPool).shutdown(); verify(threadPool, times(2)).awaitTermination(wait, TimeUnit.SECONDS); verify(threadPool).shutdownNow(); verifyNoMoreInteractions(threadPool); }
@Test public void testShutdownInterrupted() throws InterruptedException { final int wait = 1; ExecutorService threadPool = mock(ExecutorService.class); when(threadPool.awaitTermination(wait, TimeUnit.SECONDS)).thenThrow(InterruptedException.class); ThreadPoolKiller.shutdown(threadPool, "TestPool", wait); verify(threadPool).shutdown(); verify(threadPool).awaitTermination(wait, TimeUnit.SECONDS); verifyNoMoreInteractions(threadPool); }
@Test public void testShutdownDefaultTimeout() throws InterruptedException { final long wait = ThreadPoolKiller.DEFAULT_WAIT_DOWN_SECONDS; ExecutorService threadPool = mock(ExecutorService.class); when(threadPool.awaitTermination(wait, TimeUnit.SECONDS)).thenReturn(true); ThreadPoolKiller.shutdown(threadPool, "TestPool"); verify(threadPool).shutdown(); verify(threadPool).awaitTermination(wait, TimeUnit.SECONDS); verifyNoMoreInteractions(threadPool); } |
### Question:
AgentServiceClient extends ServiceClientBase<AgentDto, ApiObjectRef> implements AgentService { @Override public ApiObjectRef create(CreateAgentArg createArg, String routerRef) throws CommsRouterException { return post(createArg, routerRef); } @Inject AgentServiceClient(Client client, String endpoint, String routerRef); @Override ApiObjectRef create(CreateAgentArg createArg, String routerRef); @Override ApiObjectRef replace(CreateAgentArg createArg, RouterObjectRef objectRef); @Override void update(UpdateAgentArg updateArg, RouterObjectRef objectRef); @Override AgentDto get(RouterObjectRef routerObjectRef); @Override PaginatedList<AgentDto> list(PagingRequest request); @Override void delete(RouterObjectRef routerObjectRef); }### Answer:
@Test public void create() throws Exception { String agentRef = UUID.randomUUID().toString(); stubFor(post(urlEqualTo("/api/routers/" + routerRef + "/agents")) .withHeader("Accept", equalTo("application/json")) .willReturn(aResponse() .withStatus(201) .withHeader("Content-Type", "application/json") .withBody("{\"ref\":\"" + agentRef + "\"}"))); CreateAgentArg createArg = new CreateAgentArg(); createArg.setAddress("sip:someone@somesip.pip"); ApiObjectRef apiObjectId = serviceClient.create(createArg, routerRef); LOGGER.debug("apiObjectId: {}", apiObjectId); assertEquals("agentRef", agentRef, apiObjectId.getRef()); } |
### Question:
AgentServiceClient extends ServiceClientBase<AgentDto, ApiObjectRef> implements AgentService { @Override public ApiObjectRef replace(CreateAgentArg createArg, RouterObjectRef objectRef) throws CommsRouterException { return put(createArg, objectRef); } @Inject AgentServiceClient(Client client, String endpoint, String routerRef); @Override ApiObjectRef create(CreateAgentArg createArg, String routerRef); @Override ApiObjectRef replace(CreateAgentArg createArg, RouterObjectRef objectRef); @Override void update(UpdateAgentArg updateArg, RouterObjectRef objectRef); @Override AgentDto get(RouterObjectRef routerObjectRef); @Override PaginatedList<AgentDto> list(PagingRequest request); @Override void delete(RouterObjectRef routerObjectRef); }### Answer:
@Test public void createWithId() throws Exception { String agentRef = UUID.randomUUID().toString(); stubFor(put(urlEqualTo("/api/routers/" + routerRef + "/agents/" + agentRef)) .withHeader("Accept", equalTo("application/json")) .willReturn(aResponse() .withStatus(201) .withHeader("Content-Type", "application/json") .withBody("{\"ref\":\"" + agentRef + "\"}"))); CreateAgentArg createArg = new CreateAgentArg(); createArg.setAddress("sip:someone@somesip.pip"); ApiObjectRef apiObjectRef = serviceClient.replace(createArg, new RouterObjectRef(agentRef, routerRef)); LOGGER.debug("apiObjectId: {}", apiObjectRef); assertEquals("agentRef", agentRef, apiObjectRef.getRef()); } |
### Question:
AgentServiceClient extends ServiceClientBase<AgentDto, ApiObjectRef> implements AgentService { @Override public void update(UpdateAgentArg updateArg, RouterObjectRef objectRef) throws CommsRouterException { post(updateArg, objectRef); } @Inject AgentServiceClient(Client client, String endpoint, String routerRef); @Override ApiObjectRef create(CreateAgentArg createArg, String routerRef); @Override ApiObjectRef replace(CreateAgentArg createArg, RouterObjectRef objectRef); @Override void update(UpdateAgentArg updateArg, RouterObjectRef objectRef); @Override AgentDto get(RouterObjectRef routerObjectRef); @Override PaginatedList<AgentDto> list(PagingRequest request); @Override void delete(RouterObjectRef routerObjectRef); }### Answer:
@Test public void update() throws Exception { String agentId = UUID.randomUUID().toString(); stubFor(put(urlEqualTo("/api/routers/" + routerRef + "/agents/" + agentId)) .withHeader("Accept", equalTo("application/json")) .willReturn(aResponse() .withStatus(204) .withHeader("Content-Type", "application/json"))); UpdateAgentArg updateAgentArg = new UpdateAgentArg(); updateAgentArg.setAddress("sip:someone@somesip.pip"); serviceClient.update(updateAgentArg, new RouterObjectRef(agentId, routerRef)); } |
### Question:
AgentServiceClient extends ServiceClientBase<AgentDto, ApiObjectRef> implements AgentService { @Override public AgentDto get(RouterObjectRef routerObjectRef) throws CommsRouterException { return getItem(routerObjectRef); } @Inject AgentServiceClient(Client client, String endpoint, String routerRef); @Override ApiObjectRef create(CreateAgentArg createArg, String routerRef); @Override ApiObjectRef replace(CreateAgentArg createArg, RouterObjectRef objectRef); @Override void update(UpdateAgentArg updateArg, RouterObjectRef objectRef); @Override AgentDto get(RouterObjectRef routerObjectRef); @Override PaginatedList<AgentDto> list(PagingRequest request); @Override void delete(RouterObjectRef routerObjectRef); }### Answer:
@Test public void get() throws Exception { String agentId = UUID.randomUUID().toString(); AgentDto agent = new AgentDto(); agent.setAddress("sip:someone@somesip.pip"); stubFor(WireMock.get(urlEqualTo("/api/routers/" + routerRef + "/agents/" + agentId)) .withHeader("Accept", equalTo("application/json")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(objectMapper.writeValueAsString(agent)))); AgentDto agentDto = serviceClient.get(new RouterObjectRef(agentId, routerRef)); assertNotNull("agent is found", agentDto); assertEquals("address matches", agent.getAddress(), agentDto.getAddress()); } |
### Question:
AgentServiceClient extends ServiceClientBase<AgentDto, ApiObjectRef> implements AgentService { @Override public PaginatedList<AgentDto> list(PagingRequest request) throws CommsRouterException { PagingRequest pagingRequest = new PagingRequest( routerRef, request.getToken(), request.getPerPage(), request.getSort(), request.getQuery()); return getList(pagingRequest, new GenericType<List<AgentDto>>() {}); } @Inject AgentServiceClient(Client client, String endpoint, String routerRef); @Override ApiObjectRef create(CreateAgentArg createArg, String routerRef); @Override ApiObjectRef replace(CreateAgentArg createArg, RouterObjectRef objectRef); @Override void update(UpdateAgentArg updateArg, RouterObjectRef objectRef); @Override AgentDto get(RouterObjectRef routerObjectRef); @Override PaginatedList<AgentDto> list(PagingRequest request); @Override void delete(RouterObjectRef routerObjectRef); }### Answer:
@Test public void list() throws Exception { } |
### Question:
AgentServiceClient extends ServiceClientBase<AgentDto, ApiObjectRef> implements AgentService { @Override public void delete(RouterObjectRef routerObjectRef) { routerObjectRef.setRouterRef(routerRef); deleteRequest(routerObjectRef); } @Inject AgentServiceClient(Client client, String endpoint, String routerRef); @Override ApiObjectRef create(CreateAgentArg createArg, String routerRef); @Override ApiObjectRef replace(CreateAgentArg createArg, RouterObjectRef objectRef); @Override void update(UpdateAgentArg updateArg, RouterObjectRef objectRef); @Override AgentDto get(RouterObjectRef routerObjectRef); @Override PaginatedList<AgentDto> list(PagingRequest request); @Override void delete(RouterObjectRef routerObjectRef); }### Answer:
@Test public void delete() throws Exception { String agentRef = UUID.randomUUID().toString(); stubFor(WireMock.delete(urlEqualTo("/api/routers/" + routerRef + "/agents/" + agentRef)) .withHeader("Accept", equalTo("application/json")) .willReturn(aResponse() .withStatus(204) .withHeader("Content-Type", "application/json"))); serviceClient.delete(new RouterObjectRef(agentRef, routerRef)); } |
### Question:
ConfigurationImpl implements Configuration { @Override public JWTAuthMethod getJwtAuthMethod() { return jwtAuthMethod; } @Inject ConfigurationImpl(ConfigurationProperties properties); @Override JWTAuthMethod getJwtAuthMethod(); @Override Endpoint getAssociatedPhone(); @Override String getCallbackBaseUrl(); @Override String getNexmoCallbackBaseUrl(); @Override String getCommsApiEndpoint(); @Override String getCommsRouterId(); @Override String getMusicOnHoldUrl(); @Override String getCommsQueueId(); @Override String getCommsPlanId(); }### Answer:
@Test public void getJwtAuthMethod() throws Exception { assertNotNull("JWT is not null", configuration.getJwtAuthMethod()); } |
### Question:
ConfigurationImpl implements Configuration { @Override public Endpoint getAssociatedPhone() { return phoneEndpoint; } @Inject ConfigurationImpl(ConfigurationProperties properties); @Override JWTAuthMethod getJwtAuthMethod(); @Override Endpoint getAssociatedPhone(); @Override String getCallbackBaseUrl(); @Override String getNexmoCallbackBaseUrl(); @Override String getCommsApiEndpoint(); @Override String getCommsRouterId(); @Override String getMusicOnHoldUrl(); @Override String getCommsQueueId(); @Override String getCommsPlanId(); }### Answer:
@Test public void getAssociatedPhone() throws Exception { assertEquals("Phone equals", "17072158889", configuration.getAssociatedPhone().toLog()); } |
### Question:
ConfigurationImpl implements Configuration { @Override public String getCallbackBaseUrl() { return callbackBaseUrl; } @Inject ConfigurationImpl(ConfigurationProperties properties); @Override JWTAuthMethod getJwtAuthMethod(); @Override Endpoint getAssociatedPhone(); @Override String getCallbackBaseUrl(); @Override String getNexmoCallbackBaseUrl(); @Override String getCommsApiEndpoint(); @Override String getCommsRouterId(); @Override String getMusicOnHoldUrl(); @Override String getCommsQueueId(); @Override String getCommsPlanId(); }### Answer:
@Test public void getCallbackBaseUrl() throws Exception { assertEquals("Url equals", "https: } |
### Question:
Cfg4jConfiguration implements ConfigurationProperties { @Override public String callbackBaseUrl() { return provider.getProperty("app.callbackBaseUrl", String.class); } Cfg4jConfiguration(); @Override String callbackBaseUrl(); @Override String nexmoCallbackBaseUrl(); @Override String phone(); @Override String commsRouterUrl(); @Override String commsRouterId(); @Override String appId(); @Override String appPrivateKey(); @Override String musicOnHoldUrl(); @Override String commsQueueId(); @Override String commsPlanId(); }### Answer:
@Test public void getCallbackBaseUrl() throws Exception { assertEquals("Url equals", "https: } |
### Question:
Cfg4jConfiguration implements ConfigurationProperties { @Override public String phone() { return provider.getProperty("app.phone", String.class); } Cfg4jConfiguration(); @Override String callbackBaseUrl(); @Override String nexmoCallbackBaseUrl(); @Override String phone(); @Override String commsRouterUrl(); @Override String commsRouterId(); @Override String appId(); @Override String appPrivateKey(); @Override String musicOnHoldUrl(); @Override String commsQueueId(); @Override String commsPlanId(); }### Answer:
@Test public void getPhone() throws Exception { assertEquals("Phone equals", "17072158889", configuration.phone()); } |
### Question:
Cfg4jConfiguration implements ConfigurationProperties { @Override public String appId() { return provider.getProperty("nexmo.appId", String.class); } Cfg4jConfiguration(); @Override String callbackBaseUrl(); @Override String nexmoCallbackBaseUrl(); @Override String phone(); @Override String commsRouterUrl(); @Override String commsRouterId(); @Override String appId(); @Override String appPrivateKey(); @Override String musicOnHoldUrl(); @Override String commsQueueId(); @Override String commsPlanId(); }### Answer:
@Test public void getAppId() throws Exception { assertEquals("App Id equals", "some-app-id", configuration.appId()); } |
### Question:
Cfg4jConfiguration implements ConfigurationProperties { @Override public String appPrivateKey() { return provider.getProperty("nexmo.appPrivateKey", String.class); } Cfg4jConfiguration(); @Override String callbackBaseUrl(); @Override String nexmoCallbackBaseUrl(); @Override String phone(); @Override String commsRouterUrl(); @Override String commsRouterId(); @Override String appId(); @Override String appPrivateKey(); @Override String musicOnHoldUrl(); @Override String commsQueueId(); @Override String commsPlanId(); }### Answer:
@Test public void getPrivateKey() throws Exception { assertNotNull("JWT is not null", configuration.appPrivateKey()); } |
### Question:
PropertiesConfiguration implements ConfigurationProperties { @Override public String callbackBaseUrl() { return properties.getProperty(CALLBACK_BASE_URL); } PropertiesConfiguration(); @Override String callbackBaseUrl(); @Override String nexmoCallbackBaseUrl(); @Override String phone(); @Override String commsRouterUrl(); @Override String commsRouterId(); @Override String appId(); @Override String appPrivateKey(); @Override String musicOnHoldUrl(); @Override String commsQueueId(); @Override String commsPlanId(); }### Answer:
@Test public void getCallbackBaseUrl() throws Exception { assertEquals("Url equals", "https: } |
### Question:
PropertiesConfiguration implements ConfigurationProperties { @Override public String phone() { return properties.getProperty(APP_PHONE); } PropertiesConfiguration(); @Override String callbackBaseUrl(); @Override String nexmoCallbackBaseUrl(); @Override String phone(); @Override String commsRouterUrl(); @Override String commsRouterId(); @Override String appId(); @Override String appPrivateKey(); @Override String musicOnHoldUrl(); @Override String commsQueueId(); @Override String commsPlanId(); }### Answer:
@Test public void getPhone() throws Exception { assertEquals("Phone equals", "17072158889", configuration.phone()); } |
### Question:
PropertiesConfiguration implements ConfigurationProperties { @Override public String appId() { return properties.getProperty(NEXMO_APP_ID); } PropertiesConfiguration(); @Override String callbackBaseUrl(); @Override String nexmoCallbackBaseUrl(); @Override String phone(); @Override String commsRouterUrl(); @Override String commsRouterId(); @Override String appId(); @Override String appPrivateKey(); @Override String musicOnHoldUrl(); @Override String commsQueueId(); @Override String commsPlanId(); }### Answer:
@Test public void getAppId() throws Exception { assertEquals("App Id equals", "some-app-id", configuration.appId()); } |
### Question:
PropertiesConfiguration implements ConfigurationProperties { @Override public String appPrivateKey() { return properties.getProperty(NEXMO_APP_PRIVATE_KEY); } PropertiesConfiguration(); @Override String callbackBaseUrl(); @Override String nexmoCallbackBaseUrl(); @Override String phone(); @Override String commsRouterUrl(); @Override String commsRouterId(); @Override String appId(); @Override String appPrivateKey(); @Override String musicOnHoldUrl(); @Override String commsQueueId(); @Override String commsPlanId(); }### Answer:
@Test public void getPrivateKey() throws Exception { assertNotNull("JWT is not null", configuration.appPrivateKey()); } |
### Question:
JEvalEvaluator implements CommsRouterEvaluator { @Override public void validate() throws ExpressionException { long millis = System.currentTimeMillis(); evaluator.validateImpl(); LOGGER.trace("Predicate expression validation time is: {}", (System.currentTimeMillis() - millis)); } JEvalEvaluator(CommsRouterEvaluatorFactory factory, String predicate); @Override CommsRouterEvaluator changeExpression(String expression, String routerRef); @Override void validate(); @Override boolean evaluate(AttributeGroup attributesGroup); }### Answer:
@Test public void testValidate() throws Exception { System.out.println("evaluate"); CommsRouterEvaluatorFactory ef = new CommsRouterEvaluatorFactory(); try { ef.provide("HAS(#{allowedBools}, true) && IN(true, #{allowedBools}) && #{~bool}", null).validate(); assertTrue(false); } catch (ExpressionException ex) { } try { ef.provide("#{boolTrue} && #{price}>10 && #{$price}^10", null).validate(); assertTrue(false); } catch (ExpressionException ex) { } try { ef.provide("#{color}$'red'", null).validate(); assertTrue(false); } catch (ExpressionException ex) { } try { ef.provide("true", null).validate(); } catch (ExpressionException ex) { assertTrue(false); } try { ef.provide(predicateOK3, null).validate(); } catch (ExpressionException ex) { assertTrue(false); } try { ef.provide("CONTAINS([10, 20, 30], 20)", null).validate(); } catch (ExpressionException ex) { assertTrue(false); } try { ef.provide("IN('fr', ['en','fr'])", null).validate(); } catch (ExpressionException ex) { assertTrue(false); } } |
### Question:
RsqlEvaluatorFactory { public RsqlEvaluator create(String expression, String routerRef) throws ExpressionException { try { return new RsqlEvaluator(factory, parse(expression), routerRef); } catch (RSQLParserException ex) { throw new ExpressionException("Invalid expression: " + ex.getMessage()); } } RsqlEvaluatorFactory(CommsRouterEvaluatorFactory factory); Node parse(String expression); void validate(String expression); RsqlEvaluator create(String expression, String routerRef); boolean evaluate(String expression, AttributeGroup attributeGroup, String routerRef); }### Answer:
@Test(expected = ExpressionException.class) public void comparisionGtMultyArgTest() throws Exception { rsqlEvaluatorFactory.create("skill>(1,2,3)", "routerRef"); }
@Test(expected = ExpressionException.class) public void comparisionGeMultyArgTest() throws Exception { rsqlEvaluatorFactory.create("skill>=(1,2,3)", "routerRef"); }
@Test(expected = ExpressionException.class) public void comparisionLtMultyArgTest() throws Exception { rsqlEvaluatorFactory.create("skill<(1,2,3)", "routerRef"); }
@Test(expected = ExpressionException.class) public void comparisionLeMultyArgTest() throws Exception { rsqlEvaluatorFactory.create("skill<=(1,2,3)", "routerRef"); }
@Test(expected = ExpressionException.class) public void comparisionEqMultyArgTest() throws Exception { rsqlEvaluatorFactory.create("skill==(1,2,3)", "routerRef"); }
@Test(expected = ExpressionException.class) public void comparisionNeMultyArgTest() throws Exception { rsqlEvaluatorFactory.create("skill!=(1,2,3)", "routerRef"); }
@Test public void comparisionAllSingleArgTest() throws Exception { rsqlEvaluatorFactory.create("skill>1", "routerRef"); rsqlEvaluatorFactory.create("skill>=1", "routerRef"); rsqlEvaluatorFactory.create("skill<1", "routerRef"); rsqlEvaluatorFactory.create("skill<=1", "routerRef"); rsqlEvaluatorFactory.create("skill==1", "routerRef"); rsqlEvaluatorFactory.create("skill!=1", "routerRef"); } |
### Question:
RsqlEvaluatorFactory { public boolean evaluate(String expression, AttributeGroup attributeGroup, String routerRef) throws ExpressionException { return create(expression, routerRef).evaluate(attributeGroup); } RsqlEvaluatorFactory(CommsRouterEvaluatorFactory factory); Node parse(String expression); void validate(String expression); RsqlEvaluator create(String expression, String routerRef); boolean evaluate(String expression, AttributeGroup attributeGroup, String routerRef); }### Answer:
@Test(expected = ExpressionException.class) public void evaluateExpressionInvalidAttributesNumber() throws Exception { String predicate = "languages=gt=en"; rsqlEvaluatorFactory.evaluate(predicate, attributeGroupe, "routerRef"); } |
### Question:
RsqlEvaluatorFactory { public void validate(String expression) throws ExpressionException { try { parse(expression); } catch (RSQLParserException ex) { throw new ExpressionException("Invalid expression: " + ex.getMessage()); } } RsqlEvaluatorFactory(CommsRouterEvaluatorFactory factory); Node parse(String expression); void validate(String expression); RsqlEvaluator create(String expression, String routerRef); boolean evaluate(String expression, AttributeGroup attributeGroup, String routerRef); }### Answer:
@Test public void validateExpressionValid() throws Exception { String predicateOK1 = "language==en;price=in=(20,30,40);price=gt=10;boolTrue==true"; String predicateOK2 = "language==bg,price<100;boolFalse==false"; String predicateOK3 = "language=in=(en,fr,es);prices==30,color==blue"; rsqlEvaluatorFactory.validate(predicateOK1); rsqlEvaluatorFactory.validate(predicateOK2); rsqlEvaluatorFactory.validate(predicateOK3); }
@Test(expected = ExpressionException.class) public void validateExpressionInalid1() throws Exception { String predicateNOK1 = "language===en"; rsqlEvaluatorFactory.validate(predicateNOK1); }
@Test(expected = ExpressionException.class) public void validateExpressionInalid2() throws Exception { String predicateNOK2 = "language==bg:boolFalse==true"; rsqlEvaluatorFactory.validate(predicateNOK2); }
@Test(expected = ExpressionException.class) public void validateExpressionInalid3() throws Exception { String predicateNOK3 = "language==in=(bg,fr,es)"; rsqlEvaluatorFactory.validate(predicateNOK3); } |
### Question:
SkillValidator { public void validate(AttributeGroupDto capabilities, String routerRef) throws CommsRouterException { if (capabilities != null) { for (Map.Entry<String, AttributeValueDto> capability : capabilities.entrySet()) { validateCapability(capability.getKey(), capability.getValue(), routerRef); } } } SkillValidator(CoreSkillService coreSkillService); void validate(AttributeGroupDto capabilities, String routerRef); }### Answer:
@Test public void testAttributeGroupDtoOK() throws CommsRouterException { AttributeGroupDto attributeGroupDto = new AttributeGroupDto(); attributeGroupDto.add("isTechnical", true); attributeGroupDto.add("age", 5.0); attributeGroupDto.add("ageWithBoundary", 18.0); attributeGroupDto.add("multiAgeWithBoundary", 18.0); attributeGroupDto.add("language", "en"); attributeGroupDto.add("nameWithRegex", "suzie"); attributeGroupDto.add("name", "suzie5"); skillValidator.validate(attributeGroupDto, routerRef); }
@Test(expected = CommsRouterException.class) public void testDoubleUnderInterval() throws CommsRouterException { AttributeGroupDto attributeGroupDto = new AttributeGroupDto(); attributeGroupDto.add("ageWithBoundary", 5.0); skillValidator.validate(attributeGroupDto, routerRef); }
@Test public void testDoubleOnInclusiveBoundary() throws CommsRouterException { AttributeGroupDto attributeGroupDto = new AttributeGroupDto(); attributeGroupDto.add("ageWithBoundary", 18.0); skillValidator.validate(attributeGroupDto, routerRef); }
@Test(expected = CommsRouterException.class) public void testDoubleOnExclusiveBoundary() throws CommsRouterException { AttributeGroupDto attributeGroupDto = new AttributeGroupDto(); attributeGroupDto.add("ageWithBoundary", 45.0); skillValidator.validate(attributeGroupDto, routerRef); }
@Test(expected = CommsRouterException.class) public void testDoubleAboveInterval() throws CommsRouterException { AttributeGroupDto attributeGroupDto = new AttributeGroupDto(); attributeGroupDto.add("ageWithBoundary", 46.0); skillValidator.validate(attributeGroupDto, routerRef); }
@Test public void testDoubleInSecondInterval() throws CommsRouterException { AttributeGroupDto attributeGroupDto = new AttributeGroupDto(); attributeGroupDto.add("ageWithBoundary", 55.0); skillValidator.validate(attributeGroupDto, routerRef); }
@Test(expected = CommsRouterException.class) public void testSkillDoesNotExist() throws CommsRouterException { AttributeGroupDto attributeGroupDto = new AttributeGroupDto(); attributeGroupDto.add("babaiaga", true); skillValidator.validate(attributeGroupDto, routerRef); }
@Test(expected = CommsRouterException.class) public void testSkillUnexpectedValue() throws CommsRouterException { AttributeGroupDto attributeGroupDto = new AttributeGroupDto(); attributeGroupDto.add("isTechnical", "yes"); skillValidator.validate(attributeGroupDto, routerRef); }
@Test(expected = CommsRouterException.class) public void testSkillBadStringValue() throws CommsRouterException { AttributeGroupDto attributeGroupDto = new AttributeGroupDto(); attributeGroupDto.add("nameWithRegex", "suzie5"); skillValidator.validate(attributeGroupDto, routerRef); }
@Test(expected = CommsRouterException.class) public void testSkillBadEnumValue() throws CommsRouterException { AttributeGroupDto attributeGroupDto = new AttributeGroupDto(); attributeGroupDto.add("language", "pl"); skillValidator.validate(attributeGroupDto, routerRef); }
@Test(expected = CommsRouterException.class) public void testSkillBadNumberValue() throws CommsRouterException { AttributeGroupDto attributeGroupDto = new AttributeGroupDto(); attributeGroupDto.add("ageWithBoundary", "5"); skillValidator.validate(attributeGroupDto, routerRef); } |
### Question:
AttributeDomainMapper { public static AttributeType getAttributeType(AttributeDomainDefinition jpa) { if (jpa.getEnumValue() != null) { assert jpa.getBoundary() == null && jpa.getInclusive() == null && jpa.getRegex() == null; return AttributeType.enumeration; } if (jpa.getBoundary() != null) { assert jpa.getEnumValue() == null && jpa.getRegex() == null; return AttributeType.number; } if (jpa.getRegex() != null) { assert jpa.getEnumValue() == null && jpa.getBoundary() == null && jpa.getInclusive() == null; return AttributeType.string; } throw new RuntimeException("AttributeDomainDefinition with no value: " + jpa.getId()); } static AttributeType getAttributeType(AttributeDomainDefinition jpa); AttributeDomainDto toDto(AttributeDomain jpa); AttributeDomain fromDto(AttributeDomainDto dto); }### Answer:
@Test public void testGetAttributeType() { AttributeType actual; AttributeDomainDefinition def; def = new AttributeDomainDefinition(); def.setEnumValue("enum-value"); actual = AttributeDomainMapper.getAttributeType(def); assertEquals(AttributeType.enumeration, actual); def = new AttributeDomainDefinition(); def.setBoundary(Double.POSITIVE_INFINITY); actual = AttributeDomainMapper.getAttributeType(def); assertEquals(AttributeType.number, actual); def = new AttributeDomainDefinition(); def.setRegex("regex-value"); actual = AttributeDomainMapper.getAttributeType(def); assertEquals(AttributeType.string, actual); } |
### Question:
RouterObject extends ApiObject { @Override public boolean equals(Object object) { boolean equals = super.equals(object); if (equals) { RouterObject routerObject = (RouterObject) object; return Objects.equals(getRouter(), routerObject.getRouter()); } return false; } RouterObject(); RouterObject(RouterObject rhs); RouterObject(String id); Router getRouter(); void setRouter(Router router); @Override String toString(); @Override boolean equals(Object object); @Override int hashCode(); }### Answer:
@Test public void equalsTest() throws Exception { assertTrue("The same object", planP1R1.equals(planP1R1)); assertTrue("Diff object", planP1R1.equals(planP1R1new)); assertFalse("Should not equals", planP1R1.equals(planP1R2)); assertFalse("Diff class", planP1R1.equals(task)); assertFalse("Diff class", planP1R1.equals(new Rule())); } |
### Question:
RouterObject extends ApiObject { @Override public int hashCode() { return Objects.hash(getRef(), getRouter(), getVersion(), getClass()); } RouterObject(); RouterObject(RouterObject rhs); RouterObject(String id); Router getRouter(); void setRouter(Router router); @Override String toString(); @Override boolean equals(Object object); @Override int hashCode(); }### Answer:
@Test public void hashCodeTest() throws Exception { assertEquals("The same object", planP1R1.hashCode(), planP1R1.hashCode()); assertEquals("Diff object", planP1R1.hashCode(), planP1R1new.hashCode()); assertNotEquals("Should not equals", planP1R1.hashCode(), planP1R2.hashCode()); assertNotEquals("Diff class", planP1R1.hashCode(), task.hashCode()); } |
### Question:
AdjustableSemaphore extends Semaphore { public synchronized void setMaxPermits(int maxPermits) { if (maxPermits < 1) { throw new IllegalArgumentException("Semaphore size(" + maxPermits + ") must be at least 1"); } int delta = maxPermits - this.maxPermits; if (delta == 0) { return; } else if (delta > 0) { super.release(delta); } else { delta *= -1; super.reducePermits(delta); } this.maxPermits = maxPermits; } AdjustableSemaphore(); AdjustableSemaphore(int permits); AdjustableSemaphore(int permits, boolean fair); synchronized void setMaxPermits(int maxPermits); }### Answer:
@Test public void semaphoreTest() throws Exception { AdjustableSemaphore semaphore = new AdjustableSemaphore(5); for (int i = 0; i < 20; i++) { semaphore.tryAcquire(); } Assert.assertEquals(0, semaphore.availablePermits()); semaphore.setMaxPermits(2); Assert.assertEquals(-3, semaphore.availablePermits()); semaphore.setMaxPermits(20); Assert.assertEquals(15, semaphore.availablePermits()); semaphore.setMaxPermits(3); Assert.assertEquals(-2, semaphore.availablePermits()); semaphore.setMaxPermits(1); Assert.assertEquals(-4, semaphore.availablePermits()); semaphore.setMaxPermits(10); Assert.assertEquals(5, semaphore.availablePermits()); for (int i = 0; i < 7; i++) { semaphore.release(); } Assert.assertEquals(12, semaphore.availablePermits()); } |
### Question:
RetryerBuilder { public RetryerBuilder<V> withWaitStrategy(WaitStrategy waitStrategy) throws IllegalStateException { Preconditions.checkNotNull(waitStrategy, "waitStrategy may not be null"); Preconditions.checkState(this.waitStrategy == null, "a wait strategy has already been set %s", this.waitStrategy); this.waitStrategy = waitStrategy; return this; } private RetryerBuilder(); static RetryerBuilder<V> newBuilder(); RetryerBuilder<V> withRetryListener(RetryListener listener); RetryerBuilder<V> withWaitStrategy(WaitStrategy waitStrategy); RetryerBuilder<V> withStopStrategy(StopStrategy stopStrategy); RetryerBuilder<V> withBlockStrategy(BlockStrategy blockStrategy); RetryerBuilder<V> withAttemptTimeLimiter(AttemptTimeLimiter<V> attemptTimeLimiter); RetryerBuilder<V> retryIfException(); RetryerBuilder<V> retryIfRuntimeException(); RetryerBuilder<V> retryIfExceptionOfType(Class<? extends Throwable> exceptionClass); RetryerBuilder<V> retryIfException(Predicate<Throwable> exceptionPredicate); RetryerBuilder<V> retryIfResult(Predicate<V> resultPredicate); Retryer<V> build(); }### Answer:
@Test public void testWithWaitStrategy() throws ExecutionException, RetryException { Callable<Boolean> callable = notNullAfter5Attempts(); Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder() .withWaitStrategy(WaitStrategies.fixedWait(50L, TimeUnit.MILLISECONDS)) .retryIfResult(Predicates.<Boolean>isNull()) .build(); long start = System.currentTimeMillis(); boolean result = retryer.call(callable); assertTrue(System.currentTimeMillis() - start >= 250L); assertTrue(result); } |
### Question:
RetryerBuilder { public RetryerBuilder<V> withStopStrategy(StopStrategy stopStrategy) throws IllegalStateException { Preconditions.checkNotNull(stopStrategy, "stopStrategy may not be null"); Preconditions.checkState(this.stopStrategy == null, "a stop strategy has already been set %s", this.stopStrategy); this.stopStrategy = stopStrategy; return this; } private RetryerBuilder(); static RetryerBuilder<V> newBuilder(); RetryerBuilder<V> withRetryListener(RetryListener listener); RetryerBuilder<V> withWaitStrategy(WaitStrategy waitStrategy); RetryerBuilder<V> withStopStrategy(StopStrategy stopStrategy); RetryerBuilder<V> withBlockStrategy(BlockStrategy blockStrategy); RetryerBuilder<V> withAttemptTimeLimiter(AttemptTimeLimiter<V> attemptTimeLimiter); RetryerBuilder<V> retryIfException(); RetryerBuilder<V> retryIfRuntimeException(); RetryerBuilder<V> retryIfExceptionOfType(Class<? extends Throwable> exceptionClass); RetryerBuilder<V> retryIfException(Predicate<Throwable> exceptionPredicate); RetryerBuilder<V> retryIfResult(Predicate<V> resultPredicate); Retryer<V> build(); }### Answer:
@Test public void testWithStopStrategy() throws ExecutionException { Callable<Boolean> callable = notNullAfter5Attempts(); Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder() .withStopStrategy(StopStrategies.stopAfterAttempt(3)) .retryIfResult(Predicates.<Boolean>isNull()) .build(); try { retryer.call(callable); fail("RetryException expected"); } catch (RetryException e) { assertEquals(3, e.getNumberOfFailedAttempts()); } } |
### Question:
RetryerBuilder { public RetryerBuilder<V> withBlockStrategy(BlockStrategy blockStrategy) throws IllegalStateException { Preconditions.checkNotNull(blockStrategy, "blockStrategy may not be null"); Preconditions.checkState(this.blockStrategy == null, "a block strategy has already been set %s", this.blockStrategy); this.blockStrategy = blockStrategy; return this; } private RetryerBuilder(); static RetryerBuilder<V> newBuilder(); RetryerBuilder<V> withRetryListener(RetryListener listener); RetryerBuilder<V> withWaitStrategy(WaitStrategy waitStrategy); RetryerBuilder<V> withStopStrategy(StopStrategy stopStrategy); RetryerBuilder<V> withBlockStrategy(BlockStrategy blockStrategy); RetryerBuilder<V> withAttemptTimeLimiter(AttemptTimeLimiter<V> attemptTimeLimiter); RetryerBuilder<V> retryIfException(); RetryerBuilder<V> retryIfRuntimeException(); RetryerBuilder<V> retryIfExceptionOfType(Class<? extends Throwable> exceptionClass); RetryerBuilder<V> retryIfException(Predicate<Throwable> exceptionPredicate); RetryerBuilder<V> retryIfResult(Predicate<V> resultPredicate); Retryer<V> build(); }### Answer:
@Test public void testWithBlockStrategy() throws ExecutionException, RetryException { Callable<Boolean> callable = notNullAfter5Attempts(); final AtomicInteger counter = new AtomicInteger(); BlockStrategy blockStrategy = new BlockStrategy() { @Override public void block(long sleepTime) throws InterruptedException { counter.incrementAndGet(); } }; Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder() .withBlockStrategy(blockStrategy) .retryIfResult(Predicates.<Boolean>isNull()) .build(); final int retryCount = 5; boolean result = retryer.call(callable); assertTrue(result); assertEquals(counter.get(), retryCount); } |
### Question:
RetryerBuilder { public RetryerBuilder<V> retryIfException() { rejectionPredicate = Predicates.or(rejectionPredicate, new ExceptionClassPredicate<V>(Exception.class)); return this; } private RetryerBuilder(); static RetryerBuilder<V> newBuilder(); RetryerBuilder<V> withRetryListener(RetryListener listener); RetryerBuilder<V> withWaitStrategy(WaitStrategy waitStrategy); RetryerBuilder<V> withStopStrategy(StopStrategy stopStrategy); RetryerBuilder<V> withBlockStrategy(BlockStrategy blockStrategy); RetryerBuilder<V> withAttemptTimeLimiter(AttemptTimeLimiter<V> attemptTimeLimiter); RetryerBuilder<V> retryIfException(); RetryerBuilder<V> retryIfRuntimeException(); RetryerBuilder<V> retryIfExceptionOfType(Class<? extends Throwable> exceptionClass); RetryerBuilder<V> retryIfException(Predicate<Throwable> exceptionPredicate); RetryerBuilder<V> retryIfResult(Predicate<V> resultPredicate); Retryer<V> build(); }### Answer:
@Test public void testRetryIfException() throws ExecutionException, RetryException { Callable<Boolean> callable = noIOExceptionAfter5Attempts(); Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder() .retryIfException() .build(); boolean result = retryer.call(callable); assertTrue(result); callable = noIOExceptionAfter5Attempts(); retryer = RetryerBuilder.<Boolean>newBuilder() .retryIfException() .withStopStrategy(StopStrategies.stopAfterAttempt(3)) .build(); try { retryer.call(callable); fail("RetryException expected"); } catch (RetryException e) { assertEquals(3, e.getNumberOfFailedAttempts()); assertTrue(e.getLastFailedAttempt().hasException()); assertTrue(e.getLastFailedAttempt().getExceptionCause() instanceof IOException); assertTrue(e.getCause() instanceof IOException); } callable = noIllegalStateExceptionAfter5Attempts(); retryer = RetryerBuilder.<Boolean>newBuilder() .retryIfException() .withStopStrategy(StopStrategies.stopAfterAttempt(3)) .build(); try { retryer.call(callable); fail("RetryException expected"); } catch (RetryException e) { assertEquals(3, e.getNumberOfFailedAttempts()); assertTrue(e.getLastFailedAttempt().hasException()); assertTrue(e.getLastFailedAttempt().getExceptionCause() instanceof IllegalStateException); assertTrue(e.getCause() instanceof IllegalStateException); } } |
### Question:
RetryerBuilder { public RetryerBuilder<V> retryIfRuntimeException() { rejectionPredicate = Predicates.or(rejectionPredicate, new ExceptionClassPredicate<V>(RuntimeException.class)); return this; } private RetryerBuilder(); static RetryerBuilder<V> newBuilder(); RetryerBuilder<V> withRetryListener(RetryListener listener); RetryerBuilder<V> withWaitStrategy(WaitStrategy waitStrategy); RetryerBuilder<V> withStopStrategy(StopStrategy stopStrategy); RetryerBuilder<V> withBlockStrategy(BlockStrategy blockStrategy); RetryerBuilder<V> withAttemptTimeLimiter(AttemptTimeLimiter<V> attemptTimeLimiter); RetryerBuilder<V> retryIfException(); RetryerBuilder<V> retryIfRuntimeException(); RetryerBuilder<V> retryIfExceptionOfType(Class<? extends Throwable> exceptionClass); RetryerBuilder<V> retryIfException(Predicate<Throwable> exceptionPredicate); RetryerBuilder<V> retryIfResult(Predicate<V> resultPredicate); Retryer<V> build(); }### Answer:
@Test public void testRetryIfRuntimeException() throws ExecutionException, RetryException { Callable<Boolean> callable = noIOExceptionAfter5Attempts(); Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder() .retryIfRuntimeException() .build(); try { retryer.call(callable); fail("ExecutionException expected"); } catch (ExecutionException e) { assertTrue(e.getCause() instanceof IOException); } callable = noIllegalStateExceptionAfter5Attempts(); assertTrue(retryer.call(callable)); callable = noIllegalStateExceptionAfter5Attempts(); retryer = RetryerBuilder.<Boolean>newBuilder() .retryIfRuntimeException() .withStopStrategy(StopStrategies.stopAfterAttempt(3)) .build(); try { retryer.call(callable); fail("RetryException expected"); } catch (RetryException e) { assertEquals(3, e.getNumberOfFailedAttempts()); assertTrue(e.getLastFailedAttempt().hasException()); assertTrue(e.getLastFailedAttempt().getExceptionCause() instanceof IllegalStateException); assertTrue(e.getCause() instanceof IllegalStateException); } } |
### Question:
RetryerBuilder { public RetryerBuilder<V> retryIfExceptionOfType(Class<? extends Throwable> exceptionClass) { Preconditions.checkNotNull(exceptionClass, "exceptionClass may not be null"); rejectionPredicate = Predicates.or(rejectionPredicate, new ExceptionClassPredicate<V>(exceptionClass)); return this; } private RetryerBuilder(); static RetryerBuilder<V> newBuilder(); RetryerBuilder<V> withRetryListener(RetryListener listener); RetryerBuilder<V> withWaitStrategy(WaitStrategy waitStrategy); RetryerBuilder<V> withStopStrategy(StopStrategy stopStrategy); RetryerBuilder<V> withBlockStrategy(BlockStrategy blockStrategy); RetryerBuilder<V> withAttemptTimeLimiter(AttemptTimeLimiter<V> attemptTimeLimiter); RetryerBuilder<V> retryIfException(); RetryerBuilder<V> retryIfRuntimeException(); RetryerBuilder<V> retryIfExceptionOfType(Class<? extends Throwable> exceptionClass); RetryerBuilder<V> retryIfException(Predicate<Throwable> exceptionPredicate); RetryerBuilder<V> retryIfResult(Predicate<V> resultPredicate); Retryer<V> build(); }### Answer:
@Test public void testRetryIfExceptionOfType() throws RetryException, ExecutionException { Callable<Boolean> callable = noIOExceptionAfter5Attempts(); Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder() .retryIfExceptionOfType(IOException.class) .build(); assertTrue(retryer.call(callable)); callable = noIllegalStateExceptionAfter5Attempts(); try { retryer.call(callable); fail("ExecutionException expected"); } catch (ExecutionException e) { assertTrue(e.getCause() instanceof IllegalStateException); } callable = noIOExceptionAfter5Attempts(); retryer = RetryerBuilder.<Boolean>newBuilder() .retryIfExceptionOfType(IOException.class) .withStopStrategy(StopStrategies.stopAfterAttempt(3)) .build(); try { retryer.call(callable); fail("RetryException expected"); } catch (RetryException e) { assertEquals(3, e.getNumberOfFailedAttempts()); assertTrue(e.getLastFailedAttempt().hasException()); assertTrue(e.getLastFailedAttempt().getExceptionCause() instanceof IOException); assertTrue(e.getCause() instanceof IOException); } } |
### Question:
RetryerBuilder { public RetryerBuilder<V> retryIfResult(Predicate<V> resultPredicate) { Preconditions.checkNotNull(resultPredicate, "resultPredicate may not be null"); rejectionPredicate = Predicates.or(rejectionPredicate, new ResultPredicate<V>(resultPredicate)); return this; } private RetryerBuilder(); static RetryerBuilder<V> newBuilder(); RetryerBuilder<V> withRetryListener(RetryListener listener); RetryerBuilder<V> withWaitStrategy(WaitStrategy waitStrategy); RetryerBuilder<V> withStopStrategy(StopStrategy stopStrategy); RetryerBuilder<V> withBlockStrategy(BlockStrategy blockStrategy); RetryerBuilder<V> withAttemptTimeLimiter(AttemptTimeLimiter<V> attemptTimeLimiter); RetryerBuilder<V> retryIfException(); RetryerBuilder<V> retryIfRuntimeException(); RetryerBuilder<V> retryIfExceptionOfType(Class<? extends Throwable> exceptionClass); RetryerBuilder<V> retryIfException(Predicate<Throwable> exceptionPredicate); RetryerBuilder<V> retryIfResult(Predicate<V> resultPredicate); Retryer<V> build(); }### Answer:
@Test public void testRetryIfResult() throws ExecutionException, RetryException { Callable<Boolean> callable = notNullAfter5Attempts(); Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder() .retryIfResult(Predicates.<Boolean>isNull()) .build(); assertTrue(retryer.call(callable)); callable = notNullAfter5Attempts(); retryer = RetryerBuilder.<Boolean>newBuilder() .retryIfResult(Predicates.<Boolean>isNull()) .withStopStrategy(StopStrategies.stopAfterAttempt(3)) .build(); try { retryer.call(callable); fail("RetryException expected"); } catch (RetryException e) { assertEquals(3, e.getNumberOfFailedAttempts()); assertTrue(e.getLastFailedAttempt().hasResult()); assertNull(e.getLastFailedAttempt().getResult()); assertNull(e.getCause()); } } |
### Question:
AttemptTimeLimiters { public static <V> AttemptTimeLimiter<V> fixedTimeLimit(long duration, TimeUnit timeUnit) { Preconditions.checkNotNull(timeUnit); return new FixedAttemptTimeLimit<V>(duration, timeUnit); } private AttemptTimeLimiters(); static AttemptTimeLimiter<V> noTimeLimit(); static AttemptTimeLimiter<V> fixedTimeLimit(long duration, TimeUnit timeUnit); static AttemptTimeLimiter<V> fixedTimeLimit(long duration, TimeUnit timeUnit, ExecutorService executorService); }### Answer:
@Test public void fixedTimeLimitTest() { try { AttemptTimeLimiters.fixedTimeLimit(3000, TimeUnit.MILLISECONDS).call(new Callable<Object>() { @Override public Object call() throws Exception { Thread.sleep(2000); return null; } }); } catch (Exception e) { e.printStackTrace(); } } |
### Question:
CircuitBreaker { public void open() { lastOpenedTime = System.currentTimeMillis(); state = CircuitBreakerState.OPEN; logger.debug("circuit open,key:{}", name); } CircuitBreaker(String name, CircuitBreakerConfig config); boolean isOpen(); boolean isHalfOpen(); boolean isClosed(); void open(); void openHalf(); void close(); boolean isOpen2HalfOpenTimeout(); boolean isCloseFailThresholdReached(); boolean isConsecutiveSuccessThresholdReached(); void incrFailCount(); AtomicInteger getConsecutiveSuccCount(); CircuitBreakerState getState(); }### Answer:
@Test(expected = CircuitBreakerOpenException.class) public void testOpen() { for (int i = 0; i < 6; i++) { try { demoService.getUuid(2); } catch (Exception e) { } } demoService.getUuid(1); } |
### Question:
JavaVersion { static Version parseVersion(String version) { if (version.startsWith("1.")) { String[] versions = version.split("\\."); if (versions.length <= 1) { throw new IllegalStateException("Invalid Java version: " + version); } return new Version(1, Integer.parseInt(versions[1])); } else { final Matcher matcher = JDK9_AND_HIGHER.matcher(version); if (matcher.matches()) { int major = Integer.parseInt(matcher.group(1)); String minorGroup = matcher.group(3); int minor = minorGroup != null && !minorGroup.isEmpty() ? Integer.parseInt(minorGroup) : 0; return new Version(major, minor); } else { throw new IllegalStateException("Invalid Java version: " + version); } } } static final int getMajorVersion(); static final int getMinorVersion(); static boolean isJava8OrLater(); static final int MAJOR_VERSION; static final int MINOR_VERSION; }### Answer:
@Test public void parseJavaVersion() { JavaVersion.Version parsedVersion = JavaVersion.parseVersion(version); assertEquals("Major version mismatch", expected.major, parsedVersion.major); assertEquals("Minor version mismatch", expected.minor, parsedVersion.minor); } |
### Question:
FileStringBinding extends AbstractStringBinding<File> implements Binding<File, String> { @Override public File unmarshal(String object) { return new File(object); } @Override File unmarshal(String object); Class<File> getBoundClass(); }### Answer:
@Test public void testUnmarshal() { assertEquals(new File("/tmp/Atomic"), BINDING.unmarshal("/tmp/Atomic")); } |
### Question:
StringBuilderStringBinding extends AbstractStringBinding<StringBuilder> implements Binding<StringBuilder, String> { @Override public StringBuilder unmarshal(String object) { return new StringBuilder(object); } @Override StringBuilder unmarshal(String object); Class<StringBuilder> getBoundClass(); }### Answer:
@Test public void testUnmarshal() { assertEquals(new StringBuilder("Hello World").toString(), BINDING.unmarshal("Hello World").toString()); } |
### Question:
StringBufferStringBinding extends AbstractStringBinding<StringBuffer> implements Binding<StringBuffer, String> { @Override public StringBuffer unmarshal(String object) { return new StringBuffer(object); } @Override StringBuffer unmarshal(String object); Class<StringBuffer> getBoundClass(); }### Answer:
@Test public void testUnmarshal() { assertEquals(new StringBuffer("Hello World").toString(), BINDING.unmarshal("Hello World").toString()); } |
### Question:
URIStringBinding extends AbstractStringBinding<URI> implements Binding<URI, String> { @Override public URI unmarshal(String object) { return URI.create(object); } @Override URI unmarshal(String object); Class<URI> getBoundClass(); }### Answer:
@Test public void testUnmarshal(){ assertEquals(URI.create("www.example.com"), BINDING.unmarshal("www.example.com")); } |
### Question:
DoubleStringBinding extends AbstractStringBinding<Double> implements Binding<Double, String> { @Override public Double unmarshal(String object) { return Double.valueOf(Double.parseDouble(object)); } @Override Double unmarshal(String object); Class<Double> getBoundClass(); }### Answer:
@Test public void testUnmarshal() { assertEquals(new Double(0).toString(), BINDING.unmarshal("0").toString()); assertEquals(new Double(1).toString(), BINDING.unmarshal("1").toString()); assertEquals(new Double(9223372036854775807D), BINDING.unmarshal(new Double(9.223372036854776E18).toString())); assertEquals(new Double(-9223372036854775808D).toString(), BINDING.unmarshal("" + Long.MIN_VALUE).toString()); assertEquals(new Double("9223372036854775808").toString(), BINDING.unmarshal("9223372036854775808").toString()); assertEquals(new Double("-9223372036854775809").toString(), BINDING.unmarshal("-9223372036854775809").toString()); assertEquals(new Double("0.0").toString(), BINDING.unmarshal("0.0").toString()); assertEquals(new Double("1.123").toString(), BINDING.unmarshal("1.123").toString()); assertEquals(new Double("9.223372036854776E18").toString(), BINDING.unmarshal("9223372036854775807.034").toString()); assertEquals(new Double("-9.223372036854776E18").toString(), BINDING.unmarshal("-9223372036854775808.034").toString()); assertEquals(new Double("9.223372036854776E18").toString(), BINDING.unmarshal("9223372036854775808.234234324324324").toString()); assertEquals(new Double("-9.223372036854776E18").toString(), BINDING.unmarshal("-9223372036854775809.234234324324324").toString()); } |
### Question:
BigDecimalStringBinding extends AbstractStringBinding<BigDecimal> implements Binding<BigDecimal, String> { @Override public BigDecimal unmarshal(String object) { return new BigDecimal(object); } @Override BigDecimal unmarshal(String object); Class<BigDecimal> getBoundClass(); }### Answer:
@Test public void testUnmarshal() { assertEquals(new BigDecimal(0).toString(), BINDING.unmarshal("0").toString()); assertEquals(new BigDecimal(1).toString(), BINDING.unmarshal("1").toString()); assertEquals(new BigDecimal(9223372036854775807L).toString(), BINDING.unmarshal("" + Long.MAX_VALUE).toString()); assertEquals(new BigDecimal(-9223372036854775808L).toString(), BINDING.unmarshal("" + Long.MIN_VALUE).toString()); assertEquals(new BigDecimal("9223372036854775808").toString(), BINDING.unmarshal("9223372036854775808").toString()); assertEquals(new BigDecimal("-9223372036854775809").toString(), BINDING.unmarshal("-9223372036854775809").toString()); assertEquals(new BigDecimal("0.0").toString(), BINDING.unmarshal("0.0").toString()); assertEquals(new BigDecimal("1.123").toString(), BINDING.unmarshal("1.123").toString()); assertEquals(new BigDecimal("9223372036854775807.034").toString(), BINDING.unmarshal("9223372036854775807.034").toString()); assertEquals(new BigDecimal("-9223372036854775808.034").toString(), BINDING.unmarshal("-9223372036854775808.034").toString()); assertEquals(new BigDecimal("9223372036854775808.234234324324324").toString(), BINDING.unmarshal("9223372036854775808.234234324324324").toString()); assertEquals(new BigDecimal("-9223372036854775809.234234324324324").toString(), BINDING.unmarshal("-9223372036854775809.234234324324324").toString()); } |
### Question:
URLStringBinding extends AbstractStringBinding<URL> implements Binding<URL, String> { @Override public URL unmarshal(String object) { try { return new URL(object); } catch (MalformedURLException ex) { throw new IllegalArgumentException(object + " is not a valid URL"); } } @Override URL unmarshal(String object); Class<URL> getBoundClass(); }### Answer:
@Test public void testUnmarshal() throws MalformedURLException{ assertEquals(new URL("http: } |
### Question:
BooleanStringBinding extends AbstractStringBinding<Boolean> implements Binding<Boolean, String> { @Override public Boolean unmarshal(String object) { return Boolean.valueOf(object); } @Override Boolean unmarshal(String object); Class<Boolean> getBoundClass(); }### Answer:
@Test public void testUnmarshal() { assertEquals(Boolean.TRUE.toString(), BINDING.unmarshal("true").toString()); assertEquals(Boolean.FALSE.toString(), BINDING.unmarshal("false").toString()); } |
### Question:
LocaleStringBinding extends AbstractStringBinding<Locale> implements Binding<Locale, String> { @Override public Locale unmarshal(String object) { String[] components = object.split("_", 3); final Locale result; if (components.length == 1) { result = new Locale(components[0]); } else if (components.length == 2) { result = new Locale(components[0], components[1]); } else if (components.length == 3) { result = new Locale(components[0], components[1], components[2]); } else { throw new IllegalArgumentException("Unable to unmarshall String to Locale: " + object); } return result; } @Override Locale unmarshal(String object); Class<Locale> getBoundClass(); }### Answer:
@Test public void testUnmarshal() { assertEquals(new Locale("en"), BINDING.unmarshal("en")); assertEquals(new Locale("en","GB"), BINDING.unmarshal("en_GB")); assertEquals(new Locale("en","GB","ck"), BINDING.unmarshal("en_gb_ck")); } |
### Question:
StringStringBinding extends AbstractStringBinding<String> implements Binding<String, String> { @Override public String unmarshal(String object) { return object; } @Override String unmarshal(String object); Class<String> getBoundClass(); }### Answer:
@Test public void testUnmarshal() { assertEquals("Hello World", BINDING.unmarshal("Hello World")); } |
### Question:
IntervalBisection implements CompositeFunction<Double, QuantitativeFunction<Double, Double>> { public IntervalBisection(double lowerBound, double higherBound) { this(lowerBound, higherBound, 20); } IntervalBisection(double lowerBound, double higherBound); IntervalBisection(double lowerBound, double higherBound, int iterations); IntervalBisection(double lowerBound, double higherBound, int iterations, double precision, PrecisionStrategy precisionStrategy); double getLowerBound(); double getHigherBound(); int getIterations(); double getPrecision(); @Override Double apply(QuantitativeFunction<Double, Double> computeFunction); }### Answer:
@Test public void testIntervalBisection() { IntervalBisection bisection = new IntervalBisection(0D, 2D); Double result = bisection.apply(new QuantitativeFunction<Double, Double>() { @Override public Double apply(Double value) { return 2 - Math.pow(Math.E, value); } }); assertEquals(0.693359375D, result, 0.0000000001D); } |
### Question:
PackageStringBinding extends AbstractStringBinding<Package> implements Binding<Package, String> { @Override public Package unmarshal(String object) { return Package.getPackage(object); } @Override String marshal(Package object); @Override Package unmarshal(String object); Class<Package> getBoundClass(); }### Answer:
@Test public void testUnmarshal() { assertEquals(Package.getPackage("org.jadira.bindings.core.jdk"), BINDING.unmarshal("org.jadira.bindings.core.jdk")); } |
### Question:
PackageStringBinding extends AbstractStringBinding<Package> implements Binding<Package, String> { @Override public String marshal(Package object) { return ((Package) object).getName(); } @Override String marshal(Package object); @Override Package unmarshal(String object); Class<Package> getBoundClass(); }### Answer:
@Test public void testMarshal() { assertEquals("org.jadira.bindings.core.jdk", BINDING.marshal(Package.getPackage("org.jadira.bindings.core.jdk"))); } |
### Question:
IntegerStringBinding extends AbstractStringBinding<Integer> implements Binding<Integer, String> { @Override public Integer unmarshal(String object) { return Integer.valueOf(Integer.parseInt(object)); } @Override Integer unmarshal(String object); Class<Integer> getBoundClass(); }### Answer:
@Test public void testUnmarshal() { assertEquals(new Integer(0).toString(), BINDING.unmarshal("0").toString()); assertEquals(new Integer(1).toString(), BINDING.unmarshal("1").toString()); assertEquals(new Integer(2147483647).toString(), BINDING.unmarshal("" + Integer.MAX_VALUE).toString()); assertEquals(new Integer(-2147483648).toString(), BINDING.unmarshal("" + Integer.MIN_VALUE).toString()); } |
### Question:
BigIntegerStringBinding extends AbstractStringBinding<BigInteger> implements Binding<BigInteger, String> { @Override public BigInteger unmarshal(String object) { return new BigInteger(object); } @Override BigInteger unmarshal(String object); Class<BigInteger> getBoundClass(); }### Answer:
@Test public void testUnmarshal() { assertEquals(BigInteger.valueOf(0).toString(), BINDING.unmarshal("0").toString()); assertEquals(BigInteger.valueOf(1).toString(), BINDING.unmarshal("1").toString()); assertEquals(BigInteger.valueOf(9223372036854775807L).toString(), BINDING.unmarshal("" + Long.MAX_VALUE).toString()); assertEquals(BigInteger.valueOf(-9223372036854775808L).toString(), BINDING.unmarshal("" + Long.MIN_VALUE).toString()); assertEquals(new BigInteger("9223372036854775808").toString(), BINDING.unmarshal("9223372036854775808").toString()); assertEquals(new BigInteger("-9223372036854775809").toString(), BINDING.unmarshal("-9223372036854775809").toString()); } |
### Question:
UUIDStringBinding extends AbstractStringBinding<UUID> implements Binding<UUID, String> { @Override public UUID unmarshal(String object) { return java.util.UUID.fromString(object); } @Override UUID unmarshal(String object); Class<UUID> getBoundClass(); }### Answer:
@Test public void testUnmarshal(){ assertEquals(RND, BINDING.unmarshal(RND.toString())); } |
### Question:
TimeZoneStringBinding extends AbstractStringBinding<TimeZone> implements Binding<TimeZone, String> { @Override public TimeZone unmarshal(String str) { return TimeZone.getTimeZone(str); } @Override String marshal(TimeZone object); @Override TimeZone unmarshal(String str); Class<TimeZone> getBoundClass(); }### Answer:
@Test public void testUnmarshal() { assertEquals(TimeZone.getTimeZone("PST"), BINDING.unmarshal("PST")); assertEquals(TimeZone.getTimeZone("GMT+08:00"), BINDING.unmarshal("GMT+08:00")); } |
### Question:
TimeZoneStringBinding extends AbstractStringBinding<TimeZone> implements Binding<TimeZone, String> { @Override public String marshal(TimeZone object) { return object.getID(); } @Override String marshal(TimeZone object); @Override TimeZone unmarshal(String str); Class<TimeZone> getBoundClass(); }### Answer:
@Test public void testMarshal() { assertEquals("PST", BINDING.marshal(TimeZone.getTimeZone("PST"))); assertEquals("GMT+08:00", BINDING.marshal(TimeZone.getTimeZone("GMT+08:00"))); } |
### Question:
CharacterStringBinding extends AbstractStringBinding<Character> implements Binding<Character, String> { @Override public Character unmarshal(String object) { if (object.length() == 1) { return Character.valueOf(object.charAt(0)); } else { throw new IllegalArgumentException("Only single character String can be unmarshalled to a Character"); } } @Override Character unmarshal(String object); Class<Character> getBoundClass(); }### Answer:
@Test public void testUnmarshal() { assertEquals(new Character('a'), BINDING.unmarshal("a")); assertEquals(new Character('\u00df'), BINDING.unmarshal("\u00df")); } |
### Question:
FloatStringBinding extends AbstractStringBinding<Float> implements Binding<Float, String> { @Override public Float unmarshal(String object) { return Float.valueOf(Float.parseFloat(object)); } @Override Float unmarshal(String object); Class<Float> getBoundClass(); }### Answer:
@Test public void testUnmarshal() { assertEquals(new Float(0), BINDING.unmarshal("0")); assertEquals(new Float(1), BINDING.unmarshal("1")); assertEquals(new Float(3.4028235E38F), BINDING.unmarshal("" + Float.MAX_VALUE)); assertEquals(new Float(1.4E-45), BINDING.unmarshal("" + Float.MIN_VALUE)); assertEquals(new Float("0.0"), BINDING.unmarshal("0.0")); assertEquals(new Float("1.123"), BINDING.unmarshal("1.123")); } |
### Question:
InetAddressStringBinding extends AbstractStringBinding<InetAddress> implements Binding<InetAddress, String> { @Override public InetAddress unmarshal(String object) { try { return InetAddress.getByName(object); } catch (UnknownHostException ex) { throw new IllegalArgumentException("Unknown host " + object + ":" + object); } } @Override InetAddress unmarshal(String object); @Override String marshal(InetAddress object); Class<InetAddress> getBoundClass(); }### Answer:
@Test public void testUnmarshal() throws UnknownHostException { assertEquals(InetAddress.getByName("www.google.com"), BINDING.unmarshal("www.google.com")); } |
### Question:
IntervalBisection implements CompositeFunction<Double, QuantitativeFunction<Double, Double>> { @Override public Double apply(QuantitativeFunction<Double, Double> computeFunction) { final double resultA = computeFunction.apply(lowerBound); final double resultB = computeFunction.apply(higherBound); if (resultA != 0.0D && resultB != 0.0D && (Double.compare(resultA, 0.0D) ^ Double.compare(0.0D, resultB)) != 0) { throw new IntervalBisectionOutOfRangeException(lowerBound, higherBound); } double currentLower = lowerBound; double currentHigher = higherBound; double currentMiddle = Double.NaN; double midValueResult = Double.NaN; double preceedingMidValueResult = Double.NaN; for (int i = 0; i < iterations; i++) { preceedingMidValueResult = midValueResult; currentMiddle = currentLower + 0.5 * (currentHigher - currentLower); midValueResult = computeFunction.apply(currentMiddle); if (resultA * midValueResult < 0) { currentHigher = currentMiddle; } else if (resultA * midValueResult > 0) { currentLower = currentMiddle; } if (PrecisionStrategy.TO_INTERVAL == precisionStrategy) { if (Math.abs(midValueResult) <= precision) { break; } } else if ((PrecisionStrategy.BETWEEN_RESULTS == precisionStrategy || null == precisionStrategy) && (Math.abs(midValueResult - preceedingMidValueResult) <= precision)) { break; } } return currentMiddle; } IntervalBisection(double lowerBound, double higherBound); IntervalBisection(double lowerBound, double higherBound, int iterations); IntervalBisection(double lowerBound, double higherBound, int iterations, double precision, PrecisionStrategy precisionStrategy); double getLowerBound(); double getHigherBound(); int getIterations(); double getPrecision(); @Override Double apply(QuantitativeFunction<Double, Double> computeFunction); }### Answer:
@Test(expected=IntervalBisectionOutOfRangeException.class) public void testOutOfRange() { IntervalBisection bisection = new IntervalBisection(-3D, -1D); Double result = bisection.apply(new QuantitativeFunction<Double, Double>() { @Override public Double apply(Double value) { return 2 - Math.pow(Math.E, value); } }); assertEquals(0.693359375D, result, 0.0000000001D); } |
### Question:
InetAddressStringBinding extends AbstractStringBinding<InetAddress> implements Binding<InetAddress, String> { @Override public String marshal(InetAddress object) { return object.getHostAddress(); } @Override InetAddress unmarshal(String object); @Override String marshal(InetAddress object); Class<InetAddress> getBoundClass(); }### Answer:
@Test public void testMarshal() throws UnknownHostException { assertEquals("173.194.36.104", BINDING.marshal(InetAddress.getByAddress("173.194.36.104", new byte[]{(byte)173,(byte)194,36,104}))); } |
### Question:
CurrencyStringBinding extends AbstractStringBinding<Currency> implements Binding<Currency, String> { @Override public Currency unmarshal(String object) { return Currency.getInstance(object); } @Override Currency unmarshal(String object); Class<Currency> getBoundClass(); }### Answer:
@Test public void testUnmarshal() { assertEquals(Currency.getInstance("USD"), BINDING.unmarshal("USD")); assertEquals(Currency.getInstance("GBP"), BINDING.unmarshal("GBP")); assertEquals(Currency.getInstance("AUD"), BINDING.unmarshal("AUD")); } |
### Question:
LongStringBinding extends AbstractStringBinding<Long> implements Binding<Long, String> { @Override public Long unmarshal(String object) { return Long.valueOf(Long.parseLong(object)); } @Override Long unmarshal(String object); Class<Long> getBoundClass(); }### Answer:
@Test public void testUnmarshal() { assertEquals(new Long(0).toString(), BINDING.unmarshal("0").toString()); assertEquals(new Long(1).toString(), BINDING.unmarshal("1").toString()); assertEquals(new Long(9223372036854775807L).toString(), BINDING.unmarshal("" + Long.MAX_VALUE).toString()); assertEquals(new Long(-9223372036854775808L).toString(), BINDING.unmarshal("" + Long.MIN_VALUE).toString()); } |
### Question:
CharSequenceStringBinding extends AbstractStringBinding<CharSequence> implements Binding<CharSequence, String> { @Override public CharSequence unmarshal(String object) { return object; } @Override CharSequence unmarshal(String object); Class<CharSequence> getBoundClass(); }### Answer:
@Test public void testUnmarshal() { assertEquals("Hello World", BINDING.unmarshal("Hello World")); } |
### Question:
AtomicBooleanStringBinding extends AbstractStringBinding<AtomicBoolean> implements Binding<AtomicBoolean, String> { @Override public AtomicBoolean unmarshal(String object) { return new AtomicBoolean(Boolean.parseBoolean(object)); } @Override AtomicBoolean unmarshal(String object); Class<AtomicBoolean> getBoundClass(); }### Answer:
@Test public void testUnmarshal() { assertEquals(new AtomicBoolean(true).toString(), BINDING.unmarshal("true").toString()); assertEquals(new AtomicBoolean(false).toString(), BINDING.unmarshal("false").toString()); } |
### Question:
ClassUtils { public static Class<?> getClass(String qualifiedName) { return getClass(ClassLoaderUtils.getClassLoader(), qualifiedName); } private ClassUtils(); static Class<?> getClass(String qualifiedName); static Class<?> getClass(ClassLoader classLoader, String className); static String determineQualifiedName(String className); static String determineReadableClassName(String qualifiedName); static final char PACKAGE_SEPARATOR_CHARACTER; static final char INNER_CLASS_SEPARATOR_CHAR; }### Answer:
@Test public void testGetClass() { String className = "java.net.URL"; assertEquals(URL.class, ClassUtils.getClass(getClass().getClassLoader(), className)); assertEquals(URL.class, ClassUtils.getClass(getClass().getClassLoader(), className + " ")); assertEquals(new URL[]{}.getClass(), ClassUtils.getClass(getClass().getClassLoader(), className + "[]")); assertEquals(new URL[][]{}.getClass(), ClassUtils.getClass(getClass().getClassLoader(), className + "[][]")); assertEquals(Long.TYPE, ClassUtils.getClass(getClass().getClassLoader(), "long")); assertEquals(Boolean.TYPE, ClassUtils.getClass(getClass().getClassLoader(), "boolean")); assertEquals(Float.TYPE, ClassUtils.getClass(getClass().getClassLoader(), "float")); assertEquals(Short.TYPE, ClassUtils.getClass(getClass().getClassLoader(), "short")); assertEquals(Byte.TYPE, ClassUtils.getClass(getClass().getClassLoader(), "byte")); assertEquals(Double.TYPE, ClassUtils.getClass(getClass().getClassLoader(), "double")); assertEquals(Character.TYPE, ClassUtils.getClass(getClass().getClassLoader(), "char")); assertEquals(new long[]{}.getClass(), ClassUtils.getClass(getClass().getClassLoader(), "long[]")); assertEquals(new boolean[]{}.getClass(), ClassUtils.getClass(getClass().getClassLoader(), "boolean[]")); assertEquals(new float[]{}.getClass(), ClassUtils.getClass(getClass().getClassLoader(), "float[]")); assertEquals(new short[]{}.getClass(), ClassUtils.getClass(getClass().getClassLoader(), "short[]")); assertEquals(new byte[]{}.getClass(), ClassUtils.getClass(getClass().getClassLoader(), "byte[]")); assertEquals(new double[]{}.getClass(), ClassUtils.getClass(getClass().getClassLoader(), "double[]")); assertEquals(new char[]{}.getClass(), ClassUtils.getClass(getClass().getClassLoader(), "char[]")); assertEquals(new long[][]{}.getClass(), ClassUtils.getClass(getClass().getClassLoader(), "long[][]")); } |
### Question:
ClassUtils { public static String determineQualifiedName(String className) { String readableClassName = StringUtils.removeWhitespace(className); if (readableClassName == null) { throw new IllegalArgumentException("readableClassName must not be null."); } else if (readableClassName.endsWith("[]")) { StringBuilder classNameBuffer = new StringBuilder(); while (readableClassName.endsWith("[]")) { readableClassName = readableClassName.substring(0, readableClassName.length() - 2); classNameBuffer.append("["); } String abbreviation = PRIMITIVE_MAPPING.get(readableClassName); if (abbreviation == null) { classNameBuffer.append("L").append(readableClassName).append(";"); } else { classNameBuffer.append(abbreviation); } readableClassName = classNameBuffer.toString(); } return readableClassName; } private ClassUtils(); static Class<?> getClass(String qualifiedName); static Class<?> getClass(ClassLoader classLoader, String className); static String determineQualifiedName(String className); static String determineReadableClassName(String qualifiedName); static final char PACKAGE_SEPARATOR_CHARACTER; static final char INNER_CLASS_SEPARATOR_CHAR; }### Answer:
@Test public void testDetermineQualifiedName() { String className = "org.jadira.bindings.core.utils.string.ClassUtilsTest"; assertEquals("org.jadira.bindings.core.utils.string.ClassUtilsTest", ClassUtils.determineQualifiedName(className)); assertEquals("org.jadira.bindings.core.utils.string.ClassUtilsTest", ClassUtils.determineQualifiedName(className + " ")); assertEquals("[Lorg.jadira.bindings.core.utils.string.ClassUtilsTest;", ClassUtils.determineQualifiedName(className + "[]")); assertEquals("[[Lorg.jadira.bindings.core.utils.string.ClassUtilsTest;", ClassUtils.determineQualifiedName(className + "[][]")); assertEquals("long", ClassUtils.determineQualifiedName("long")); assertEquals("boolean", ClassUtils.determineQualifiedName("boolean")); assertEquals("float", ClassUtils.determineQualifiedName("float")); assertEquals("short", ClassUtils.determineQualifiedName("short")); assertEquals("byte", ClassUtils.determineQualifiedName("byte")); assertEquals("double", ClassUtils.determineQualifiedName("double")); assertEquals("char", ClassUtils.determineQualifiedName("char")); assertEquals("[J", ClassUtils.determineQualifiedName("long[]")); assertEquals("[Z", ClassUtils.determineQualifiedName("boolean[]")); assertEquals("[F", ClassUtils.determineQualifiedName("float[]")); assertEquals("[S", ClassUtils.determineQualifiedName("short[]")); assertEquals("[B", ClassUtils.determineQualifiedName("byte[]")); assertEquals("[D", ClassUtils.determineQualifiedName("double[]")); assertEquals("[C", ClassUtils.determineQualifiedName("char[]")); assertEquals("[[J", ClassUtils.determineQualifiedName("long[][]")); assertEquals("[[Ljava.net.URL;", ClassUtils.determineQualifiedName("java.net.URL[][]")); } |
### Question:
ClassUtils { public static String determineReadableClassName(String qualifiedName) { String readableClassName = StringUtils.removeWhitespace(qualifiedName); if (readableClassName == null) { throw new IllegalArgumentException("qualifiedName must not be null."); } else if (readableClassName.startsWith("[")) { StringBuilder classNameBuffer = new StringBuilder(); while (readableClassName.startsWith("[")) { classNameBuffer.append("[]"); readableClassName = readableClassName.substring(1); } if (PRIMITIVE_MAPPING.containsValue(readableClassName)) { for (Map.Entry<String,String> next : PRIMITIVE_MAPPING.entrySet()) { if (next.getValue().equals(readableClassName)) { readableClassName = next.getKey() + classNameBuffer.toString(); break; } } } else if (readableClassName.startsWith("L") && readableClassName.endsWith(";")) { readableClassName = readableClassName.substring(1, readableClassName.length() - 1) + classNameBuffer.toString(); } else { throw new IllegalArgumentException("qualifiedName was invalid {" + readableClassName + "}"); } } else if (readableClassName.endsWith("]")) { throw new IllegalArgumentException("qualifiedName was invalid {" + readableClassName + "}"); } return readableClassName; } private ClassUtils(); static Class<?> getClass(String qualifiedName); static Class<?> getClass(ClassLoader classLoader, String className); static String determineQualifiedName(String className); static String determineReadableClassName(String qualifiedName); static final char PACKAGE_SEPARATOR_CHARACTER; static final char INNER_CLASS_SEPARATOR_CHAR; }### Answer:
@Test public void testDetermineReadableClassName() { String className = "org.jadira.bindings.core.utils.string.ClassUtilsTest"; assertEquals("org.jadira.bindings.core.utils.string.ClassUtilsTest", ClassUtils.determineReadableClassName(className)); assertEquals("org.jadira.bindings.core.utils.string.ClassUtilsTest", ClassUtils.determineReadableClassName(className + " ")); assertEquals("org.jadira.bindings.core.utils.string.ClassUtilsTest[]", ClassUtils.determineReadableClassName("[L" + className + ";")); assertEquals("org.jadira.bindings.core.utils.string.ClassUtilsTest[][]", ClassUtils.determineReadableClassName("[[L" + className + ";")); assertEquals("long", ClassUtils.determineReadableClassName("long")); assertEquals("boolean", ClassUtils.determineReadableClassName("boolean")); assertEquals("float", ClassUtils.determineReadableClassName("float")); assertEquals("short", ClassUtils.determineReadableClassName("short")); assertEquals("byte", ClassUtils.determineReadableClassName("byte")); assertEquals("double", ClassUtils.determineReadableClassName("double")); assertEquals("char", ClassUtils.determineReadableClassName("char")); assertEquals("long[]", ClassUtils.determineReadableClassName("[J")); assertEquals("boolean[]", ClassUtils.determineReadableClassName("[Z")); assertEquals("float[]", ClassUtils.determineReadableClassName("[F")); assertEquals("short[]", ClassUtils.determineReadableClassName("[S")); assertEquals("byte[]", ClassUtils.determineReadableClassName("[B")); assertEquals("double[]", ClassUtils.determineReadableClassName("[D")); assertEquals("char[]", ClassUtils.determineReadableClassName("[C")); assertEquals("long[][]", ClassUtils.determineReadableClassName("[[J")); assertEquals("java.net.URL[][]", ClassUtils.determineReadableClassName("[[Ljava.net.URL;")); } |
### Question:
ClassLoaderUtils { public static ClassLoader getClassLoader() { ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) { cl = ClassStringBinding.class.getClassLoader(); } return cl; } private ClassLoaderUtils(); static ClassLoader getClassLoader(); }### Answer:
@Test public void testGetClassLoader() { assertEquals("sun.misc.Launcher$AppClassLoader", ClassLoaderUtils.getClassLoader().getClass().getName()); } |
### Question:
AtomicLongStringBinding extends AbstractStringBinding<AtomicLong> implements Binding<AtomicLong, String> { @Override public AtomicLong unmarshal(String object) { return new AtomicLong(Long.parseLong(object)); } @Override AtomicLong unmarshal(String object); Class<AtomicLong> getBoundClass(); }### Answer:
@Test public void testUnmarshal() { assertEquals(new AtomicLong(0).toString(), BINDING.unmarshal("0").toString()); assertEquals(new AtomicLong(1).toString(), BINDING.unmarshal("1").toString()); assertEquals(new AtomicLong(9223372036854775807L).toString(), BINDING.unmarshal("" + Long.MAX_VALUE).toString()); assertEquals(new AtomicLong(-9223372036854775808L).toString(), BINDING.unmarshal("" + Long.MIN_VALUE).toString()); } |
### Question:
IterableEnumeration implements Iterable<E> { public IterableEnumeration(Enumeration<E> enumeration) { this.enumeration = enumeration; } IterableEnumeration(Enumeration<E> enumeration); Iterator<E> iterator(); static Iterable<E> wrapEnumeration(Enumeration<E> enumeration); }### Answer:
@Test public void testIterableEnumeration() { Iterable<String> testIterable = new IterableEnumeration<String>(ELEMENTS.elements()); Iterator<String> myIter = testIterable.iterator(); testValues(myIter); testIterable = IterableEnumeration.wrapEnumeration(ELEMENTS.elements()); myIter = testIterable.iterator(); testValues(myIter); } |
### Question:
StringUtils { public static String removeWhitespace(String string) { if (string == null || string.length() == 0) { return string; } else { int codePoints = string.codePointCount(0, string.length()); StringBuilder sb = new StringBuilder(); for (int i = 0; i < codePoints; i++) { int offset = string.offsetByCodePoints(0, i); int nextCodePoint = string.codePointAt(offset); if (!Character.isWhitespace(nextCodePoint)) { sb.appendCodePoint(nextCodePoint); } } if (string.length() == sb.length()) { return string; } else { return sb.toString(); } } } private StringUtils(); static String removeWhitespace(String string); }### Answer:
@Test public void testRemoveWhitespace() { assertEquals("Helloworld", StringUtils.removeWhitespace("Hello world")); assertEquals("Hello\uD840\uDC08", StringUtils.removeWhitespace("Hello \uD840\uDC08")); assertEquals("Hello\uD840\uDC08", StringUtils.removeWhitespace(" Hello \uD840\uDC08 ")); assertEquals("Hello\uD840\uDC08", StringUtils.removeWhitespace(" Hello \n \uD840\uDC08 ")); } |
### Question:
BindingConverter implements ConditionalGenericConverter { public Object convert(Object object, TypeDescriptor sourceType, TypeDescriptor targetType) { final Object result; result = BINDING.convertTo(object.getClass(), targetType.getObjectType(), object, matchAnnotationToScope(targetType.getAnnotations())); return result; } Set<ConvertiblePair> getConvertibleTypes(); Object convert(Object object, TypeDescriptor sourceType, TypeDescriptor targetType); boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType); }### Answer:
@Test public void testBindingConverter() { assertEquals(new SubjectC("String"), svc.convert("String:String", SubjectC.class)); } |
### Question:
E164PhoneNumberWithExtension implements PhoneNumber, Serializable { public String getCountryDiallingCode() { return "+" + number.getCountryCode(); } E164PhoneNumberWithExtension(Phonenumber.PhoneNumber prototype); protected E164PhoneNumberWithExtension(String e164PhoneNumberWithExtension); protected E164PhoneNumberWithExtension(String e164PhoneNumber, String extension); protected E164PhoneNumberWithExtension(String phoneNumber, CountryCode defaultCountryCode); protected E164PhoneNumberWithExtension(String phoneNumber, String extension, CountryCode defaultCountryCode); static E164PhoneNumberWithExtension ofE164PhoneNumberString(String e164PhoneNumber); @FromString static E164PhoneNumberWithExtension ofE164PhoneNumberWithExtensionString(String e164PhoneNumber); static E164PhoneNumberWithExtension ofE164PhoneNumberStringAndExtension(String e164PhoneNumber, String extension); static E164PhoneNumberWithExtension ofPhoneNumberString(String phoneNumber, CountryCode defaultCountryCode); static E164PhoneNumberWithExtension ofPhoneNumberStringAndExtension(String phoneNumber, String extension, CountryCode defaultCountryCode); Phonenumber.PhoneNumber getUnderlyingPhoneNumber(); ISOCountryCode extractCountryCode(); String getCountryDiallingCode(); String getNationalNumber(); String getExtension(); String toE164NumberString(); @ToString String toE164NumberWithExtensionString(); String extractAreaCode(); String extractSubscriberNumber(); @Override String toString(); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test public void testGetCountryDiallingCode() { E164PhoneNumberWithExtension number = E164PhoneNumberWithExtension.ofPhoneNumberStringAndExtension("1963350474", null, ISOCountryCode.GB); assertEquals("+44", number.getCountryDiallingCode()); } |
### Question:
E164PhoneNumberWithExtension implements PhoneNumber, Serializable { public String getNationalNumber() { return "" + number.getNationalNumber(); } E164PhoneNumberWithExtension(Phonenumber.PhoneNumber prototype); protected E164PhoneNumberWithExtension(String e164PhoneNumberWithExtension); protected E164PhoneNumberWithExtension(String e164PhoneNumber, String extension); protected E164PhoneNumberWithExtension(String phoneNumber, CountryCode defaultCountryCode); protected E164PhoneNumberWithExtension(String phoneNumber, String extension, CountryCode defaultCountryCode); static E164PhoneNumberWithExtension ofE164PhoneNumberString(String e164PhoneNumber); @FromString static E164PhoneNumberWithExtension ofE164PhoneNumberWithExtensionString(String e164PhoneNumber); static E164PhoneNumberWithExtension ofE164PhoneNumberStringAndExtension(String e164PhoneNumber, String extension); static E164PhoneNumberWithExtension ofPhoneNumberString(String phoneNumber, CountryCode defaultCountryCode); static E164PhoneNumberWithExtension ofPhoneNumberStringAndExtension(String phoneNumber, String extension, CountryCode defaultCountryCode); Phonenumber.PhoneNumber getUnderlyingPhoneNumber(); ISOCountryCode extractCountryCode(); String getCountryDiallingCode(); String getNationalNumber(); String getExtension(); String toE164NumberString(); @ToString String toE164NumberWithExtensionString(); String extractAreaCode(); String extractSubscriberNumber(); @Override String toString(); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test public void testGetNationalNumber() { E164PhoneNumberWithExtension number = E164PhoneNumberWithExtension.ofPhoneNumberStringAndExtension("+441963350474", null, ISOCountryCode.DE); assertEquals("1963350474", number.getNationalNumber()); } |
### Question:
E164PhoneNumberWithExtension implements PhoneNumber, Serializable { public String getExtension() { return number.hasExtension() ? number.getExtension() : null; } E164PhoneNumberWithExtension(Phonenumber.PhoneNumber prototype); protected E164PhoneNumberWithExtension(String e164PhoneNumberWithExtension); protected E164PhoneNumberWithExtension(String e164PhoneNumber, String extension); protected E164PhoneNumberWithExtension(String phoneNumber, CountryCode defaultCountryCode); protected E164PhoneNumberWithExtension(String phoneNumber, String extension, CountryCode defaultCountryCode); static E164PhoneNumberWithExtension ofE164PhoneNumberString(String e164PhoneNumber); @FromString static E164PhoneNumberWithExtension ofE164PhoneNumberWithExtensionString(String e164PhoneNumber); static E164PhoneNumberWithExtension ofE164PhoneNumberStringAndExtension(String e164PhoneNumber, String extension); static E164PhoneNumberWithExtension ofPhoneNumberString(String phoneNumber, CountryCode defaultCountryCode); static E164PhoneNumberWithExtension ofPhoneNumberStringAndExtension(String phoneNumber, String extension, CountryCode defaultCountryCode); Phonenumber.PhoneNumber getUnderlyingPhoneNumber(); ISOCountryCode extractCountryCode(); String getCountryDiallingCode(); String getNationalNumber(); String getExtension(); String toE164NumberString(); @ToString String toE164NumberWithExtensionString(); String extractAreaCode(); String extractSubscriberNumber(); @Override String toString(); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test public void testGetExtension() { E164PhoneNumberWithExtension number = E164PhoneNumberWithExtension.ofPhoneNumberStringAndExtension("+441963350474", null, ISOCountryCode.DE); assertNull(number.getExtension()); number = E164PhoneNumberWithExtension.ofPhoneNumberStringAndExtension("+441963350474", "14354", ISOCountryCode.DE); assertEquals("14354", number.getExtension()); } |
### Question:
E164PhoneNumberWithExtension implements PhoneNumber, Serializable { public String toE164NumberString() { StringBuilder result = new StringBuilder(); PHONE_NUMBER_UTIL.format(number, PhoneNumberFormat.E164, result); return result.toString(); } E164PhoneNumberWithExtension(Phonenumber.PhoneNumber prototype); protected E164PhoneNumberWithExtension(String e164PhoneNumberWithExtension); protected E164PhoneNumberWithExtension(String e164PhoneNumber, String extension); protected E164PhoneNumberWithExtension(String phoneNumber, CountryCode defaultCountryCode); protected E164PhoneNumberWithExtension(String phoneNumber, String extension, CountryCode defaultCountryCode); static E164PhoneNumberWithExtension ofE164PhoneNumberString(String e164PhoneNumber); @FromString static E164PhoneNumberWithExtension ofE164PhoneNumberWithExtensionString(String e164PhoneNumber); static E164PhoneNumberWithExtension ofE164PhoneNumberStringAndExtension(String e164PhoneNumber, String extension); static E164PhoneNumberWithExtension ofPhoneNumberString(String phoneNumber, CountryCode defaultCountryCode); static E164PhoneNumberWithExtension ofPhoneNumberStringAndExtension(String phoneNumber, String extension, CountryCode defaultCountryCode); Phonenumber.PhoneNumber getUnderlyingPhoneNumber(); ISOCountryCode extractCountryCode(); String getCountryDiallingCode(); String getNationalNumber(); String getExtension(); String toE164NumberString(); @ToString String toE164NumberWithExtensionString(); String extractAreaCode(); String extractSubscriberNumber(); @Override String toString(); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test public void testToE164NumberString() { E164PhoneNumberWithExtension number = E164PhoneNumberWithExtension.ofPhoneNumberStringAndExtension("1963350474", null, ISOCountryCode.GB); assertEquals("+441963350474", number.toE164NumberString()); } |
### Question:
E164PhoneNumberWithExtension implements PhoneNumber, Serializable { @Override public String toString() { return toE164NumberWithExtensionString(); } E164PhoneNumberWithExtension(Phonenumber.PhoneNumber prototype); protected E164PhoneNumberWithExtension(String e164PhoneNumberWithExtension); protected E164PhoneNumberWithExtension(String e164PhoneNumber, String extension); protected E164PhoneNumberWithExtension(String phoneNumber, CountryCode defaultCountryCode); protected E164PhoneNumberWithExtension(String phoneNumber, String extension, CountryCode defaultCountryCode); static E164PhoneNumberWithExtension ofE164PhoneNumberString(String e164PhoneNumber); @FromString static E164PhoneNumberWithExtension ofE164PhoneNumberWithExtensionString(String e164PhoneNumber); static E164PhoneNumberWithExtension ofE164PhoneNumberStringAndExtension(String e164PhoneNumber, String extension); static E164PhoneNumberWithExtension ofPhoneNumberString(String phoneNumber, CountryCode defaultCountryCode); static E164PhoneNumberWithExtension ofPhoneNumberStringAndExtension(String phoneNumber, String extension, CountryCode defaultCountryCode); Phonenumber.PhoneNumber getUnderlyingPhoneNumber(); ISOCountryCode extractCountryCode(); String getCountryDiallingCode(); String getNationalNumber(); String getExtension(); String toE164NumberString(); @ToString String toE164NumberWithExtensionString(); String extractAreaCode(); String extractSubscriberNumber(); @Override String toString(); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test public void testToString() { E164PhoneNumberWithExtension number = E164PhoneNumberWithExtension.ofPhoneNumberStringAndExtension("+441963350474", null, ISOCountryCode.DE); assertEquals("+441963350474", number.toString()); number = E164PhoneNumberWithExtension.ofPhoneNumberStringAndExtension("+441963350474", "14354", ISOCountryCode.DE); assertEquals("+441963350474;ext=14354", number.toString()); number = E164PhoneNumberWithExtension.ofE164PhoneNumberWithExtensionString("+441963350474;ext=14354"); assertEquals("+441963350474;ext=14354", number.toString()); } |
### Question:
ClassStringBinding extends AbstractStringBinding<Class> implements Binding<Class, String> { @Override public Class unmarshal(String object) { return ClassUtils.getClass(object); } @Override Class unmarshal(String object); @Override String marshal(Class clazz); Class<Class> getBoundClass(); }### Answer:
@Test public void testUnmarshal() { String className = "java.net.URL"; assertEquals(URL.class, BINDING.unmarshal(className)); assertEquals(new URL[]{}.getClass(), BINDING.unmarshal(className + "[]")); assertEquals(new URL[][]{}.getClass(), BINDING.unmarshal(className + "[][]")); assertEquals(Long.TYPE, BINDING.unmarshal("long")); assertEquals(Boolean.TYPE, BINDING.unmarshal("boolean")); assertEquals(Float.TYPE, BINDING.unmarshal("float")); assertEquals(Short.TYPE, BINDING.unmarshal("short")); assertEquals(Byte.TYPE, BINDING.unmarshal("byte")); assertEquals(Double.TYPE, BINDING.unmarshal("double")); assertEquals(Character.TYPE, BINDING.unmarshal("char")); assertEquals(new long[]{}.getClass(), BINDING.unmarshal("long[]")); assertEquals(new boolean[]{}.getClass(), BINDING.unmarshal("boolean[]")); assertEquals(new float[]{}.getClass(), BINDING.unmarshal("float[]")); assertEquals(new short[]{}.getClass(), BINDING.unmarshal("short[]")); assertEquals(new byte[]{}.getClass(), BINDING.unmarshal("byte[]")); assertEquals(new double[]{}.getClass(), BINDING.unmarshal("double[]")); assertEquals(new char[]{}.getClass(), BINDING.unmarshal("char[]")); assertEquals(new long[][]{}.getClass(), BINDING.unmarshal("long[][]")); } |
### Question:
JInterface extends JType { public List<JInterface> getSuperInterfaces() throws ClasspathAccessException { final List<JInterface> retVal = new ArrayList<JInterface>(); String[] interfaces = getClassFile().getInterfaces(); for (String next : interfaces) { retVal.add(JInterface.getJInterface(next, getResolver())); } return retVal; } protected JInterface(String name, ClasspathResolver resolver); protected JInterface(ClassFile classFile, ClasspathResolver resolver); static JInterface getJInterface(String name, ClasspathResolver resolver); static JInterface getJInterface(ClassFile classFile, ClasspathResolver resolver); List<JInterface> getSuperInterfaces(); List<Class<?>> getActualSuperInterfaces(); List<JMethod> getMethods(); Class<?> getActualInterface(); @Override Set<JAnnotation<?>> getAnnotations(); @Override JPackage getPackage(); @Override Class<?> getActualClass(); Set<JInterface> getSubInterfaces(); Set<JClass> getImplementingClasses(); @Override void acceptVisitor(IntrospectionVisitor visitor); @Override JPackage getEnclosingElement(); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test public void getSuperInterfaces() throws ClasspathAccessException { ClasspathResolver helper = new ClasspathResolver(); JInterface intf = JInterface.getJInterface("java.awt.event.AWTEventListener", helper); List<JInterface> superIntf = intf.getSuperInterfaces(); assertEquals(1, superIntf.size()); assertEquals(java.util.EventListener.class, superIntf.get(0).getActualClass()); } |