src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
WXSDKEngine { public static boolean registerDomObject(String type, Class<? extends WXDomObject> clazz) throws WXException { return WXDomRegistry.registerDomObject(type, clazz); } @Deprecated static void init(Application application); @Deprecated static void init(Application application, IWXUserTrackAdapter utAdapter); @Deprecated static void init(Application application, IWXUserTrackAdapter utAdapter, String framework); static boolean isInitialized(); static void initialize(Application application,InitConfig config); @Deprecated static void init(Application application, String framework, IWXUserTrackAdapter utAdapter, IWXImgLoaderAdapter imgLoaderAdapter, IWXHttpAdapter httpAdapter); static void setJSExcetptionAdapter(IWXJSExceptionAdapter excetptionAdapter); static boolean registerComponent(String type, Class<? extends WXComponent> clazz, boolean appendTree); static boolean registerComponent(String type, IExternalComponentGetter componentGetter, boolean appendTree); static boolean registerComponent(Class<? extends WXComponent> clazz, boolean appendTree,String ... names); static boolean registerComponent(IFComponentHolder holder, boolean appendTree, String ... names); static boolean registerModule(String moduleName, Class<T> moduleClass,boolean global); static boolean registerModuleWithFactory(String moduleName, DestroyableModuleFactory factory, boolean global); static boolean registerModuleWithFactory(String moduleName, IExternalModuleGetter factory, boolean global); static boolean registerModule(String moduleName, Class<? extends WXModule> moduleClass); static boolean registerService(String name, String serviceScript, Map<String, String> options); static boolean unRegisterService(String name); static boolean registerDomObject(String type, Class<? extends WXDomObject> clazz); static void callback(String instanceId, String funcId, Map<String, Object> data); static void restartBridge(boolean debug); static boolean registerComponent(String type, Class<? extends WXComponent> clazz); static boolean registerComponent(Map<String, Object> componentInfo, Class<? extends WXComponent> clazz); static void addCustomOptions(String key, String value); static IWXUserTrackAdapter getIWXUserTrackAdapter(); static IWXImgLoaderAdapter getIWXImgLoaderAdapter(); static IDrawableLoader getDrawableLoader(); static IWXHttpAdapter getIWXHttpAdapter(); static IWXStorageAdapter getIWXStorageAdapter(); static IActivityNavBarSetter getActivityNavBarSetter(); static void setActivityNavBarSetter(IActivityNavBarSetter activityNavBarSetter); static void show3DLayer(boolean show); static void switchDebugModel(boolean debug, String debugUrl); static void reload(final Context context,String framework, boolean remoteDebug); static void reload(final Context context, boolean remoteDebug); static void reload(); static final String JS_FRAMEWORK_RELOAD; }
@Test public void testRegisterDomObject() throws Exception { assertFalse(WXSDKEngine.registerDomObject("test",null)); assertFalse(WXSDKEngine.registerDomObject("", TestDomObject.class)); assertTrue(WXSDKEngine.registerDomObject("test",TestDomObject.class)); }
WXSlider extends WXVContainer<FrameLayout> { @Override protected boolean setProperty(String key, Object param) { switch (key) { case Constants.Name.VALUE: String value = WXUtils.getString(param, null); if (value != null) { setValue(value); } return true; case Constants.Name.AUTO_PLAY: String aotu_play = WXUtils.getString(param, null); if (aotu_play != null) { setAutoPlay(aotu_play); } return true; case Constants.Name.SHOW_INDICATORS: String indicators = WXUtils.getString(param, null); if (indicators != null) { setShowIndicators(indicators); } return true; case Constants.Name.INTERVAL: Integer interval = WXUtils.getInteger(param, null); if (interval != null) { setInterval(interval); } return true; case Constants.Name.INDEX: Integer index = WXUtils.getInteger(param, null); if (index != null) { setIndex(index); } return true; case Constants.Name.OFFSET_X_ACCURACY: Float accuracy = WXUtils.getFloat(param, 0.1f); if (accuracy != 0) { setOffsetXAccuracy(accuracy); } return true; case Constants.Name.SCROLLABLE: boolean scrollable = WXUtils.getBoolean(param, true); setScrollable(scrollable); return true; } return super.setProperty(key, param); } @Deprecated WXSlider(WXSDKInstance instance, WXDomObject dom, WXVContainer parent, String instanceId, boolean isLazy); WXSlider(WXSDKInstance instance, WXDomObject node, WXVContainer parent); @Override LayoutParams getChildLayoutParams(WXComponent child,View childView, int width, int height, int left, int right, int top, int bottom); @Override void addEvent(String type); @Override boolean containsGesture(WXGestureType WXGestureType); @Override ViewGroup getRealView(); @Override void remove(WXComponent child, boolean destroy); @Override void destroy(); @Override void onActivityResume(); @Override void onActivityStop(); void addIndicator(WXIndicator indicator); @Deprecated @WXComponentProp(name = Constants.Name.VALUE) void setValue(String value); @WXComponentProp(name = Constants.Name.AUTO_PLAY) void setAutoPlay(String autoPlay); @WXComponentProp(name = Constants.Name.SHOW_INDICATORS) void setShowIndicators(String show); @WXComponentProp(name = Constants.Name.INTERVAL) void setInterval(int intervalMS); @WXComponentProp(name = Constants.Name.INDEX) void setIndex(int index); @WXComponentProp(name = Constants.Name.SCROLLABLE) void setScrollable(boolean scrollable); @WXComponentProp(name = Constants.Name.OFFSET_X_ACCURACY) void setOffsetXAccuracy(float accuracy); static final String INDEX; static final String INFINITE; }
@Test public void testSetProperties() throws Exception { ComponentTest.setProperty(component,PROPS,VALUES); } @Test public void testIndicator() throws Exception { WXIndicator indicator = createIndicator(component); ComponentTest.create(indicator); component.addChild(indicator); ComponentTest.setProperty(indicator,IPROPS,IVALUES); }
WXSlider extends WXVContainer<FrameLayout> { @WXComponentProp(name = Constants.Name.OFFSET_X_ACCURACY) public void setOffsetXAccuracy(float accuracy) { this.offsetXAccuracy = accuracy; } @Deprecated WXSlider(WXSDKInstance instance, WXDomObject dom, WXVContainer parent, String instanceId, boolean isLazy); WXSlider(WXSDKInstance instance, WXDomObject node, WXVContainer parent); @Override LayoutParams getChildLayoutParams(WXComponent child,View childView, int width, int height, int left, int right, int top, int bottom); @Override void addEvent(String type); @Override boolean containsGesture(WXGestureType WXGestureType); @Override ViewGroup getRealView(); @Override void remove(WXComponent child, boolean destroy); @Override void destroy(); @Override void onActivityResume(); @Override void onActivityStop(); void addIndicator(WXIndicator indicator); @Deprecated @WXComponentProp(name = Constants.Name.VALUE) void setValue(String value); @WXComponentProp(name = Constants.Name.AUTO_PLAY) void setAutoPlay(String autoPlay); @WXComponentProp(name = Constants.Name.SHOW_INDICATORS) void setShowIndicators(String show); @WXComponentProp(name = Constants.Name.INTERVAL) void setInterval(int intervalMS); @WXComponentProp(name = Constants.Name.INDEX) void setIndex(int index); @WXComponentProp(name = Constants.Name.SCROLLABLE) void setScrollable(boolean scrollable); @WXComponentProp(name = Constants.Name.OFFSET_X_ACCURACY) void setOffsetXAccuracy(float accuracy); static final String INDEX; static final String INFINITE; }
@Test public void testOnScrollListener() throws Exception { component.mViewPager.addOnPageChangeListener(new WXSlider.SliderOnScrollListener(component)); component.setOffsetXAccuracy(0.05f); component.mViewPager.setCurrentItem(0); for (int index=1;index<component.mViewPager.getRealCount();index++) { component.mViewPager.setCurrentItem(index,true); } for (int index=component.mViewPager.getRealCount() - 1;index>=0;index--) { component.mViewPager.setCurrentItem(index,true); } component.mViewPager.setCurrentItem(3,true); component.mViewPager.setCurrentItem(0,true); }
WXImage extends WXComponent<ImageView> { @Override protected ImageView initComponentHostView(@NonNull Context context) { WXImageView view = new WXImageView(context); view.setScaleType(ScaleType.FIT_XY); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { view.setCropToPadding(true); } view.holdComponent(this); return view; } @Deprecated WXImage(WXSDKInstance instance, WXDomObject dom, WXVContainer parent, String instanceId, boolean isLazy); WXImage(WXSDKInstance instance, WXDomObject node, WXVContainer parent); @Override void refreshData(WXComponent component); @WXComponentProp(name = Constants.Name.RESIZE_MODE) void setResizeMode(String resizeMode); @WXComponentProp(name = Constants.Name.RESIZE) void setResize(String resize); @WXComponentProp(name = Constants.Name.SRC) void setSrc(String src); @Override void recycled(); @Override void updateProperties(Map<String, Object> props); @JSMethod(uiThread = false) void save(final JSCallback saveStatuCallback); static final String SUCCEED; static final String ERRORDESC; }
@Test @PrepareForTest(WXImageView.class) public void testInitComponentHostView() throws Exception { ImageView imageView = mWXImage.initComponentHostView(Robolectric.setupActivity(TestActivity.class)); assertEquals(imageView.getClass(), WXImageView.class); } @Test @PrepareForTest(WXImageView.class) public void testSetBackgroundColor() throws Exception { ImageView imageView = mWXImage.initComponentHostView(Robolectric.setupActivity(TestActivity.class)); mWXImage.mHost = imageView; mWXImage.setBackgroundColor("#FFFFFF"); Drawable drawable = mWXImage.getHostView().getBackground(); assertEquals(drawable instanceof BorderDrawable, true); } @Test public void testSetImageBitmap(){ ImageView imageView = mWXImage.initComponentHostView(Robolectric.setupActivity(TestActivity.class)); imageView.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); imageView.setImageBitmap(null); assertNull(imageView.getDrawable()); imageView.setImageBitmap(Bitmap.createBitmap(100, 100, Bitmap.Config.RGB_565)); assertNotNull(imageView.getDrawable()); }
WXImage extends WXComponent<ImageView> { @Override protected boolean setProperty(String key, Object param) { switch (key) { case Constants.Name.RESIZE_MODE: String resize_mode = WXUtils.getString(param, null); if (resize_mode != null) setResizeMode(resize_mode); return true; case Constants.Name.RESIZE: String resize = WXUtils.getString(param, null); if (resize != null) setResize(resize); return true; case Constants.Name.SRC: String src = WXUtils.getString(param, null); if (src != null) setSrc(src); return true; case Constants.Name.IMAGE_QUALITY: return true; case Constants.Name.FILTER: int blurRadius = 0; if(param != null && param instanceof String) { blurRadius = parseBlurRadius((String)param); } if(!TextUtils.isEmpty(this.mSrc)) { setBlurRadius(this.mSrc,blurRadius); } return true; } return super.setProperty(key, param); } @Deprecated WXImage(WXSDKInstance instance, WXDomObject dom, WXVContainer parent, String instanceId, boolean isLazy); WXImage(WXSDKInstance instance, WXDomObject node, WXVContainer parent); @Override void refreshData(WXComponent component); @WXComponentProp(name = Constants.Name.RESIZE_MODE) void setResizeMode(String resizeMode); @WXComponentProp(name = Constants.Name.RESIZE) void setResize(String resize); @WXComponentProp(name = Constants.Name.SRC) void setSrc(String src); @Override void recycled(); @Override void updateProperties(Map<String, Object> props); @JSMethod(uiThread = false) void save(final JSCallback saveStatuCallback); static final String SUCCEED; static final String ERRORDESC; }
@Test public void testSetProperty() throws Exception { ImageView imageView = mWXImage.initComponentHostView(Robolectric.setupActivity(TestActivity.class)); mWXImage.mHost = imageView; mWXImage.setProperty(Constants.Name.RESIZE_MODE, "cover"); ImageView.ScaleType scaleType = mWXImage.getHostView().getScaleType(); assertEquals(scaleType, ImageView.ScaleType.CENTER_CROP); }
WXSDKInstance implements IWXActivityStateListener,DomContext, View.OnLayoutChangeListener { public void fireEvent(String elementRef,final String type, final Map<String, Object> data,final Map<String, Object> domChanges){ WXBridgeManager.getInstance().fireEventOnNode(getInstanceId(),elementRef,type,data,domChanges); } WXSDKInstance(Context context); WXSDKInstance(Context context,String id); void setRenderContainer(RenderContainer a); boolean isTrackComponent(); void setTrackComponent(boolean trackComponent); boolean isLayerTypeEnabled(); void enableLayerType(boolean enable); boolean isNeedValidate(); @Deprecated void setViewPortWidth(int viewPortWidth); @Deprecated static int getViewPortWidth(); void setInstanceViewPortWidth(int instanceViewPortWidth); int getInstanceViewPortWidth(); WXComponent getRootComponent(); void setNestedInstanceInterceptor(NestedInstanceInterceptor interceptor); final WXSDKInstance createNestedInstance(NestedContainer container); void addOnInstanceVisibleListener(OnInstanceVisibleListener l); void removeOnInstanceVisibleListener(OnInstanceVisibleListener l); void init(Context context); void setComponentObserver(ComponentObserver observer); ComponentObserver getComponentObserver(); NativeInvokeHelper getNativeInvokeHelper(); void setBizType(String bizType); ScrollView getScrollView(); void setRootScrollView(ScrollView scrollView); @Deprecated void registerScrollViewListener(WXScrollViewListener scrollViewListener); @Deprecated WXScrollViewListener getScrollViewListener(); @Deprecated void setIWXUserTrackAdapter(IWXUserTrackAdapter adapter); void render(String template, Map<String, Object> options, String jsonInitData); @Deprecated void render(String template, Map<String, Object> options, String jsonInitData, WXRenderStrategy flag); void render(String pageName, String template, Map<String, Object> options, String jsonInitData, WXRenderStrategy flag); @Deprecated void render(String pageName, String template, Map<String, Object> options, String jsonInitData, int width, int height, WXRenderStrategy flag); void render(String template); @Deprecated void render(String template, int width, int height); @Deprecated void renderByUrl(String pageName, final String url, Map<String, Object> options, final String jsonInitData, final int width, final int height, final WXRenderStrategy flag); void renderByUrl(String pageName, final String url, Map<String, Object> options, final String jsonInitData, final WXRenderStrategy flag); void refreshInstance(Map<String, Object> data); void refreshInstance(String jsonData); WXRenderStrategy getRenderStrategy(); @Override Context getUIContext(); String getInstanceId(); Context getContext(); int getWeexHeight(); int getWeexWidth(); IWXImgLoaderAdapter getImgLoaderAdapter(); IDrawableLoader getDrawableLoader(); URIAdapter getURIAdapter(); Uri rewriteUri(Uri uri,String type); IWXHttpAdapter getWXHttpAdapter(); IWXStatisticsListener getWXStatisticsListener(); @Nullable IWebSocketAdapter getWXWebSocketAdapter(); @Deprecated void reloadImages(); boolean isPreRenderMode(); void setPreRenderMode(final boolean isPreRenderMode); void setContext(@NonNull Context context); void registerRenderListener(IWXRenderListener listener); @Deprecated void registerActivityStateListener(IWXActivityStateListener listener); void registerStatisticsListener(IWXStatisticsListener listener); void setLayoutFinishListener(@Nullable LayoutFinishListener listener); LayoutFinishListener getLayoutFinishListener(); void setRenderStartTime(long renderStartTime); @Override void onActivityCreate(); @Override void onActivityStart(); boolean onCreateOptionsMenu(Menu menu); @Override void onActivityPause(); @Override void onActivityResume(); @Override void onActivityStop(); @Override void onActivityDestroy(); @Override boolean onActivityBack(); boolean onBackPressed(); void onActivityResult(int requestCode, int resultCode, Intent data); void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults); void onViewDisappear(); void onViewAppear(); void onCreateFinish(); void onUpdateFinish(); void runOnUiThread(Runnable action); void onRenderSuccess(final int width, final int height); void onRefreshSuccess(final int width, final int height); void onRenderError(final String errCode, final String msg); void onJSException(final String errCode, final String function, final String exception); @Override final void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom); void onLayoutChange(View godView); void firstScreenCreateInstanceTime(long time); void callNativeTime(long time); void jsonParseTime(long time); void firstScreenRenderFinished(); void batchTime(long time); void cssLayoutTime(long time); void applyUpdateTime(long time); void updateDomObjTime(long time); void createInstanceFinished(long time); void commitUTStab(final String type, final WXErrorCode errorCode); synchronized void destroy(); boolean isDestroy(); @Nullable String getBundleUrl(); View getRootView(); View getContainerView(); @Deprecated void setBundleUrl(String url); void onRootCreated(WXComponent root); void moveFixedView(View fixedChild); void removeFixedView(View fixedChild); synchronized List<OnWXScrollListener> getWXScrollListeners(); synchronized void registerOnWXScrollListener(OnWXScrollListener wxScrollListener); void setSize(int width, int height); void fireGlobalEventCallback(String eventName, Map<String,Object> params); void fireEvent(String elementRef,final String type, final Map<String, Object> data,final Map<String, Object> domChanges); void fireEvent(String elementRef,final String type, final Map<String, Object> data); void fireEvent(String ref, String type); void fireModuleEvent(String eventName, WXModule module,Map<String, Object> params); boolean checkModuleEventRegistered(String eventName,WXModule module); WXPerformance getWXPerformance(); Map<String, Serializable> getUserTrackParams(); void addUserTrackParameter(String key,Serializable value); void clearUserTrackParameters(); void removeUserTrackParameter(String key); int getMaxDeepLayer(); void setMaxDeepLayer(int maxDeepLayer); public boolean mEnd; static final String BUNDLE_URL; }
@Test public void testFireEvent() throws Exception { mInstance.fireEvent("1","test"); Map<String,Object> params = new HashMap<>(); params.put("arg1",null); params.put("arg2",123); mInstance.fireEvent("1","test",params); Map<String,Object> domChange = new HashMap<>(); domChange.put("attr1","123"); mInstance.fireEvent("1","test",params,domChange); }
WXImage extends WXComponent<ImageView> { @WXComponentProp(name = Constants.Name.RESIZE_MODE) public void setResizeMode(String resizeMode) { (getHostView()).setScaleType(getResizeMode(resizeMode)); } @Deprecated WXImage(WXSDKInstance instance, WXDomObject dom, WXVContainer parent, String instanceId, boolean isLazy); WXImage(WXSDKInstance instance, WXDomObject node, WXVContainer parent); @Override void refreshData(WXComponent component); @WXComponentProp(name = Constants.Name.RESIZE_MODE) void setResizeMode(String resizeMode); @WXComponentProp(name = Constants.Name.RESIZE) void setResize(String resize); @WXComponentProp(name = Constants.Name.SRC) void setSrc(String src); @Override void recycled(); @Override void updateProperties(Map<String, Object> props); @JSMethod(uiThread = false) void save(final JSCallback saveStatuCallback); static final String SUCCEED; static final String ERRORDESC; }
@Test public void testSetResizeMode() throws Exception { ImageView imageView = mWXImage.initComponentHostView(Robolectric.setupActivity(TestActivity.class)); mWXImage.mHost = imageView; mWXImage.setResizeMode("cover"); ImageView.ScaleType scaleType = mWXImage.getHostView().getScaleType(); assertEquals(scaleType, ImageView.ScaleType.CENTER_CROP); }
WXImage extends WXComponent<ImageView> { @WXComponentProp(name = Constants.Name.RESIZE) public void setResize(String resize) { (getHostView()).setScaleType(getResizeMode(resize)); } @Deprecated WXImage(WXSDKInstance instance, WXDomObject dom, WXVContainer parent, String instanceId, boolean isLazy); WXImage(WXSDKInstance instance, WXDomObject node, WXVContainer parent); @Override void refreshData(WXComponent component); @WXComponentProp(name = Constants.Name.RESIZE_MODE) void setResizeMode(String resizeMode); @WXComponentProp(name = Constants.Name.RESIZE) void setResize(String resize); @WXComponentProp(name = Constants.Name.SRC) void setSrc(String src); @Override void recycled(); @Override void updateProperties(Map<String, Object> props); @JSMethod(uiThread = false) void save(final JSCallback saveStatuCallback); static final String SUCCEED; static final String ERRORDESC; }
@Test public void testSetResize() throws Exception { ImageView imageView = mWXImage.initComponentHostView(Robolectric.setupActivity(TestActivity.class)); mWXImage.mHost = imageView; mWXImage.setResize("cover"); ImageView.ScaleType scaleType = mWXImage.getHostView().getScaleType(); assertEquals(scaleType, ImageView.ScaleType.CENTER_CROP); }
WXImage extends WXComponent<ImageView> { @WXComponentProp(name = Constants.Name.SRC) public void setSrc(String src) { if (src == null) { return; } ImageView image = getHostView(); if("".equals(src) && image != null){ image.setImageDrawable(null); return; } this.mSrc = src; WXSDKInstance instance = getInstance(); Uri rewrited = instance.rewriteUri(Uri.parse(src), URIAdapter.IMAGE); if (Constants.Scheme.LOCAL.equals(rewrited.getScheme())) { setLocalSrc(rewrited); } else { int blur = 0; if(getDomObject() != null) { String blurStr = getDomObject().getStyles().getBlur(); blur = parseBlurRadius(blurStr); } setRemoteSrc(rewrited, blur); } } @Deprecated WXImage(WXSDKInstance instance, WXDomObject dom, WXVContainer parent, String instanceId, boolean isLazy); WXImage(WXSDKInstance instance, WXDomObject node, WXVContainer parent); @Override void refreshData(WXComponent component); @WXComponentProp(name = Constants.Name.RESIZE_MODE) void setResizeMode(String resizeMode); @WXComponentProp(name = Constants.Name.RESIZE) void setResize(String resize); @WXComponentProp(name = Constants.Name.SRC) void setSrc(String src); @Override void recycled(); @Override void updateProperties(Map<String, Object> props); @JSMethod(uiThread = false) void save(final JSCallback saveStatuCallback); static final String SUCCEED; static final String ERRORDESC; }
@Test public void testSetSrc() throws Exception { TestDomObject.setAttribute((WXDomObject)mWXImage.getDomObject(),PowerMockito.mock(WXAttr.class)); PowerMockito.when(mWXImage.getDomObject().getAttrs().getImageSharpen()).thenReturn(WXImageSharpen.SHARPEN); mWXImage.setSrc(""); }
WXComponent implements IWXObject, IWXActivityStateListener,OnActivePseudoListner { protected boolean setProperty(String key, Object param) { switch (key) { case Constants.Name.PREVENT_MOVE_EVENT: if(mGesture != null){ mGesture.setPreventMoveEvent(WXUtils.getBoolean(param,false)); } return true; case Constants.Name.DISABLED: Boolean disabled = WXUtils.getBoolean(param,null); if (disabled != null) { setDisabled(disabled); setPseudoClassStatus(Constants.PSEUDO.DISABLED, disabled); } return true; case Constants.Name.POSITION: String position = WXUtils.getString(param,null); if (position != null) setSticky(position); return true; case Constants.Name.BACKGROUND_COLOR: String bgColor = WXUtils.getString(param,null); if (bgColor != null) setBackgroundColor(bgColor); return true; case Constants.Name.BACKGROUND_IMAGE: String bgImage = WXUtils.getString(param, null); if (bgImage != null && mHost != null) { setBackgroundImage(bgImage); } return true; case Constants.Name.OPACITY: Float opacity = WXUtils.getFloat(param,null); if (opacity != null) setOpacity(opacity); return true; case Constants.Name.BORDER_RADIUS: case Constants.Name.BORDER_TOP_LEFT_RADIUS: case Constants.Name.BORDER_TOP_RIGHT_RADIUS: case Constants.Name.BORDER_BOTTOM_RIGHT_RADIUS: case Constants.Name.BORDER_BOTTOM_LEFT_RADIUS: Float radius = WXUtils.getFloat(param,null); if (radius != null) setBorderRadius(key,radius); return true; case Constants.Name.BORDER_WIDTH: case Constants.Name.BORDER_TOP_WIDTH: case Constants.Name.BORDER_RIGHT_WIDTH: case Constants.Name.BORDER_BOTTOM_WIDTH: case Constants.Name.BORDER_LEFT_WIDTH: Float width = WXUtils.getFloat(param,null); if (width != null) setBorderWidth(key,width); return true; case Constants.Name.BORDER_STYLE: case Constants.Name.BORDER_RIGHT_STYLE: case Constants.Name.BORDER_BOTTOM_STYLE: case Constants.Name.BORDER_LEFT_STYLE: case Constants.Name.BORDER_TOP_STYLE: String border_style = WXUtils.getString(param,null); if (border_style != null) setBorderStyle(key, border_style); return true; case Constants.Name.BORDER_COLOR: case Constants.Name.BORDER_TOP_COLOR: case Constants.Name.BORDER_RIGHT_COLOR: case Constants.Name.BORDER_BOTTOM_COLOR: case Constants.Name.BORDER_LEFT_COLOR: String border_color = WXUtils.getString(param,null); if (border_color != null) setBorderColor(key, border_color); return true; case Constants.Name.VISIBILITY: String visibility = WXUtils.getString(param,null); if (visibility != null) setVisibility(visibility); return true; case Constants.Name.ELEVATION: if(param!=null) { updateElevation(); } return true; case PROP_FIXED_SIZE: String fixedSize = WXUtils.getString(param, PROP_FS_MATCH_PARENT); setFixedSize(fixedSize); return true; case Constants.Name.ARIA_LABEL: String label = WXUtils.getString(param,""); setAriaLabel(label); return true; case Constants.Name.ARIA_HIDDEN: boolean isHidden = WXUtils.getBoolean(param,false); setAriaHidden(isHidden); return true; case Constants.Name.WIDTH: case Constants.Name.MIN_WIDTH: case Constants.Name.MAX_WIDTH: case Constants.Name.HEIGHT: case Constants.Name.MIN_HEIGHT: case Constants.Name.MAX_HEIGHT: case Constants.Name.ALIGN_ITEMS: case Constants.Name.ALIGN_SELF: case Constants.Name.FLEX: case Constants.Name.FLEX_DIRECTION: case Constants.Name.JUSTIFY_CONTENT: case Constants.Name.FLEX_WRAP: case Constants.Name.MARGIN: case Constants.Name.MARGIN_TOP: case Constants.Name.MARGIN_LEFT: case Constants.Name.MARGIN_RIGHT: case Constants.Name.MARGIN_BOTTOM: case Constants.Name.PADDING: case Constants.Name.PADDING_TOP: case Constants.Name.PADDING_LEFT: case Constants.Name.PADDING_RIGHT: case Constants.Name.PADDING_BOTTOM: case Constants.Name.LEFT: case Constants.Name.TOP: case Constants.Name.RIGHT: case Constants.Name.BOTTOM: return true; default: return false; } } @Deprecated WXComponent(WXSDKInstance instance, WXDomObject dom, WXVContainer parent, String instanceId, boolean isLazy); @Deprecated WXComponent(WXSDKInstance instance, WXDomObject dom, WXVContainer parent, boolean isLazy); WXComponent(WXSDKInstance instance, WXDomObject dom, WXVContainer parent); WXComponent(WXSDKInstance instance, WXDomObject dom, WXVContainer parent, int type); void postAnimation(WXAnimationModule.AnimationHolder holder); String getInstanceId(); Rect getComponentSize(); final void invoke(String method, JSONArray args); void bindHolder(IFComponentHolder holder); WXSDKInstance getInstance(); Context getContext(); final void fireEvent(String type); final void fireEvent(String type, Map<String, Object> params); boolean isLazy(); void applyLayoutAndEvent(WXComponent component); void bindData(WXComponent component); void updateStyle(WXComponent component); void updateAttrs(WXComponent component); void refreshData(WXComponent component); final void setLayout(ImmutableDomObject domObject); int getLayoutTopOffsetForSibling(); float getLayoutWidth(); float getLayoutHeight(); void setPadding(Spacing padding, Spacing border); void updateExtra(Object extra); ImmutableDomObject getDomObject(); @Deprecated void updateProperties(Map<String, Object> props); void addEvent(String type); View getRealView(); Scrollable getParentScroller(); @Nullable Scrollable getFirstScroller(); WXVContainer getParent(); String getRef(); final void createView(); T getHostView(); @Deprecated View getView(); int getAbsoluteY(); int getAbsoluteX(); void updateDom(WXDomObject dom); final void removeEvent(String type); final void removeAllEvent(); final void removeStickyStyle(); boolean isSticky(); boolean isFixed(); void setDisabled(boolean disabled); boolean isDisabled(); void setSticky(String sticky); void setBackgroundColor(String color); void setBackgroundImage(@NonNull String bgImage); void setOpacity(float opacity); void setBorderRadius(String key, float borderRadius); void setBorderWidth(String key, float borderWidth); void setBorderStyle(String key, String borderStyle); void setBorderColor(String key, String borderColor); @Nullable String getVisibility(); void setVisibility(String visibility); @Deprecated void registerActivityStateListener(); void onActivityCreate(); void onActivityStart(); void onActivityPause(); void onActivityResume(); void onActivityStop(); void onActivityDestroy(); boolean onActivityBack(); void onActivityResult(int requestCode, int resultCode, Intent data); boolean onCreateOptionsMenu(Menu menu); void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults); void recycled(); void destroy(); boolean isDestoryed(); View detachViewAndClearPreInfo(); void computeVisiblePointInViewCoordinate(PointF pointF); boolean containsGesture(WXGestureType WXGestureType); void notifyAppearStateChange(String wxEventType,String direction); boolean isUsing(); void setUsing(boolean using); void readyToRender(); boolean isVirtualComponent(); void removeVirtualComponent(); void setType(int type); boolean hasScrollParent(WXComponent component); @Override void updateActivePseudo(boolean isSet); int getStickyOffset(); boolean canRecycled(); void setStickyOffset(int stickyOffset); boolean isLayerTypeEnabled(); void setNeedLayoutOnAnimation(boolean need); void notifyNativeSizeChanged(int w, int h); static final String PROP_FIXED_SIZE; static final String PROP_FS_MATCH_PARENT; static final String PROP_FS_WRAP_CONTENT; static int mComponentNum; static final int TYPE_COMMON; static final int TYPE_VIRTUAL; }
@Test public void testSetProperty() throws Exception { assertTrue(component.setProperty(Constants.Name.VISIBILITY,null)); assertTrue(component.setProperty(Constants.Name.VISIBILITY, Constants.Value.VISIBLE)); assertTrue(component.setProperty(Constants.Name.DISABLED,true)); assertTrue(component.setProperty(Constants.Name.POSITION, Constants.Value.FIXED)); assertTrue(component.setProperty(Constants.Name.BACKGROUND_COLOR, "#ffffff")); assertTrue(component.setProperty(Constants.Name.OPACITY, 0.5f)); assertTrue(component.setProperty(Constants.Name.BORDER_RADIUS,0.5f)); assertTrue(component.setProperty(Constants.Name.BORDER_RADIUS,null)); assertTrue(component.setProperty(Constants.Name.BORDER_WIDTH,null)); assertTrue(component.setProperty(Constants.Name.BORDER_WIDTH,10)); assertTrue(component.setProperty(Constants.Name.BORDER_STYLE,null)); assertTrue(component.setProperty(Constants.Name.BORDER_STYLE, "SOLID")); assertTrue(component.setProperty(Constants.Name.BORDER_COLOR,null)); assertTrue(component.setProperty(Constants.Name.BORDER_COLOR, "#ff0000")); assertTrue(component.setProperty(Constants.Name.BORDER_TOP_LEFT_RADIUS, 1)); assertTrue(component.setProperty(Constants.Name.BORDER_TOP_RIGHT_RADIUS, 1)); assertTrue(component.setProperty(Constants.Name.BORDER_BOTTOM_LEFT_RADIUS, 1)); assertTrue(component.setProperty(Constants.Name.BORDER_BOTTOM_RIGHT_RADIUS, 1)); assertTrue(component.setProperty(Constants.Name.BORDER_TOP_WIDTH, 1)); assertTrue(component.setProperty(Constants.Name.BORDER_LEFT_WIDTH, 1)); assertTrue(component.setProperty(Constants.Name.BORDER_BOTTOM_WIDTH, 1)); assertTrue(component.setProperty(Constants.Name.BORDER_RIGHT_WIDTH,1)); assertTrue(component.setProperty(Constants.Name.BORDER_TOP_COLOR, "#ff0000")); assertTrue(component.setProperty(Constants.Name.BORDER_BOTTOM_COLOR, "#ff0000")); assertTrue(component.setProperty(Constants.Name.BORDER_LEFT_COLOR, "#ff0000")); assertTrue(component.setProperty(Constants.Name.BORDER_RIGHT_COLOR, "#ff0000")); assertTrue(component.setProperty(Constants.Name.WIDTH, null)); assertTrue(component.setProperty(Constants.Name.MIN_WIDTH, null)); assertTrue(component.setProperty(Constants.Name.MAX_WIDTH, null)); assertTrue(component.setProperty(Constants.Name.HEIGHT, null)); assertTrue(component.setProperty(Constants.Name.MIN_HEIGHT, null)); assertTrue(component.setProperty(Constants.Name.MAX_HEIGHT, null)); assertTrue(component.setProperty(Constants.Name.ALIGN_ITEMS, null)); assertTrue(component.setProperty(Constants.Name.ALIGN_SELF, null)); assertTrue(component.setProperty(Constants.Name.FLEX, null)); assertTrue(component.setProperty(Constants.Name.FLEX_DIRECTION, null)); assertTrue(component.setProperty(Constants.Name.JUSTIFY_CONTENT, null)); assertTrue(component.setProperty(Constants.Name.FLEX_WRAP, null)); assertTrue(component.setProperty(Constants.Name.MARGIN, null)); assertTrue(component.setProperty(Constants.Name.MARGIN_TOP, null)); assertTrue(component.setProperty(Constants.Name.MARGIN_LEFT, null)); assertTrue(component.setProperty(Constants.Name.MARGIN_RIGHT, null)); assertTrue(component.setProperty(Constants.Name.MARGIN_BOTTOM, null)); assertTrue(component.setProperty(Constants.Name.PADDING, null)); assertTrue(component.setProperty(Constants.Name.PADDING_TOP, null)); assertTrue(component.setProperty(Constants.Name.PADDING_LEFT, null)); assertTrue(component.setProperty(Constants.Name.PADDING_RIGHT, null)); assertTrue(component.setProperty(Constants.Name.PADDING_BOTTOM, null)); }
WXComponent implements IWXObject, IWXActivityStateListener,OnActivePseudoListner { public void addEvent(String type) { if (TextUtils.isEmpty(type) || mAppendEvents.contains(type)) { return; } mAppendEvents.add(type); View view = getRealView(); if (type.equals(Constants.Event.CLICK) && view != null) { addClickListener(mClickEventListener); } else if ((type.equals( Constants.Event.FOCUS) || type.equals( Constants.Event.BLUR)) ) { addFocusChangeListener(new OnFocusChangeListener() { public void onFocusChange(boolean hasFocus) { Map<String, Object> params = new HashMap<>(); params.put("timeStamp", System.currentTimeMillis()); fireEvent(hasFocus ? Constants.Event.FOCUS : Constants.Event.BLUR, params); } }); } else if (view != null && needGestureDetector(type)) { if (view instanceof WXGestureObservable) { if (mGesture == null) { mGesture = new WXGesture(this, mContext); boolean isPreventMove = WXUtils.getBoolean(getDomObject().getAttrs().get(Constants.Name.PREVENT_MOVE_EVENT),false); mGesture.setPreventMoveEvent(isPreventMove); } mGestureType.add(type); ((WXGestureObservable) view).registerGestureListener(mGesture); } else { WXLogUtils.e(view.getClass().getSimpleName() + " don't implement " + "WXGestureObservable, so no gesture is supported."); } } else { Scrollable scroller = getParentScroller(); if (type.equals(Constants.Event.APPEAR) && scroller != null) { scroller.bindAppearEvent(this); } if (type.equals(Constants.Event.DISAPPEAR) && scroller != null) { scroller.bindDisappearEvent(this); } } } @Deprecated WXComponent(WXSDKInstance instance, WXDomObject dom, WXVContainer parent, String instanceId, boolean isLazy); @Deprecated WXComponent(WXSDKInstance instance, WXDomObject dom, WXVContainer parent, boolean isLazy); WXComponent(WXSDKInstance instance, WXDomObject dom, WXVContainer parent); WXComponent(WXSDKInstance instance, WXDomObject dom, WXVContainer parent, int type); void postAnimation(WXAnimationModule.AnimationHolder holder); String getInstanceId(); Rect getComponentSize(); final void invoke(String method, JSONArray args); void bindHolder(IFComponentHolder holder); WXSDKInstance getInstance(); Context getContext(); final void fireEvent(String type); final void fireEvent(String type, Map<String, Object> params); boolean isLazy(); void applyLayoutAndEvent(WXComponent component); void bindData(WXComponent component); void updateStyle(WXComponent component); void updateAttrs(WXComponent component); void refreshData(WXComponent component); final void setLayout(ImmutableDomObject domObject); int getLayoutTopOffsetForSibling(); float getLayoutWidth(); float getLayoutHeight(); void setPadding(Spacing padding, Spacing border); void updateExtra(Object extra); ImmutableDomObject getDomObject(); @Deprecated void updateProperties(Map<String, Object> props); void addEvent(String type); View getRealView(); Scrollable getParentScroller(); @Nullable Scrollable getFirstScroller(); WXVContainer getParent(); String getRef(); final void createView(); T getHostView(); @Deprecated View getView(); int getAbsoluteY(); int getAbsoluteX(); void updateDom(WXDomObject dom); final void removeEvent(String type); final void removeAllEvent(); final void removeStickyStyle(); boolean isSticky(); boolean isFixed(); void setDisabled(boolean disabled); boolean isDisabled(); void setSticky(String sticky); void setBackgroundColor(String color); void setBackgroundImage(@NonNull String bgImage); void setOpacity(float opacity); void setBorderRadius(String key, float borderRadius); void setBorderWidth(String key, float borderWidth); void setBorderStyle(String key, String borderStyle); void setBorderColor(String key, String borderColor); @Nullable String getVisibility(); void setVisibility(String visibility); @Deprecated void registerActivityStateListener(); void onActivityCreate(); void onActivityStart(); void onActivityPause(); void onActivityResume(); void onActivityStop(); void onActivityDestroy(); boolean onActivityBack(); void onActivityResult(int requestCode, int resultCode, Intent data); boolean onCreateOptionsMenu(Menu menu); void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults); void recycled(); void destroy(); boolean isDestoryed(); View detachViewAndClearPreInfo(); void computeVisiblePointInViewCoordinate(PointF pointF); boolean containsGesture(WXGestureType WXGestureType); void notifyAppearStateChange(String wxEventType,String direction); boolean isUsing(); void setUsing(boolean using); void readyToRender(); boolean isVirtualComponent(); void removeVirtualComponent(); void setType(int type); boolean hasScrollParent(WXComponent component); @Override void updateActivePseudo(boolean isSet); int getStickyOffset(); boolean canRecycled(); void setStickyOffset(int stickyOffset); boolean isLayerTypeEnabled(); void setNeedLayoutOnAnimation(boolean need); void notifyNativeSizeChanged(int w, int h); static final String PROP_FIXED_SIZE; static final String PROP_FS_MATCH_PARENT; static final String PROP_FS_WRAP_CONTENT; static int mComponentNum; static final int TYPE_COMMON; static final int TYPE_VIRTUAL; }
@Test public void testAddEvent() throws Exception { component.addEvent(Constants.Event.FOCUS); }
WXListComponent extends BasicListComponent<BounceRecyclerView> { @Override public void addChild(WXComponent child, int index) { super.addChild(child, index); if (child == null || index < -1) { return; } setRefreshOrLoading(child); if(mDomObject != null && getHostView() != null && (mColumnWidth != mDomObject.getColumnWidth() || mColumnCount != mDomObject.getColumnCount() || mColumnGap != mDomObject.getColumnGap())) { updateRecyclerAttr(); getHostView().getInnerView().initView(getContext(), mLayoutType,mColumnCount,mColumnGap,getOrientation()); } } @Deprecated WXListComponent(WXSDKInstance instance, WXDomObject dom, WXVContainer parent, String instanceId, boolean isLazy); WXListComponent(WXSDKInstance instance, WXDomObject node, WXVContainer parent, boolean lazy); @Override void addChild(WXComponent child, int index); @WXComponentProp(name = Constants.Name.COLUMN_WIDTH) void setColumnWidth(int columnCount); @WXComponentProp(name = Constants.Name.COLUMN_COUNT) void setColumnCount(int columnCount); @WXComponentProp(name = Constants.Name.COLUMN_GAP) void setColumnGap(float columnGap); @WXComponentProp(name = Constants.Name.SCROLLABLE) void setScrollable(boolean scrollable); @Override void updateProperties(Map<String, Object> props); @Override void createChildViewAt(int index); void remove(WXComponent child, boolean destroy); }
@Test public void testAddChild() throws Exception { WXComponent child = WXDivTest.create(component); ComponentTest.create(child); component.addChild(child); child = WXHeaderTest.create(component); ComponentTest.create(child); component.addChild(child); } @Test public void testScrollTo() throws Exception { WXComponent child = WXDivTest.create(component); ComponentTest.create(child); component.addChild(child); child = WXHeaderTest.create(component); ComponentTest.create(child); component.addChild(child); Map<String, Object> options = new HashMap<>(2); options.put("offset", 10); options.put("animated", false); component.scrollTo(child,options); } @Test public void testAppear() throws Exception { WXComponent child = WXDivTest.create(component); ComponentTest.create(child); component.addChild(child); component.bindAppearEvent(child); component.notifyAppearStateChange(0,0,0,10); }
DefaultDragHelper implements DragHelper { @Override public void onDragStart(@NonNull WXComponent component, int from) { if (WXEnvironment.isApkDebugable()) { WXLogUtils.d(TAG, "list on drag start : from index " + from); } mEventTrigger.triggerEvent(EVENT_START_DRAG, buildEvent(component.getRef(), from, -1)); } DefaultDragHelper(@NonNull List<WXComponent> dataSource, @NonNull RecyclerView recyclerView, @NonNull EventTrigger trigger); @Override void onDragStart(@NonNull WXComponent component, int from); @Override void onDragEnd(@NonNull WXComponent component, int from, int to); @Override void onDragging(int fromPos, int toPos); @Override boolean isLongPressDragEnabled(); @Override void setLongPressDragEnabled(boolean enabled); @Override void startDrag(@NonNull RecyclerView.ViewHolder viewHolder); @Override boolean isDraggable(); @Override void setDraggable(boolean draggable); @Override void setDragExcluded(@NonNull RecyclerView.ViewHolder viewHolder, boolean isExcluded); @Override boolean isDragExcluded(@NonNull RecyclerView.ViewHolder viewHolder); }
@Test public void onDragStart() throws Exception { WXComponent c = new WXCell(WXSDKInstanceTest.createInstance(),new TestDomObject(),null,false); mFakeDragHelper.onDragStart(c,3); verify(mockedEventTrigger).triggerEvent(eq("dragstart"),anyMap()); }
WXSDKInstance implements IWXActivityStateListener,DomContext, View.OnLayoutChangeListener { public void onJSException(final String errCode, final String function, final String exception) { if (mRenderListener != null && mContext != null) { runOnUiThread(new Runnable() { @Override public void run() { if (mRenderListener != null && mContext != null) { StringBuilder builder = new StringBuilder(); builder.append(function); builder.append(exception); mRenderListener.onException(WXSDKInstance.this, errCode, builder.toString()); } } }); } } WXSDKInstance(Context context); WXSDKInstance(Context context,String id); void setRenderContainer(RenderContainer a); boolean isTrackComponent(); void setTrackComponent(boolean trackComponent); boolean isLayerTypeEnabled(); void enableLayerType(boolean enable); boolean isNeedValidate(); @Deprecated void setViewPortWidth(int viewPortWidth); @Deprecated static int getViewPortWidth(); void setInstanceViewPortWidth(int instanceViewPortWidth); int getInstanceViewPortWidth(); WXComponent getRootComponent(); void setNestedInstanceInterceptor(NestedInstanceInterceptor interceptor); final WXSDKInstance createNestedInstance(NestedContainer container); void addOnInstanceVisibleListener(OnInstanceVisibleListener l); void removeOnInstanceVisibleListener(OnInstanceVisibleListener l); void init(Context context); void setComponentObserver(ComponentObserver observer); ComponentObserver getComponentObserver(); NativeInvokeHelper getNativeInvokeHelper(); void setBizType(String bizType); ScrollView getScrollView(); void setRootScrollView(ScrollView scrollView); @Deprecated void registerScrollViewListener(WXScrollViewListener scrollViewListener); @Deprecated WXScrollViewListener getScrollViewListener(); @Deprecated void setIWXUserTrackAdapter(IWXUserTrackAdapter adapter); void render(String template, Map<String, Object> options, String jsonInitData); @Deprecated void render(String template, Map<String, Object> options, String jsonInitData, WXRenderStrategy flag); void render(String pageName, String template, Map<String, Object> options, String jsonInitData, WXRenderStrategy flag); @Deprecated void render(String pageName, String template, Map<String, Object> options, String jsonInitData, int width, int height, WXRenderStrategy flag); void render(String template); @Deprecated void render(String template, int width, int height); @Deprecated void renderByUrl(String pageName, final String url, Map<String, Object> options, final String jsonInitData, final int width, final int height, final WXRenderStrategy flag); void renderByUrl(String pageName, final String url, Map<String, Object> options, final String jsonInitData, final WXRenderStrategy flag); void refreshInstance(Map<String, Object> data); void refreshInstance(String jsonData); WXRenderStrategy getRenderStrategy(); @Override Context getUIContext(); String getInstanceId(); Context getContext(); int getWeexHeight(); int getWeexWidth(); IWXImgLoaderAdapter getImgLoaderAdapter(); IDrawableLoader getDrawableLoader(); URIAdapter getURIAdapter(); Uri rewriteUri(Uri uri,String type); IWXHttpAdapter getWXHttpAdapter(); IWXStatisticsListener getWXStatisticsListener(); @Nullable IWebSocketAdapter getWXWebSocketAdapter(); @Deprecated void reloadImages(); boolean isPreRenderMode(); void setPreRenderMode(final boolean isPreRenderMode); void setContext(@NonNull Context context); void registerRenderListener(IWXRenderListener listener); @Deprecated void registerActivityStateListener(IWXActivityStateListener listener); void registerStatisticsListener(IWXStatisticsListener listener); void setLayoutFinishListener(@Nullable LayoutFinishListener listener); LayoutFinishListener getLayoutFinishListener(); void setRenderStartTime(long renderStartTime); @Override void onActivityCreate(); @Override void onActivityStart(); boolean onCreateOptionsMenu(Menu menu); @Override void onActivityPause(); @Override void onActivityResume(); @Override void onActivityStop(); @Override void onActivityDestroy(); @Override boolean onActivityBack(); boolean onBackPressed(); void onActivityResult(int requestCode, int resultCode, Intent data); void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults); void onViewDisappear(); void onViewAppear(); void onCreateFinish(); void onUpdateFinish(); void runOnUiThread(Runnable action); void onRenderSuccess(final int width, final int height); void onRefreshSuccess(final int width, final int height); void onRenderError(final String errCode, final String msg); void onJSException(final String errCode, final String function, final String exception); @Override final void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom); void onLayoutChange(View godView); void firstScreenCreateInstanceTime(long time); void callNativeTime(long time); void jsonParseTime(long time); void firstScreenRenderFinished(); void batchTime(long time); void cssLayoutTime(long time); void applyUpdateTime(long time); void updateDomObjTime(long time); void createInstanceFinished(long time); void commitUTStab(final String type, final WXErrorCode errorCode); synchronized void destroy(); boolean isDestroy(); @Nullable String getBundleUrl(); View getRootView(); View getContainerView(); @Deprecated void setBundleUrl(String url); void onRootCreated(WXComponent root); void moveFixedView(View fixedChild); void removeFixedView(View fixedChild); synchronized List<OnWXScrollListener> getWXScrollListeners(); synchronized void registerOnWXScrollListener(OnWXScrollListener wxScrollListener); void setSize(int width, int height); void fireGlobalEventCallback(String eventName, Map<String,Object> params); void fireEvent(String elementRef,final String type, final Map<String, Object> data,final Map<String, Object> domChanges); void fireEvent(String elementRef,final String type, final Map<String, Object> data); void fireEvent(String ref, String type); void fireModuleEvent(String eventName, WXModule module,Map<String, Object> params); boolean checkModuleEventRegistered(String eventName,WXModule module); WXPerformance getWXPerformance(); Map<String, Serializable> getUserTrackParams(); void addUserTrackParameter(String key,Serializable value); void clearUserTrackParameters(); void removeUserTrackParameter(String key); int getMaxDeepLayer(); void setMaxDeepLayer(int maxDeepLayer); public boolean mEnd; static final String BUNDLE_URL; }
@Test public void testOnJSException() throws Exception { mInstance.onJSException(null,null,null); mInstance.onJSException("100","test","some error"); }
AnnotationSpans { public static AnnotationSpans extractAnnotationSpans(JCas jCas) { BidiMap sentenceBeginIndexToCharacterIndex = new TreeBidiMap(); BidiMap sentenceEndIndexToCharacterIndex = new TreeBidiMap(); List<Sentence> sentences = new ArrayList<>(JCasUtil.select(jCas, Sentence.class)); for (int i = 0; i < sentences.size(); i++) { Sentence sentence = sentences.get(i); sentenceBeginIndexToCharacterIndex.put(i, sentence.getBegin()); sentenceEndIndexToCharacterIndex.put(i, sentence.getEnd()); } AnnotationSpans annotationSpans = new AnnotationSpans( sentenceBeginIndexToCharacterIndex.size()); Collection<ArgumentComponent> components = JCasUtil.select(jCas, ArgumentComponent.class); for (ArgumentComponent component : components) { if (!ArgumentUnitUtils.isImplicit(component)) { int relativeOffset = (int) sentenceBeginIndexToCharacterIndex .getKey(component.getBegin()); int endingSentenceIndex = (int) sentenceEndIndexToCharacterIndex .getKey(component.getEnd()); int length = endingSentenceIndex - relativeOffset + 1; String type = component.getType().getShortName(); SingleAnnotationSpan singleAnnotationSpan = new SingleAnnotationSpan(type, relativeOffset, length); annotationSpans.getAnnotationSpans().add(singleAnnotationSpan); } } return annotationSpans; } AnnotationSpans(int documentLength); static AnnotationSpans extractAnnotationSpans(JCas jCas); int getDocumentLength(); List<SingleAnnotationSpan> getAnnotationSpans(); @Override String toString(); }
@Test public void extractAnnotationSpans() throws Exception { System.out.println(AnnotationSpans.extractAnnotationSpans(jCas)); }
BookResource { @DELETE @Path("/{id : \\d+}") @ApiOperation(value = "Delete a Book") @ApiResponses(value = { @ApiResponse(code = 204, message = "Book has been deleted"), @ApiResponse(code = 400, message = "Invalid input") }) public Response delete(@PathParam("id") final Long id) { log.info("Deleting the book " + id); bookRepository.deleteById(id); return noContent().build(); } @GET @Path("/{id : \\d+}") @Produces(APPLICATION_JSON) @ApiOperation(value = "Find a Book by the Id.", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Book found"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 404, message = "Book not found") }) Response findById(@PathParam("id") final Long id); @GET @Produces(APPLICATION_JSON) @ApiOperation(value = "Find all Books", response = Book.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = "All books found"), @ApiResponse(code = 404, message = "Books not found")} ) Response findAll(); @POST @Consumes(APPLICATION_JSON) @ApiOperation(value = "Create a Book") @ApiResponses(value = { @ApiResponse(code = 201, message = "The book is created"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 415, message = "Format is not JSon") }) // tag::adocSnippet[] Response create(@ApiParam(value = "Book to be created", required = true) Book book, @Context UriInfo uriInfo); @PUT @Path("/{id : \\d+}") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) @ApiOperation(value = "Update a Book", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "The book is updated"), @ApiResponse(code = 400, message = "Invalid input") }) Response update(@PathParam("id") final Long id, @ApiParam(value = "Book to be updated", required = true) Book book); @DELETE @Path("/{id : \\d+}") @ApiOperation(value = "Delete a Book") @ApiResponses(value = { @ApiResponse(code = 204, message = "Book has been deleted"), @ApiResponse(code = 400, message = "Invalid input") }) Response delete(@PathParam("id") final Long id); @GET @Path("health") @ApiOperation(value = "Checks the health of this REST endpoint", response = String.class) Response health(); @GET @Path("number") @ApiOperation(value = "Wraps the Number API to retrive a Book Number", response = String.class) Response number(); }
@Test @InSequence(5) public void delete() throws Exception { final Response response = webTarget.path("{id}") .resolveTemplate("id", 1) .request() .delete(); assertEquals(NO_CONTENT.getStatusCode(), response.getStatus()); }
NumberResource { @GET @Path("book") @ApiOperation(value = "Generates a book number.", response = String.class) public Response generateBookNumber() throws InterruptedException { final Config config = ConfigProvider.getConfig(); config.getOptionalValue("NUMBER_API_FAKE_TIMEOUT", Integer.class).ifPresent(t -> numberApiFakeTimeout = t); log.info("Waiting for " + numberApiFakeTimeout + " seconds"); TimeUnit.SECONDS.sleep(numberApiFakeTimeout); log.info("Generating a book number"); return Response.ok("BK-" + Math.random()).build(); } @GET @Path("book") @ApiOperation(value = "Generates a book number.", response = String.class) Response generateBookNumber(); @GET @Path("health") @ApiOperation(value = "Health of this REST endpoint", response = String.class) Response health(); }
@Test public void generateBookNumber() throws Exception { final Response response = webTarget.path("book").request().get(); assertEquals(OK.getStatusCode(), response.getStatus()); assertTrue(response.readEntity(String.class).startsWith("BK-")); }
BookResource { @GET @Path("/{id : \\d+}") @Produces(APPLICATION_JSON) @ApiOperation(value = "Find a Book by the Id.", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Book found"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 404, message = "Book not found") }) public Response findById(@PathParam("id") final Long id) { log.info("Getting the book " + id); return ofNullable(bookRepository.findById(id)) .map(Response::ok) .orElse(status(NOT_FOUND)) .build(); } @GET @Path("/{id : \\d+}") @Produces(APPLICATION_JSON) @ApiOperation(value = "Find a Book by the Id.", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Book found"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 404, message = "Book not found") }) Response findById(@PathParam("id") final Long id); @GET @Produces(APPLICATION_JSON) @ApiOperation(value = "Find all Books", response = Book.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = "All books found"), @ApiResponse(code = 404, message = "Books not found")} ) Response findAll(); @POST @Consumes(APPLICATION_JSON) @ApiOperation(value = "Create a Book") @ApiResponses(value = { @ApiResponse(code = 201, message = "The book is created"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 415, message = "Format is not JSon") }) // tag::adocSnippet[] Response create(@ApiParam(value = "Book to be created", required = true) Book book, @Context UriInfo uriInfo); @PUT @Path("/{id : \\d+}") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) @ApiOperation(value = "Update a Book", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "The book is updated"), @ApiResponse(code = 400, message = "Invalid input") }) Response update(@PathParam("id") final Long id, @ApiParam(value = "Book to be updated", required = true) Book book); @DELETE @Path("/{id : \\d+}") @ApiOperation(value = "Delete a Book") @ApiResponses(value = { @ApiResponse(code = 204, message = "Book has been deleted"), @ApiResponse(code = 400, message = "Invalid input") }) Response delete(@PathParam("id") final Long id); @GET @Path("health") @ApiOperation(value = "Checks the health of this REST endpoint", response = String.class) Response health(); }
@Test @InSequence(1) public void findById() throws Exception { final Response response = webTarget.path("{id}").resolveTemplate("id", 0).request().get(); assertEquals(OK.getStatusCode(), response.getStatus()); }
BookResource { @GET @Produces(APPLICATION_JSON) @ApiOperation(value = "Find all Books", response = Book.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = "All books found"), @ApiResponse(code = 404, message = "Books not found")} ) public Response findAll() { log.info("Getting all the books"); return ok(bookRepository.findAll()).build(); } @GET @Path("/{id : \\d+}") @Produces(APPLICATION_JSON) @ApiOperation(value = "Find a Book by the Id.", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Book found"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 404, message = "Book not found") }) Response findById(@PathParam("id") final Long id); @GET @Produces(APPLICATION_JSON) @ApiOperation(value = "Find all Books", response = Book.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = "All books found"), @ApiResponse(code = 404, message = "Books not found")} ) Response findAll(); @POST @Consumes(APPLICATION_JSON) @ApiOperation(value = "Create a Book") @ApiResponses(value = { @ApiResponse(code = 201, message = "The book is created"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 415, message = "Format is not JSon") }) // tag::adocSnippet[] Response create(@ApiParam(value = "Book to be created", required = true) Book book, @Context UriInfo uriInfo); @PUT @Path("/{id : \\d+}") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) @ApiOperation(value = "Update a Book", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "The book is updated"), @ApiResponse(code = 400, message = "Invalid input") }) Response update(@PathParam("id") final Long id, @ApiParam(value = "Book to be updated", required = true) Book book); @DELETE @Path("/{id : \\d+}") @ApiOperation(value = "Delete a Book") @ApiResponses(value = { @ApiResponse(code = 204, message = "Book has been deleted"), @ApiResponse(code = 400, message = "Invalid input") }) Response delete(@PathParam("id") final Long id); @GET @Path("health") @ApiOperation(value = "Checks the health of this REST endpoint", response = String.class) Response health(); }
@Test @InSequence(2) public void findAll() throws Exception { final Response response = webTarget.request().get(); assertEquals(OK.getStatusCode(), response.getStatus()); }
BookResource { @POST @Consumes(APPLICATION_JSON) @ApiOperation(value = "Create a Book") @ApiResponses(value = { @ApiResponse(code = 201, message = "The book is created"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 415, message = "Format is not JSon") }) public Response create(@ApiParam(value = "Book to be created", required = true) Book book, @Context UriInfo uriInfo) { log.info("Creating the book " + book); log.info("Invoking the number-api"); String isbn = numbersApi.generateBookNumber(); book.setIsbn(isbn); log.info("Creating the book with ISBN " + book); final Book created = bookRepository.create(book); URI createdURI = uriInfo.getBaseUriBuilder().path(String.valueOf(created.getId())).build(); return Response.created(createdURI).build(); } @GET @Path("/{id : \\d+}") @Produces(APPLICATION_JSON) @ApiOperation(value = "Find a Book by the Id.", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Book found"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 404, message = "Book not found") }) Response findById(@PathParam("id") final Long id); @GET @Produces(APPLICATION_JSON) @ApiOperation(value = "Find all Books", response = Book.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = "All books found"), @ApiResponse(code = 404, message = "Books not found")} ) Response findAll(); @POST @Consumes(APPLICATION_JSON) @ApiOperation(value = "Create a Book") @ApiResponses(value = { @ApiResponse(code = 201, message = "The book is created"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 415, message = "Format is not JSon") }) // tag::adocSnippet[] Response create(@ApiParam(value = "Book to be created", required = true) Book book, @Context UriInfo uriInfo); @PUT @Path("/{id : \\d+}") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) @ApiOperation(value = "Update a Book", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "The book is updated"), @ApiResponse(code = 400, message = "Invalid input") }) Response update(@PathParam("id") final Long id, @ApiParam(value = "Book to be updated", required = true) Book book); @DELETE @Path("/{id : \\d+}") @ApiOperation(value = "Delete a Book") @ApiResponses(value = { @ApiResponse(code = 204, message = "Book has been deleted"), @ApiResponse(code = 400, message = "Invalid input") }) Response delete(@PathParam("id") final Long id); @GET @Path("health") @ApiOperation(value = "Checks the health of this REST endpoint", response = String.class) Response health(); }
@Test @InSequence(3) public void create() throws Exception { final Book book = new Book("Joshua Bloch", "Effective Java (2nd Edition)", 2001, "Tech", " 978-0-3213-5668-0"); final Response response = webTarget.request().post(entity(book, APPLICATION_JSON_TYPE)); assertEquals(CREATED.getStatusCode(), response.getStatus()); }
BookResource { @PUT @Path("/{id : \\d+}") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) @ApiOperation(value = "Update a Book", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "The book is updated"), @ApiResponse(code = 400, message = "Invalid input") }) public Response update(@PathParam("id") final Long id, @ApiParam(value = "Book to be updated", required = true) Book book) { log.info("Updating the book " + book); return ok(bookRepository.update(book)).build(); } @GET @Path("/{id : \\d+}") @Produces(APPLICATION_JSON) @ApiOperation(value = "Find a Book by the Id.", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Book found"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 404, message = "Book not found") }) Response findById(@PathParam("id") final Long id); @GET @Produces(APPLICATION_JSON) @ApiOperation(value = "Find all Books", response = Book.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = "All books found"), @ApiResponse(code = 404, message = "Books not found")} ) Response findAll(); @POST @Consumes(APPLICATION_JSON) @ApiOperation(value = "Create a Book") @ApiResponses(value = { @ApiResponse(code = 201, message = "The book is created"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 415, message = "Format is not JSon") }) // tag::adocSnippet[] Response create(@ApiParam(value = "Book to be created", required = true) Book book, @Context UriInfo uriInfo); @PUT @Path("/{id : \\d+}") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) @ApiOperation(value = "Update a Book", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "The book is updated"), @ApiResponse(code = 400, message = "Invalid input") }) Response update(@PathParam("id") final Long id, @ApiParam(value = "Book to be updated", required = true) Book book); @DELETE @Path("/{id : \\d+}") @ApiOperation(value = "Delete a Book") @ApiResponses(value = { @ApiResponse(code = 204, message = "Book has been deleted"), @ApiResponse(code = 400, message = "Invalid input") }) Response delete(@PathParam("id") final Long id); @GET @Path("health") @ApiOperation(value = "Checks the health of this REST endpoint", response = String.class) Response health(); }
@Test @InSequence(4) public void update() throws Exception { final Book book = new Book("Joshua Bloch", "Effective Java (3rd Edition)", 2018, "Tech", " 978-0-1346-8599-1"); final Response response = webTarget.path("{id}") .resolveTemplate("id", 1) .request() .put(entity(book, APPLICATION_JSON_TYPE)); assertEquals(OK.getStatusCode(), response.getStatus()); }
BookResource { @DELETE @Path("/{id : \\d+}") @ApiOperation(value = "Delete a Book") @ApiResponses(value = { @ApiResponse(code = 204, message = "Book has been deleted"), @ApiResponse(code = 400, message = "Invalid input") }) public Response delete(@PathParam("id") final Long id) { log.info("Deleting the book " + id); bookRepository.deleteById(id); return noContent().build(); } @GET @Path("/{id : \\d+}") @Produces(APPLICATION_JSON) @ApiOperation(value = "Find a Book by the Id.", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Book found"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 404, message = "Book not found") }) Response findById(@PathParam("id") final Long id); @GET @Produces(APPLICATION_JSON) @ApiOperation(value = "Find all Books", response = Book.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = "All books found"), @ApiResponse(code = 404, message = "Books not found")} ) Response findAll(); @POST @Consumes(APPLICATION_JSON) @ApiOperation(value = "Create a Book") @ApiResponses(value = { @ApiResponse(code = 201, message = "The book is created"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 415, message = "Format is not JSon") }) // tag::adocSnippet[] Response create(@ApiParam(value = "Book to be created", required = true) Book book, @Context UriInfo uriInfo); @PUT @Path("/{id : \\d+}") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) @ApiOperation(value = "Update a Book", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "The book is updated"), @ApiResponse(code = 400, message = "Invalid input") }) Response update(@PathParam("id") final Long id, @ApiParam(value = "Book to be updated", required = true) Book book); @DELETE @Path("/{id : \\d+}") @ApiOperation(value = "Delete a Book") @ApiResponses(value = { @ApiResponse(code = 204, message = "Book has been deleted"), @ApiResponse(code = 400, message = "Invalid input") }) Response delete(@PathParam("id") final Long id); @GET @Path("health") @ApiOperation(value = "Checks the health of this REST endpoint", response = String.class) Response health(); }
@Test @InSequence(5) public void delete() throws Exception { final Response response = webTarget.path("{id}") .resolveTemplate("id", 1) .request() .delete(); assertEquals(NO_CONTENT.getStatusCode(), response.getStatus()); }
NumberResource { @GET @Path("book") @ApiOperation(value = "Generates a book number.", response = String.class) public Response generateBookNumber() { log.info("Generating a book number"); return Response.ok("BK-" + Math.random()).build(); } @GET @Path("book") @ApiOperation(value = "Generates a book number.", response = String.class) Response generateBookNumber(); @GET @Path("health") @ApiOperation(value = "Health of this REST endpoint", response = String.class) Response health(); }
@Test public void generateBookNumber() throws Exception { final Response response = webTarget.path("book").request().get(); assertEquals(OK.getStatusCode(), response.getStatus()); assertTrue(response.readEntity(String.class).startsWith("BK-")); }
BookResource { @GET @Produces(APPLICATION_JSON) @ApiOperation(value = "Find all Books", response = Book.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = "All books found"), @ApiResponse(code = 404, message = "Books not found")} ) public Response findAll() { log.info("Getting all the books"); return ok(bookRepository.findAll()).build(); } @GET @Path("/{id : \\d+}") @Produces(APPLICATION_JSON) @ApiOperation(value = "Find a Book by the Id.", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Book found"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 404, message = "Book not found") }) Response findById(@PathParam("id") final Long id); @GET @Produces(APPLICATION_JSON) @ApiOperation(value = "Find all Books", response = Book.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = "All books found"), @ApiResponse(code = 404, message = "Books not found")} ) Response findAll(); @POST @Consumes(APPLICATION_JSON) @ApiOperation(value = "Create a Book") @ApiResponses(value = { @ApiResponse(code = 201, message = "The book is created"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 415, message = "Format is not JSon") }) Response create(@ApiParam(value = "Book to be created", required = true) Book book, @Context UriInfo uriInfo); @PUT @Path("/{id : \\d+}") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) @ApiOperation(value = "Update a Book", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "The book is updated"), @ApiResponse(code = 400, message = "Invalid input") }) Response update(@PathParam("id") final Long id, @ApiParam(value = "Book to be updated", required = true) Book book); @DELETE @Path("/{id : \\d+}") @ApiOperation(value = "Delete a Book") @ApiResponses(value = { @ApiResponse(code = 204, message = "Book has been deleted"), @ApiResponse(code = 400, message = "Invalid input") }) Response delete(@PathParam("id") final Long id); }
@Test @InSequence(2) public void findAll() throws Exception { final Response response = webTarget.request().get(); assertEquals(OK.getStatusCode(), response.getStatus()); }
NumberResource { @GET @Path("book") @ApiOperation(value = "Generates a book number.", response = String.class) public Response generateBookNumber() throws InterruptedException { final Config config = ConfigProvider.getConfig(); config.getOptionalValue("NUMBER_API_FAKE_TIMEOUT", Integer.class).ifPresent(t -> numberApiFakeTimeout = t); log.info("Waiting for " + numberApiFakeTimeout + " seconds"); TimeUnit.SECONDS.sleep(numberApiFakeTimeout); log.info("Generating a book number"); return Response.ok("BK-" + Math.random()).build(); } @GET @Path("book") @ApiOperation(value = "Generates a book number.", response = String.class) Response generateBookNumber(); @GET @Path("health") @ApiOperation(value = "Checks the health of this REST endpoint", response = String.class) Response health(); }
@Test public void generateBookNumber() throws Exception { final Response response = webTarget.path("book").request().get(); assertEquals(OK.getStatusCode(), response.getStatus()); assertTrue(response.readEntity(String.class).startsWith("BK-")); }
BookResource { @POST @Consumes(APPLICATION_JSON) @ApiOperation(value = "Create a Book") @ApiResponses(value = { @ApiResponse(code = 201, message = "The book is created"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 415, message = "Format is not JSon") }) public Response create(@ApiParam(value = "Book to be created", required = true) Book book, @Context UriInfo uriInfo) { log.info("Creating the book " + book); log.info("Invoking the number-api"); String isbn = numbersApi.generateBookNumber(); book.setIsbn(isbn); log.info("Creating the book with ISBN " + book); final Book created = bookRepository.create(book); URI createdURI = uriInfo.getBaseUriBuilder().path(String.valueOf(created.getId())).build(); return Response.created(createdURI).build(); } @GET @Path("/{id : \\d+}") @Produces(APPLICATION_JSON) @ApiOperation(value = "Find a Book by the Id.", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Book found"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 404, message = "Book not found") }) Response findById(@PathParam("id") final Long id); @GET @Produces(APPLICATION_JSON) @ApiOperation(value = "Find all Books", response = Book.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = "All books found"), @ApiResponse(code = 404, message = "Books not found")} ) Response findAll(); @POST @Consumes(APPLICATION_JSON) @ApiOperation(value = "Create a Book") @ApiResponses(value = { @ApiResponse(code = 201, message = "The book is created"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 415, message = "Format is not JSon") }) Response create(@ApiParam(value = "Book to be created", required = true) Book book, @Context UriInfo uriInfo); @PUT @Path("/{id : \\d+}") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) @ApiOperation(value = "Update a Book", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "The book is updated"), @ApiResponse(code = 400, message = "Invalid input") }) Response update(@PathParam("id") final Long id, @ApiParam(value = "Book to be updated", required = true) Book book); @DELETE @Path("/{id : \\d+}") @ApiOperation(value = "Delete a Book") @ApiResponses(value = { @ApiResponse(code = 204, message = "Book has been deleted"), @ApiResponse(code = 400, message = "Invalid input") }) Response delete(@PathParam("id") final Long id); }
@Test @InSequence(3) public void create() throws Exception { final Book book = new Book("Joshua Bloch", "Effective Java (2nd Edition)", 2001, "Tech", " 978-0-3213-5668-0"); final Response response = webTarget.request().post(entity(book, APPLICATION_JSON_TYPE)); assertEquals(CREATED.getStatusCode(), response.getStatus()); }
BookResource { @GET @Path("/{id : \\d+}") @Produces(APPLICATION_JSON) @ApiOperation(value = "Find a Book by the Id.", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Book found"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 404, message = "Book not found") }) public Response findById(@PathParam("id") final Long id) { log.info("Getting the book " + id); return ofNullable(bookRepository.findById(id)) .map(Response::ok) .orElse(status(NOT_FOUND)) .build(); } @GET @Path("/{id : \\d+}") // tag::adocSkip[] @Produces(APPLICATION_JSON) @ApiOperation(value = "Find a Book by the Id.", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Book found"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 404, message = "Book not found") }) // end::adocSkip[] Response findById(@PathParam("id") final Long id); @GET @Produces(APPLICATION_JSON) // tag::adocSkip[] @ApiOperation(value = "Find all Books", response = Book.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = "All books found"), @ApiResponse(code = 404, message = "Books not found")} ) // end::adocSkip[] Response findAll(); @POST @Consumes(APPLICATION_JSON) // tag::adocSkip[] @ApiOperation(value = "Create a Book") @ApiResponses(value = { @ApiResponse(code = 201, message = "The book is created"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 415, message = "Format is not JSon") }) // end::adocSkip[] // tag::adocSnippet[] // tag::adocCall[] Response create(@ApiParam(value = "Book to be created", required = true) Book book, @Context UriInfo uriInfo); @PUT @Path("/{id : \\d+}") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) // tag::adocSkip[] @ApiOperation(value = "Update a Book", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "The book is updated"), @ApiResponse(code = 400, message = "Invalid input") }) // end::adocSkip[] Response update(@PathParam("id") final Long id, @ApiParam(value = "Book to be updated", required = true) Book book); @DELETE @Path("/{id : \\d+}") // tag::adocSkip[] @ApiOperation(value = "Delete a Book") @ApiResponses(value = { @ApiResponse(code = 204, message = "Book has been deleted"), @ApiResponse(code = 400, message = "Invalid input") }) // end::adocSkip[] Response delete(@PathParam("id") final Long id); }
@Test @InSequence(1) public void findById() throws Exception { final Response response = webTarget.path("{id}").resolveTemplate("id", 0).request().get(); assertEquals(OK.getStatusCode(), response.getStatus()); }
BookResource { @GET @Produces(APPLICATION_JSON) @ApiOperation(value = "Find all Books", response = Book.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = "All books found"), @ApiResponse(code = 404, message = "Books not found")} ) public Response findAll() { log.info("Getting all the books"); return ok(bookRepository.findAll()).build(); } @GET @Path("/{id : \\d+}") // tag::adocSkip[] @Produces(APPLICATION_JSON) @ApiOperation(value = "Find a Book by the Id.", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Book found"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 404, message = "Book not found") }) // end::adocSkip[] Response findById(@PathParam("id") final Long id); @GET @Produces(APPLICATION_JSON) // tag::adocSkip[] @ApiOperation(value = "Find all Books", response = Book.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = "All books found"), @ApiResponse(code = 404, message = "Books not found")} ) // end::adocSkip[] Response findAll(); @POST @Consumes(APPLICATION_JSON) // tag::adocSkip[] @ApiOperation(value = "Create a Book") @ApiResponses(value = { @ApiResponse(code = 201, message = "The book is created"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 415, message = "Format is not JSon") }) // end::adocSkip[] // tag::adocSnippet[] // tag::adocCall[] Response create(@ApiParam(value = "Book to be created", required = true) Book book, @Context UriInfo uriInfo); @PUT @Path("/{id : \\d+}") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) // tag::adocSkip[] @ApiOperation(value = "Update a Book", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "The book is updated"), @ApiResponse(code = 400, message = "Invalid input") }) // end::adocSkip[] Response update(@PathParam("id") final Long id, @ApiParam(value = "Book to be updated", required = true) Book book); @DELETE @Path("/{id : \\d+}") // tag::adocSkip[] @ApiOperation(value = "Delete a Book") @ApiResponses(value = { @ApiResponse(code = 204, message = "Book has been deleted"), @ApiResponse(code = 400, message = "Invalid input") }) // end::adocSkip[] Response delete(@PathParam("id") final Long id); }
@Test @InSequence(2) public void findAll() throws Exception { final Response response = webTarget.request().get(); assertEquals(OK.getStatusCode(), response.getStatus()); }
BookResource { @POST @Consumes(APPLICATION_JSON) @ApiOperation(value = "Create a Book") @ApiResponses(value = { @ApiResponse(code = 201, message = "The book is created"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 415, message = "Format is not JSon") }) public Response create(@ApiParam(value = "Book to be created", required = true) Book book, @Context UriInfo uriInfo) { log.info("Creating the book " + book); log.info("Invoking the number-api"); String isbn = numbersApi.generateBookNumber(); book.setIsbn(isbn); final Book created = bookRepository.create(book); URI createdURI = uriInfo.getBaseUriBuilder().path(String.valueOf(created.getId())).build(); return Response.created(createdURI).build(); } @GET @Path("/{id : \\d+}") // tag::adocSkip[] @Produces(APPLICATION_JSON) @ApiOperation(value = "Find a Book by the Id.", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Book found"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 404, message = "Book not found") }) // end::adocSkip[] Response findById(@PathParam("id") final Long id); @GET @Produces(APPLICATION_JSON) // tag::adocSkip[] @ApiOperation(value = "Find all Books", response = Book.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = "All books found"), @ApiResponse(code = 404, message = "Books not found")} ) // end::adocSkip[] Response findAll(); @POST @Consumes(APPLICATION_JSON) // tag::adocSkip[] @ApiOperation(value = "Create a Book") @ApiResponses(value = { @ApiResponse(code = 201, message = "The book is created"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 415, message = "Format is not JSon") }) // end::adocSkip[] // tag::adocSnippet[] // tag::adocCall[] Response create(@ApiParam(value = "Book to be created", required = true) Book book, @Context UriInfo uriInfo); @PUT @Path("/{id : \\d+}") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) // tag::adocSkip[] @ApiOperation(value = "Update a Book", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "The book is updated"), @ApiResponse(code = 400, message = "Invalid input") }) // end::adocSkip[] Response update(@PathParam("id") final Long id, @ApiParam(value = "Book to be updated", required = true) Book book); @DELETE @Path("/{id : \\d+}") // tag::adocSkip[] @ApiOperation(value = "Delete a Book") @ApiResponses(value = { @ApiResponse(code = 204, message = "Book has been deleted"), @ApiResponse(code = 400, message = "Invalid input") }) // end::adocSkip[] Response delete(@PathParam("id") final Long id); }
@Test @InSequence(3) public void create() throws Exception { final Book book = new Book("Joshua Bloch", "Effective Java (2nd Edition)", 2001, "Tech", " 978-0-3213-5668-0"); final Response response = webTarget.request().post(entity(book, APPLICATION_JSON_TYPE)); assertEquals(CREATED.getStatusCode(), response.getStatus()); }
BookResource { @PUT @Path("/{id : \\d+}") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) @ApiOperation(value = "Update a Book", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "The book is updated"), @ApiResponse(code = 400, message = "Invalid input") }) public Response update(@PathParam("id") final Long id, @ApiParam(value = "Book to be updated", required = true) Book book) { log.info("Updating the book " + book); return ok(bookRepository.update(book)).build(); } @GET @Path("/{id : \\d+}") // tag::adocSkip[] @Produces(APPLICATION_JSON) @ApiOperation(value = "Find a Book by the Id.", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Book found"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 404, message = "Book not found") }) // end::adocSkip[] Response findById(@PathParam("id") final Long id); @GET @Produces(APPLICATION_JSON) // tag::adocSkip[] @ApiOperation(value = "Find all Books", response = Book.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = "All books found"), @ApiResponse(code = 404, message = "Books not found")} ) // end::adocSkip[] Response findAll(); @POST @Consumes(APPLICATION_JSON) // tag::adocSkip[] @ApiOperation(value = "Create a Book") @ApiResponses(value = { @ApiResponse(code = 201, message = "The book is created"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 415, message = "Format is not JSon") }) // end::adocSkip[] // tag::adocSnippet[] // tag::adocCall[] Response create(@ApiParam(value = "Book to be created", required = true) Book book, @Context UriInfo uriInfo); @PUT @Path("/{id : \\d+}") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) // tag::adocSkip[] @ApiOperation(value = "Update a Book", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "The book is updated"), @ApiResponse(code = 400, message = "Invalid input") }) // end::adocSkip[] Response update(@PathParam("id") final Long id, @ApiParam(value = "Book to be updated", required = true) Book book); @DELETE @Path("/{id : \\d+}") // tag::adocSkip[] @ApiOperation(value = "Delete a Book") @ApiResponses(value = { @ApiResponse(code = 204, message = "Book has been deleted"), @ApiResponse(code = 400, message = "Invalid input") }) // end::adocSkip[] Response delete(@PathParam("id") final Long id); }
@Test @InSequence(4) public void update() throws Exception { final Book book = new Book("Joshua Bloch", "Effective Java (3rd Edition)", 2018, "Tech", " 978-0-1346-8599-1"); final Response response = webTarget.path("{id}") .resolveTemplate("id", 1) .request() .put(entity(book, APPLICATION_JSON_TYPE)); assertEquals(OK.getStatusCode(), response.getStatus()); }
BookResource { @PUT @Path("/{id : \\d+}") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) @ApiOperation(value = "Update a Book", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "The book is updated"), @ApiResponse(code = 400, message = "Invalid input") }) public Response update(@PathParam("id") final Long id, @ApiParam(value = "Book to be updated", required = true) Book book) { log.info("Updating the book " + book); return ok(bookRepository.update(book)).build(); } @GET @Path("/{id : \\d+}") @Produces(APPLICATION_JSON) @ApiOperation(value = "Find a Book by the Id.", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Book found"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 404, message = "Book not found") }) Response findById(@PathParam("id") final Long id); @GET @Produces(APPLICATION_JSON) @ApiOperation(value = "Find all Books", response = Book.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = "All books found"), @ApiResponse(code = 404, message = "Books not found")} ) Response findAll(); @POST @Consumes(APPLICATION_JSON) @ApiOperation(value = "Create a Book") @ApiResponses(value = { @ApiResponse(code = 201, message = "The book is created"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 415, message = "Format is not JSon") }) Response create(@ApiParam(value = "Book to be created", required = true) Book book, @Context UriInfo uriInfo); @PUT @Path("/{id : \\d+}") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) @ApiOperation(value = "Update a Book", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "The book is updated"), @ApiResponse(code = 400, message = "Invalid input") }) Response update(@PathParam("id") final Long id, @ApiParam(value = "Book to be updated", required = true) Book book); @DELETE @Path("/{id : \\d+}") @ApiOperation(value = "Delete a Book") @ApiResponses(value = { @ApiResponse(code = 204, message = "Book has been deleted"), @ApiResponse(code = 400, message = "Invalid input") }) Response delete(@PathParam("id") final Long id); }
@Test @InSequence(4) public void update() throws Exception { final Book book = new Book("Joshua Bloch", "Effective Java (3rd Edition)", 2018, "Tech", " 978-0-1346-8599-1"); final Response response = webTarget.path("{id}") .resolveTemplate("id", 1) .request() .put(entity(book, APPLICATION_JSON_TYPE)); assertEquals(OK.getStatusCode(), response.getStatus()); }
BookResource { @DELETE @Path("/{id : \\d+}") @ApiOperation(value = "Delete a Book") @ApiResponses(value = { @ApiResponse(code = 204, message = "Book has been deleted"), @ApiResponse(code = 400, message = "Invalid input") }) public Response delete(@PathParam("id") final Long id) { log.info("Deleting the book " + id); bookRepository.deleteById(id); return noContent().build(); } @GET @Path("/{id : \\d+}") // tag::adocSkip[] @Produces(APPLICATION_JSON) @ApiOperation(value = "Find a Book by the Id.", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Book found"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 404, message = "Book not found") }) // end::adocSkip[] Response findById(@PathParam("id") final Long id); @GET @Produces(APPLICATION_JSON) // tag::adocSkip[] @ApiOperation(value = "Find all Books", response = Book.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = "All books found"), @ApiResponse(code = 404, message = "Books not found")} ) // end::adocSkip[] Response findAll(); @POST @Consumes(APPLICATION_JSON) // tag::adocSkip[] @ApiOperation(value = "Create a Book") @ApiResponses(value = { @ApiResponse(code = 201, message = "The book is created"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 415, message = "Format is not JSon") }) // end::adocSkip[] // tag::adocSnippet[] // tag::adocCall[] Response create(@ApiParam(value = "Book to be created", required = true) Book book, @Context UriInfo uriInfo); @PUT @Path("/{id : \\d+}") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) // tag::adocSkip[] @ApiOperation(value = "Update a Book", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "The book is updated"), @ApiResponse(code = 400, message = "Invalid input") }) // end::adocSkip[] Response update(@PathParam("id") final Long id, @ApiParam(value = "Book to be updated", required = true) Book book); @DELETE @Path("/{id : \\d+}") // tag::adocSkip[] @ApiOperation(value = "Delete a Book") @ApiResponses(value = { @ApiResponse(code = 204, message = "Book has been deleted"), @ApiResponse(code = 400, message = "Invalid input") }) // end::adocSkip[] Response delete(@PathParam("id") final Long id); }
@Test @InSequence(5) public void delete() throws Exception { final Response response = webTarget.path("{id}") .resolveTemplate("id", 1) .request() .delete(); assertEquals(NO_CONTENT.getStatusCode(), response.getStatus()); }
NumberResource { @GET @Path("book") @ApiOperation(value = "Generates a book number.", response = String.class) public Response generateBookNumber() { log.info("Generating a book number"); return Response.ok("BK-" + Math.random()).build(); } @GET @Path("book") // tag::adocSwagger[] @ApiOperation(value = "Generates a book number.", response = String.class) // end::adocSwagger[] Response generateBookNumber(); }
@Test public void generateBookNumber() throws Exception { final Response response = webTarget.path("book").request().get(); assertEquals(OK.getStatusCode(), response.getStatus()); assertTrue(response.readEntity(String.class).startsWith("BK-")); }
BookResource { @GET @Path("/{id : \\d+}") @Produces(APPLICATION_JSON) @ApiOperation(value = "Find a Book by the Id.", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Book found"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 404, message = "Book not found") }) public Response findById(@PathParam("id") final Long id) { log.info("Getting the book " + id); return ofNullable(bookRepository.findById(id)) .map(Response::ok) .orElse(status(NOT_FOUND)) .build(); } @GET @Path("/{id : \\d+}") @Produces(APPLICATION_JSON) @ApiOperation(value = "Find a Book by the Id.", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Book found"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 404, message = "Book not found") }) Response findById(@PathParam("id") final Long id); @GET @Produces(APPLICATION_JSON) @ApiOperation(value = "Find all Books", response = Book.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = "All books found"), @ApiResponse(code = 404, message = "Books not found")} ) Response findAll(); @POST @Consumes(APPLICATION_JSON) @ApiOperation(value = "Create a Book") @ApiResponses(value = { @ApiResponse(code = 201, message = "The book is created"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 415, message = "Format is not JSon") }) Response create(@ApiParam(value = "Book to be created", required = true) Book book, @Context UriInfo uriInfo); @PUT @Path("/{id : \\d+}") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) @ApiOperation(value = "Update a Book", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "The book is updated"), @ApiResponse(code = 400, message = "Invalid input") }) Response update(@PathParam("id") final Long id, @ApiParam(value = "Book to be updated", required = true) Book book); @DELETE @Path("/{id : \\d+}") @ApiOperation(value = "Delete a Book") @ApiResponses(value = { @ApiResponse(code = 204, message = "Book has been deleted"), @ApiResponse(code = 400, message = "Invalid input") }) Response delete(@PathParam("id") final Long id); }
@Test @InSequence(1) public void findById() throws Exception { final Response response = webTarget.path("{id}").resolveTemplate("id", 0).request().get(); assertEquals(OK.getStatusCode(), response.getStatus()); }
BookResource { @DELETE @Path("/{id : \\d+}") @ApiOperation(value = "Delete a Book") @ApiResponses(value = { @ApiResponse(code = 204, message = "Book has been deleted"), @ApiResponse(code = 400, message = "Invalid input") }) public Response delete(@PathParam("id") final Long id) { log.info("Deleting the book " + id); bookRepository.deleteById(id); return noContent().build(); } @GET @Path("/{id : \\d+}") @Produces(APPLICATION_JSON) @ApiOperation(value = "Find a Book by the Id.", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Book found"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 404, message = "Book not found") }) Response findById(@PathParam("id") final Long id); @GET @Produces(APPLICATION_JSON) @ApiOperation(value = "Find all Books", response = Book.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = "All books found"), @ApiResponse(code = 404, message = "Books not found")} ) Response findAll(); @POST @Consumes(APPLICATION_JSON) @ApiOperation(value = "Create a Book") @ApiResponses(value = { @ApiResponse(code = 201, message = "The book is created"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 415, message = "Format is not JSon") }) Response create(@ApiParam(value = "Book to be created", required = true) Book book, @Context UriInfo uriInfo); @PUT @Path("/{id : \\d+}") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) @ApiOperation(value = "Update a Book", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "The book is updated"), @ApiResponse(code = 400, message = "Invalid input") }) Response update(@PathParam("id") final Long id, @ApiParam(value = "Book to be updated", required = true) Book book); @DELETE @Path("/{id : \\d+}") @ApiOperation(value = "Delete a Book") @ApiResponses(value = { @ApiResponse(code = 204, message = "Book has been deleted"), @ApiResponse(code = 400, message = "Invalid input") }) Response delete(@PathParam("id") final Long id); }
@Test @InSequence(5) public void delete() throws Exception { final Response response = webTarget.path("{id}") .resolveTemplate("id", 1) .request() .delete(); assertEquals(NO_CONTENT.getStatusCode(), response.getStatus()); }
NumberResource { @GET @Path("book") @ApiOperation(value = "Generates a book number.", response = String.class) public Response generateBookNumber() { log.info("Generating a book number"); return Response.ok("BK-" + Math.random()).build(); } @GET @Path("book") @ApiOperation(value = "Generates a book number.", response = String.class) Response generateBookNumber(); }
@Test public void generateBookNumber() throws Exception { final Response response = webTarget.path("book").request().get(); assertEquals(OK.getStatusCode(), response.getStatus()); assertTrue(response.readEntity(String.class).startsWith("BK-")); }
BookResource { @GET @Path("/{id : \\d+}") @Produces(APPLICATION_JSON) @ApiOperation(value = "Find a Book by the Id.", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Book found"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 404, message = "Book not found") }) public Response findById(@PathParam("id") final Long id) { log.info("Getting the book " + id); return ofNullable(bookRepository.findById(id)) .map(Response::ok) .orElse(status(NOT_FOUND)) .build(); } @GET @Path("/{id : \\d+}") @Produces(APPLICATION_JSON) @ApiOperation(value = "Find a Book by the Id.", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Book found"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 404, message = "Book not found") }) Response findById(@PathParam("id") final Long id); @GET @Produces(APPLICATION_JSON) @ApiOperation(value = "Find all Books", response = Book.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = "All books found"), @ApiResponse(code = 404, message = "Books not found")} ) Response findAll(); @POST @Consumes(APPLICATION_JSON) @ApiOperation(value = "Create a Book") @ApiResponses(value = { @ApiResponse(code = 201, message = "The book is created"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 415, message = "Format is not JSon") }) // tag::adocSnippet[] Response create(@ApiParam(value = "Book to be created", required = true) Book book, @Context UriInfo uriInfo); @PUT @Path("/{id : \\d+}") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) @ApiOperation(value = "Update a Book", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "The book is updated"), @ApiResponse(code = 400, message = "Invalid input") }) Response update(@PathParam("id") final Long id, @ApiParam(value = "Book to be updated", required = true) Book book); @DELETE @Path("/{id : \\d+}") @ApiOperation(value = "Delete a Book") @ApiResponses(value = { @ApiResponse(code = 204, message = "Book has been deleted"), @ApiResponse(code = 400, message = "Invalid input") }) Response delete(@PathParam("id") final Long id); @GET @Path("health") @ApiOperation(value = "Checks the health of this REST endpoint", response = String.class) Response health(); @GET @Path("number") @ApiOperation(value = "Wraps the Number API to retrive a Book Number", response = String.class) Response number(); }
@Test @InSequence(1) public void findById() throws Exception { final Response response = webTarget.path("{id}").resolveTemplate("id", 0).request().get(); assertEquals(OK.getStatusCode(), response.getStatus()); }
BookResource { @GET @Produces(APPLICATION_JSON) @ApiOperation(value = "Find all Books", response = Book.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = "All books found"), @ApiResponse(code = 404, message = "Books not found")} ) public Response findAll() { log.info("Getting all the books"); return ok(bookRepository.findAll()).build(); } @GET @Path("/{id : \\d+}") @Produces(APPLICATION_JSON) @ApiOperation(value = "Find a Book by the Id.", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Book found"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 404, message = "Book not found") }) Response findById(@PathParam("id") final Long id); @GET @Produces(APPLICATION_JSON) @ApiOperation(value = "Find all Books", response = Book.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = "All books found"), @ApiResponse(code = 404, message = "Books not found")} ) Response findAll(); @POST @Consumes(APPLICATION_JSON) @ApiOperation(value = "Create a Book") @ApiResponses(value = { @ApiResponse(code = 201, message = "The book is created"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 415, message = "Format is not JSon") }) // tag::adocSnippet[] Response create(@ApiParam(value = "Book to be created", required = true) Book book, @Context UriInfo uriInfo); @PUT @Path("/{id : \\d+}") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) @ApiOperation(value = "Update a Book", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "The book is updated"), @ApiResponse(code = 400, message = "Invalid input") }) Response update(@PathParam("id") final Long id, @ApiParam(value = "Book to be updated", required = true) Book book); @DELETE @Path("/{id : \\d+}") @ApiOperation(value = "Delete a Book") @ApiResponses(value = { @ApiResponse(code = 204, message = "Book has been deleted"), @ApiResponse(code = 400, message = "Invalid input") }) Response delete(@PathParam("id") final Long id); @GET @Path("health") @ApiOperation(value = "Checks the health of this REST endpoint", response = String.class) Response health(); @GET @Path("number") @ApiOperation(value = "Wraps the Number API to retrive a Book Number", response = String.class) Response number(); }
@Test @InSequence(2) public void findAll() throws Exception { final Response response = webTarget.request().get(); assertEquals(OK.getStatusCode(), response.getStatus()); }
BookResource { @POST @Consumes(APPLICATION_JSON) @ApiOperation(value = "Create a Book") @ApiResponses(value = { @ApiResponse(code = 201, message = "The book is created"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 415, message = "Format is not JSon") }) public Response create(@ApiParam(value = "Book to be created", required = true) Book book, @Context UriInfo uriInfo) { log.info("Creating the book " + book); log.info("Invoking the number-api"); String isbn = numbersApi.generateBookNumber(); book.setIsbn(isbn); log.info("Creating the book with ISBN " + book); final Book created = bookRepository.create(book); URI createdURI = uriInfo.getBaseUriBuilder().path(String.valueOf(created.getId())).build(); return Response.created(createdURI).build(); } @GET @Path("/{id : \\d+}") @Produces(APPLICATION_JSON) @ApiOperation(value = "Find a Book by the Id.", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Book found"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 404, message = "Book not found") }) Response findById(@PathParam("id") final Long id); @GET @Produces(APPLICATION_JSON) @ApiOperation(value = "Find all Books", response = Book.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = "All books found"), @ApiResponse(code = 404, message = "Books not found")} ) Response findAll(); @POST @Consumes(APPLICATION_JSON) @ApiOperation(value = "Create a Book") @ApiResponses(value = { @ApiResponse(code = 201, message = "The book is created"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 415, message = "Format is not JSon") }) // tag::adocSnippet[] Response create(@ApiParam(value = "Book to be created", required = true) Book book, @Context UriInfo uriInfo); @PUT @Path("/{id : \\d+}") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) @ApiOperation(value = "Update a Book", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "The book is updated"), @ApiResponse(code = 400, message = "Invalid input") }) Response update(@PathParam("id") final Long id, @ApiParam(value = "Book to be updated", required = true) Book book); @DELETE @Path("/{id : \\d+}") @ApiOperation(value = "Delete a Book") @ApiResponses(value = { @ApiResponse(code = 204, message = "Book has been deleted"), @ApiResponse(code = 400, message = "Invalid input") }) Response delete(@PathParam("id") final Long id); @GET @Path("health") @ApiOperation(value = "Checks the health of this REST endpoint", response = String.class) Response health(); @GET @Path("number") @ApiOperation(value = "Wraps the Number API to retrive a Book Number", response = String.class) Response number(); }
@Test @InSequence(3) public void create() throws Exception { final Book book = new Book("Joshua Bloch", "Effective Java (2nd Edition)", 2001, "Tech", " 978-0-3213-5668-0"); final Response response = webTarget.request().post(entity(book, APPLICATION_JSON_TYPE)); assertEquals(CREATED.getStatusCode(), response.getStatus()); }
BookResource { @PUT @Path("/{id : \\d+}") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) @ApiOperation(value = "Update a Book", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "The book is updated"), @ApiResponse(code = 400, message = "Invalid input") }) public Response update(@PathParam("id") final Long id, @ApiParam(value = "Book to be updated", required = true) Book book) { log.info("Updating the book " + book); return ok(bookRepository.update(book)).build(); } @GET @Path("/{id : \\d+}") @Produces(APPLICATION_JSON) @ApiOperation(value = "Find a Book by the Id.", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Book found"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 404, message = "Book not found") }) Response findById(@PathParam("id") final Long id); @GET @Produces(APPLICATION_JSON) @ApiOperation(value = "Find all Books", response = Book.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = 200, message = "All books found"), @ApiResponse(code = 404, message = "Books not found")} ) Response findAll(); @POST @Consumes(APPLICATION_JSON) @ApiOperation(value = "Create a Book") @ApiResponses(value = { @ApiResponse(code = 201, message = "The book is created"), @ApiResponse(code = 400, message = "Invalid input"), @ApiResponse(code = 415, message = "Format is not JSon") }) // tag::adocSnippet[] Response create(@ApiParam(value = "Book to be created", required = true) Book book, @Context UriInfo uriInfo); @PUT @Path("/{id : \\d+}") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) @ApiOperation(value = "Update a Book", response = Book.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "The book is updated"), @ApiResponse(code = 400, message = "Invalid input") }) Response update(@PathParam("id") final Long id, @ApiParam(value = "Book to be updated", required = true) Book book); @DELETE @Path("/{id : \\d+}") @ApiOperation(value = "Delete a Book") @ApiResponses(value = { @ApiResponse(code = 204, message = "Book has been deleted"), @ApiResponse(code = 400, message = "Invalid input") }) Response delete(@PathParam("id") final Long id); @GET @Path("health") @ApiOperation(value = "Checks the health of this REST endpoint", response = String.class) Response health(); @GET @Path("number") @ApiOperation(value = "Wraps the Number API to retrive a Book Number", response = String.class) Response number(); }
@Test @InSequence(4) public void update() throws Exception { final Book book = new Book("Joshua Bloch", "Effective Java (3rd Edition)", 2018, "Tech", " 978-0-1346-8599-1"); final Response response = webTarget.path("{id}") .resolveTemplate("id", 1) .request() .put(entity(book, APPLICATION_JSON_TYPE)); assertEquals(OK.getStatusCode(), response.getStatus()); }
AlbumService implements PaginatedService { public ResourceDto<AlbumDto> getAlbumsPage() { return getAlbumsPage(FIRST_PAGE_NUM); } @Inject AlbumService(@Named("albumDao") AlbumDao albumDao, @Named("artistDao") MaprDbDao<Artist> artistDao, LanguageDao languageDao, SlugService slugService, StatisticService statisticService, AlbumRateDao albumRateDao); @Override long getTotalNum(); ResourceDto<AlbumDto> getAlbumsPage(); ResourceDto<AlbumDto> getAlbumsPage(String order, List<String> orderFields); ResourceDto<AlbumDto> getAlbumsPage(Long page); ResourceDto<AlbumDto> getAlbumsPage(Long perPage, Long page, String order, List<String> orderFields); ResourceDto<AlbumDto> getAlbumsPage(Long perPage, Long page, List<SortOption> sortOptions); ResourceDto<AlbumDto> getAlbumsPageByLanguage(Long perPage, Long page, List<SortOption> sortOptions, String lang); AlbumDto getAlbumById(String id); AlbumDto getAlbumBySlugName(String slugName); void deleteAlbumById(String id); AlbumDto createAlbum(AlbumDto albumDto); AlbumDto updateAlbum(AlbumDto albumDto); @SuppressWarnings("unchecked") AlbumDto updateAlbum(String id, AlbumDto albumDto); TrackDto getTrackById(String id, String trackId); List<TrackDto> getAlbumTracksList(String id); TrackDto addTrackToAlbumTrackList(String id, TrackDto track); List<TrackDto> addTracksToAlbumTrackList(String id, List<TrackDto> tracks); TrackDto updateAlbumTrack(String id, String trackId, TrackDto track); List<TrackDto> setAlbumTrackList(String id, List<TrackDto> trackList); void deleteAlbumTrack(String id, String trackId); List<Language> getSupportedAlbumsLanguages(); List<AlbumDto> searchAlbums(String nameEntry, Long limit); }
@Test public void getNegativePageTest() { thrown.expect(IllegalArgumentException.class); AlbumDao albumDao = mock(AlbumDao.class); LanguageDao languageDao = mock(LanguageDao.class); SlugService slugService = mock(SlugService.class); StatisticService statisticService = mock(StatisticService.class); MaprDbDao<Artist> artistDao = mock(MaprDbDao.class); AlbumRateDao albumRateDao = mock(AlbumRateDao.class); AlbumService albumService = new AlbumService(albumDao, artistDao, languageDao, slugService, statisticService, albumRateDao); albumService.getAlbumsPage(-1L); }
AlbumService implements PaginatedService { public AlbumDto getAlbumById(String id) { if (id == null || id.isEmpty()) { throw new IllegalArgumentException("Album's identifier can not be empty"); } Album album = albumDao.getById(id); if (album == null) { throw new ResourceNotFoundException("Album with id '" + id + "' not found"); } return albumToDto(album); } @Inject AlbumService(@Named("albumDao") AlbumDao albumDao, @Named("artistDao") MaprDbDao<Artist> artistDao, LanguageDao languageDao, SlugService slugService, StatisticService statisticService, AlbumRateDao albumRateDao); @Override long getTotalNum(); ResourceDto<AlbumDto> getAlbumsPage(); ResourceDto<AlbumDto> getAlbumsPage(String order, List<String> orderFields); ResourceDto<AlbumDto> getAlbumsPage(Long page); ResourceDto<AlbumDto> getAlbumsPage(Long perPage, Long page, String order, List<String> orderFields); ResourceDto<AlbumDto> getAlbumsPage(Long perPage, Long page, List<SortOption> sortOptions); ResourceDto<AlbumDto> getAlbumsPageByLanguage(Long perPage, Long page, List<SortOption> sortOptions, String lang); AlbumDto getAlbumById(String id); AlbumDto getAlbumBySlugName(String slugName); void deleteAlbumById(String id); AlbumDto createAlbum(AlbumDto albumDto); AlbumDto updateAlbum(AlbumDto albumDto); @SuppressWarnings("unchecked") AlbumDto updateAlbum(String id, AlbumDto albumDto); TrackDto getTrackById(String id, String trackId); List<TrackDto> getAlbumTracksList(String id); TrackDto addTrackToAlbumTrackList(String id, TrackDto track); List<TrackDto> addTracksToAlbumTrackList(String id, List<TrackDto> tracks); TrackDto updateAlbumTrack(String id, String trackId, TrackDto track); List<TrackDto> setAlbumTrackList(String id, List<TrackDto> trackList); void deleteAlbumTrack(String id, String trackId); List<Language> getSupportedAlbumsLanguages(); List<AlbumDto> searchAlbums(String nameEntry, Long limit); }
@Test public void getByNullId() { thrown.expect(IllegalArgumentException.class); AlbumDao albumDao = mock(AlbumDao.class); LanguageDao languageDao = mock(LanguageDao.class); SlugService slugService = mock(SlugService.class); StatisticService statisticService = mock(StatisticService.class); MaprDbDao<Artist> artistDao = mock(MaprDbDao.class); AlbumRateDao albumRateDao = mock(AlbumRateDao.class); AlbumService albumService = new AlbumService(albumDao, artistDao, languageDao, slugService, statisticService, albumRateDao); albumService.getAlbumById(""); }
SecKillCommandService { public SecKillGrabResult addCouponTo(T customerId) { if (recoveryInfo.getClaimedCustomers().add(customerId)) { if (claimedCoupons.getAndIncrement() < recoveryInfo.remainingCoupons()) { return couponQueue.offer(customerId) ? SecKillGrabResult.Success : SecKillGrabResult.Failed; } return SecKillGrabResult.Failed; } return SecKillGrabResult.Duplicate; } SecKillCommandService(Queue<T> couponQueue, AtomicInteger claimedCoupons, SecKillRecoveryCheckResult<T> recoveryInfo); SecKillGrabResult addCouponTo(T customerId); }
@Test public void putsAllCustomersInQueue() { for (int i = 0; i < 5; i++) { SecKillGrabResult success = commandService.addCouponTo(i); assertThat(success, is(SecKillGrabResult.Success)); } assertThat(coupons, contains(0, 1, 2, 3, 4)); } @Test public void noMoreItemAddedToQueueOnceFull() { keepConsumingCoupons(); int threads = 200; CyclicBarrier barrier = new CyclicBarrier(threads); addCouponsAsync(threads , () -> { try { barrier.await(); return commandService.addCouponTo(customerIdGenerator.incrementAndGet()) == SecKillGrabResult.Success; } catch (InterruptedException | BrokenBarrierException e) { throw new RuntimeException(e); } }, success -> { if (success) { numberOfSuccess.incrementAndGet(); } }); assertThat(numberOfSuccess.get(), is(10)); } @Test public void failsToAddCustomerIfQueueIsFull() { for (int i = 0; i < numberOfCoupons; i++) { SecKillGrabResult success = commandService.addCouponTo(i); assertThat(success, is(SecKillGrabResult.Success)); } assertThat(coupons.size(), is(numberOfCoupons)); SecKillGrabResult success = commandService.addCouponTo(100); assertThat(success, is(SecKillGrabResult.Failed)); assertThat(coupons, contains(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)); } @Test public void failsDuplicateAddCustomer() { SecKillGrabResult success = commandService.addCouponTo(1); assertThat(success, is(SecKillGrabResult.Success)); success = commandService.addCouponTo(1); assertThat(success, is(SecKillGrabResult.Duplicate)); }
SecKillRecoveryService { public SecKillRecoveryCheckResult<T> check(PromotionEntity promotion) { List<EventEntity> entities = this.repository.findByPromotionId(promotion.getPromotionId()); if (!entities.isEmpty()) { long count = entities.stream() .filter(event -> SecKillEventType.CouponGrabbedEvent.equals(event.getType())) .count(); Set<T> claimedCustomers = ConcurrentHashMap.newKeySet(); claimedCustomers.addAll(entities.stream() .filter(entity -> SecKillEventType.CouponGrabbedEvent.equals(entity.getType())) .map(entity -> ((CouponGrabbedEvent<T>) eventFormat.fromEntity(entity)).getCoupon().getCustomerId()) .collect(Collectors.toSet())); boolean isFinished = entities.stream() .anyMatch(event -> SecKillEventType.PromotionFinishEvent.equals(event.getType())); return new SecKillRecoveryCheckResult<>(true, isFinished, promotion.getNumberOfCoupons() - (int) count, claimedCustomers); } return new SecKillRecoveryCheckResult<>(promotion.getNumberOfCoupons()); } SecKillRecoveryService(SpringSecKillEventRepository repository, SecKillEventFormat eventFormat); SecKillRecoveryCheckResult<T> check(PromotionEntity promotion); }
@Test public void unstartPromotionCheck() { SecKillRecoveryCheckResult<String> result = recoveryService.check(unpublishedPromotion); assertThat(result.isStarted(), is(false)); assertThat(result.isFinished(), is(false)); assertThat(result.remainingCoupons(), is(unpublishedPromotion.getNumberOfCoupons())); assertThat(result.getClaimedCustomers().isEmpty(), is(true)); } @Test public void recoverPromotionCheck() { SecKillRecoveryCheckResult<String> result = recoveryService.check(runningPromotion); assertThat(result.isStarted(), is(true)); assertThat(result.isFinished(), is(false)); assertThat(result.remainingCoupons(), is(runningPromotion.getNumberOfCoupons() - 1)); assertThat(result.getClaimedCustomers(), contains("zyy")); } @Test public void finishPromotionCheck() { SecKillRecoveryCheckResult<String> result = recoveryService.check(endedPromotion); assertThat(result.isStarted(), is(true)); assertThat(result.isFinished(), is(true)); assertThat(result.remainingCoupons(), is(0)); assertThat(result.getClaimedCustomers(), contains("0", "1", "2", "3", "4")); }
SpanTemplate implements SpanOperations { @Override public ActiveSpan startActive(String name) { return tracer.buildSpan(name) .startActive(); } SpanTemplate(Tracer tracer); @Override void doInTracer(SpanCallback callback); @Override Span start(String name); @Override ActiveSpan startActive(String name); @Override ActiveSpan startActive(String name, ActiveSpan parent); @Override ActiveSpan startActive(String name, SpanContext parent); @Override void inject(SpanContext ctx, HttpHeaders headers); @Override SpanContext extract(Map<String, Object> map); }
@Test public void testStartActive() throws InterruptedException { try (ActiveSpan span = spanOps.startActive("hello sematextains")) { span.setTag("app", "console"); } Thread.sleep(2000); } @Test public void testStartActiveWithParent() throws InterruptedException { try (ActiveSpan parent = spanOps.startActive("parent")) { parent.setTag("app", "console"); Thread.sleep(500); try (ActiveSpan child = spanOps.startActive("child", parent)) { child.setTag("encoding", "utf-8"); } } Thread.sleep(2000); }
SpanTemplate implements SpanOperations { @Override public void inject(SpanContext ctx, HttpHeaders headers) { HttpHeadersInjectAdapter injectAdapter = new HttpHeadersInjectAdapter(headers); tracer.inject(ctx, Format.Builtin.HTTP_HEADERS, injectAdapter); } SpanTemplate(Tracer tracer); @Override void doInTracer(SpanCallback callback); @Override Span start(String name); @Override ActiveSpan startActive(String name); @Override ActiveSpan startActive(String name, ActiveSpan parent); @Override ActiveSpan startActive(String name, SpanContext parent); @Override void inject(SpanContext ctx, HttpHeaders headers); @Override SpanContext extract(Map<String, Object> map); }
@Test public void testInject() { try (ActiveSpan span = spanOps.startActive("parent")) { Map<String, Object> map = new HashMap<>(); map.put("app", "console"); HttpHeaders headers = new HttpHeaders(); spanOps.inject(span.context(), headers); } }
StateCapture { public static Executor capturingDecorator(final Executor executor) { if (stateCaptors.isEmpty() || executor instanceof CapturingExecutor) { return executor; } else { return new CapturingExecutor(executor); } } private StateCapture(); static Executor capturingDecorator(final Executor executor); static ExecutorService capturingDecorator(final ExecutorService executorService); static ScheduledExecutorService capturingDecorator(final ScheduledExecutorService executorService); static CompletionService<T> capturingDecorator(final CompletionService<T> completionService); static Runnable capturingDecorator(Runnable delegate); static Callable<V> capturingDecorator(Callable<V> delegate); }
@Test public void testExecutorCaptures() throws InterruptedException { ExecutorService e = Executors.newCachedThreadPool(); Executor f = StateCapture.capturingDecorator(e); CapturedState mockCapturedState = mock(CapturedState.class); Runnable mockRunnable = mock(Runnable.class); ThreadLocalStateCaptor.THREAD_LOCAL.set(mockCapturedState); f.execute(mockRunnable); e.shutdown(); e.awaitTermination(10, TimeUnit.HOURS); verifyStandardCaptures(mockCapturedState, mockRunnable); } @Test public void testScheduledExecutorServiceCaptures() throws InterruptedException { ScheduledExecutorService e = Executors.newScheduledThreadPool(10); ScheduledExecutorService f = StateCapture.capturingDecorator(e); CapturedState mockCapturedState = mock(CapturedState.class); Runnable mockRunnable = mock(Runnable.class); ThreadLocalStateCaptor.THREAD_LOCAL.set(mockCapturedState); f.execute(mockRunnable); e.shutdown(); e.awaitTermination(10, TimeUnit.HOURS); verifyStandardCaptures(mockCapturedState, mockRunnable); } @Test public void testCompletionServiceRunnableCaptures() throws InterruptedException, Exception { ExecutorService executor = Executors.newCachedThreadPool(); CompletionService<Object> delegate = new ExecutorCompletionService<>(executor); CompletionService<Object> cs = StateCapture.capturingDecorator(delegate); CapturedState mockCapturedState = mock(CapturedState.class); Runnable mockRunnable = mock(Runnable.class); ThreadLocalStateCaptor.THREAD_LOCAL.set(mockCapturedState); Object result = new Object(); Future<Object> futureResult = cs.submit(mockRunnable, result); assertThat("Expected the delegate response to return", result, sameInstance(futureResult.get())); executor.shutdown(); verifyStandardCaptures(mockCapturedState, mockRunnable); } @Test public void testCompletionServiceCallableCaptures() throws InterruptedException, Exception { ExecutorService executor = Executors.newCachedThreadPool(); CompletionService<Object> delegate = new ExecutorCompletionService<>(executor); CompletionService<Object> cs = StateCapture.capturingDecorator(delegate); CapturedState mockCapturedState = mock(CapturedState.class); Object expectedResult = new Object(); @SuppressWarnings("unchecked") Callable<Object> mockCallable = mock(Callable.class); when(mockCallable.call()).thenReturn(expectedResult); ThreadLocalStateCaptor.THREAD_LOCAL.set(mockCapturedState); Future<Object> futureResult = cs.submit(mockCallable); executor.shutdown(); verifyStandardCaptures(mockCapturedState, mockCallable, expectedResult, futureResult.get()); }
MXBeanPoller { public void shutdown() { running.set(false); executor.shutdown(); try { executor.awaitTermination(SHUTDOWN_TIMEOUT, TimeUnit.SECONDS); } catch (InterruptedException e) { executor.shutdownNow(); Thread.currentThread().interrupt(); } } MXBeanPoller(final MetricRecorder metricRecorder, final int pollingIntervalSeconds, final List<Sensor> sensors); MXBeanPoller(final ScheduledExecutorService executor, final MetricRecorder metricRecorder, final int pollingIntervalSeconds, final List<Sensor> sensors); static final MXBeanPoller withAutoShutdown( final MetricRecorder metricRecorder, int pollingIntervalSeconds, List<Sensor> sensors); void shutdown(); }
@Test public void shutdown() throws Exception { final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); MXBeanPoller poller = new MXBeanPoller(executor, new NullRecorder(), 5, Collections.emptyList()); poller.shutdown(); assertTrue("Executor not shutdown on poller shutdown", executor.isShutdown()); } @Test public void senses() throws Exception { final MetricRecorder recorder = new NullRecorder(); final Sensor sensor1 = mock(Sensor.class); final Sensor sensor2 = mock(Sensor.class); when(sensor1.addContext(any(TypedMap.class))).then(invocation -> invocation.getArgument(0)); when(sensor2.addContext(any(TypedMap.class))).then(invocation -> invocation.getArgument(0)); List<Sensor> sensors = new ArrayList<>(); sensors.add(sensor1); sensors.add(sensor2); MXBeanPoller poller = new MXBeanPoller(recorder, 1, sensors); Thread.sleep(1500); poller.shutdown(); final ArgumentMatcher<TypedMap> dataMatch = new DataMatcher(); verify(sensor1).addContext(argThat(dataMatch)); verify(sensor2).addContext(argThat(dataMatch)); verify(sensor1, atLeastOnce()).sense(any(MetricContext.class)); verify(sensor2, atLeastOnce()).sense(any(MetricContext.class)); }
FileRecorder extends MetricRecorder<MetricRecorder.RecorderContext> { static boolean isValid(final Metric label) { final String str = label.toString(); return !(str.contains("\n") || str.contains(",") || str.contains(":") || str.contains("=")); } FileRecorder(final String filename); static final FileRecorder withAutoShutdown( final String filename); void shutdown(); }
@Test public void validation() { final String[] good = { "snake_case_metric", "camelCaseMetric", "hyphenated-metric", "spaced out metric", "digits 0123456789", "G\u00FCnther", "\t!\"#$%&'()*+./;<>?@[\\]^`{|}~" }; for (final String s : good) { assertTrue("valid name [" + s + "]", FileRecorder.isValid(Metric.define(s))); } final String[] bad = { "metric_name, dimension=value", "metric_name:100ms:", "metric_name\nmetric", "metric=metric_name" }; for (final String s : bad) { assertFalse("invalid name [" + s + "]", FileRecorder.isValid(Metric.define(s))); } }
DimensionMapper { public List<Dimension> getDimensions(final Metric metric, final MetricRecorder.RecorderContext context) { TypedMap attributes = flattenContextHierarchy(context); Set<TypedMap.Key> dimensionKeys = filterMap.get(metric); if (dimensionKeys == null) { dimensionKeys = Collections.emptySet(); } Stream<TypedMap.Key> keys = Stream.concat(globalDimensions.stream(), dimensionKeys.stream()); return keys.map(key -> new Dimension().withName(key.name).withValue(String.valueOf(attributes.get(key)))) .distinct() .sorted(Comparator.comparing(Dimension::getName)) .collect(Collectors.toList()); } private DimensionMapper( final Set<TypedMap.Key> globalDimensions, final Map<Metric, Set<TypedMap.Key>> filterMap); List<Dimension> getDimensions(final Metric metric, final MetricRecorder.RecorderContext context); }
@Test public void no_mappings() throws Exception { MetricRecorder.RecorderContext context = new MetricRecorder.RecorderContext(ContextData.withId(ID) .add(StandardContext.SERVICE, SERVICE_NAME) .build()); DimensionMapper mapper = new DimensionMapper.Builder().build(); assertTrue("Empty mapping resulted in non-empty dimension list", mapper.getDimensions(METRIC, context).isEmpty()); } @Test public void one_global() throws Exception { MetricRecorder.RecorderContext context = new MetricRecorder.RecorderContext(ContextData.withId(ID) .add(StandardContext.SERVICE, SERVICE_NAME) .build()); DimensionMapper mapper = new DimensionMapper.Builder() .addGlobalDimension(ContextData.ID) .build(); List<Dimension> dims = mapper.getDimensions(METRIC, context); assertEquals("Unexpected size of dimension list", 1, dims.size()); assertEquals("Unexpected name for dimension", ContextData.ID.name, dims.get(0).getName()); assertEquals("Unexpected value for dimension", ID, dims.get(0).getValue()); } @Test public void one_global_empty_context() throws Exception { MetricRecorder.RecorderContext context = new MetricRecorder.RecorderContext(TypedMap.empty()); DimensionMapper mapper = new DimensionMapper.Builder() .addGlobalDimension(ContextData.ID) .build(); List<Dimension> dims = mapper.getDimensions(METRIC, context); assertEquals("Unexpected size of dimension list", 1, dims.size()); assertEquals("Unexpected name for dimension", ContextData.ID.name, dims.get(0).getName()); assertEquals("Unexpected value for missing dimension", "null", dims.get(0).getValue()); } @Test public void global_and_normal_dimensions_combine() throws Exception { MetricRecorder.RecorderContext context = new MetricRecorder.RecorderContext(ContextData.withId(ID) .add(StandardContext.SERVICE, SERVICE_NAME) .build()); DimensionMapper mapper = new DimensionMapper.Builder() .addGlobalDimension(ContextData.ID) .addMetric(METRIC, Arrays.asList(StandardContext.SERVICE)) .build(); Dimension expectedIdDimension = new Dimension().withName(ContextData.ID.name).withValue(ID); Dimension expectedServiceDimension = new Dimension().withName(StandardContext.SERVICE.name).withValue(SERVICE_NAME); List<Dimension> dims = mapper.getDimensions(METRIC, context); assertTrue("Dimension list is missing mapped ID dimension", dims.contains(expectedIdDimension)); assertTrue("Dimension list is missing mapped SERVICE dimension", dims.contains(expectedServiceDimension)); assertEquals("Unexpected size of dimension list", 2, dims.size()); } @Test public void mappings() throws Exception { Metric metricA = Metric.define("Alpha"); Metric metricB = Metric.define("Beta"); Metric metricC = Metric.define("Gamma"); String operation = "doStuff"; MetricRecorder.RecorderContext context = new MetricRecorder.RecorderContext(ContextData.withId(ID) .add(StandardContext.SERVICE, SERVICE_NAME) .add(StandardContext.OPERATION, operation) .build()); DimensionMapper mapper = new DimensionMapper.Builder() .addMetric(metricA, Arrays.asList(StandardContext.SERVICE)) .addMetric(metricB, Arrays.asList(StandardContext.SERVICE, StandardContext.OPERATION)) .addMetric(metricC, Arrays.asList(StandardContext.ID, StandardContext.SERVICE)) .build(); List<Dimension> dimsA = mapper.getDimensions(metricA, context); assertEquals("Unexpected size of dimension list", 1, dimsA.size()); assertEquals("Unexpected name for dimension", StandardContext.SERVICE.name, dimsA.get(0).getName()); assertEquals("Unexpected value for dimension", SERVICE_NAME, dimsA.get(0).getValue()); List<Dimension> dimsB = mapper.getDimensions(metricB, context); assertEquals("Unexpected size of dimension list", 2, dimsB.size()); boolean seenB[] = {false, false}; for (Dimension d : dimsB) { if (d.getName().equals(StandardContext.SERVICE.name) && d.getValue().equals(SERVICE_NAME)) { seenB[0] = true; } else if (d.getName().equals(StandardContext.OPERATION.name) && d.getValue().equals(operation)) { seenB[1] = true; } else { fail("Unexpected dimension present in mapped list"); } } assertTrue("Dimension list is missing mapped SERVICE dimension", seenB[0]); assertTrue("Dimension list is missing mapped OPERATION dimension", seenB[1]); List<Dimension> dimsC = mapper.getDimensions(metricC, context); assertEquals("Unexpected size of dimension list", 2, dimsC.size()); boolean seenC[] = {false, false}; for (Dimension d : dimsC) { if (d.getName().equals(StandardContext.SERVICE.name) && d.getValue().equals(SERVICE_NAME)) { seenC[0] = true; } else if (d.getName().equals(StandardContext.ID.name) && d.getValue().equals(ID)) { seenC[1] = true; } else { fail("Unexpected dimension present in mapped list"); } } assertTrue("Dimension list is missing mapped SERVICE dimension", seenC[0]); assertTrue("Dimension list is missing mapped ID dimension", seenC[1]); } @Test public void attributes_are_sorted() throws Exception { MetricRecorder.RecorderContext context = new MetricRecorder.RecorderContext(ContextData.withId(ID) .add(StandardContext.SERVICE, SERVICE_NAME) .add(StandardContext.OPERATION, OPERATION) .add(StandardContext.MARKETPLACE, MARKETPLACE) .add(StandardContext.PROGRAM, PROGRAM) .build()); DimensionMapper mapper = new DimensionMapper.Builder() .addGlobalDimension(ContextData.ID) .addMetric(METRIC, Arrays.asList(StandardContext.SERVICE, StandardContext.OPERATION, StandardContext.MARKETPLACE, StandardContext.PROGRAM)) .build(); Dimension expectedIdDimension = new Dimension().withName(ContextData.ID.name).withValue(ID); Dimension expectedServiceDimension = new Dimension().withName(StandardContext.SERVICE.name).withValue(SERVICE_NAME); Dimension expectedOperationDimension = new Dimension().withName(StandardContext.OPERATION.name).withValue(OPERATION); Dimension expectedMarketplaceDimension = new Dimension().withName(StandardContext.MARKETPLACE.name).withValue(MARKETPLACE); Dimension expectedProgramDimension = new Dimension().withName(StandardContext.PROGRAM.name).withValue(PROGRAM); List<Dimension> expected = Arrays.asList(expectedIdDimension, expectedMarketplaceDimension, expectedOperationDimension, expectedProgramDimension, expectedServiceDimension); List<Dimension> dims = mapper.getDimensions(METRIC, context); assertEquals(expected, dims); } @Test public void parent_and_child_attributes_combine() throws Exception { String childId = UUID.randomUUID().toString(); MetricRecorder.RecorderContext context = new MetricRecorder.RecorderContext(ContextData.withId(ID) .add(StandardContext.SERVICE, SERVICE_NAME) .build()); MetricRecorder.RecorderContext childContext = context.newChild(ContextData.withId(childId) .add(StandardContext.OPERATION, OPERATION) .build()); DimensionMapper mapper = new DimensionMapper.Builder() .addGlobalDimension(ContextData.ID) .addMetric(METRIC, Arrays.asList(StandardContext.SERVICE, StandardContext.OPERATION)) .build(); Dimension expectedIdDimension = new Dimension().withName(ContextData.ID.name).withValue(childId); Dimension expectedServiceDimension = new Dimension().withName(StandardContext.SERVICE.name).withValue(SERVICE_NAME); Dimension expectedOperationDimension = new Dimension().withName(StandardContext.OPERATION.name).withValue(OPERATION); List<Dimension> expected = Arrays.asList(expectedIdDimension, expectedOperationDimension, expectedServiceDimension); List<Dimension> dims = mapper.getDimensions(METRIC, childContext); assertEquals(expected, dims); } @Test public void child_attributes_override_parent() throws Exception { String childId = UUID.randomUUID().toString(); String childService = UUID.randomUUID().toString(); String childOperation = UUID.randomUUID().toString(); MetricRecorder.RecorderContext context = new MetricRecorder.RecorderContext(ContextData.withId(ID) .add(StandardContext.SERVICE, SERVICE_NAME) .add(StandardContext.OPERATION, OPERATION) .build()); MetricRecorder.RecorderContext childContext = context.newChild(ContextData.withId(childId) .add(StandardContext.SERVICE, childService) .add(StandardContext.OPERATION, childOperation) .build()); DimensionMapper mapper = new DimensionMapper.Builder() .addGlobalDimension(ContextData.ID) .addMetric(METRIC, Arrays.asList(StandardContext.SERVICE, StandardContext.OPERATION)) .build(); Dimension expectedIdDimension = new Dimension().withName(ContextData.ID.name).withValue(childId); Dimension expectedServiceDimension = new Dimension().withName(StandardContext.SERVICE.name).withValue(childService); Dimension expectedOperationDimension = new Dimension().withName(StandardContext.OPERATION.name).withValue(childOperation); List<Dimension> expected = Arrays.asList(expectedIdDimension, expectedOperationDimension, expectedServiceDimension); List<Dimension> dims = mapper.getDimensions(METRIC, childContext); assertEquals(expected, dims); }
DoubleFormat { public static void format(Appendable sb, double value) { try { format_exception(sb, value); } catch (IOException e) { throw new IllegalStateException("Appendable must not throw IOException", e); } } private DoubleFormat(); static void format(Appendable sb, double value); }
@Test public void benchmark() throws Exception { final long iterations = 1000000; long duration_StringFormat = run_benchmark(iterations, (a) -> String.format("%.6f", a)); NumberFormat javaFormatter = NumberFormat.getInstance(); javaFormatter.setMinimumFractionDigits(0); javaFormatter.setMaximumFractionDigits(6); javaFormatter.setGroupingUsed(false); long duration_JavaFormat = run_benchmark(iterations, (a) -> javaFormatter.format(a)); long duration_JavaStringBuilder = run_benchmark(iterations, (a) -> (new StringBuilder()).append(a)); long duration_DoubleFormat = run_benchmark(iterations, (a) -> DoubleFormat.format(new StringBuilder(), a)); System.out.println("DoubleFormat Performance comparison: " + iterations +" iterations"); System.out.println("\tJava String.format: " + duration_StringFormat + " ms"); System.out.println("\tJava NumberFormat: " + duration_JavaFormat + " ms"); System.out.println("\tJava StringBuilder: " + duration_JavaStringBuilder + " ms"); System.out.println("\tDoubleFormat: " + duration_DoubleFormat + " ms"); assertTrue(duration_DoubleFormat < duration_StringFormat); assertTrue(duration_DoubleFormat < duration_JavaFormat); assertTrue(duration_DoubleFormat < duration_JavaStringBuilder); }
ContextAwareExecutor implements Executor { @Override public void execute(Runnable command) { executor.execute(ThreadContext.current().wrap(command)); } ContextAwareExecutor(Executor executor); @Override void execute(Runnable command); }
@Test public void currentContextIsPropagatedToTask() throws Exception { ThreadContext context = ThreadContext.emptyContext().with(KEY, "value"); try (ThreadContext.CloseableContext ignored = context.open()) { executor.execute(captureTask); } latch.await(); assertSame(context, contextCapture.get()); } @Test public void withNoContextDefaultIsUsed() throws Exception { executor.execute(captureTask); latch.await(); assertSame(ThreadContext.emptyContext(), contextCapture.get()); }
ImmutableTypedMap implements TypedMap { @Override public Set<Key> keySet() { return this.dataMap.keySet(); } private ImmutableTypedMap(Map<Key<?>, Entry<?>> dataMap); @Override final T get(Key<T> key); @Override int size(); @Override boolean isEmpty(); @Override Iterator<Entry> iterator(); @Override Iterator<Entry<T>> typedIterator(Class<T> clazz); @Override Set<Key> keySet(); @Override Set<Key<T>> typedKeySet(final Class<T> clazz); @Override boolean containsKey(final Key<?> key); @Override boolean containsValue(final Object value); }
@Test public void keyset() throws Exception { final TypedMap.Key<Double> ka = TypedMap.key("Alpha", Double.class); final TypedMap.Key<String> kb = TypedMap.key("Beta", String.class); final TypedMap.Key<UUID> kc = TypedMap.key("Gamma", UUID.class); final TypedMap.Key<Object> kd = TypedMap.key("Delta", Object.class); final Double va = Double.valueOf(867.5309); final String vb = "Here is a string, with...\nmultiple lines and stuff."; final UUID vc = UUID.randomUUID(); final Object vd = new Object(); TypedMap data = ImmutableTypedMap.Builder .with(kc, vc) .add(ka, va) .add(kb, vb) .add(kd, vd) .build(); Set<TypedMap.Key> s = data.keySet(); assertEquals("Set of keys has wrong size", 4, s.size()); assertTrue("Set of keys is missing a key", s.contains(ka)); assertTrue("Set of keys is missing a key", s.contains(kb)); assertTrue("Set of keys is missing a key", s.contains(kc)); assertTrue("Set of keys is missing a key", s.contains(kd)); }
ImmutableTypedMap implements TypedMap { @Override public <T> Set<Key<T>> typedKeySet(final Class<T> clazz) { Set<Key<T>> keys = new HashSet<>(); for (Key k : this.keySet()) { if (k.valueType.equals(clazz)) { keys.add(k); } } return Collections.unmodifiableSet(keys); } private ImmutableTypedMap(Map<Key<?>, Entry<?>> dataMap); @Override final T get(Key<T> key); @Override int size(); @Override boolean isEmpty(); @Override Iterator<Entry> iterator(); @Override Iterator<Entry<T>> typedIterator(Class<T> clazz); @Override Set<Key> keySet(); @Override Set<Key<T>> typedKeySet(final Class<T> clazz); @Override boolean containsKey(final Key<?> key); @Override boolean containsValue(final Object value); }
@Test public void typedKeyset() throws Exception { final TypedMap.Key<Double> ka = TypedMap.key("A", Double.class); final TypedMap.Key<String> kb = TypedMap.key("B", String.class); final TypedMap.Key<String> kc = TypedMap.key("C", String.class); final TypedMap.Key<Object> kd = TypedMap.key("D", Object.class); final Double va = Double.valueOf(3.14159); final String vb = "Mmm tasty pi"; final String vc = "but no love for tau"; final Object vd = "or a type safe string"; TypedMap data = ImmutableTypedMap.Builder .with(kc, vc) .add(ka, va) .add(kb, vb) .add(kd, vd) .build(); Set<TypedMap.Key<String>> s = data.typedKeySet(String.class); assertEquals("Typed set of keys has wrong size", 2, s.size()); assertFalse("Typed set of keys has unexpected member", s.contains(ka)); assertTrue("Typed set of keys is missing a key", s.contains(kb)); assertTrue("Typed set of keys is missing a key", s.contains(kc)); assertFalse("Typed set of keys has unexpected member", s.contains(kd)); }
ImmutableTypedMap implements TypedMap { @Override public Iterator<Entry> iterator() { return this.dataMap.values().iterator(); } private ImmutableTypedMap(Map<Key<?>, Entry<?>> dataMap); @Override final T get(Key<T> key); @Override int size(); @Override boolean isEmpty(); @Override Iterator<Entry> iterator(); @Override Iterator<Entry<T>> typedIterator(Class<T> clazz); @Override Set<Key> keySet(); @Override Set<Key<T>> typedKeySet(final Class<T> clazz); @Override boolean containsKey(final Key<?> key); @Override boolean containsValue(final Object value); }
@Test public void iterator() throws Exception { final TypedMap.Key<Long> ka = TypedMap.key("1", Long.class); final TypedMap.Key<Short> kb = TypedMap.key("2", Short.class); final TypedMap.Key<BigInteger> kc = TypedMap.key("5", BigInteger.class); final Long va = Long.valueOf(999999999); final Short vb = Short.valueOf((short)1); final BigInteger vc = BigInteger.valueOf(Long.MAX_VALUE+Short.MAX_VALUE); TypedMap data = ImmutableTypedMap.Builder .with(ka, va) .add(kb, vb) .add(kc, vc) .build(); assertEquals(3, data.size()); int i = 0; boolean seen_a = false; boolean seen_b = false; boolean seen_c = false; for (TypedMap.Entry e : data) { i++; if (e.getKey().equals(ka) && e.getValue().equals(va)) { seen_a = true; } if (e.getKey().equals(kb) && e.getValue().equals(vb)) { seen_b = true; } if (e.getKey().equals(kc) && e.getValue().equals(vc)) { seen_c = true; } } assertEquals("Iterator iterated incorrect increments", 3, i); assertTrue("Iterator missed an entry", seen_a); assertTrue("Iterator missed an entry", seen_b); assertTrue("Iterator missed an entry", seen_c); } @Test(expected=UnsupportedOperationException.class) public void iterator_remove() throws Exception { final TypedMap.Key<Long> ka = TypedMap.key("1", Long.class); final Long va = Long.valueOf(999999999); TypedMap data = ImmutableTypedMap.Builder.with(ka, va).build(); Iterator<TypedMap.Entry> it = data.iterator(); it.remove(); }
ImmutableTypedMap implements TypedMap { @Override public int size() { return this.dataMap.size(); } private ImmutableTypedMap(Map<Key<?>, Entry<?>> dataMap); @Override final T get(Key<T> key); @Override int size(); @Override boolean isEmpty(); @Override Iterator<Entry> iterator(); @Override Iterator<Entry<T>> typedIterator(Class<T> clazz); @Override Set<Key> keySet(); @Override Set<Key<T>> typedKeySet(final Class<T> clazz); @Override boolean containsKey(final Key<?> key); @Override boolean containsValue(final Object value); }
@Test public void forEach() throws Exception { final TypedMap.Key<Long> ka = TypedMap.key("1", Long.class); final TypedMap.Key<Short> kb = TypedMap.key("2", Short.class); final TypedMap.Key<BigInteger> kc = TypedMap.key("5", BigInteger.class); final Long va = Long.valueOf(999999999); final Short vb = Short.valueOf((short)1); final BigInteger vc = BigInteger.valueOf(Long.MAX_VALUE+Short.MAX_VALUE); TypedMap data = ImmutableTypedMap.Builder .with(ka, va) .add(kb, vb) .add(kc, vc) .build(); assertEquals(3, data.size()); final boolean[] seen = {false,false,false,false}; data.forEach((e) -> { if (e.getKey().equals(ka) && e.getValue().equals(va)) { seen[0] = true; } else if (e.getKey().equals(kb) && e.getValue().equals(vb)) { seen[1] = true; } else if (e.getKey().equals(kc) && e.getValue().equals(vc)) { seen[2] = true; } else { seen[3] = true; } }); assertTrue("forEach missed an entry", seen[0]); assertTrue("forEach missed an entry", seen[1]); assertTrue("forEach missed an entry", seen[2]); assertFalse("forEach hit an unexpected entry", seen[3]); } @Test public void forEachTyped() throws Exception { final TypedMap.Key<String> ka = TypedMap.key("y", String.class); final TypedMap.Key<Object> kb = TypedMap.key("n", Object.class); final TypedMap.Key<String> kc = TypedMap.key("m", String.class); final TypedMap.Key<Integer> kd = TypedMap.key("s", Integer.class); final String va = "yes"; final String vb = "no"; final String vc = "maybe"; final Integer vd = 50; TypedMap data = ImmutableTypedMap.Builder .with(ka, va) .add(kb, vb) .add(kc, vc) .add(kd, vd) .build(); assertEquals(4, data.size()); final boolean[] seen = {false,false,false,false,false}; data.forEachTyped(String.class, (e) -> { TypedMap.Key<String> k = e.getKey(); String v = e.getValue(); if (k.equals(ka) && v.equals(va)) { seen[0] = true; } else if (k.equals(kb) && v.equals(vb)) { seen[1] = true; } else if (k.equals(kc) && v.equals(vc)) { seen[2] = true; } else if (k.equals(kd) && v.equals(vd)) { seen[3] = true; } else { seen[4] = true; } }); assertTrue("forEachTyped missed an entry", seen[0]); assertFalse("forEachTyped hit an unexpected entry", seen[1]); assertTrue("forEachTyped missed an entry", seen[2]); assertFalse("forEachTyped hit an unexpected entry", seen[3]); assertFalse("forEachTyped hit an unexpected entry", seen[4]); }
ImmutableTypedMap implements TypedMap { @Override public <T> Iterator<Entry<T>> typedIterator(Class<T> clazz) { List<Entry<T>> entries = new ArrayList(); for (Iterator<Entry> it = this.iterator(); it.hasNext(); ) { final Entry e = it.next(); if (e.getKey().valueType.equals(clazz)) { entries.add(e); } } return Collections.unmodifiableCollection(entries).iterator(); } private ImmutableTypedMap(Map<Key<?>, Entry<?>> dataMap); @Override final T get(Key<T> key); @Override int size(); @Override boolean isEmpty(); @Override Iterator<Entry> iterator(); @Override Iterator<Entry<T>> typedIterator(Class<T> clazz); @Override Set<Key> keySet(); @Override Set<Key<T>> typedKeySet(final Class<T> clazz); @Override boolean containsKey(final Key<?> key); @Override boolean containsValue(final Object value); }
@Test public void typedIterator() throws Exception { final TypedMap.Key<String> ka = TypedMap.key("y", String.class); final TypedMap.Key<Object> kb = TypedMap.key("n", Object.class); final TypedMap.Key<String> kc = TypedMap.key("m", String.class); final String va = "yes"; final String vb = "no"; final String vc = "maybe"; TypedMap data = ImmutableTypedMap.Builder .with(ka, va) .add(kb, vb) .add(kc, vc) .build(); assertEquals(3, data.size()); int i = 0; boolean seen_a = false; boolean seen_b = false; boolean seen_c = false; Iterator<TypedMap.Entry<String>> it = data.typedIterator(String.class); while (it.hasNext()) { i++; final TypedMap.Entry<String> e = it.next(); TypedMap.Key<String> k = e.getKey(); String v = e.getValue(); if (k.equals(ka) && v.equals(va)) { seen_a = true; } if (k.equals(kb) && v.equals(vb)) { seen_b = true; } if (k.equals(kc) && v.equals(vc)) { seen_c = true; } } assertEquals("Iterator iterated incorrect increments", 2, i); assertTrue("Typed iterator missed an entry", seen_a); assertFalse("Typed iterator returned an entry of wrong type", seen_b); assertTrue("Typed iterator missed an entry", seen_c); } @Test(expected=UnsupportedOperationException.class) public void typedIterator_remove() throws Exception { final TypedMap.Key<String> ka = TypedMap.key("y", String.class); final String va = "yes"; TypedMap data = ImmutableTypedMap.Builder.with(ka, va).build(); Iterator<TypedMap.Entry<String>> it = data.typedIterator(String.class); it.remove(); }
NullContext implements MetricContext { @Override public TypedMap attributes() { return attributes; } NullContext(TypedMap attributes); NullContext(TypedMap attributes, MetricContext parent); static NullContext empty(); @Override TypedMap attributes(); @Override void record(Metric label, Number value, Unit unit, Instant time); @Override void count(Metric label, long delta); @Override void close(); @Override MetricContext newChild(TypedMap attributes); @Override MetricContext parent(); }
@Test public void nullContextCanHaveAttributes() { TypedMap.Key<String> ID = TypedMap.key("ID", String.class); TypedMap attributes = ImmutableTypedMap.Builder.with(ID, "id").build(); NullContext context = new NullContext(attributes); assertSame(attributes, context.attributes()); }
Metric { public static Metric define(final String name) { return new Metric(name); } private Metric(final String name); static Metric define(final String name); @Override final String toString(); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void validation() throws Exception { final String[] goods = { "snake_case_metric", "camelCaseMetric", "hyphenated-metric", "spaced out metric", "digits 0123456789", "G\u00FCnther", "\t\n!\"#$%&'()*+,./:;<=>?@[\\]^`{|}~", " " }; for (String s : goods) { Metric.define(s); } final String[] bads = { null, "" }; for (String s : bads) { try { Metric.define(""); } catch (IllegalArgumentException expected) { continue; } fail("Expected exception not thrown for bad name '"+s+"'"); } }
MultiRecorder extends MetricRecorder<MultiRecorder.MultiRecorderContext> { @Override protected void record(Metric label, Number value, Unit unit, Instant time, MultiRecorderContext context) { context.contexts.parallelStream().forEach(t -> t.record(label, value, unit, time)); } MultiRecorder(List<MetricRecorder<?>> recorders); }
@Test public void recordIsSentToAllDelegates() { MetricContext context = recorder.context(attributes); context.record(METRIC, 42L, Unit.NONE, timestamp); verify(delegate1).record(eq(METRIC), eq(42L), eq(Unit.NONE), eq(timestamp), argThat(t -> attributes == t.attributes())); verify(delegate2).record(eq(METRIC), eq(42L), eq(Unit.NONE), eq(timestamp), argThat(t -> attributes == t.attributes())); }
MultiRecorder extends MetricRecorder<MultiRecorder.MultiRecorderContext> { @Override protected void count(Metric label, long delta, MultiRecorderContext context) { context.contexts.parallelStream().forEach(t -> t.count(label, delta)); } MultiRecorder(List<MetricRecorder<?>> recorders); }
@Test public void countIsSentToAllDelegates() { MetricContext context = recorder.context(attributes); context.count(METRIC, 42L); verify(delegate1).count(eq(METRIC), eq(42L), argThat(t -> attributes == t.attributes())); verify(delegate2).count(eq(METRIC), eq(42L), argThat(t -> attributes == t.attributes())); }
MultiRecorder extends MetricRecorder<MultiRecorder.MultiRecorderContext> { @Override protected void close(MultiRecorderContext context) { context.contexts.parallelStream().forEach(MetricContext::close); } MultiRecorder(List<MetricRecorder<?>> recorders); }
@Test public void closeIsSentToAllDelegates() { MetricContext context = recorder.context(attributes); context.close(); verify(delegate1).close(argThat(t -> attributes == t.attributes())); verify(delegate2).close(argThat(t -> attributes == t.attributes())); }
DocHighlighter { protected void highlightSingleFieldValue(String field, String s, Set<HighlightingQuery> highlightingQueries, Analyzer analyzer, AtomicBoolean anythingHighlighted, RhapsodeXHTMLHandler xhtml) throws IOException, SAXException { if (highlightingQueries == null || highlightingQueries.size() == 0) { xhtml.characters(s); return; } List<PriorityOffset> tokenOffsets = new ArrayList<>(); Map<Integer, Offset> charOffsets = new HashMap<>(); MemoryIndex index = new MemoryIndex(true); index.addField(field, s, analyzer); index.freeze(); IndexSearcher searcher = index.createSearcher(); for (HighlightingQuery hq : highlightingQueries) { addPriorityOffsets(searcher, hq, tokenOffsets, charOffsets); } List<PriorityOffset> winnowed = PriorityOffsetUtil.removeOverlapsAndSort(tokenOffsets); highlight(winnowed, charOffsets, s, anythingHighlighted, xhtml); } void highlightDocsToFile(Path p, String defaultContentField, String embeddedPathField, List<String> fields, List<Document> docs, Collection<ComplexQuery> queries, Analyzer analyzer, String optionalStyleString, int targetAttachmentOffset); void highlightDocToFile(Path p, String defaultContentField, List<String> fields, Document doc, Collection<ComplexQuery> queries, Analyzer analyzer, String optionalStyleString); void highlightDocs(String defaultContentField, String embeddedPathField, List<String> fields, List<Document> docs, Collection<ComplexQuery> queries, Analyzer analyzer, AtomicBoolean anythingHighlighted, int targetOffset, RhapsodeXHTMLHandler xhtml); void highlightDoc(String contentField, List<String> fields, Document doc, Collection<ComplexQuery> queries, Analyzer analyzer, AtomicBoolean anythingHighlighted, RhapsodeXHTMLHandler xhtml); void setTableClass(String tableClass); void setTDClass(String tdClass); }
@Test public void testBasic() throws IOException, SAXException { String s = "the quick brown fox as well as some other fox and quick"; SpanQuery spanQuery = new SpanOrQuery(foxQuick, foxAs, new SpanTermQuery(new Term(field, "fox"))); Analyzer analyzer = new WhitespaceAnalyzer(); ContentHandler handler = new ToHTMLContentHandler(); RhapsodeXHTMLHandler xhtml = new RhapsodeXHTMLHandler(handler); RhapsodeXHTMLHandler.simpleInit(xhtml); Set<HighlightingQuery> highlightingQueries = new HashSet<>(); highlightingQueries.add(new HighlightingQuery(spanQuery, 1, "this-the-one")); DocHighlighter h = new DocHighlighter(); h.highlightSingleFieldValue(field, s, highlightingQueries, analyzer, new AtomicBoolean(false), xhtml); xhtml.endElement(H.BODY); xhtml.endDocument(); assertTrue(handler.toString().contains("<span id=\"first\" class=\"this-the-one\">quick brown fox</span>")); assertTrue(handler.toString().contains("<span class=\"this-the-one\">fox and quick</span>")); } @Test public void testPriority() throws IOException, SAXException { String s = "the quick brown fox as well as some other fox and quick"; SpanQuery spanQuery = new SpanOrQuery(foxQuick, foxAs); Analyzer analyzer = new WhitespaceAnalyzer(); ContentHandler handler = new ToHTMLContentHandler(); RhapsodeXHTMLHandler xhtml = new RhapsodeXHTMLHandler(handler); RhapsodeXHTMLHandler.simpleInit(xhtml); Set<HighlightingQuery> highlightingQueries = new HashSet<>(); highlightingQueries.add(new HighlightingQuery(spanQuery, 2, "this-the-one")); highlightingQueries.add(new HighlightingQuery(new SpanTermQuery(new Term(field, "fox")), 1, "this-the-two")); DocHighlighter h = new DocHighlighter(); h.highlightSingleFieldValue(field, s, highlightingQueries, analyzer, new AtomicBoolean(false), xhtml); xhtml.endElement(H.BODY); xhtml.endDocument(); assertTrue(handler.toString().contains("brown <span id=\"first\" class=\"this-the-two\">fox</span>")); assertTrue(handler.toString().contains(" other <span class=\"this-the-two\">fox</span>")); }