target
stringlengths
20
113k
src_fm
stringlengths
11
86.3k
src_fm_fc
stringlengths
21
86.4k
src_fm_fc_co
stringlengths
30
86.4k
src_fm_fc_ms
stringlengths
42
86.8k
src_fm_fc_ms_ff
stringlengths
43
86.8k
@Test public void testFireEvent() throws Exception { getInstance().fireEvent(instance.getInstanceId(),"100", Constants.Event.CLICK,null,null); }
@Deprecated public void fireEvent(final String instanceId, final String ref, final String type, final Map<String, Object> data){ this.fireEvent(instanceId, ref, type, data, null); }
WXBridgeManager implements Callback,BactchExecutor { @Deprecated public void fireEvent(final String instanceId, final String ref, final String type, final Map<String, Object> data){ this.fireEvent(instanceId, ref, type, data, null); } }
WXBridgeManager implements Callback,BactchExecutor { @Deprecated public void fireEvent(final String instanceId, final String ref, final String type, final Map<String, Object> data){ this.fireEvent(instanceId, ref, type, data, null); } private WXBridgeManager(); }
WXBridgeManager implements Callback,BactchExecutor { @Deprecated public void fireEvent(final String instanceId, final String ref, final String type, final Map<String, Object> data){ this.fireEvent(instanceId, ref, type, data, null); } private WXBridgeManager(); static WXBridgeManager getInstance(); void stopRemoteDebug(); Object callModuleMethod(String instanceId, String moduleStr, String methodStr, JSONArray args); void restart(); synchronized void setStackTopInstance(final String instanceId); @Override void post(Runnable r); @Override void setInterceptor(Interceptor interceptor); void post(Runnable r, Object token); void sendMessageDelayed(Message message, long delayMillis); void removeMessage(int what,Object obj); Object callNativeModule(String instanceId, String module, String method, JSONArray arguments, Object options); Object callNativeComponent(String instanceId, String componentRef, String method, JSONArray arguments, Object options); int callNative(String instanceId, String tasks, String callback); int callCreateBody(String instanceId, String tasks, String callback); int callUpdateFinish(String instanceId, String callback); int callCreateFinish(String instanceId, String callback); int callRefreshFinish(String instanceId, String callback); int callUpdateAttrs(String instanceId, String ref, String task, String callback); int callUpdateStyle(String instanceId, String ref, String task, String callback); int callRemoveElement(String instanceId, String ref, String callback); int callMoveElement(String instanceId, String ref, String parentref, String index, String callback); int callAddEvent(String instanceId, String ref, String event, String callback); int callRemoveEvent(String instanceId, String ref, String event, String callback); int callAddElement(String instanceId, String ref,String dom,String index, String callback); synchronized void initScriptsFramework(String framework); @Deprecated void fireEvent(final String instanceId, final String ref, final String type, final Map<String, Object> data); @Deprecated void fireEvent(final String instanceId, final String ref, final String type, final Map<String, Object> data,final Map<String, Object> domChanges); void fireEventOnNode(final String instanceId, final String ref, final String type, final Map<String, Object> data,final Map<String, Object> domChanges); @Deprecated void callback(String instanceId, String callback,String data); @Deprecated void callback(final String instanceId, final String callback, final Map<String, Object> data); @Deprecated void callback(final String instanceId, final String callback, final Object data,boolean keepAlive); void refreshInstance(final String instanceId, final WXRefreshData jsonData); void commitJSBridgeAlarmMonitor(String instanceId, WXErrorCode errCode, String errMsg); void commitJSFrameworkAlarmMonitor(final String type, final WXErrorCode errorCode, String errMsg); void createInstance(final String instanceId, final String template, final Map<String, Object> options, final String data); void destroyInstance(final String instanceId); @Override boolean handleMessage(Message msg); void invokeExecJS(String instanceId, String namespace, String function, WXJSObject[] args,boolean logTaskDetail); void registerModules(final Map<String, Object> modules); void registerComponents(final List<Map<String, Object>> components); void execJSService(final String service); void destroy(); void reportJSException(String instanceId, String function, String exception); @Deprecated void notifyTrimMemory(); @Nullable Looper getJSLooper(); void notifySerializeCodeCache(); void takeJSHeapSnapshot(String filename); }
WXBridgeManager implements Callback,BactchExecutor { @Deprecated public void fireEvent(final String instanceId, final String ref, final String type, final Map<String, Object> data){ this.fireEvent(instanceId, ref, type, data, null); } private WXBridgeManager(); static WXBridgeManager getInstance(); void stopRemoteDebug(); Object callModuleMethod(String instanceId, String moduleStr, String methodStr, JSONArray args); void restart(); synchronized void setStackTopInstance(final String instanceId); @Override void post(Runnable r); @Override void setInterceptor(Interceptor interceptor); void post(Runnable r, Object token); void sendMessageDelayed(Message message, long delayMillis); void removeMessage(int what,Object obj); Object callNativeModule(String instanceId, String module, String method, JSONArray arguments, Object options); Object callNativeComponent(String instanceId, String componentRef, String method, JSONArray arguments, Object options); int callNative(String instanceId, String tasks, String callback); int callCreateBody(String instanceId, String tasks, String callback); int callUpdateFinish(String instanceId, String callback); int callCreateFinish(String instanceId, String callback); int callRefreshFinish(String instanceId, String callback); int callUpdateAttrs(String instanceId, String ref, String task, String callback); int callUpdateStyle(String instanceId, String ref, String task, String callback); int callRemoveElement(String instanceId, String ref, String callback); int callMoveElement(String instanceId, String ref, String parentref, String index, String callback); int callAddEvent(String instanceId, String ref, String event, String callback); int callRemoveEvent(String instanceId, String ref, String event, String callback); int callAddElement(String instanceId, String ref,String dom,String index, String callback); synchronized void initScriptsFramework(String framework); @Deprecated void fireEvent(final String instanceId, final String ref, final String type, final Map<String, Object> data); @Deprecated void fireEvent(final String instanceId, final String ref, final String type, final Map<String, Object> data,final Map<String, Object> domChanges); void fireEventOnNode(final String instanceId, final String ref, final String type, final Map<String, Object> data,final Map<String, Object> domChanges); @Deprecated void callback(String instanceId, String callback,String data); @Deprecated void callback(final String instanceId, final String callback, final Map<String, Object> data); @Deprecated void callback(final String instanceId, final String callback, final Object data,boolean keepAlive); void refreshInstance(final String instanceId, final WXRefreshData jsonData); void commitJSBridgeAlarmMonitor(String instanceId, WXErrorCode errCode, String errMsg); void commitJSFrameworkAlarmMonitor(final String type, final WXErrorCode errorCode, String errMsg); void createInstance(final String instanceId, final String template, final Map<String, Object> options, final String data); void destroyInstance(final String instanceId); @Override boolean handleMessage(Message msg); void invokeExecJS(String instanceId, String namespace, String function, WXJSObject[] args,boolean logTaskDetail); void registerModules(final Map<String, Object> modules); void registerComponents(final List<Map<String, Object>> components); void execJSService(final String service); void destroy(); void reportJSException(String instanceId, String function, String exception); @Deprecated void notifyTrimMemory(); @Nullable Looper getJSLooper(); void notifySerializeCodeCache(); void takeJSHeapSnapshot(String filename); static final String METHOD_CREATE_INSTANCE; static final String METHOD_DESTROY_INSTANCE; static final String METHOD_CALL_JS; static final String METHOD_SET_TIMEOUT; static final String METHOD_REGISTER_MODULES; static final String METHOD_REGISTER_COMPONENTS; static final String METHOD_FIRE_EVENT; static final String METHOD_CALLBACK; static final String METHOD_REFRESH_INSTANCE; static final String METHOD_NOTIFY_TRIM_MEMORY; static final String METHOD_NOTIFY_SERIALIZE_CODE_CACHE; static final String KEY_METHOD; static final String KEY_ARGS; static final String COMPONENT; static final String REF; static final String MODULE; static final String METHOD; static final String ARGS; }
@Test public void testCallback() throws Exception { getInstance().callbackJavascript(instance.getInstanceId(),"test",null,false); }
@Deprecated public void callback(String instanceId, String callback,String data) { callback(instanceId, callback,data,false); }
WXBridgeManager implements Callback,BactchExecutor { @Deprecated public void callback(String instanceId, String callback,String data) { callback(instanceId, callback,data,false); } }
WXBridgeManager implements Callback,BactchExecutor { @Deprecated public void callback(String instanceId, String callback,String data) { callback(instanceId, callback,data,false); } private WXBridgeManager(); }
WXBridgeManager implements Callback,BactchExecutor { @Deprecated public void callback(String instanceId, String callback,String data) { callback(instanceId, callback,data,false); } private WXBridgeManager(); static WXBridgeManager getInstance(); void stopRemoteDebug(); Object callModuleMethod(String instanceId, String moduleStr, String methodStr, JSONArray args); void restart(); synchronized void setStackTopInstance(final String instanceId); @Override void post(Runnable r); @Override void setInterceptor(Interceptor interceptor); void post(Runnable r, Object token); void sendMessageDelayed(Message message, long delayMillis); void removeMessage(int what,Object obj); Object callNativeModule(String instanceId, String module, String method, JSONArray arguments, Object options); Object callNativeComponent(String instanceId, String componentRef, String method, JSONArray arguments, Object options); int callNative(String instanceId, String tasks, String callback); int callCreateBody(String instanceId, String tasks, String callback); int callUpdateFinish(String instanceId, String callback); int callCreateFinish(String instanceId, String callback); int callRefreshFinish(String instanceId, String callback); int callUpdateAttrs(String instanceId, String ref, String task, String callback); int callUpdateStyle(String instanceId, String ref, String task, String callback); int callRemoveElement(String instanceId, String ref, String callback); int callMoveElement(String instanceId, String ref, String parentref, String index, String callback); int callAddEvent(String instanceId, String ref, String event, String callback); int callRemoveEvent(String instanceId, String ref, String event, String callback); int callAddElement(String instanceId, String ref,String dom,String index, String callback); synchronized void initScriptsFramework(String framework); @Deprecated void fireEvent(final String instanceId, final String ref, final String type, final Map<String, Object> data); @Deprecated void fireEvent(final String instanceId, final String ref, final String type, final Map<String, Object> data,final Map<String, Object> domChanges); void fireEventOnNode(final String instanceId, final String ref, final String type, final Map<String, Object> data,final Map<String, Object> domChanges); @Deprecated void callback(String instanceId, String callback,String data); @Deprecated void callback(final String instanceId, final String callback, final Map<String, Object> data); @Deprecated void callback(final String instanceId, final String callback, final Object data,boolean keepAlive); void refreshInstance(final String instanceId, final WXRefreshData jsonData); void commitJSBridgeAlarmMonitor(String instanceId, WXErrorCode errCode, String errMsg); void commitJSFrameworkAlarmMonitor(final String type, final WXErrorCode errorCode, String errMsg); void createInstance(final String instanceId, final String template, final Map<String, Object> options, final String data); void destroyInstance(final String instanceId); @Override boolean handleMessage(Message msg); void invokeExecJS(String instanceId, String namespace, String function, WXJSObject[] args,boolean logTaskDetail); void registerModules(final Map<String, Object> modules); void registerComponents(final List<Map<String, Object>> components); void execJSService(final String service); void destroy(); void reportJSException(String instanceId, String function, String exception); @Deprecated void notifyTrimMemory(); @Nullable Looper getJSLooper(); void notifySerializeCodeCache(); void takeJSHeapSnapshot(String filename); }
WXBridgeManager implements Callback,BactchExecutor { @Deprecated public void callback(String instanceId, String callback,String data) { callback(instanceId, callback,data,false); } private WXBridgeManager(); static WXBridgeManager getInstance(); void stopRemoteDebug(); Object callModuleMethod(String instanceId, String moduleStr, String methodStr, JSONArray args); void restart(); synchronized void setStackTopInstance(final String instanceId); @Override void post(Runnable r); @Override void setInterceptor(Interceptor interceptor); void post(Runnable r, Object token); void sendMessageDelayed(Message message, long delayMillis); void removeMessage(int what,Object obj); Object callNativeModule(String instanceId, String module, String method, JSONArray arguments, Object options); Object callNativeComponent(String instanceId, String componentRef, String method, JSONArray arguments, Object options); int callNative(String instanceId, String tasks, String callback); int callCreateBody(String instanceId, String tasks, String callback); int callUpdateFinish(String instanceId, String callback); int callCreateFinish(String instanceId, String callback); int callRefreshFinish(String instanceId, String callback); int callUpdateAttrs(String instanceId, String ref, String task, String callback); int callUpdateStyle(String instanceId, String ref, String task, String callback); int callRemoveElement(String instanceId, String ref, String callback); int callMoveElement(String instanceId, String ref, String parentref, String index, String callback); int callAddEvent(String instanceId, String ref, String event, String callback); int callRemoveEvent(String instanceId, String ref, String event, String callback); int callAddElement(String instanceId, String ref,String dom,String index, String callback); synchronized void initScriptsFramework(String framework); @Deprecated void fireEvent(final String instanceId, final String ref, final String type, final Map<String, Object> data); @Deprecated void fireEvent(final String instanceId, final String ref, final String type, final Map<String, Object> data,final Map<String, Object> domChanges); void fireEventOnNode(final String instanceId, final String ref, final String type, final Map<String, Object> data,final Map<String, Object> domChanges); @Deprecated void callback(String instanceId, String callback,String data); @Deprecated void callback(final String instanceId, final String callback, final Map<String, Object> data); @Deprecated void callback(final String instanceId, final String callback, final Object data,boolean keepAlive); void refreshInstance(final String instanceId, final WXRefreshData jsonData); void commitJSBridgeAlarmMonitor(String instanceId, WXErrorCode errCode, String errMsg); void commitJSFrameworkAlarmMonitor(final String type, final WXErrorCode errorCode, String errMsg); void createInstance(final String instanceId, final String template, final Map<String, Object> options, final String data); void destroyInstance(final String instanceId); @Override boolean handleMessage(Message msg); void invokeExecJS(String instanceId, String namespace, String function, WXJSObject[] args,boolean logTaskDetail); void registerModules(final Map<String, Object> modules); void registerComponents(final List<Map<String, Object>> components); void execJSService(final String service); void destroy(); void reportJSException(String instanceId, String function, String exception); @Deprecated void notifyTrimMemory(); @Nullable Looper getJSLooper(); void notifySerializeCodeCache(); void takeJSHeapSnapshot(String filename); static final String METHOD_CREATE_INSTANCE; static final String METHOD_DESTROY_INSTANCE; static final String METHOD_CALL_JS; static final String METHOD_SET_TIMEOUT; static final String METHOD_REGISTER_MODULES; static final String METHOD_REGISTER_COMPONENTS; static final String METHOD_FIRE_EVENT; static final String METHOD_CALLBACK; static final String METHOD_REFRESH_INSTANCE; static final String METHOD_NOTIFY_TRIM_MEMORY; static final String METHOD_NOTIFY_SERIALIZE_CODE_CACHE; static final String KEY_METHOD; static final String KEY_ARGS; static final String COMPONENT; static final String REF; static final String MODULE; static final String METHOD; static final String ARGS; }
@Test public void testRefreshInstance() throws Exception { getInstance().refreshInstance(instance.getInstanceId(),null); }
public void refreshInstance(final String instanceId, final WXRefreshData jsonData) { if (TextUtils.isEmpty(instanceId) || jsonData == null) { return; } mJSHandler.postDelayed(WXThread.secure(new Runnable() { @Override public void run() { invokeRefreshInstance(instanceId, jsonData); } }), 0); }
WXBridgeManager implements Callback,BactchExecutor { public void refreshInstance(final String instanceId, final WXRefreshData jsonData) { if (TextUtils.isEmpty(instanceId) || jsonData == null) { return; } mJSHandler.postDelayed(WXThread.secure(new Runnable() { @Override public void run() { invokeRefreshInstance(instanceId, jsonData); } }), 0); } }
WXBridgeManager implements Callback,BactchExecutor { public void refreshInstance(final String instanceId, final WXRefreshData jsonData) { if (TextUtils.isEmpty(instanceId) || jsonData == null) { return; } mJSHandler.postDelayed(WXThread.secure(new Runnable() { @Override public void run() { invokeRefreshInstance(instanceId, jsonData); } }), 0); } private WXBridgeManager(); }
WXBridgeManager implements Callback,BactchExecutor { public void refreshInstance(final String instanceId, final WXRefreshData jsonData) { if (TextUtils.isEmpty(instanceId) || jsonData == null) { return; } mJSHandler.postDelayed(WXThread.secure(new Runnable() { @Override public void run() { invokeRefreshInstance(instanceId, jsonData); } }), 0); } private WXBridgeManager(); static WXBridgeManager getInstance(); void stopRemoteDebug(); Object callModuleMethod(String instanceId, String moduleStr, String methodStr, JSONArray args); void restart(); synchronized void setStackTopInstance(final String instanceId); @Override void post(Runnable r); @Override void setInterceptor(Interceptor interceptor); void post(Runnable r, Object token); void sendMessageDelayed(Message message, long delayMillis); void removeMessage(int what,Object obj); Object callNativeModule(String instanceId, String module, String method, JSONArray arguments, Object options); Object callNativeComponent(String instanceId, String componentRef, String method, JSONArray arguments, Object options); int callNative(String instanceId, String tasks, String callback); int callCreateBody(String instanceId, String tasks, String callback); int callUpdateFinish(String instanceId, String callback); int callCreateFinish(String instanceId, String callback); int callRefreshFinish(String instanceId, String callback); int callUpdateAttrs(String instanceId, String ref, String task, String callback); int callUpdateStyle(String instanceId, String ref, String task, String callback); int callRemoveElement(String instanceId, String ref, String callback); int callMoveElement(String instanceId, String ref, String parentref, String index, String callback); int callAddEvent(String instanceId, String ref, String event, String callback); int callRemoveEvent(String instanceId, String ref, String event, String callback); int callAddElement(String instanceId, String ref,String dom,String index, String callback); synchronized void initScriptsFramework(String framework); @Deprecated void fireEvent(final String instanceId, final String ref, final String type, final Map<String, Object> data); @Deprecated void fireEvent(final String instanceId, final String ref, final String type, final Map<String, Object> data,final Map<String, Object> domChanges); void fireEventOnNode(final String instanceId, final String ref, final String type, final Map<String, Object> data,final Map<String, Object> domChanges); @Deprecated void callback(String instanceId, String callback,String data); @Deprecated void callback(final String instanceId, final String callback, final Map<String, Object> data); @Deprecated void callback(final String instanceId, final String callback, final Object data,boolean keepAlive); void refreshInstance(final String instanceId, final WXRefreshData jsonData); void commitJSBridgeAlarmMonitor(String instanceId, WXErrorCode errCode, String errMsg); void commitJSFrameworkAlarmMonitor(final String type, final WXErrorCode errorCode, String errMsg); void createInstance(final String instanceId, final String template, final Map<String, Object> options, final String data); void destroyInstance(final String instanceId); @Override boolean handleMessage(Message msg); void invokeExecJS(String instanceId, String namespace, String function, WXJSObject[] args,boolean logTaskDetail); void registerModules(final Map<String, Object> modules); void registerComponents(final List<Map<String, Object>> components); void execJSService(final String service); void destroy(); void reportJSException(String instanceId, String function, String exception); @Deprecated void notifyTrimMemory(); @Nullable Looper getJSLooper(); void notifySerializeCodeCache(); void takeJSHeapSnapshot(String filename); }
WXBridgeManager implements Callback,BactchExecutor { public void refreshInstance(final String instanceId, final WXRefreshData jsonData) { if (TextUtils.isEmpty(instanceId) || jsonData == null) { return; } mJSHandler.postDelayed(WXThread.secure(new Runnable() { @Override public void run() { invokeRefreshInstance(instanceId, jsonData); } }), 0); } private WXBridgeManager(); static WXBridgeManager getInstance(); void stopRemoteDebug(); Object callModuleMethod(String instanceId, String moduleStr, String methodStr, JSONArray args); void restart(); synchronized void setStackTopInstance(final String instanceId); @Override void post(Runnable r); @Override void setInterceptor(Interceptor interceptor); void post(Runnable r, Object token); void sendMessageDelayed(Message message, long delayMillis); void removeMessage(int what,Object obj); Object callNativeModule(String instanceId, String module, String method, JSONArray arguments, Object options); Object callNativeComponent(String instanceId, String componentRef, String method, JSONArray arguments, Object options); int callNative(String instanceId, String tasks, String callback); int callCreateBody(String instanceId, String tasks, String callback); int callUpdateFinish(String instanceId, String callback); int callCreateFinish(String instanceId, String callback); int callRefreshFinish(String instanceId, String callback); int callUpdateAttrs(String instanceId, String ref, String task, String callback); int callUpdateStyle(String instanceId, String ref, String task, String callback); int callRemoveElement(String instanceId, String ref, String callback); int callMoveElement(String instanceId, String ref, String parentref, String index, String callback); int callAddEvent(String instanceId, String ref, String event, String callback); int callRemoveEvent(String instanceId, String ref, String event, String callback); int callAddElement(String instanceId, String ref,String dom,String index, String callback); synchronized void initScriptsFramework(String framework); @Deprecated void fireEvent(final String instanceId, final String ref, final String type, final Map<String, Object> data); @Deprecated void fireEvent(final String instanceId, final String ref, final String type, final Map<String, Object> data,final Map<String, Object> domChanges); void fireEventOnNode(final String instanceId, final String ref, final String type, final Map<String, Object> data,final Map<String, Object> domChanges); @Deprecated void callback(String instanceId, String callback,String data); @Deprecated void callback(final String instanceId, final String callback, final Map<String, Object> data); @Deprecated void callback(final String instanceId, final String callback, final Object data,boolean keepAlive); void refreshInstance(final String instanceId, final WXRefreshData jsonData); void commitJSBridgeAlarmMonitor(String instanceId, WXErrorCode errCode, String errMsg); void commitJSFrameworkAlarmMonitor(final String type, final WXErrorCode errorCode, String errMsg); void createInstance(final String instanceId, final String template, final Map<String, Object> options, final String data); void destroyInstance(final String instanceId); @Override boolean handleMessage(Message msg); void invokeExecJS(String instanceId, String namespace, String function, WXJSObject[] args,boolean logTaskDetail); void registerModules(final Map<String, Object> modules); void registerComponents(final List<Map<String, Object>> components); void execJSService(final String service); void destroy(); void reportJSException(String instanceId, String function, String exception); @Deprecated void notifyTrimMemory(); @Nullable Looper getJSLooper(); void notifySerializeCodeCache(); void takeJSHeapSnapshot(String filename); static final String METHOD_CREATE_INSTANCE; static final String METHOD_DESTROY_INSTANCE; static final String METHOD_CALL_JS; static final String METHOD_SET_TIMEOUT; static final String METHOD_REGISTER_MODULES; static final String METHOD_REGISTER_COMPONENTS; static final String METHOD_FIRE_EVENT; static final String METHOD_CALLBACK; static final String METHOD_REFRESH_INSTANCE; static final String METHOD_NOTIFY_TRIM_MEMORY; static final String METHOD_NOTIFY_SERIALIZE_CODE_CACHE; static final String KEY_METHOD; static final String KEY_ARGS; static final String COMPONENT; static final String REF; static final String MODULE; static final String METHOD; static final String ARGS; }
@Test public void testCreateInstance() throws Exception { getInstance().createInstance(instance.getInstanceId(),"",null,null); }
public void createInstance(final String instanceId, final String template, final Map<String, Object> options, final String data) { final WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId); if(instance == null){ WXLogUtils.e("WXBridgeManager","createInstance failed, SDKInstance is not exist"); return; } if ( TextUtils.isEmpty(instanceId) || TextUtils.isEmpty(template) || mJSHandler == null) { instance.onRenderError(WXRenderErrorCode.WX_CREATE_INSTANCE_ERROR, "createInstance fail!"); return; } WXModuleManager.createDomModule(instance); post(new Runnable() { @Override public void run() { long start = System.currentTimeMillis(); invokeCreateInstance(instance, template, options, data); final long totalTime = System.currentTimeMillis() - start; WXSDKManager.getInstance().postOnUiThread(new Runnable() { @Override public void run() { instance.createInstanceFinished(totalTime); } }, 0); } }, instanceId); }
WXBridgeManager implements Callback,BactchExecutor { public void createInstance(final String instanceId, final String template, final Map<String, Object> options, final String data) { final WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId); if(instance == null){ WXLogUtils.e("WXBridgeManager","createInstance failed, SDKInstance is not exist"); return; } if ( TextUtils.isEmpty(instanceId) || TextUtils.isEmpty(template) || mJSHandler == null) { instance.onRenderError(WXRenderErrorCode.WX_CREATE_INSTANCE_ERROR, "createInstance fail!"); return; } WXModuleManager.createDomModule(instance); post(new Runnable() { @Override public void run() { long start = System.currentTimeMillis(); invokeCreateInstance(instance, template, options, data); final long totalTime = System.currentTimeMillis() - start; WXSDKManager.getInstance().postOnUiThread(new Runnable() { @Override public void run() { instance.createInstanceFinished(totalTime); } }, 0); } }, instanceId); } }
WXBridgeManager implements Callback,BactchExecutor { public void createInstance(final String instanceId, final String template, final Map<String, Object> options, final String data) { final WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId); if(instance == null){ WXLogUtils.e("WXBridgeManager","createInstance failed, SDKInstance is not exist"); return; } if ( TextUtils.isEmpty(instanceId) || TextUtils.isEmpty(template) || mJSHandler == null) { instance.onRenderError(WXRenderErrorCode.WX_CREATE_INSTANCE_ERROR, "createInstance fail!"); return; } WXModuleManager.createDomModule(instance); post(new Runnable() { @Override public void run() { long start = System.currentTimeMillis(); invokeCreateInstance(instance, template, options, data); final long totalTime = System.currentTimeMillis() - start; WXSDKManager.getInstance().postOnUiThread(new Runnable() { @Override public void run() { instance.createInstanceFinished(totalTime); } }, 0); } }, instanceId); } private WXBridgeManager(); }
WXBridgeManager implements Callback,BactchExecutor { public void createInstance(final String instanceId, final String template, final Map<String, Object> options, final String data) { final WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId); if(instance == null){ WXLogUtils.e("WXBridgeManager","createInstance failed, SDKInstance is not exist"); return; } if ( TextUtils.isEmpty(instanceId) || TextUtils.isEmpty(template) || mJSHandler == null) { instance.onRenderError(WXRenderErrorCode.WX_CREATE_INSTANCE_ERROR, "createInstance fail!"); return; } WXModuleManager.createDomModule(instance); post(new Runnable() { @Override public void run() { long start = System.currentTimeMillis(); invokeCreateInstance(instance, template, options, data); final long totalTime = System.currentTimeMillis() - start; WXSDKManager.getInstance().postOnUiThread(new Runnable() { @Override public void run() { instance.createInstanceFinished(totalTime); } }, 0); } }, instanceId); } private WXBridgeManager(); static WXBridgeManager getInstance(); void stopRemoteDebug(); Object callModuleMethod(String instanceId, String moduleStr, String methodStr, JSONArray args); void restart(); synchronized void setStackTopInstance(final String instanceId); @Override void post(Runnable r); @Override void setInterceptor(Interceptor interceptor); void post(Runnable r, Object token); void sendMessageDelayed(Message message, long delayMillis); void removeMessage(int what,Object obj); Object callNativeModule(String instanceId, String module, String method, JSONArray arguments, Object options); Object callNativeComponent(String instanceId, String componentRef, String method, JSONArray arguments, Object options); int callNative(String instanceId, String tasks, String callback); int callCreateBody(String instanceId, String tasks, String callback); int callUpdateFinish(String instanceId, String callback); int callCreateFinish(String instanceId, String callback); int callRefreshFinish(String instanceId, String callback); int callUpdateAttrs(String instanceId, String ref, String task, String callback); int callUpdateStyle(String instanceId, String ref, String task, String callback); int callRemoveElement(String instanceId, String ref, String callback); int callMoveElement(String instanceId, String ref, String parentref, String index, String callback); int callAddEvent(String instanceId, String ref, String event, String callback); int callRemoveEvent(String instanceId, String ref, String event, String callback); int callAddElement(String instanceId, String ref,String dom,String index, String callback); synchronized void initScriptsFramework(String framework); @Deprecated void fireEvent(final String instanceId, final String ref, final String type, final Map<String, Object> data); @Deprecated void fireEvent(final String instanceId, final String ref, final String type, final Map<String, Object> data,final Map<String, Object> domChanges); void fireEventOnNode(final String instanceId, final String ref, final String type, final Map<String, Object> data,final Map<String, Object> domChanges); @Deprecated void callback(String instanceId, String callback,String data); @Deprecated void callback(final String instanceId, final String callback, final Map<String, Object> data); @Deprecated void callback(final String instanceId, final String callback, final Object data,boolean keepAlive); void refreshInstance(final String instanceId, final WXRefreshData jsonData); void commitJSBridgeAlarmMonitor(String instanceId, WXErrorCode errCode, String errMsg); void commitJSFrameworkAlarmMonitor(final String type, final WXErrorCode errorCode, String errMsg); void createInstance(final String instanceId, final String template, final Map<String, Object> options, final String data); void destroyInstance(final String instanceId); @Override boolean handleMessage(Message msg); void invokeExecJS(String instanceId, String namespace, String function, WXJSObject[] args,boolean logTaskDetail); void registerModules(final Map<String, Object> modules); void registerComponents(final List<Map<String, Object>> components); void execJSService(final String service); void destroy(); void reportJSException(String instanceId, String function, String exception); @Deprecated void notifyTrimMemory(); @Nullable Looper getJSLooper(); void notifySerializeCodeCache(); void takeJSHeapSnapshot(String filename); }
WXBridgeManager implements Callback,BactchExecutor { public void createInstance(final String instanceId, final String template, final Map<String, Object> options, final String data) { final WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId); if(instance == null){ WXLogUtils.e("WXBridgeManager","createInstance failed, SDKInstance is not exist"); return; } if ( TextUtils.isEmpty(instanceId) || TextUtils.isEmpty(template) || mJSHandler == null) { instance.onRenderError(WXRenderErrorCode.WX_CREATE_INSTANCE_ERROR, "createInstance fail!"); return; } WXModuleManager.createDomModule(instance); post(new Runnable() { @Override public void run() { long start = System.currentTimeMillis(); invokeCreateInstance(instance, template, options, data); final long totalTime = System.currentTimeMillis() - start; WXSDKManager.getInstance().postOnUiThread(new Runnable() { @Override public void run() { instance.createInstanceFinished(totalTime); } }, 0); } }, instanceId); } private WXBridgeManager(); static WXBridgeManager getInstance(); void stopRemoteDebug(); Object callModuleMethod(String instanceId, String moduleStr, String methodStr, JSONArray args); void restart(); synchronized void setStackTopInstance(final String instanceId); @Override void post(Runnable r); @Override void setInterceptor(Interceptor interceptor); void post(Runnable r, Object token); void sendMessageDelayed(Message message, long delayMillis); void removeMessage(int what,Object obj); Object callNativeModule(String instanceId, String module, String method, JSONArray arguments, Object options); Object callNativeComponent(String instanceId, String componentRef, String method, JSONArray arguments, Object options); int callNative(String instanceId, String tasks, String callback); int callCreateBody(String instanceId, String tasks, String callback); int callUpdateFinish(String instanceId, String callback); int callCreateFinish(String instanceId, String callback); int callRefreshFinish(String instanceId, String callback); int callUpdateAttrs(String instanceId, String ref, String task, String callback); int callUpdateStyle(String instanceId, String ref, String task, String callback); int callRemoveElement(String instanceId, String ref, String callback); int callMoveElement(String instanceId, String ref, String parentref, String index, String callback); int callAddEvent(String instanceId, String ref, String event, String callback); int callRemoveEvent(String instanceId, String ref, String event, String callback); int callAddElement(String instanceId, String ref,String dom,String index, String callback); synchronized void initScriptsFramework(String framework); @Deprecated void fireEvent(final String instanceId, final String ref, final String type, final Map<String, Object> data); @Deprecated void fireEvent(final String instanceId, final String ref, final String type, final Map<String, Object> data,final Map<String, Object> domChanges); void fireEventOnNode(final String instanceId, final String ref, final String type, final Map<String, Object> data,final Map<String, Object> domChanges); @Deprecated void callback(String instanceId, String callback,String data); @Deprecated void callback(final String instanceId, final String callback, final Map<String, Object> data); @Deprecated void callback(final String instanceId, final String callback, final Object data,boolean keepAlive); void refreshInstance(final String instanceId, final WXRefreshData jsonData); void commitJSBridgeAlarmMonitor(String instanceId, WXErrorCode errCode, String errMsg); void commitJSFrameworkAlarmMonitor(final String type, final WXErrorCode errorCode, String errMsg); void createInstance(final String instanceId, final String template, final Map<String, Object> options, final String data); void destroyInstance(final String instanceId); @Override boolean handleMessage(Message msg); void invokeExecJS(String instanceId, String namespace, String function, WXJSObject[] args,boolean logTaskDetail); void registerModules(final Map<String, Object> modules); void registerComponents(final List<Map<String, Object>> components); void execJSService(final String service); void destroy(); void reportJSException(String instanceId, String function, String exception); @Deprecated void notifyTrimMemory(); @Nullable Looper getJSLooper(); void notifySerializeCodeCache(); void takeJSHeapSnapshot(String filename); static final String METHOD_CREATE_INSTANCE; static final String METHOD_DESTROY_INSTANCE; static final String METHOD_CALL_JS; static final String METHOD_SET_TIMEOUT; static final String METHOD_REGISTER_MODULES; static final String METHOD_REGISTER_COMPONENTS; static final String METHOD_FIRE_EVENT; static final String METHOD_CALLBACK; static final String METHOD_REFRESH_INSTANCE; static final String METHOD_NOTIFY_TRIM_MEMORY; static final String METHOD_NOTIFY_SERIALIZE_CODE_CACHE; static final String KEY_METHOD; static final String KEY_ARGS; static final String COMPONENT; static final String REF; static final String MODULE; static final String METHOD; static final String ARGS; }
@Test public void testDestroyInstance() throws Exception { getInstance().destroyInstance(instance.getInstanceId()); }
public void destroyInstance(final String instanceId) { if ( mJSHandler == null || TextUtils.isEmpty(instanceId)) { return; } if(mDestroyedInstanceId!=null) { mDestroyedInstanceId.add(instanceId); } mJSHandler.removeCallbacksAndMessages(instanceId); post(new Runnable() { @Override public void run() { removeTaskByInstance(instanceId); invokeDestroyInstance(instanceId); } }, instanceId); }
WXBridgeManager implements Callback,BactchExecutor { public void destroyInstance(final String instanceId) { if ( mJSHandler == null || TextUtils.isEmpty(instanceId)) { return; } if(mDestroyedInstanceId!=null) { mDestroyedInstanceId.add(instanceId); } mJSHandler.removeCallbacksAndMessages(instanceId); post(new Runnable() { @Override public void run() { removeTaskByInstance(instanceId); invokeDestroyInstance(instanceId); } }, instanceId); } }
WXBridgeManager implements Callback,BactchExecutor { public void destroyInstance(final String instanceId) { if ( mJSHandler == null || TextUtils.isEmpty(instanceId)) { return; } if(mDestroyedInstanceId!=null) { mDestroyedInstanceId.add(instanceId); } mJSHandler.removeCallbacksAndMessages(instanceId); post(new Runnable() { @Override public void run() { removeTaskByInstance(instanceId); invokeDestroyInstance(instanceId); } }, instanceId); } private WXBridgeManager(); }
WXBridgeManager implements Callback,BactchExecutor { public void destroyInstance(final String instanceId) { if ( mJSHandler == null || TextUtils.isEmpty(instanceId)) { return; } if(mDestroyedInstanceId!=null) { mDestroyedInstanceId.add(instanceId); } mJSHandler.removeCallbacksAndMessages(instanceId); post(new Runnable() { @Override public void run() { removeTaskByInstance(instanceId); invokeDestroyInstance(instanceId); } }, instanceId); } private WXBridgeManager(); static WXBridgeManager getInstance(); void stopRemoteDebug(); Object callModuleMethod(String instanceId, String moduleStr, String methodStr, JSONArray args); void restart(); synchronized void setStackTopInstance(final String instanceId); @Override void post(Runnable r); @Override void setInterceptor(Interceptor interceptor); void post(Runnable r, Object token); void sendMessageDelayed(Message message, long delayMillis); void removeMessage(int what,Object obj); Object callNativeModule(String instanceId, String module, String method, JSONArray arguments, Object options); Object callNativeComponent(String instanceId, String componentRef, String method, JSONArray arguments, Object options); int callNative(String instanceId, String tasks, String callback); int callCreateBody(String instanceId, String tasks, String callback); int callUpdateFinish(String instanceId, String callback); int callCreateFinish(String instanceId, String callback); int callRefreshFinish(String instanceId, String callback); int callUpdateAttrs(String instanceId, String ref, String task, String callback); int callUpdateStyle(String instanceId, String ref, String task, String callback); int callRemoveElement(String instanceId, String ref, String callback); int callMoveElement(String instanceId, String ref, String parentref, String index, String callback); int callAddEvent(String instanceId, String ref, String event, String callback); int callRemoveEvent(String instanceId, String ref, String event, String callback); int callAddElement(String instanceId, String ref,String dom,String index, String callback); synchronized void initScriptsFramework(String framework); @Deprecated void fireEvent(final String instanceId, final String ref, final String type, final Map<String, Object> data); @Deprecated void fireEvent(final String instanceId, final String ref, final String type, final Map<String, Object> data,final Map<String, Object> domChanges); void fireEventOnNode(final String instanceId, final String ref, final String type, final Map<String, Object> data,final Map<String, Object> domChanges); @Deprecated void callback(String instanceId, String callback,String data); @Deprecated void callback(final String instanceId, final String callback, final Map<String, Object> data); @Deprecated void callback(final String instanceId, final String callback, final Object data,boolean keepAlive); void refreshInstance(final String instanceId, final WXRefreshData jsonData); void commitJSBridgeAlarmMonitor(String instanceId, WXErrorCode errCode, String errMsg); void commitJSFrameworkAlarmMonitor(final String type, final WXErrorCode errorCode, String errMsg); void createInstance(final String instanceId, final String template, final Map<String, Object> options, final String data); void destroyInstance(final String instanceId); @Override boolean handleMessage(Message msg); void invokeExecJS(String instanceId, String namespace, String function, WXJSObject[] args,boolean logTaskDetail); void registerModules(final Map<String, Object> modules); void registerComponents(final List<Map<String, Object>> components); void execJSService(final String service); void destroy(); void reportJSException(String instanceId, String function, String exception); @Deprecated void notifyTrimMemory(); @Nullable Looper getJSLooper(); void notifySerializeCodeCache(); void takeJSHeapSnapshot(String filename); }
WXBridgeManager implements Callback,BactchExecutor { public void destroyInstance(final String instanceId) { if ( mJSHandler == null || TextUtils.isEmpty(instanceId)) { return; } if(mDestroyedInstanceId!=null) { mDestroyedInstanceId.add(instanceId); } mJSHandler.removeCallbacksAndMessages(instanceId); post(new Runnable() { @Override public void run() { removeTaskByInstance(instanceId); invokeDestroyInstance(instanceId); } }, instanceId); } private WXBridgeManager(); static WXBridgeManager getInstance(); void stopRemoteDebug(); Object callModuleMethod(String instanceId, String moduleStr, String methodStr, JSONArray args); void restart(); synchronized void setStackTopInstance(final String instanceId); @Override void post(Runnable r); @Override void setInterceptor(Interceptor interceptor); void post(Runnable r, Object token); void sendMessageDelayed(Message message, long delayMillis); void removeMessage(int what,Object obj); Object callNativeModule(String instanceId, String module, String method, JSONArray arguments, Object options); Object callNativeComponent(String instanceId, String componentRef, String method, JSONArray arguments, Object options); int callNative(String instanceId, String tasks, String callback); int callCreateBody(String instanceId, String tasks, String callback); int callUpdateFinish(String instanceId, String callback); int callCreateFinish(String instanceId, String callback); int callRefreshFinish(String instanceId, String callback); int callUpdateAttrs(String instanceId, String ref, String task, String callback); int callUpdateStyle(String instanceId, String ref, String task, String callback); int callRemoveElement(String instanceId, String ref, String callback); int callMoveElement(String instanceId, String ref, String parentref, String index, String callback); int callAddEvent(String instanceId, String ref, String event, String callback); int callRemoveEvent(String instanceId, String ref, String event, String callback); int callAddElement(String instanceId, String ref,String dom,String index, String callback); synchronized void initScriptsFramework(String framework); @Deprecated void fireEvent(final String instanceId, final String ref, final String type, final Map<String, Object> data); @Deprecated void fireEvent(final String instanceId, final String ref, final String type, final Map<String, Object> data,final Map<String, Object> domChanges); void fireEventOnNode(final String instanceId, final String ref, final String type, final Map<String, Object> data,final Map<String, Object> domChanges); @Deprecated void callback(String instanceId, String callback,String data); @Deprecated void callback(final String instanceId, final String callback, final Map<String, Object> data); @Deprecated void callback(final String instanceId, final String callback, final Object data,boolean keepAlive); void refreshInstance(final String instanceId, final WXRefreshData jsonData); void commitJSBridgeAlarmMonitor(String instanceId, WXErrorCode errCode, String errMsg); void commitJSFrameworkAlarmMonitor(final String type, final WXErrorCode errorCode, String errMsg); void createInstance(final String instanceId, final String template, final Map<String, Object> options, final String data); void destroyInstance(final String instanceId); @Override boolean handleMessage(Message msg); void invokeExecJS(String instanceId, String namespace, String function, WXJSObject[] args,boolean logTaskDetail); void registerModules(final Map<String, Object> modules); void registerComponents(final List<Map<String, Object>> components); void execJSService(final String service); void destroy(); void reportJSException(String instanceId, String function, String exception); @Deprecated void notifyTrimMemory(); @Nullable Looper getJSLooper(); void notifySerializeCodeCache(); void takeJSHeapSnapshot(String filename); static final String METHOD_CREATE_INSTANCE; static final String METHOD_DESTROY_INSTANCE; static final String METHOD_CALL_JS; static final String METHOD_SET_TIMEOUT; static final String METHOD_REGISTER_MODULES; static final String METHOD_REGISTER_COMPONENTS; static final String METHOD_FIRE_EVENT; static final String METHOD_CALLBACK; static final String METHOD_REFRESH_INSTANCE; static final String METHOD_NOTIFY_TRIM_MEMORY; static final String METHOD_NOTIFY_SERIALIZE_CODE_CACHE; static final String KEY_METHOD; static final String KEY_ARGS; static final String COMPONENT; static final String REF; static final String MODULE; static final String METHOD; static final String ARGS; }
@Test public void testHandleMessage() throws Exception { int[] msgs = { WXJSBridgeMsgType.INIT_FRAMEWORK, WXJSBridgeMsgType.CALL_JS_BATCH, WXJSBridgeMsgType.SET_TIMEOUT, WXJSBridgeMsgType.MODULE_INTERVAL, WXJSBridgeMsgType.MODULE_TIMEOUT }; Message msg = new Message(); for(int w:msgs) { msg.what = w; getInstance().handleMessage(msg); } }
@Override public boolean handleMessage(Message msg) { if (msg == null) { return false; } int what = msg.what; switch (what) { case WXJSBridgeMsgType.INIT_FRAMEWORK: invokeInitFramework(msg); break; case WXJSBridgeMsgType.CALL_JS_BATCH: invokeCallJSBatch(msg); break; case WXJSBridgeMsgType.SET_TIMEOUT: TimerInfo timerInfo = (TimerInfo) msg.obj; if(timerInfo == null){ break; } WXJSObject obj = new WXJSObject(WXJSObject.String, timerInfo.callbackId); WXJSObject[] args = {obj}; invokeExecJS("", null, METHOD_SET_TIMEOUT, args); break; case WXJSBridgeMsgType.TAKE_HEAP_SNAPSHOT: if (msg.obj != null) { String filename = (String) msg.obj; mWXBridge.takeHeapSnapshot(filename); } break; default: break; } return false; }
WXBridgeManager implements Callback,BactchExecutor { @Override public boolean handleMessage(Message msg) { if (msg == null) { return false; } int what = msg.what; switch (what) { case WXJSBridgeMsgType.INIT_FRAMEWORK: invokeInitFramework(msg); break; case WXJSBridgeMsgType.CALL_JS_BATCH: invokeCallJSBatch(msg); break; case WXJSBridgeMsgType.SET_TIMEOUT: TimerInfo timerInfo = (TimerInfo) msg.obj; if(timerInfo == null){ break; } WXJSObject obj = new WXJSObject(WXJSObject.String, timerInfo.callbackId); WXJSObject[] args = {obj}; invokeExecJS("", null, METHOD_SET_TIMEOUT, args); break; case WXJSBridgeMsgType.TAKE_HEAP_SNAPSHOT: if (msg.obj != null) { String filename = (String) msg.obj; mWXBridge.takeHeapSnapshot(filename); } break; default: break; } return false; } }
WXBridgeManager implements Callback,BactchExecutor { @Override public boolean handleMessage(Message msg) { if (msg == null) { return false; } int what = msg.what; switch (what) { case WXJSBridgeMsgType.INIT_FRAMEWORK: invokeInitFramework(msg); break; case WXJSBridgeMsgType.CALL_JS_BATCH: invokeCallJSBatch(msg); break; case WXJSBridgeMsgType.SET_TIMEOUT: TimerInfo timerInfo = (TimerInfo) msg.obj; if(timerInfo == null){ break; } WXJSObject obj = new WXJSObject(WXJSObject.String, timerInfo.callbackId); WXJSObject[] args = {obj}; invokeExecJS("", null, METHOD_SET_TIMEOUT, args); break; case WXJSBridgeMsgType.TAKE_HEAP_SNAPSHOT: if (msg.obj != null) { String filename = (String) msg.obj; mWXBridge.takeHeapSnapshot(filename); } break; default: break; } return false; } private WXBridgeManager(); }
WXBridgeManager implements Callback,BactchExecutor { @Override public boolean handleMessage(Message msg) { if (msg == null) { return false; } int what = msg.what; switch (what) { case WXJSBridgeMsgType.INIT_FRAMEWORK: invokeInitFramework(msg); break; case WXJSBridgeMsgType.CALL_JS_BATCH: invokeCallJSBatch(msg); break; case WXJSBridgeMsgType.SET_TIMEOUT: TimerInfo timerInfo = (TimerInfo) msg.obj; if(timerInfo == null){ break; } WXJSObject obj = new WXJSObject(WXJSObject.String, timerInfo.callbackId); WXJSObject[] args = {obj}; invokeExecJS("", null, METHOD_SET_TIMEOUT, args); break; case WXJSBridgeMsgType.TAKE_HEAP_SNAPSHOT: if (msg.obj != null) { String filename = (String) msg.obj; mWXBridge.takeHeapSnapshot(filename); } break; default: break; } return false; } private WXBridgeManager(); static WXBridgeManager getInstance(); void stopRemoteDebug(); Object callModuleMethod(String instanceId, String moduleStr, String methodStr, JSONArray args); void restart(); synchronized void setStackTopInstance(final String instanceId); @Override void post(Runnable r); @Override void setInterceptor(Interceptor interceptor); void post(Runnable r, Object token); void sendMessageDelayed(Message message, long delayMillis); void removeMessage(int what,Object obj); Object callNativeModule(String instanceId, String module, String method, JSONArray arguments, Object options); Object callNativeComponent(String instanceId, String componentRef, String method, JSONArray arguments, Object options); int callNative(String instanceId, String tasks, String callback); int callCreateBody(String instanceId, String tasks, String callback); int callUpdateFinish(String instanceId, String callback); int callCreateFinish(String instanceId, String callback); int callRefreshFinish(String instanceId, String callback); int callUpdateAttrs(String instanceId, String ref, String task, String callback); int callUpdateStyle(String instanceId, String ref, String task, String callback); int callRemoveElement(String instanceId, String ref, String callback); int callMoveElement(String instanceId, String ref, String parentref, String index, String callback); int callAddEvent(String instanceId, String ref, String event, String callback); int callRemoveEvent(String instanceId, String ref, String event, String callback); int callAddElement(String instanceId, String ref,String dom,String index, String callback); synchronized void initScriptsFramework(String framework); @Deprecated void fireEvent(final String instanceId, final String ref, final String type, final Map<String, Object> data); @Deprecated void fireEvent(final String instanceId, final String ref, final String type, final Map<String, Object> data,final Map<String, Object> domChanges); void fireEventOnNode(final String instanceId, final String ref, final String type, final Map<String, Object> data,final Map<String, Object> domChanges); @Deprecated void callback(String instanceId, String callback,String data); @Deprecated void callback(final String instanceId, final String callback, final Map<String, Object> data); @Deprecated void callback(final String instanceId, final String callback, final Object data,boolean keepAlive); void refreshInstance(final String instanceId, final WXRefreshData jsonData); void commitJSBridgeAlarmMonitor(String instanceId, WXErrorCode errCode, String errMsg); void commitJSFrameworkAlarmMonitor(final String type, final WXErrorCode errorCode, String errMsg); void createInstance(final String instanceId, final String template, final Map<String, Object> options, final String data); void destroyInstance(final String instanceId); @Override boolean handleMessage(Message msg); void invokeExecJS(String instanceId, String namespace, String function, WXJSObject[] args,boolean logTaskDetail); void registerModules(final Map<String, Object> modules); void registerComponents(final List<Map<String, Object>> components); void execJSService(final String service); void destroy(); void reportJSException(String instanceId, String function, String exception); @Deprecated void notifyTrimMemory(); @Nullable Looper getJSLooper(); void notifySerializeCodeCache(); void takeJSHeapSnapshot(String filename); }
WXBridgeManager implements Callback,BactchExecutor { @Override public boolean handleMessage(Message msg) { if (msg == null) { return false; } int what = msg.what; switch (what) { case WXJSBridgeMsgType.INIT_FRAMEWORK: invokeInitFramework(msg); break; case WXJSBridgeMsgType.CALL_JS_BATCH: invokeCallJSBatch(msg); break; case WXJSBridgeMsgType.SET_TIMEOUT: TimerInfo timerInfo = (TimerInfo) msg.obj; if(timerInfo == null){ break; } WXJSObject obj = new WXJSObject(WXJSObject.String, timerInfo.callbackId); WXJSObject[] args = {obj}; invokeExecJS("", null, METHOD_SET_TIMEOUT, args); break; case WXJSBridgeMsgType.TAKE_HEAP_SNAPSHOT: if (msg.obj != null) { String filename = (String) msg.obj; mWXBridge.takeHeapSnapshot(filename); } break; default: break; } return false; } private WXBridgeManager(); static WXBridgeManager getInstance(); void stopRemoteDebug(); Object callModuleMethod(String instanceId, String moduleStr, String methodStr, JSONArray args); void restart(); synchronized void setStackTopInstance(final String instanceId); @Override void post(Runnable r); @Override void setInterceptor(Interceptor interceptor); void post(Runnable r, Object token); void sendMessageDelayed(Message message, long delayMillis); void removeMessage(int what,Object obj); Object callNativeModule(String instanceId, String module, String method, JSONArray arguments, Object options); Object callNativeComponent(String instanceId, String componentRef, String method, JSONArray arguments, Object options); int callNative(String instanceId, String tasks, String callback); int callCreateBody(String instanceId, String tasks, String callback); int callUpdateFinish(String instanceId, String callback); int callCreateFinish(String instanceId, String callback); int callRefreshFinish(String instanceId, String callback); int callUpdateAttrs(String instanceId, String ref, String task, String callback); int callUpdateStyle(String instanceId, String ref, String task, String callback); int callRemoveElement(String instanceId, String ref, String callback); int callMoveElement(String instanceId, String ref, String parentref, String index, String callback); int callAddEvent(String instanceId, String ref, String event, String callback); int callRemoveEvent(String instanceId, String ref, String event, String callback); int callAddElement(String instanceId, String ref,String dom,String index, String callback); synchronized void initScriptsFramework(String framework); @Deprecated void fireEvent(final String instanceId, final String ref, final String type, final Map<String, Object> data); @Deprecated void fireEvent(final String instanceId, final String ref, final String type, final Map<String, Object> data,final Map<String, Object> domChanges); void fireEventOnNode(final String instanceId, final String ref, final String type, final Map<String, Object> data,final Map<String, Object> domChanges); @Deprecated void callback(String instanceId, String callback,String data); @Deprecated void callback(final String instanceId, final String callback, final Map<String, Object> data); @Deprecated void callback(final String instanceId, final String callback, final Object data,boolean keepAlive); void refreshInstance(final String instanceId, final WXRefreshData jsonData); void commitJSBridgeAlarmMonitor(String instanceId, WXErrorCode errCode, String errMsg); void commitJSFrameworkAlarmMonitor(final String type, final WXErrorCode errorCode, String errMsg); void createInstance(final String instanceId, final String template, final Map<String, Object> options, final String data); void destroyInstance(final String instanceId); @Override boolean handleMessage(Message msg); void invokeExecJS(String instanceId, String namespace, String function, WXJSObject[] args,boolean logTaskDetail); void registerModules(final Map<String, Object> modules); void registerComponents(final List<Map<String, Object>> components); void execJSService(final String service); void destroy(); void reportJSException(String instanceId, String function, String exception); @Deprecated void notifyTrimMemory(); @Nullable Looper getJSLooper(); void notifySerializeCodeCache(); void takeJSHeapSnapshot(String filename); static final String METHOD_CREATE_INSTANCE; static final String METHOD_DESTROY_INSTANCE; static final String METHOD_CALL_JS; static final String METHOD_SET_TIMEOUT; static final String METHOD_REGISTER_MODULES; static final String METHOD_REGISTER_COMPONENTS; static final String METHOD_FIRE_EVENT; static final String METHOD_CALLBACK; static final String METHOD_REFRESH_INSTANCE; static final String METHOD_NOTIFY_TRIM_MEMORY; static final String METHOD_NOTIFY_SERIALIZE_CODE_CACHE; static final String KEY_METHOD; static final String KEY_ARGS; static final String COMPONENT; static final String REF; static final String MODULE; static final String METHOD; static final String ARGS; }
@Test public void testReportJSException() throws Exception { getInstance().reportJSException(instance.getInstanceId(),"test","test exception"); }
public void reportJSException(String instanceId, String function, String exception) { if (WXEnvironment.isApkDebugable()) { WXLogUtils.e("reportJSException >>>> instanceId:" + instanceId + ", exception function:" + function + ", exception:" + exception); } WXSDKInstance instance; if (instanceId != null && (instance = WXSDKManager.getInstance().getSDKInstance(instanceId)) != null) { instance.onJSException(WXErrorCode.WX_ERR_JS_EXECUTE.getErrorCode(), function, exception); String err = "function:" + function + "#exception:" + exception; commitJSBridgeAlarmMonitor(instanceId, WXErrorCode.WX_ERR_JS_EXECUTE, err); IWXJSExceptionAdapter adapter = WXSDKManager.getInstance().getIWXJSExceptionAdapter(); if (adapter != null) { WXJSExceptionInfo jsException = new WXJSExceptionInfo(instanceId, instance.getBundleUrl(), WXErrorCode.WX_ERR_JS_EXECUTE.getErrorCode(), function, exception, null); adapter.onJSException(jsException); if (WXEnvironment.isApkDebugable()) { WXLogUtils.d(jsException.toString()); } } } }
WXBridgeManager implements Callback,BactchExecutor { public void reportJSException(String instanceId, String function, String exception) { if (WXEnvironment.isApkDebugable()) { WXLogUtils.e("reportJSException >>>> instanceId:" + instanceId + ", exception function:" + function + ", exception:" + exception); } WXSDKInstance instance; if (instanceId != null && (instance = WXSDKManager.getInstance().getSDKInstance(instanceId)) != null) { instance.onJSException(WXErrorCode.WX_ERR_JS_EXECUTE.getErrorCode(), function, exception); String err = "function:" + function + "#exception:" + exception; commitJSBridgeAlarmMonitor(instanceId, WXErrorCode.WX_ERR_JS_EXECUTE, err); IWXJSExceptionAdapter adapter = WXSDKManager.getInstance().getIWXJSExceptionAdapter(); if (adapter != null) { WXJSExceptionInfo jsException = new WXJSExceptionInfo(instanceId, instance.getBundleUrl(), WXErrorCode.WX_ERR_JS_EXECUTE.getErrorCode(), function, exception, null); adapter.onJSException(jsException); if (WXEnvironment.isApkDebugable()) { WXLogUtils.d(jsException.toString()); } } } } }
WXBridgeManager implements Callback,BactchExecutor { public void reportJSException(String instanceId, String function, String exception) { if (WXEnvironment.isApkDebugable()) { WXLogUtils.e("reportJSException >>>> instanceId:" + instanceId + ", exception function:" + function + ", exception:" + exception); } WXSDKInstance instance; if (instanceId != null && (instance = WXSDKManager.getInstance().getSDKInstance(instanceId)) != null) { instance.onJSException(WXErrorCode.WX_ERR_JS_EXECUTE.getErrorCode(), function, exception); String err = "function:" + function + "#exception:" + exception; commitJSBridgeAlarmMonitor(instanceId, WXErrorCode.WX_ERR_JS_EXECUTE, err); IWXJSExceptionAdapter adapter = WXSDKManager.getInstance().getIWXJSExceptionAdapter(); if (adapter != null) { WXJSExceptionInfo jsException = new WXJSExceptionInfo(instanceId, instance.getBundleUrl(), WXErrorCode.WX_ERR_JS_EXECUTE.getErrorCode(), function, exception, null); adapter.onJSException(jsException); if (WXEnvironment.isApkDebugable()) { WXLogUtils.d(jsException.toString()); } } } } private WXBridgeManager(); }
WXBridgeManager implements Callback,BactchExecutor { public void reportJSException(String instanceId, String function, String exception) { if (WXEnvironment.isApkDebugable()) { WXLogUtils.e("reportJSException >>>> instanceId:" + instanceId + ", exception function:" + function + ", exception:" + exception); } WXSDKInstance instance; if (instanceId != null && (instance = WXSDKManager.getInstance().getSDKInstance(instanceId)) != null) { instance.onJSException(WXErrorCode.WX_ERR_JS_EXECUTE.getErrorCode(), function, exception); String err = "function:" + function + "#exception:" + exception; commitJSBridgeAlarmMonitor(instanceId, WXErrorCode.WX_ERR_JS_EXECUTE, err); IWXJSExceptionAdapter adapter = WXSDKManager.getInstance().getIWXJSExceptionAdapter(); if (adapter != null) { WXJSExceptionInfo jsException = new WXJSExceptionInfo(instanceId, instance.getBundleUrl(), WXErrorCode.WX_ERR_JS_EXECUTE.getErrorCode(), function, exception, null); adapter.onJSException(jsException); if (WXEnvironment.isApkDebugable()) { WXLogUtils.d(jsException.toString()); } } } } private WXBridgeManager(); static WXBridgeManager getInstance(); void stopRemoteDebug(); Object callModuleMethod(String instanceId, String moduleStr, String methodStr, JSONArray args); void restart(); synchronized void setStackTopInstance(final String instanceId); @Override void post(Runnable r); @Override void setInterceptor(Interceptor interceptor); void post(Runnable r, Object token); void sendMessageDelayed(Message message, long delayMillis); void removeMessage(int what,Object obj); Object callNativeModule(String instanceId, String module, String method, JSONArray arguments, Object options); Object callNativeComponent(String instanceId, String componentRef, String method, JSONArray arguments, Object options); int callNative(String instanceId, String tasks, String callback); int callCreateBody(String instanceId, String tasks, String callback); int callUpdateFinish(String instanceId, String callback); int callCreateFinish(String instanceId, String callback); int callRefreshFinish(String instanceId, String callback); int callUpdateAttrs(String instanceId, String ref, String task, String callback); int callUpdateStyle(String instanceId, String ref, String task, String callback); int callRemoveElement(String instanceId, String ref, String callback); int callMoveElement(String instanceId, String ref, String parentref, String index, String callback); int callAddEvent(String instanceId, String ref, String event, String callback); int callRemoveEvent(String instanceId, String ref, String event, String callback); int callAddElement(String instanceId, String ref,String dom,String index, String callback); synchronized void initScriptsFramework(String framework); @Deprecated void fireEvent(final String instanceId, final String ref, final String type, final Map<String, Object> data); @Deprecated void fireEvent(final String instanceId, final String ref, final String type, final Map<String, Object> data,final Map<String, Object> domChanges); void fireEventOnNode(final String instanceId, final String ref, final String type, final Map<String, Object> data,final Map<String, Object> domChanges); @Deprecated void callback(String instanceId, String callback,String data); @Deprecated void callback(final String instanceId, final String callback, final Map<String, Object> data); @Deprecated void callback(final String instanceId, final String callback, final Object data,boolean keepAlive); void refreshInstance(final String instanceId, final WXRefreshData jsonData); void commitJSBridgeAlarmMonitor(String instanceId, WXErrorCode errCode, String errMsg); void commitJSFrameworkAlarmMonitor(final String type, final WXErrorCode errorCode, String errMsg); void createInstance(final String instanceId, final String template, final Map<String, Object> options, final String data); void destroyInstance(final String instanceId); @Override boolean handleMessage(Message msg); void invokeExecJS(String instanceId, String namespace, String function, WXJSObject[] args,boolean logTaskDetail); void registerModules(final Map<String, Object> modules); void registerComponents(final List<Map<String, Object>> components); void execJSService(final String service); void destroy(); void reportJSException(String instanceId, String function, String exception); @Deprecated void notifyTrimMemory(); @Nullable Looper getJSLooper(); void notifySerializeCodeCache(); void takeJSHeapSnapshot(String filename); }
WXBridgeManager implements Callback,BactchExecutor { public void reportJSException(String instanceId, String function, String exception) { if (WXEnvironment.isApkDebugable()) { WXLogUtils.e("reportJSException >>>> instanceId:" + instanceId + ", exception function:" + function + ", exception:" + exception); } WXSDKInstance instance; if (instanceId != null && (instance = WXSDKManager.getInstance().getSDKInstance(instanceId)) != null) { instance.onJSException(WXErrorCode.WX_ERR_JS_EXECUTE.getErrorCode(), function, exception); String err = "function:" + function + "#exception:" + exception; commitJSBridgeAlarmMonitor(instanceId, WXErrorCode.WX_ERR_JS_EXECUTE, err); IWXJSExceptionAdapter adapter = WXSDKManager.getInstance().getIWXJSExceptionAdapter(); if (adapter != null) { WXJSExceptionInfo jsException = new WXJSExceptionInfo(instanceId, instance.getBundleUrl(), WXErrorCode.WX_ERR_JS_EXECUTE.getErrorCode(), function, exception, null); adapter.onJSException(jsException); if (WXEnvironment.isApkDebugable()) { WXLogUtils.d(jsException.toString()); } } } } private WXBridgeManager(); static WXBridgeManager getInstance(); void stopRemoteDebug(); Object callModuleMethod(String instanceId, String moduleStr, String methodStr, JSONArray args); void restart(); synchronized void setStackTopInstance(final String instanceId); @Override void post(Runnable r); @Override void setInterceptor(Interceptor interceptor); void post(Runnable r, Object token); void sendMessageDelayed(Message message, long delayMillis); void removeMessage(int what,Object obj); Object callNativeModule(String instanceId, String module, String method, JSONArray arguments, Object options); Object callNativeComponent(String instanceId, String componentRef, String method, JSONArray arguments, Object options); int callNative(String instanceId, String tasks, String callback); int callCreateBody(String instanceId, String tasks, String callback); int callUpdateFinish(String instanceId, String callback); int callCreateFinish(String instanceId, String callback); int callRefreshFinish(String instanceId, String callback); int callUpdateAttrs(String instanceId, String ref, String task, String callback); int callUpdateStyle(String instanceId, String ref, String task, String callback); int callRemoveElement(String instanceId, String ref, String callback); int callMoveElement(String instanceId, String ref, String parentref, String index, String callback); int callAddEvent(String instanceId, String ref, String event, String callback); int callRemoveEvent(String instanceId, String ref, String event, String callback); int callAddElement(String instanceId, String ref,String dom,String index, String callback); synchronized void initScriptsFramework(String framework); @Deprecated void fireEvent(final String instanceId, final String ref, final String type, final Map<String, Object> data); @Deprecated void fireEvent(final String instanceId, final String ref, final String type, final Map<String, Object> data,final Map<String, Object> domChanges); void fireEventOnNode(final String instanceId, final String ref, final String type, final Map<String, Object> data,final Map<String, Object> domChanges); @Deprecated void callback(String instanceId, String callback,String data); @Deprecated void callback(final String instanceId, final String callback, final Map<String, Object> data); @Deprecated void callback(final String instanceId, final String callback, final Object data,boolean keepAlive); void refreshInstance(final String instanceId, final WXRefreshData jsonData); void commitJSBridgeAlarmMonitor(String instanceId, WXErrorCode errCode, String errMsg); void commitJSFrameworkAlarmMonitor(final String type, final WXErrorCode errorCode, String errMsg); void createInstance(final String instanceId, final String template, final Map<String, Object> options, final String data); void destroyInstance(final String instanceId); @Override boolean handleMessage(Message msg); void invokeExecJS(String instanceId, String namespace, String function, WXJSObject[] args,boolean logTaskDetail); void registerModules(final Map<String, Object> modules); void registerComponents(final List<Map<String, Object>> components); void execJSService(final String service); void destroy(); void reportJSException(String instanceId, String function, String exception); @Deprecated void notifyTrimMemory(); @Nullable Looper getJSLooper(); void notifySerializeCodeCache(); void takeJSHeapSnapshot(String filename); static final String METHOD_CREATE_INSTANCE; static final String METHOD_DESTROY_INSTANCE; static final String METHOD_CALL_JS; static final String METHOD_SET_TIMEOUT; static final String METHOD_REGISTER_MODULES; static final String METHOD_REGISTER_COMPONENTS; static final String METHOD_FIRE_EVENT; static final String METHOD_CALLBACK; static final String METHOD_REFRESH_INSTANCE; static final String METHOD_NOTIFY_TRIM_MEMORY; static final String METHOD_NOTIFY_SERIALIZE_CODE_CACHE; static final String KEY_METHOD; static final String KEY_ARGS; static final String COMPONENT; static final String REF; static final String MODULE; static final String METHOD; static final String ARGS; }
@Test public void testCallNative() throws Exception { bridge.callNative("1","{}","100"); }
public int callNative(String instanceId, byte [] tasks, String callback) { return callNative(instanceId,new String(tasks),callback); }
WXBridge implements IWXBridge { public int callNative(String instanceId, byte [] tasks, String callback) { return callNative(instanceId,new String(tasks),callback); } }
WXBridge implements IWXBridge { public int callNative(String instanceId, byte [] tasks, String callback) { return callNative(instanceId,new String(tasks),callback); } }
WXBridge implements IWXBridge { public int callNative(String instanceId, byte [] tasks, String callback) { return callNative(instanceId,new String(tasks),callback); } native int initFramework(String framework, WXParams params); native int execJS(String instanceId, String namespace, String function, WXJSObject[] args); native int execJSService(String javascript); native void takeHeapSnapshot(String filename); int callNative(String instanceId, byte [] tasks, String callback); int callNative(String instanceId, String tasks, String callback); int callAddElement(String instanceId, String ref,byte[] dom,String index, String callback); int callCreateBody(String instanceId, byte [] tasks, String callback); int callCreateBody(String instanceId, String tasks, String callback); int callAddElement(String instanceId, String ref,String dom,String index, String callback); void reportJSException(String instanceId, String func, String exception); @Override Object callNativeModule(String instanceId, String module, String method, byte [] arguments, byte [] options); @Override void callNativeComponent(String instanceId, String componentRef, String method, byte [] arguments, byte [] options); void setTimeoutNative(String callbackId, String time); void setJSFrmVersion(String version); int callUpdateFinish(String instanceId, byte [] tasks, String callback); int callCreateFinish(String instanceId, byte [] tasks, String callback); int callRefreshFinish(String instanceId, byte [] tasks, String callback); int callUpdateAttrs(String instanceId, String ref, byte [] tasks, String callback); int callUpdateStyle(String instanceId, String ref, byte [] tasks, String callback); int callRemoveElement(String instanceId, String ref, String callback); int callMoveElement(String instanceId, String ref, String parentref, String index, String callback); int callAddEvent(String instanceId, String ref, String event, String callback); int callRemoveEvent(String instanceId, String ref, String event, String callback); }
WXBridge implements IWXBridge { public int callNative(String instanceId, byte [] tasks, String callback) { return callNative(instanceId,new String(tasks),callback); } native int initFramework(String framework, WXParams params); native int execJS(String instanceId, String namespace, String function, WXJSObject[] args); native int execJSService(String javascript); native void takeHeapSnapshot(String filename); int callNative(String instanceId, byte [] tasks, String callback); int callNative(String instanceId, String tasks, String callback); int callAddElement(String instanceId, String ref,byte[] dom,String index, String callback); int callCreateBody(String instanceId, byte [] tasks, String callback); int callCreateBody(String instanceId, String tasks, String callback); int callAddElement(String instanceId, String ref,String dom,String index, String callback); void reportJSException(String instanceId, String func, String exception); @Override Object callNativeModule(String instanceId, String module, String method, byte [] arguments, byte [] options); @Override void callNativeComponent(String instanceId, String componentRef, String method, byte [] arguments, byte [] options); void setTimeoutNative(String callbackId, String time); void setJSFrmVersion(String version); int callUpdateFinish(String instanceId, byte [] tasks, String callback); int callCreateFinish(String instanceId, byte [] tasks, String callback); int callRefreshFinish(String instanceId, byte [] tasks, String callback); int callUpdateAttrs(String instanceId, String ref, byte [] tasks, String callback); int callUpdateStyle(String instanceId, String ref, byte [] tasks, String callback); int callRemoveElement(String instanceId, String ref, String callback); int callMoveElement(String instanceId, String ref, String parentref, String index, String callback); int callAddEvent(String instanceId, String ref, String event, String callback); int callRemoveEvent(String instanceId, String ref, String event, String callback); static final String TAG; }
@Test public void testCallAddElement() throws Exception { bridge.callAddElement("1","1","{}","0","100"); }
public int callAddElement(String instanceId, String ref,byte[] dom,String index, String callback) { return callAddElement(instanceId,ref, new String(dom),index,callback); }
WXBridge implements IWXBridge { public int callAddElement(String instanceId, String ref,byte[] dom,String index, String callback) { return callAddElement(instanceId,ref, new String(dom),index,callback); } }
WXBridge implements IWXBridge { public int callAddElement(String instanceId, String ref,byte[] dom,String index, String callback) { return callAddElement(instanceId,ref, new String(dom),index,callback); } }
WXBridge implements IWXBridge { public int callAddElement(String instanceId, String ref,byte[] dom,String index, String callback) { return callAddElement(instanceId,ref, new String(dom),index,callback); } native int initFramework(String framework, WXParams params); native int execJS(String instanceId, String namespace, String function, WXJSObject[] args); native int execJSService(String javascript); native void takeHeapSnapshot(String filename); int callNative(String instanceId, byte [] tasks, String callback); int callNative(String instanceId, String tasks, String callback); int callAddElement(String instanceId, String ref,byte[] dom,String index, String callback); int callCreateBody(String instanceId, byte [] tasks, String callback); int callCreateBody(String instanceId, String tasks, String callback); int callAddElement(String instanceId, String ref,String dom,String index, String callback); void reportJSException(String instanceId, String func, String exception); @Override Object callNativeModule(String instanceId, String module, String method, byte [] arguments, byte [] options); @Override void callNativeComponent(String instanceId, String componentRef, String method, byte [] arguments, byte [] options); void setTimeoutNative(String callbackId, String time); void setJSFrmVersion(String version); int callUpdateFinish(String instanceId, byte [] tasks, String callback); int callCreateFinish(String instanceId, byte [] tasks, String callback); int callRefreshFinish(String instanceId, byte [] tasks, String callback); int callUpdateAttrs(String instanceId, String ref, byte [] tasks, String callback); int callUpdateStyle(String instanceId, String ref, byte [] tasks, String callback); int callRemoveElement(String instanceId, String ref, String callback); int callMoveElement(String instanceId, String ref, String parentref, String index, String callback); int callAddEvent(String instanceId, String ref, String event, String callback); int callRemoveEvent(String instanceId, String ref, String event, String callback); }
WXBridge implements IWXBridge { public int callAddElement(String instanceId, String ref,byte[] dom,String index, String callback) { return callAddElement(instanceId,ref, new String(dom),index,callback); } native int initFramework(String framework, WXParams params); native int execJS(String instanceId, String namespace, String function, WXJSObject[] args); native int execJSService(String javascript); native void takeHeapSnapshot(String filename); int callNative(String instanceId, byte [] tasks, String callback); int callNative(String instanceId, String tasks, String callback); int callAddElement(String instanceId, String ref,byte[] dom,String index, String callback); int callCreateBody(String instanceId, byte [] tasks, String callback); int callCreateBody(String instanceId, String tasks, String callback); int callAddElement(String instanceId, String ref,String dom,String index, String callback); void reportJSException(String instanceId, String func, String exception); @Override Object callNativeModule(String instanceId, String module, String method, byte [] arguments, byte [] options); @Override void callNativeComponent(String instanceId, String componentRef, String method, byte [] arguments, byte [] options); void setTimeoutNative(String callbackId, String time); void setJSFrmVersion(String version); int callUpdateFinish(String instanceId, byte [] tasks, String callback); int callCreateFinish(String instanceId, byte [] tasks, String callback); int callRefreshFinish(String instanceId, byte [] tasks, String callback); int callUpdateAttrs(String instanceId, String ref, byte [] tasks, String callback); int callUpdateStyle(String instanceId, String ref, byte [] tasks, String callback); int callRemoveElement(String instanceId, String ref, String callback); int callMoveElement(String instanceId, String ref, String parentref, String index, String callback); int callAddEvent(String instanceId, String ref, String event, String callback); int callRemoveEvent(String instanceId, String ref, String event, String callback); static final String TAG; }
@Test public void testReportJSException() throws Exception { bridge.reportJSException("1","test","some exception"); }
public void reportJSException(String instanceId, String func, String exception) { WXBridgeManager.getInstance().reportJSException(instanceId, func, exception); }
WXBridge implements IWXBridge { public void reportJSException(String instanceId, String func, String exception) { WXBridgeManager.getInstance().reportJSException(instanceId, func, exception); } }
WXBridge implements IWXBridge { public void reportJSException(String instanceId, String func, String exception) { WXBridgeManager.getInstance().reportJSException(instanceId, func, exception); } }
WXBridge implements IWXBridge { public void reportJSException(String instanceId, String func, String exception) { WXBridgeManager.getInstance().reportJSException(instanceId, func, exception); } native int initFramework(String framework, WXParams params); native int execJS(String instanceId, String namespace, String function, WXJSObject[] args); native int execJSService(String javascript); native void takeHeapSnapshot(String filename); int callNative(String instanceId, byte [] tasks, String callback); int callNative(String instanceId, String tasks, String callback); int callAddElement(String instanceId, String ref,byte[] dom,String index, String callback); int callCreateBody(String instanceId, byte [] tasks, String callback); int callCreateBody(String instanceId, String tasks, String callback); int callAddElement(String instanceId, String ref,String dom,String index, String callback); void reportJSException(String instanceId, String func, String exception); @Override Object callNativeModule(String instanceId, String module, String method, byte [] arguments, byte [] options); @Override void callNativeComponent(String instanceId, String componentRef, String method, byte [] arguments, byte [] options); void setTimeoutNative(String callbackId, String time); void setJSFrmVersion(String version); int callUpdateFinish(String instanceId, byte [] tasks, String callback); int callCreateFinish(String instanceId, byte [] tasks, String callback); int callRefreshFinish(String instanceId, byte [] tasks, String callback); int callUpdateAttrs(String instanceId, String ref, byte [] tasks, String callback); int callUpdateStyle(String instanceId, String ref, byte [] tasks, String callback); int callRemoveElement(String instanceId, String ref, String callback); int callMoveElement(String instanceId, String ref, String parentref, String index, String callback); int callAddEvent(String instanceId, String ref, String event, String callback); int callRemoveEvent(String instanceId, String ref, String event, String callback); }
WXBridge implements IWXBridge { public void reportJSException(String instanceId, String func, String exception) { WXBridgeManager.getInstance().reportJSException(instanceId, func, exception); } native int initFramework(String framework, WXParams params); native int execJS(String instanceId, String namespace, String function, WXJSObject[] args); native int execJSService(String javascript); native void takeHeapSnapshot(String filename); int callNative(String instanceId, byte [] tasks, String callback); int callNative(String instanceId, String tasks, String callback); int callAddElement(String instanceId, String ref,byte[] dom,String index, String callback); int callCreateBody(String instanceId, byte [] tasks, String callback); int callCreateBody(String instanceId, String tasks, String callback); int callAddElement(String instanceId, String ref,String dom,String index, String callback); void reportJSException(String instanceId, String func, String exception); @Override Object callNativeModule(String instanceId, String module, String method, byte [] arguments, byte [] options); @Override void callNativeComponent(String instanceId, String componentRef, String method, byte [] arguments, byte [] options); void setTimeoutNative(String callbackId, String time); void setJSFrmVersion(String version); int callUpdateFinish(String instanceId, byte [] tasks, String callback); int callCreateFinish(String instanceId, byte [] tasks, String callback); int callRefreshFinish(String instanceId, byte [] tasks, String callback); int callUpdateAttrs(String instanceId, String ref, byte [] tasks, String callback); int callUpdateStyle(String instanceId, String ref, byte [] tasks, String callback); int callRemoveElement(String instanceId, String ref, String callback); int callMoveElement(String instanceId, String ref, String parentref, String index, String callback); int callAddEvent(String instanceId, String ref, String event, String callback); int callRemoveEvent(String instanceId, String ref, String event, String callback); static final String TAG; }
@Test public void testSetTimeoutNative() throws Exception { bridge.setTimeoutNative("100","1024"); }
public void setTimeoutNative(String callbackId, String time) { WXBridgeManager.getInstance().setTimeout(callbackId, time); }
WXBridge implements IWXBridge { public void setTimeoutNative(String callbackId, String time) { WXBridgeManager.getInstance().setTimeout(callbackId, time); } }
WXBridge implements IWXBridge { public void setTimeoutNative(String callbackId, String time) { WXBridgeManager.getInstance().setTimeout(callbackId, time); } }
WXBridge implements IWXBridge { public void setTimeoutNative(String callbackId, String time) { WXBridgeManager.getInstance().setTimeout(callbackId, time); } native int initFramework(String framework, WXParams params); native int execJS(String instanceId, String namespace, String function, WXJSObject[] args); native int execJSService(String javascript); native void takeHeapSnapshot(String filename); int callNative(String instanceId, byte [] tasks, String callback); int callNative(String instanceId, String tasks, String callback); int callAddElement(String instanceId, String ref,byte[] dom,String index, String callback); int callCreateBody(String instanceId, byte [] tasks, String callback); int callCreateBody(String instanceId, String tasks, String callback); int callAddElement(String instanceId, String ref,String dom,String index, String callback); void reportJSException(String instanceId, String func, String exception); @Override Object callNativeModule(String instanceId, String module, String method, byte [] arguments, byte [] options); @Override void callNativeComponent(String instanceId, String componentRef, String method, byte [] arguments, byte [] options); void setTimeoutNative(String callbackId, String time); void setJSFrmVersion(String version); int callUpdateFinish(String instanceId, byte [] tasks, String callback); int callCreateFinish(String instanceId, byte [] tasks, String callback); int callRefreshFinish(String instanceId, byte [] tasks, String callback); int callUpdateAttrs(String instanceId, String ref, byte [] tasks, String callback); int callUpdateStyle(String instanceId, String ref, byte [] tasks, String callback); int callRemoveElement(String instanceId, String ref, String callback); int callMoveElement(String instanceId, String ref, String parentref, String index, String callback); int callAddEvent(String instanceId, String ref, String event, String callback); int callRemoveEvent(String instanceId, String ref, String event, String callback); }
WXBridge implements IWXBridge { public void setTimeoutNative(String callbackId, String time) { WXBridgeManager.getInstance().setTimeout(callbackId, time); } native int initFramework(String framework, WXParams params); native int execJS(String instanceId, String namespace, String function, WXJSObject[] args); native int execJSService(String javascript); native void takeHeapSnapshot(String filename); int callNative(String instanceId, byte [] tasks, String callback); int callNative(String instanceId, String tasks, String callback); int callAddElement(String instanceId, String ref,byte[] dom,String index, String callback); int callCreateBody(String instanceId, byte [] tasks, String callback); int callCreateBody(String instanceId, String tasks, String callback); int callAddElement(String instanceId, String ref,String dom,String index, String callback); void reportJSException(String instanceId, String func, String exception); @Override Object callNativeModule(String instanceId, String module, String method, byte [] arguments, byte [] options); @Override void callNativeComponent(String instanceId, String componentRef, String method, byte [] arguments, byte [] options); void setTimeoutNative(String callbackId, String time); void setJSFrmVersion(String version); int callUpdateFinish(String instanceId, byte [] tasks, String callback); int callCreateFinish(String instanceId, byte [] tasks, String callback); int callRefreshFinish(String instanceId, byte [] tasks, String callback); int callUpdateAttrs(String instanceId, String ref, byte [] tasks, String callback); int callUpdateStyle(String instanceId, String ref, byte [] tasks, String callback); int callRemoveElement(String instanceId, String ref, String callback); int callMoveElement(String instanceId, String ref, String parentref, String index, String callback); int callAddEvent(String instanceId, String ref, String event, String callback); int callRemoveEvent(String instanceId, String ref, String event, String callback); static final String TAG; }
@Test public void testSetJSFrmVersion() throws Exception { bridge.setJSFrmVersion("v0.1"); }
public void setJSFrmVersion(String version) { if(!TextUtils.isEmpty(version)) { WXEnvironment.JS_LIB_SDK_VERSION = version; } }
WXBridge implements IWXBridge { public void setJSFrmVersion(String version) { if(!TextUtils.isEmpty(version)) { WXEnvironment.JS_LIB_SDK_VERSION = version; } } }
WXBridge implements IWXBridge { public void setJSFrmVersion(String version) { if(!TextUtils.isEmpty(version)) { WXEnvironment.JS_LIB_SDK_VERSION = version; } } }
WXBridge implements IWXBridge { public void setJSFrmVersion(String version) { if(!TextUtils.isEmpty(version)) { WXEnvironment.JS_LIB_SDK_VERSION = version; } } native int initFramework(String framework, WXParams params); native int execJS(String instanceId, String namespace, String function, WXJSObject[] args); native int execJSService(String javascript); native void takeHeapSnapshot(String filename); int callNative(String instanceId, byte [] tasks, String callback); int callNative(String instanceId, String tasks, String callback); int callAddElement(String instanceId, String ref,byte[] dom,String index, String callback); int callCreateBody(String instanceId, byte [] tasks, String callback); int callCreateBody(String instanceId, String tasks, String callback); int callAddElement(String instanceId, String ref,String dom,String index, String callback); void reportJSException(String instanceId, String func, String exception); @Override Object callNativeModule(String instanceId, String module, String method, byte [] arguments, byte [] options); @Override void callNativeComponent(String instanceId, String componentRef, String method, byte [] arguments, byte [] options); void setTimeoutNative(String callbackId, String time); void setJSFrmVersion(String version); int callUpdateFinish(String instanceId, byte [] tasks, String callback); int callCreateFinish(String instanceId, byte [] tasks, String callback); int callRefreshFinish(String instanceId, byte [] tasks, String callback); int callUpdateAttrs(String instanceId, String ref, byte [] tasks, String callback); int callUpdateStyle(String instanceId, String ref, byte [] tasks, String callback); int callRemoveElement(String instanceId, String ref, String callback); int callMoveElement(String instanceId, String ref, String parentref, String index, String callback); int callAddEvent(String instanceId, String ref, String event, String callback); int callRemoveEvent(String instanceId, String ref, String event, String callback); }
WXBridge implements IWXBridge { public void setJSFrmVersion(String version) { if(!TextUtils.isEmpty(version)) { WXEnvironment.JS_LIB_SDK_VERSION = version; } } native int initFramework(String framework, WXParams params); native int execJS(String instanceId, String namespace, String function, WXJSObject[] args); native int execJSService(String javascript); native void takeHeapSnapshot(String filename); int callNative(String instanceId, byte [] tasks, String callback); int callNative(String instanceId, String tasks, String callback); int callAddElement(String instanceId, String ref,byte[] dom,String index, String callback); int callCreateBody(String instanceId, byte [] tasks, String callback); int callCreateBody(String instanceId, String tasks, String callback); int callAddElement(String instanceId, String ref,String dom,String index, String callback); void reportJSException(String instanceId, String func, String exception); @Override Object callNativeModule(String instanceId, String module, String method, byte [] arguments, byte [] options); @Override void callNativeComponent(String instanceId, String componentRef, String method, byte [] arguments, byte [] options); void setTimeoutNative(String callbackId, String time); void setJSFrmVersion(String version); int callUpdateFinish(String instanceId, byte [] tasks, String callback); int callCreateFinish(String instanceId, byte [] tasks, String callback); int callRefreshFinish(String instanceId, byte [] tasks, String callback); int callUpdateAttrs(String instanceId, String ref, byte [] tasks, String callback); int callUpdateStyle(String instanceId, String ref, byte [] tasks, String callback); int callRemoveElement(String instanceId, String ref, String callback); int callMoveElement(String instanceId, String ref, String parentref, String index, String callback); int callAddEvent(String instanceId, String ref, String event, String callback); int callRemoveEvent(String instanceId, String ref, String event, String callback); static final String TAG; }
@Test public void testCallModuleMethod() throws Exception { WXModuleManager.callModuleMethod(instance.getInstanceId(),"test1","testMethod",null); WXModuleManager.callModuleMethod(instance.getInstanceId(),"test2","testMethod",null); }
static Object callModuleMethod(final String instanceId, String moduleStr, String methodStr, JSONArray args) { ModuleFactory factory = sModuleFactoryMap.get(moduleStr); if(factory == null){ WXLogUtils.e("[WXModuleManager] module factory not found."); return null; } final WXModule wxModule = findModule(instanceId, moduleStr,factory); if (wxModule == null) { return null; } WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId); wxModule.mWXSDKInstance = instance; final Invoker invoker = factory.getMethodInvoker(methodStr); try { if(instance != null) { IWXUserTrackAdapter userTrackAdapter = WXSDKManager.getInstance().getIWXUserTrackAdapter(); if(userTrackAdapter != null) { HashMap<String, Serializable> data = new HashMap<String, Serializable>(); data.put(MONITOR_ERROR_CODE, "101"); data.put(MONITOR_ARG, moduleStr + "." + methodStr); data.put(MONITOR_ERROR_MSG, instance.getBundleUrl()); userTrackAdapter.commit(instance.getContext(), null, IWXUserTrackAdapter.INVOKE_MODULE, null, data); } return dispatchCallModuleMethod(instance,wxModule,args,invoker); } else { WXLogUtils.e("callModuleMethod >>> instance is null"); return null; } } catch (Exception e) { WXLogUtils.e("callModuleMethod >>> invoke module:" + moduleStr + ", method:" + methodStr + " failed. ", e); return null; } finally { if (wxModule instanceof WXDomModule || wxModule instanceof WXTimerModule) { wxModule.mWXSDKInstance = null; } } }
WXModuleManager { static Object callModuleMethod(final String instanceId, String moduleStr, String methodStr, JSONArray args) { ModuleFactory factory = sModuleFactoryMap.get(moduleStr); if(factory == null){ WXLogUtils.e("[WXModuleManager] module factory not found."); return null; } final WXModule wxModule = findModule(instanceId, moduleStr,factory); if (wxModule == null) { return null; } WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId); wxModule.mWXSDKInstance = instance; final Invoker invoker = factory.getMethodInvoker(methodStr); try { if(instance != null) { IWXUserTrackAdapter userTrackAdapter = WXSDKManager.getInstance().getIWXUserTrackAdapter(); if(userTrackAdapter != null) { HashMap<String, Serializable> data = new HashMap<String, Serializable>(); data.put(MONITOR_ERROR_CODE, "101"); data.put(MONITOR_ARG, moduleStr + "." + methodStr); data.put(MONITOR_ERROR_MSG, instance.getBundleUrl()); userTrackAdapter.commit(instance.getContext(), null, IWXUserTrackAdapter.INVOKE_MODULE, null, data); } return dispatchCallModuleMethod(instance,wxModule,args,invoker); } else { WXLogUtils.e("callModuleMethod >>> instance is null"); return null; } } catch (Exception e) { WXLogUtils.e("callModuleMethod >>> invoke module:" + moduleStr + ", method:" + methodStr + " failed. ", e); return null; } finally { if (wxModule instanceof WXDomModule || wxModule instanceof WXTimerModule) { wxModule.mWXSDKInstance = null; } } } }
WXModuleManager { static Object callModuleMethod(final String instanceId, String moduleStr, String methodStr, JSONArray args) { ModuleFactory factory = sModuleFactoryMap.get(moduleStr); if(factory == null){ WXLogUtils.e("[WXModuleManager] module factory not found."); return null; } final WXModule wxModule = findModule(instanceId, moduleStr,factory); if (wxModule == null) { return null; } WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId); wxModule.mWXSDKInstance = instance; final Invoker invoker = factory.getMethodInvoker(methodStr); try { if(instance != null) { IWXUserTrackAdapter userTrackAdapter = WXSDKManager.getInstance().getIWXUserTrackAdapter(); if(userTrackAdapter != null) { HashMap<String, Serializable> data = new HashMap<String, Serializable>(); data.put(MONITOR_ERROR_CODE, "101"); data.put(MONITOR_ARG, moduleStr + "." + methodStr); data.put(MONITOR_ERROR_MSG, instance.getBundleUrl()); userTrackAdapter.commit(instance.getContext(), null, IWXUserTrackAdapter.INVOKE_MODULE, null, data); } return dispatchCallModuleMethod(instance,wxModule,args,invoker); } else { WXLogUtils.e("callModuleMethod >>> instance is null"); return null; } } catch (Exception e) { WXLogUtils.e("callModuleMethod >>> invoke module:" + moduleStr + ", method:" + methodStr + " failed. ", e); return null; } finally { if (wxModule instanceof WXDomModule || wxModule instanceof WXTimerModule) { wxModule.mWXSDKInstance = null; } } } }
WXModuleManager { static Object callModuleMethod(final String instanceId, String moduleStr, String methodStr, JSONArray args) { ModuleFactory factory = sModuleFactoryMap.get(moduleStr); if(factory == null){ WXLogUtils.e("[WXModuleManager] module factory not found."); return null; } final WXModule wxModule = findModule(instanceId, moduleStr,factory); if (wxModule == null) { return null; } WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId); wxModule.mWXSDKInstance = instance; final Invoker invoker = factory.getMethodInvoker(methodStr); try { if(instance != null) { IWXUserTrackAdapter userTrackAdapter = WXSDKManager.getInstance().getIWXUserTrackAdapter(); if(userTrackAdapter != null) { HashMap<String, Serializable> data = new HashMap<String, Serializable>(); data.put(MONITOR_ERROR_CODE, "101"); data.put(MONITOR_ARG, moduleStr + "." + methodStr); data.put(MONITOR_ERROR_MSG, instance.getBundleUrl()); userTrackAdapter.commit(instance.getContext(), null, IWXUserTrackAdapter.INVOKE_MODULE, null, data); } return dispatchCallModuleMethod(instance,wxModule,args,invoker); } else { WXLogUtils.e("callModuleMethod >>> instance is null"); return null; } } catch (Exception e) { WXLogUtils.e("callModuleMethod >>> invoke module:" + moduleStr + ", method:" + methodStr + " failed. ", e); return null; } finally { if (wxModule instanceof WXDomModule || wxModule instanceof WXTimerModule) { wxModule.mWXSDKInstance = null; } } } static boolean registerModule(final String moduleName, final ModuleFactory factory, final boolean global); static void onActivityCreate(String instanceId); static void onActivityStart(String instanceId); static void onActivityPause(String instanceId); static void onActivityResume(String instanceId); static void onActivityStop(String instanceId); static void onActivityDestroy(String instanceId); static boolean onActivityBack(String instanceId); static void onActivityResult(String instanceId,int requestCode, int resultCode, Intent data); static boolean onCreateOptionsMenu(String instanceId,Menu menu); static void onRequestPermissionsResult(String instanceId ,int requestCode, String[] permissions, int[] grantResults); static void destroyInstanceModules(String instanceId); static void createDomModule(WXSDKInstance instance); static void destoryDomModule(String instanceID); static WXDomModule getDomModule(String instanceId); static void reload(); }
WXModuleManager { static Object callModuleMethod(final String instanceId, String moduleStr, String methodStr, JSONArray args) { ModuleFactory factory = sModuleFactoryMap.get(moduleStr); if(factory == null){ WXLogUtils.e("[WXModuleManager] module factory not found."); return null; } final WXModule wxModule = findModule(instanceId, moduleStr,factory); if (wxModule == null) { return null; } WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId); wxModule.mWXSDKInstance = instance; final Invoker invoker = factory.getMethodInvoker(methodStr); try { if(instance != null) { IWXUserTrackAdapter userTrackAdapter = WXSDKManager.getInstance().getIWXUserTrackAdapter(); if(userTrackAdapter != null) { HashMap<String, Serializable> data = new HashMap<String, Serializable>(); data.put(MONITOR_ERROR_CODE, "101"); data.put(MONITOR_ARG, moduleStr + "." + methodStr); data.put(MONITOR_ERROR_MSG, instance.getBundleUrl()); userTrackAdapter.commit(instance.getContext(), null, IWXUserTrackAdapter.INVOKE_MODULE, null, data); } return dispatchCallModuleMethod(instance,wxModule,args,invoker); } else { WXLogUtils.e("callModuleMethod >>> instance is null"); return null; } } catch (Exception e) { WXLogUtils.e("callModuleMethod >>> invoke module:" + moduleStr + ", method:" + methodStr + " failed. ", e); return null; } finally { if (wxModule instanceof WXDomModule || wxModule instanceof WXTimerModule) { wxModule.mWXSDKInstance = null; } } } static boolean registerModule(final String moduleName, final ModuleFactory factory, final boolean global); static void onActivityCreate(String instanceId); static void onActivityStart(String instanceId); static void onActivityPause(String instanceId); static void onActivityResume(String instanceId); static void onActivityStop(String instanceId); static void onActivityDestroy(String instanceId); static boolean onActivityBack(String instanceId); static void onActivityResult(String instanceId,int requestCode, int resultCode, Intent data); static boolean onCreateOptionsMenu(String instanceId,Menu menu); static void onRequestPermissionsResult(String instanceId ,int requestCode, String[] permissions, int[] grantResults); static void destroyInstanceModules(String instanceId); static void createDomModule(WXSDKInstance instance); static void destoryDomModule(String instanceID); static WXDomModule getDomModule(String instanceId); static void reload(); }
@Test public void testCallModuleMethod2() throws Exception { JSONArray args = new JSONArray(); args.add("testarg"); WXModuleManager.callModuleMethod(instance.getInstanceId(),"test1","testMethod",args); }
static Object callModuleMethod(final String instanceId, String moduleStr, String methodStr, JSONArray args) { ModuleFactory factory = sModuleFactoryMap.get(moduleStr); if(factory == null){ WXLogUtils.e("[WXModuleManager] module factory not found."); return null; } final WXModule wxModule = findModule(instanceId, moduleStr,factory); if (wxModule == null) { return null; } WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId); wxModule.mWXSDKInstance = instance; final Invoker invoker = factory.getMethodInvoker(methodStr); try { if(instance != null) { IWXUserTrackAdapter userTrackAdapter = WXSDKManager.getInstance().getIWXUserTrackAdapter(); if(userTrackAdapter != null) { HashMap<String, Serializable> data = new HashMap<String, Serializable>(); data.put(MONITOR_ERROR_CODE, "101"); data.put(MONITOR_ARG, moduleStr + "." + methodStr); data.put(MONITOR_ERROR_MSG, instance.getBundleUrl()); userTrackAdapter.commit(instance.getContext(), null, IWXUserTrackAdapter.INVOKE_MODULE, null, data); } return dispatchCallModuleMethod(instance,wxModule,args,invoker); } else { WXLogUtils.e("callModuleMethod >>> instance is null"); return null; } } catch (Exception e) { WXLogUtils.e("callModuleMethod >>> invoke module:" + moduleStr + ", method:" + methodStr + " failed. ", e); return null; } finally { if (wxModule instanceof WXDomModule || wxModule instanceof WXTimerModule) { wxModule.mWXSDKInstance = null; } } }
WXModuleManager { static Object callModuleMethod(final String instanceId, String moduleStr, String methodStr, JSONArray args) { ModuleFactory factory = sModuleFactoryMap.get(moduleStr); if(factory == null){ WXLogUtils.e("[WXModuleManager] module factory not found."); return null; } final WXModule wxModule = findModule(instanceId, moduleStr,factory); if (wxModule == null) { return null; } WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId); wxModule.mWXSDKInstance = instance; final Invoker invoker = factory.getMethodInvoker(methodStr); try { if(instance != null) { IWXUserTrackAdapter userTrackAdapter = WXSDKManager.getInstance().getIWXUserTrackAdapter(); if(userTrackAdapter != null) { HashMap<String, Serializable> data = new HashMap<String, Serializable>(); data.put(MONITOR_ERROR_CODE, "101"); data.put(MONITOR_ARG, moduleStr + "." + methodStr); data.put(MONITOR_ERROR_MSG, instance.getBundleUrl()); userTrackAdapter.commit(instance.getContext(), null, IWXUserTrackAdapter.INVOKE_MODULE, null, data); } return dispatchCallModuleMethod(instance,wxModule,args,invoker); } else { WXLogUtils.e("callModuleMethod >>> instance is null"); return null; } } catch (Exception e) { WXLogUtils.e("callModuleMethod >>> invoke module:" + moduleStr + ", method:" + methodStr + " failed. ", e); return null; } finally { if (wxModule instanceof WXDomModule || wxModule instanceof WXTimerModule) { wxModule.mWXSDKInstance = null; } } } }
WXModuleManager { static Object callModuleMethod(final String instanceId, String moduleStr, String methodStr, JSONArray args) { ModuleFactory factory = sModuleFactoryMap.get(moduleStr); if(factory == null){ WXLogUtils.e("[WXModuleManager] module factory not found."); return null; } final WXModule wxModule = findModule(instanceId, moduleStr,factory); if (wxModule == null) { return null; } WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId); wxModule.mWXSDKInstance = instance; final Invoker invoker = factory.getMethodInvoker(methodStr); try { if(instance != null) { IWXUserTrackAdapter userTrackAdapter = WXSDKManager.getInstance().getIWXUserTrackAdapter(); if(userTrackAdapter != null) { HashMap<String, Serializable> data = new HashMap<String, Serializable>(); data.put(MONITOR_ERROR_CODE, "101"); data.put(MONITOR_ARG, moduleStr + "." + methodStr); data.put(MONITOR_ERROR_MSG, instance.getBundleUrl()); userTrackAdapter.commit(instance.getContext(), null, IWXUserTrackAdapter.INVOKE_MODULE, null, data); } return dispatchCallModuleMethod(instance,wxModule,args,invoker); } else { WXLogUtils.e("callModuleMethod >>> instance is null"); return null; } } catch (Exception e) { WXLogUtils.e("callModuleMethod >>> invoke module:" + moduleStr + ", method:" + methodStr + " failed. ", e); return null; } finally { if (wxModule instanceof WXDomModule || wxModule instanceof WXTimerModule) { wxModule.mWXSDKInstance = null; } } } }
WXModuleManager { static Object callModuleMethod(final String instanceId, String moduleStr, String methodStr, JSONArray args) { ModuleFactory factory = sModuleFactoryMap.get(moduleStr); if(factory == null){ WXLogUtils.e("[WXModuleManager] module factory not found."); return null; } final WXModule wxModule = findModule(instanceId, moduleStr,factory); if (wxModule == null) { return null; } WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId); wxModule.mWXSDKInstance = instance; final Invoker invoker = factory.getMethodInvoker(methodStr); try { if(instance != null) { IWXUserTrackAdapter userTrackAdapter = WXSDKManager.getInstance().getIWXUserTrackAdapter(); if(userTrackAdapter != null) { HashMap<String, Serializable> data = new HashMap<String, Serializable>(); data.put(MONITOR_ERROR_CODE, "101"); data.put(MONITOR_ARG, moduleStr + "." + methodStr); data.put(MONITOR_ERROR_MSG, instance.getBundleUrl()); userTrackAdapter.commit(instance.getContext(), null, IWXUserTrackAdapter.INVOKE_MODULE, null, data); } return dispatchCallModuleMethod(instance,wxModule,args,invoker); } else { WXLogUtils.e("callModuleMethod >>> instance is null"); return null; } } catch (Exception e) { WXLogUtils.e("callModuleMethod >>> invoke module:" + moduleStr + ", method:" + methodStr + " failed. ", e); return null; } finally { if (wxModule instanceof WXDomModule || wxModule instanceof WXTimerModule) { wxModule.mWXSDKInstance = null; } } } static boolean registerModule(final String moduleName, final ModuleFactory factory, final boolean global); static void onActivityCreate(String instanceId); static void onActivityStart(String instanceId); static void onActivityPause(String instanceId); static void onActivityResume(String instanceId); static void onActivityStop(String instanceId); static void onActivityDestroy(String instanceId); static boolean onActivityBack(String instanceId); static void onActivityResult(String instanceId,int requestCode, int resultCode, Intent data); static boolean onCreateOptionsMenu(String instanceId,Menu menu); static void onRequestPermissionsResult(String instanceId ,int requestCode, String[] permissions, int[] grantResults); static void destroyInstanceModules(String instanceId); static void createDomModule(WXSDKInstance instance); static void destoryDomModule(String instanceID); static WXDomModule getDomModule(String instanceId); static void reload(); }
WXModuleManager { static Object callModuleMethod(final String instanceId, String moduleStr, String methodStr, JSONArray args) { ModuleFactory factory = sModuleFactoryMap.get(moduleStr); if(factory == null){ WXLogUtils.e("[WXModuleManager] module factory not found."); return null; } final WXModule wxModule = findModule(instanceId, moduleStr,factory); if (wxModule == null) { return null; } WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId); wxModule.mWXSDKInstance = instance; final Invoker invoker = factory.getMethodInvoker(methodStr); try { if(instance != null) { IWXUserTrackAdapter userTrackAdapter = WXSDKManager.getInstance().getIWXUserTrackAdapter(); if(userTrackAdapter != null) { HashMap<String, Serializable> data = new HashMap<String, Serializable>(); data.put(MONITOR_ERROR_CODE, "101"); data.put(MONITOR_ARG, moduleStr + "." + methodStr); data.put(MONITOR_ERROR_MSG, instance.getBundleUrl()); userTrackAdapter.commit(instance.getContext(), null, IWXUserTrackAdapter.INVOKE_MODULE, null, data); } return dispatchCallModuleMethod(instance,wxModule,args,invoker); } else { WXLogUtils.e("callModuleMethod >>> instance is null"); return null; } } catch (Exception e) { WXLogUtils.e("callModuleMethod >>> invoke module:" + moduleStr + ", method:" + methodStr + " failed. ", e); return null; } finally { if (wxModule instanceof WXDomModule || wxModule instanceof WXTimerModule) { wxModule.mWXSDKInstance = null; } } } static boolean registerModule(final String moduleName, final ModuleFactory factory, final boolean global); static void onActivityCreate(String instanceId); static void onActivityStart(String instanceId); static void onActivityPause(String instanceId); static void onActivityResume(String instanceId); static void onActivityStop(String instanceId); static void onActivityDestroy(String instanceId); static boolean onActivityBack(String instanceId); static void onActivityResult(String instanceId,int requestCode, int resultCode, Intent data); static boolean onCreateOptionsMenu(String instanceId,Menu menu); static void onRequestPermissionsResult(String instanceId ,int requestCode, String[] permissions, int[] grantResults); static void destroyInstanceModules(String instanceId); static void createDomModule(WXSDKInstance instance); static void destoryDomModule(String instanceID); static WXDomModule getDomModule(String instanceId); static void reload(); }
@Test public void testCallModuleMethod3() throws Exception { JSONArray args = new JSONArray(); args.add("testarg"); args.add(null); WXModuleManager.callModuleMethod(instance.getInstanceId(),"test1","testCallbackMethod",args); }
static Object callModuleMethod(final String instanceId, String moduleStr, String methodStr, JSONArray args) { ModuleFactory factory = sModuleFactoryMap.get(moduleStr); if(factory == null){ WXLogUtils.e("[WXModuleManager] module factory not found."); return null; } final WXModule wxModule = findModule(instanceId, moduleStr,factory); if (wxModule == null) { return null; } WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId); wxModule.mWXSDKInstance = instance; final Invoker invoker = factory.getMethodInvoker(methodStr); try { if(instance != null) { IWXUserTrackAdapter userTrackAdapter = WXSDKManager.getInstance().getIWXUserTrackAdapter(); if(userTrackAdapter != null) { HashMap<String, Serializable> data = new HashMap<String, Serializable>(); data.put(MONITOR_ERROR_CODE, "101"); data.put(MONITOR_ARG, moduleStr + "." + methodStr); data.put(MONITOR_ERROR_MSG, instance.getBundleUrl()); userTrackAdapter.commit(instance.getContext(), null, IWXUserTrackAdapter.INVOKE_MODULE, null, data); } return dispatchCallModuleMethod(instance,wxModule,args,invoker); } else { WXLogUtils.e("callModuleMethod >>> instance is null"); return null; } } catch (Exception e) { WXLogUtils.e("callModuleMethod >>> invoke module:" + moduleStr + ", method:" + methodStr + " failed. ", e); return null; } finally { if (wxModule instanceof WXDomModule || wxModule instanceof WXTimerModule) { wxModule.mWXSDKInstance = null; } } }
WXModuleManager { static Object callModuleMethod(final String instanceId, String moduleStr, String methodStr, JSONArray args) { ModuleFactory factory = sModuleFactoryMap.get(moduleStr); if(factory == null){ WXLogUtils.e("[WXModuleManager] module factory not found."); return null; } final WXModule wxModule = findModule(instanceId, moduleStr,factory); if (wxModule == null) { return null; } WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId); wxModule.mWXSDKInstance = instance; final Invoker invoker = factory.getMethodInvoker(methodStr); try { if(instance != null) { IWXUserTrackAdapter userTrackAdapter = WXSDKManager.getInstance().getIWXUserTrackAdapter(); if(userTrackAdapter != null) { HashMap<String, Serializable> data = new HashMap<String, Serializable>(); data.put(MONITOR_ERROR_CODE, "101"); data.put(MONITOR_ARG, moduleStr + "." + methodStr); data.put(MONITOR_ERROR_MSG, instance.getBundleUrl()); userTrackAdapter.commit(instance.getContext(), null, IWXUserTrackAdapter.INVOKE_MODULE, null, data); } return dispatchCallModuleMethod(instance,wxModule,args,invoker); } else { WXLogUtils.e("callModuleMethod >>> instance is null"); return null; } } catch (Exception e) { WXLogUtils.e("callModuleMethod >>> invoke module:" + moduleStr + ", method:" + methodStr + " failed. ", e); return null; } finally { if (wxModule instanceof WXDomModule || wxModule instanceof WXTimerModule) { wxModule.mWXSDKInstance = null; } } } }
WXModuleManager { static Object callModuleMethod(final String instanceId, String moduleStr, String methodStr, JSONArray args) { ModuleFactory factory = sModuleFactoryMap.get(moduleStr); if(factory == null){ WXLogUtils.e("[WXModuleManager] module factory not found."); return null; } final WXModule wxModule = findModule(instanceId, moduleStr,factory); if (wxModule == null) { return null; } WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId); wxModule.mWXSDKInstance = instance; final Invoker invoker = factory.getMethodInvoker(methodStr); try { if(instance != null) { IWXUserTrackAdapter userTrackAdapter = WXSDKManager.getInstance().getIWXUserTrackAdapter(); if(userTrackAdapter != null) { HashMap<String, Serializable> data = new HashMap<String, Serializable>(); data.put(MONITOR_ERROR_CODE, "101"); data.put(MONITOR_ARG, moduleStr + "." + methodStr); data.put(MONITOR_ERROR_MSG, instance.getBundleUrl()); userTrackAdapter.commit(instance.getContext(), null, IWXUserTrackAdapter.INVOKE_MODULE, null, data); } return dispatchCallModuleMethod(instance,wxModule,args,invoker); } else { WXLogUtils.e("callModuleMethod >>> instance is null"); return null; } } catch (Exception e) { WXLogUtils.e("callModuleMethod >>> invoke module:" + moduleStr + ", method:" + methodStr + " failed. ", e); return null; } finally { if (wxModule instanceof WXDomModule || wxModule instanceof WXTimerModule) { wxModule.mWXSDKInstance = null; } } } }
WXModuleManager { static Object callModuleMethod(final String instanceId, String moduleStr, String methodStr, JSONArray args) { ModuleFactory factory = sModuleFactoryMap.get(moduleStr); if(factory == null){ WXLogUtils.e("[WXModuleManager] module factory not found."); return null; } final WXModule wxModule = findModule(instanceId, moduleStr,factory); if (wxModule == null) { return null; } WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId); wxModule.mWXSDKInstance = instance; final Invoker invoker = factory.getMethodInvoker(methodStr); try { if(instance != null) { IWXUserTrackAdapter userTrackAdapter = WXSDKManager.getInstance().getIWXUserTrackAdapter(); if(userTrackAdapter != null) { HashMap<String, Serializable> data = new HashMap<String, Serializable>(); data.put(MONITOR_ERROR_CODE, "101"); data.put(MONITOR_ARG, moduleStr + "." + methodStr); data.put(MONITOR_ERROR_MSG, instance.getBundleUrl()); userTrackAdapter.commit(instance.getContext(), null, IWXUserTrackAdapter.INVOKE_MODULE, null, data); } return dispatchCallModuleMethod(instance,wxModule,args,invoker); } else { WXLogUtils.e("callModuleMethod >>> instance is null"); return null; } } catch (Exception e) { WXLogUtils.e("callModuleMethod >>> invoke module:" + moduleStr + ", method:" + methodStr + " failed. ", e); return null; } finally { if (wxModule instanceof WXDomModule || wxModule instanceof WXTimerModule) { wxModule.mWXSDKInstance = null; } } } static boolean registerModule(final String moduleName, final ModuleFactory factory, final boolean global); static void onActivityCreate(String instanceId); static void onActivityStart(String instanceId); static void onActivityPause(String instanceId); static void onActivityResume(String instanceId); static void onActivityStop(String instanceId); static void onActivityDestroy(String instanceId); static boolean onActivityBack(String instanceId); static void onActivityResult(String instanceId,int requestCode, int resultCode, Intent data); static boolean onCreateOptionsMenu(String instanceId,Menu menu); static void onRequestPermissionsResult(String instanceId ,int requestCode, String[] permissions, int[] grantResults); static void destroyInstanceModules(String instanceId); static void createDomModule(WXSDKInstance instance); static void destoryDomModule(String instanceID); static WXDomModule getDomModule(String instanceId); static void reload(); }
WXModuleManager { static Object callModuleMethod(final String instanceId, String moduleStr, String methodStr, JSONArray args) { ModuleFactory factory = sModuleFactoryMap.get(moduleStr); if(factory == null){ WXLogUtils.e("[WXModuleManager] module factory not found."); return null; } final WXModule wxModule = findModule(instanceId, moduleStr,factory); if (wxModule == null) { return null; } WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId); wxModule.mWXSDKInstance = instance; final Invoker invoker = factory.getMethodInvoker(methodStr); try { if(instance != null) { IWXUserTrackAdapter userTrackAdapter = WXSDKManager.getInstance().getIWXUserTrackAdapter(); if(userTrackAdapter != null) { HashMap<String, Serializable> data = new HashMap<String, Serializable>(); data.put(MONITOR_ERROR_CODE, "101"); data.put(MONITOR_ARG, moduleStr + "." + methodStr); data.put(MONITOR_ERROR_MSG, instance.getBundleUrl()); userTrackAdapter.commit(instance.getContext(), null, IWXUserTrackAdapter.INVOKE_MODULE, null, data); } return dispatchCallModuleMethod(instance,wxModule,args,invoker); } else { WXLogUtils.e("callModuleMethod >>> instance is null"); return null; } } catch (Exception e) { WXLogUtils.e("callModuleMethod >>> invoke module:" + moduleStr + ", method:" + methodStr + " failed. ", e); return null; } finally { if (wxModule instanceof WXDomModule || wxModule instanceof WXTimerModule) { wxModule.mWXSDKInstance = null; } } } static boolean registerModule(final String moduleName, final ModuleFactory factory, final boolean global); static void onActivityCreate(String instanceId); static void onActivityStart(String instanceId); static void onActivityPause(String instanceId); static void onActivityResume(String instanceId); static void onActivityStop(String instanceId); static void onActivityDestroy(String instanceId); static boolean onActivityBack(String instanceId); static void onActivityResult(String instanceId,int requestCode, int resultCode, Intent data); static boolean onCreateOptionsMenu(String instanceId,Menu menu); static void onRequestPermissionsResult(String instanceId ,int requestCode, String[] permissions, int[] grantResults); static void destroyInstanceModules(String instanceId); static void createDomModule(WXSDKInstance instance); static void destoryDomModule(String instanceID); static WXDomModule getDomModule(String instanceId); static void reload(); }
@Test public void testCallModuleMethod4() throws Exception { JSONArray args = new JSONArray(); args.add("testarg"); args.add("testcallbackId"); WXModuleManager.callModuleMethod(instance.getInstanceId(),"test1","testCallbackMethod",args); }
static Object callModuleMethod(final String instanceId, String moduleStr, String methodStr, JSONArray args) { ModuleFactory factory = sModuleFactoryMap.get(moduleStr); if(factory == null){ WXLogUtils.e("[WXModuleManager] module factory not found."); return null; } final WXModule wxModule = findModule(instanceId, moduleStr,factory); if (wxModule == null) { return null; } WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId); wxModule.mWXSDKInstance = instance; final Invoker invoker = factory.getMethodInvoker(methodStr); try { if(instance != null) { IWXUserTrackAdapter userTrackAdapter = WXSDKManager.getInstance().getIWXUserTrackAdapter(); if(userTrackAdapter != null) { HashMap<String, Serializable> data = new HashMap<String, Serializable>(); data.put(MONITOR_ERROR_CODE, "101"); data.put(MONITOR_ARG, moduleStr + "." + methodStr); data.put(MONITOR_ERROR_MSG, instance.getBundleUrl()); userTrackAdapter.commit(instance.getContext(), null, IWXUserTrackAdapter.INVOKE_MODULE, null, data); } return dispatchCallModuleMethod(instance,wxModule,args,invoker); } else { WXLogUtils.e("callModuleMethod >>> instance is null"); return null; } } catch (Exception e) { WXLogUtils.e("callModuleMethod >>> invoke module:" + moduleStr + ", method:" + methodStr + " failed. ", e); return null; } finally { if (wxModule instanceof WXDomModule || wxModule instanceof WXTimerModule) { wxModule.mWXSDKInstance = null; } } }
WXModuleManager { static Object callModuleMethod(final String instanceId, String moduleStr, String methodStr, JSONArray args) { ModuleFactory factory = sModuleFactoryMap.get(moduleStr); if(factory == null){ WXLogUtils.e("[WXModuleManager] module factory not found."); return null; } final WXModule wxModule = findModule(instanceId, moduleStr,factory); if (wxModule == null) { return null; } WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId); wxModule.mWXSDKInstance = instance; final Invoker invoker = factory.getMethodInvoker(methodStr); try { if(instance != null) { IWXUserTrackAdapter userTrackAdapter = WXSDKManager.getInstance().getIWXUserTrackAdapter(); if(userTrackAdapter != null) { HashMap<String, Serializable> data = new HashMap<String, Serializable>(); data.put(MONITOR_ERROR_CODE, "101"); data.put(MONITOR_ARG, moduleStr + "." + methodStr); data.put(MONITOR_ERROR_MSG, instance.getBundleUrl()); userTrackAdapter.commit(instance.getContext(), null, IWXUserTrackAdapter.INVOKE_MODULE, null, data); } return dispatchCallModuleMethod(instance,wxModule,args,invoker); } else { WXLogUtils.e("callModuleMethod >>> instance is null"); return null; } } catch (Exception e) { WXLogUtils.e("callModuleMethod >>> invoke module:" + moduleStr + ", method:" + methodStr + " failed. ", e); return null; } finally { if (wxModule instanceof WXDomModule || wxModule instanceof WXTimerModule) { wxModule.mWXSDKInstance = null; } } } }
WXModuleManager { static Object callModuleMethod(final String instanceId, String moduleStr, String methodStr, JSONArray args) { ModuleFactory factory = sModuleFactoryMap.get(moduleStr); if(factory == null){ WXLogUtils.e("[WXModuleManager] module factory not found."); return null; } final WXModule wxModule = findModule(instanceId, moduleStr,factory); if (wxModule == null) { return null; } WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId); wxModule.mWXSDKInstance = instance; final Invoker invoker = factory.getMethodInvoker(methodStr); try { if(instance != null) { IWXUserTrackAdapter userTrackAdapter = WXSDKManager.getInstance().getIWXUserTrackAdapter(); if(userTrackAdapter != null) { HashMap<String, Serializable> data = new HashMap<String, Serializable>(); data.put(MONITOR_ERROR_CODE, "101"); data.put(MONITOR_ARG, moduleStr + "." + methodStr); data.put(MONITOR_ERROR_MSG, instance.getBundleUrl()); userTrackAdapter.commit(instance.getContext(), null, IWXUserTrackAdapter.INVOKE_MODULE, null, data); } return dispatchCallModuleMethod(instance,wxModule,args,invoker); } else { WXLogUtils.e("callModuleMethod >>> instance is null"); return null; } } catch (Exception e) { WXLogUtils.e("callModuleMethod >>> invoke module:" + moduleStr + ", method:" + methodStr + " failed. ", e); return null; } finally { if (wxModule instanceof WXDomModule || wxModule instanceof WXTimerModule) { wxModule.mWXSDKInstance = null; } } } }
WXModuleManager { static Object callModuleMethod(final String instanceId, String moduleStr, String methodStr, JSONArray args) { ModuleFactory factory = sModuleFactoryMap.get(moduleStr); if(factory == null){ WXLogUtils.e("[WXModuleManager] module factory not found."); return null; } final WXModule wxModule = findModule(instanceId, moduleStr,factory); if (wxModule == null) { return null; } WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId); wxModule.mWXSDKInstance = instance; final Invoker invoker = factory.getMethodInvoker(methodStr); try { if(instance != null) { IWXUserTrackAdapter userTrackAdapter = WXSDKManager.getInstance().getIWXUserTrackAdapter(); if(userTrackAdapter != null) { HashMap<String, Serializable> data = new HashMap<String, Serializable>(); data.put(MONITOR_ERROR_CODE, "101"); data.put(MONITOR_ARG, moduleStr + "." + methodStr); data.put(MONITOR_ERROR_MSG, instance.getBundleUrl()); userTrackAdapter.commit(instance.getContext(), null, IWXUserTrackAdapter.INVOKE_MODULE, null, data); } return dispatchCallModuleMethod(instance,wxModule,args,invoker); } else { WXLogUtils.e("callModuleMethod >>> instance is null"); return null; } } catch (Exception e) { WXLogUtils.e("callModuleMethod >>> invoke module:" + moduleStr + ", method:" + methodStr + " failed. ", e); return null; } finally { if (wxModule instanceof WXDomModule || wxModule instanceof WXTimerModule) { wxModule.mWXSDKInstance = null; } } } static boolean registerModule(final String moduleName, final ModuleFactory factory, final boolean global); static void onActivityCreate(String instanceId); static void onActivityStart(String instanceId); static void onActivityPause(String instanceId); static void onActivityResume(String instanceId); static void onActivityStop(String instanceId); static void onActivityDestroy(String instanceId); static boolean onActivityBack(String instanceId); static void onActivityResult(String instanceId,int requestCode, int resultCode, Intent data); static boolean onCreateOptionsMenu(String instanceId,Menu menu); static void onRequestPermissionsResult(String instanceId ,int requestCode, String[] permissions, int[] grantResults); static void destroyInstanceModules(String instanceId); static void createDomModule(WXSDKInstance instance); static void destoryDomModule(String instanceID); static WXDomModule getDomModule(String instanceId); static void reload(); }
WXModuleManager { static Object callModuleMethod(final String instanceId, String moduleStr, String methodStr, JSONArray args) { ModuleFactory factory = sModuleFactoryMap.get(moduleStr); if(factory == null){ WXLogUtils.e("[WXModuleManager] module factory not found."); return null; } final WXModule wxModule = findModule(instanceId, moduleStr,factory); if (wxModule == null) { return null; } WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId); wxModule.mWXSDKInstance = instance; final Invoker invoker = factory.getMethodInvoker(methodStr); try { if(instance != null) { IWXUserTrackAdapter userTrackAdapter = WXSDKManager.getInstance().getIWXUserTrackAdapter(); if(userTrackAdapter != null) { HashMap<String, Serializable> data = new HashMap<String, Serializable>(); data.put(MONITOR_ERROR_CODE, "101"); data.put(MONITOR_ARG, moduleStr + "." + methodStr); data.put(MONITOR_ERROR_MSG, instance.getBundleUrl()); userTrackAdapter.commit(instance.getContext(), null, IWXUserTrackAdapter.INVOKE_MODULE, null, data); } return dispatchCallModuleMethod(instance,wxModule,args,invoker); } else { WXLogUtils.e("callModuleMethod >>> instance is null"); return null; } } catch (Exception e) { WXLogUtils.e("callModuleMethod >>> invoke module:" + moduleStr + ", method:" + methodStr + " failed. ", e); return null; } finally { if (wxModule instanceof WXDomModule || wxModule instanceof WXTimerModule) { wxModule.mWXSDKInstance = null; } } } static boolean registerModule(final String moduleName, final ModuleFactory factory, final boolean global); static void onActivityCreate(String instanceId); static void onActivityStart(String instanceId); static void onActivityPause(String instanceId); static void onActivityResume(String instanceId); static void onActivityStop(String instanceId); static void onActivityDestroy(String instanceId); static boolean onActivityBack(String instanceId); static void onActivityResult(String instanceId,int requestCode, int resultCode, Intent data); static boolean onCreateOptionsMenu(String instanceId,Menu menu); static void onRequestPermissionsResult(String instanceId ,int requestCode, String[] permissions, int[] grantResults); static void destroyInstanceModules(String instanceId); static void createDomModule(WXSDKInstance instance); static void destoryDomModule(String instanceID); static WXDomModule getDomModule(String instanceId); static void reload(); }
@Test public void testDestroyInstanceModules() throws Exception { testCallModuleMethod(); WXModuleManager.destroyInstanceModules(instance.getInstanceId()); }
public static void destroyInstanceModules(String instanceId) { sDomModuleMap.remove(instanceId); Map<String, WXModule> moduleMap = sInstanceModuleMap.remove(instanceId); if (moduleMap == null || moduleMap.size() < 1) { return; } Iterator<Entry<String, WXModule>> iterator = moduleMap.entrySet().iterator(); Entry<String, WXModule> entry; while (iterator.hasNext()) { entry = iterator.next(); WXModule module = entry.getValue(); if(module instanceof Destroyable){ ((Destroyable)module).destroy(); } } }
WXModuleManager { public static void destroyInstanceModules(String instanceId) { sDomModuleMap.remove(instanceId); Map<String, WXModule> moduleMap = sInstanceModuleMap.remove(instanceId); if (moduleMap == null || moduleMap.size() < 1) { return; } Iterator<Entry<String, WXModule>> iterator = moduleMap.entrySet().iterator(); Entry<String, WXModule> entry; while (iterator.hasNext()) { entry = iterator.next(); WXModule module = entry.getValue(); if(module instanceof Destroyable){ ((Destroyable)module).destroy(); } } } }
WXModuleManager { public static void destroyInstanceModules(String instanceId) { sDomModuleMap.remove(instanceId); Map<String, WXModule> moduleMap = sInstanceModuleMap.remove(instanceId); if (moduleMap == null || moduleMap.size() < 1) { return; } Iterator<Entry<String, WXModule>> iterator = moduleMap.entrySet().iterator(); Entry<String, WXModule> entry; while (iterator.hasNext()) { entry = iterator.next(); WXModule module = entry.getValue(); if(module instanceof Destroyable){ ((Destroyable)module).destroy(); } } } }
WXModuleManager { public static void destroyInstanceModules(String instanceId) { sDomModuleMap.remove(instanceId); Map<String, WXModule> moduleMap = sInstanceModuleMap.remove(instanceId); if (moduleMap == null || moduleMap.size() < 1) { return; } Iterator<Entry<String, WXModule>> iterator = moduleMap.entrySet().iterator(); Entry<String, WXModule> entry; while (iterator.hasNext()) { entry = iterator.next(); WXModule module = entry.getValue(); if(module instanceof Destroyable){ ((Destroyable)module).destroy(); } } } static boolean registerModule(final String moduleName, final ModuleFactory factory, final boolean global); static void onActivityCreate(String instanceId); static void onActivityStart(String instanceId); static void onActivityPause(String instanceId); static void onActivityResume(String instanceId); static void onActivityStop(String instanceId); static void onActivityDestroy(String instanceId); static boolean onActivityBack(String instanceId); static void onActivityResult(String instanceId,int requestCode, int resultCode, Intent data); static boolean onCreateOptionsMenu(String instanceId,Menu menu); static void onRequestPermissionsResult(String instanceId ,int requestCode, String[] permissions, int[] grantResults); static void destroyInstanceModules(String instanceId); static void createDomModule(WXSDKInstance instance); static void destoryDomModule(String instanceID); static WXDomModule getDomModule(String instanceId); static void reload(); }
WXModuleManager { public static void destroyInstanceModules(String instanceId) { sDomModuleMap.remove(instanceId); Map<String, WXModule> moduleMap = sInstanceModuleMap.remove(instanceId); if (moduleMap == null || moduleMap.size() < 1) { return; } Iterator<Entry<String, WXModule>> iterator = moduleMap.entrySet().iterator(); Entry<String, WXModule> entry; while (iterator.hasNext()) { entry = iterator.next(); WXModule module = entry.getValue(); if(module instanceof Destroyable){ ((Destroyable)module).destroy(); } } } static boolean registerModule(final String moduleName, final ModuleFactory factory, final boolean global); static void onActivityCreate(String instanceId); static void onActivityStart(String instanceId); static void onActivityPause(String instanceId); static void onActivityResume(String instanceId); static void onActivityStop(String instanceId); static void onActivityDestroy(String instanceId); static boolean onActivityBack(String instanceId); static void onActivityResult(String instanceId,int requestCode, int resultCode, Intent data); static boolean onCreateOptionsMenu(String instanceId,Menu menu); static void onRequestPermissionsResult(String instanceId ,int requestCode, String[] permissions, int[] grantResults); static void destroyInstanceModules(String instanceId); static void createDomModule(WXSDKInstance instance); static void destoryDomModule(String instanceID); static WXDomModule getDomModule(String instanceId); static void reload(); }
@Test public void testRender() throws Exception { assertEquals(WXFileUtils.loadAsset(null,null),"{}"); mInstance.render("{}",null,null,null); }
public void render(String template, Map<String, Object> options, String jsonInitData) { render(template, options, jsonInitData, WXRenderStrategy.APPEND_ASYNC); }
WXSDKInstance implements IWXActivityStateListener,DomContext, View.OnLayoutChangeListener { public void render(String template, Map<String, Object> options, String jsonInitData) { render(template, options, jsonInitData, WXRenderStrategy.APPEND_ASYNC); } }
WXSDKInstance implements IWXActivityStateListener,DomContext, View.OnLayoutChangeListener { public void render(String template, Map<String, Object> options, String jsonInitData) { render(template, options, jsonInitData, WXRenderStrategy.APPEND_ASYNC); } WXSDKInstance(Context context); WXSDKInstance(Context context,String id); }
WXSDKInstance implements IWXActivityStateListener,DomContext, View.OnLayoutChangeListener { public void render(String template, Map<String, Object> options, String jsonInitData) { render(template, options, jsonInitData, WXRenderStrategy.APPEND_ASYNC); } 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); }
WXSDKInstance implements IWXActivityStateListener,DomContext, View.OnLayoutChangeListener { public void render(String template, Map<String, Object> options, String jsonInitData) { render(template, options, jsonInitData, WXRenderStrategy.APPEND_ASYNC); } 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 testPush() throws Exception { module.push("{}",callback); module.push("{'url':'kdkdkdkdkd'}",callback); mockSetter(); module.push("{}",callback); }
@JSMethod(uiThread = true) public void push(String param, JSCallback callback) { if (!TextUtils.isEmpty(param)) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().push(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } try { JSONObject jsonObject = JSON.parseObject(param); String url = jsonObject.getString(URL); if (!TextUtils.isEmpty(url)) { Uri rawUri = Uri.parse(url); String scheme = rawUri.getScheme(); Uri.Builder builder = rawUri.buildUpon(); if (TextUtils.isEmpty(scheme)) { builder.scheme(Constants.Scheme.HTTP); } Intent intent = new Intent(Intent.ACTION_VIEW, builder.build()); intent.addCategory(WEEX); intent.putExtra(INSTANCE_ID, mWXSDKInstance.getInstanceId()); mWXSDKInstance.getContext().startActivity(intent); if (callback != null) { callback.invoke(MSG_SUCCESS); } } } catch (Exception e) { WXLogUtils.eTag(TAG, e); if (callback != null) { callback.invoke(MSG_FAILED); } } } else if (callback != null) { callback.invoke(MSG_FAILED); } }
WXNavigatorModule extends WXModule { @JSMethod(uiThread = true) public void push(String param, JSCallback callback) { if (!TextUtils.isEmpty(param)) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().push(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } try { JSONObject jsonObject = JSON.parseObject(param); String url = jsonObject.getString(URL); if (!TextUtils.isEmpty(url)) { Uri rawUri = Uri.parse(url); String scheme = rawUri.getScheme(); Uri.Builder builder = rawUri.buildUpon(); if (TextUtils.isEmpty(scheme)) { builder.scheme(Constants.Scheme.HTTP); } Intent intent = new Intent(Intent.ACTION_VIEW, builder.build()); intent.addCategory(WEEX); intent.putExtra(INSTANCE_ID, mWXSDKInstance.getInstanceId()); mWXSDKInstance.getContext().startActivity(intent); if (callback != null) { callback.invoke(MSG_SUCCESS); } } } catch (Exception e) { WXLogUtils.eTag(TAG, e); if (callback != null) { callback.invoke(MSG_FAILED); } } } else if (callback != null) { callback.invoke(MSG_FAILED); } } }
WXNavigatorModule extends WXModule { @JSMethod(uiThread = true) public void push(String param, JSCallback callback) { if (!TextUtils.isEmpty(param)) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().push(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } try { JSONObject jsonObject = JSON.parseObject(param); String url = jsonObject.getString(URL); if (!TextUtils.isEmpty(url)) { Uri rawUri = Uri.parse(url); String scheme = rawUri.getScheme(); Uri.Builder builder = rawUri.buildUpon(); if (TextUtils.isEmpty(scheme)) { builder.scheme(Constants.Scheme.HTTP); } Intent intent = new Intent(Intent.ACTION_VIEW, builder.build()); intent.addCategory(WEEX); intent.putExtra(INSTANCE_ID, mWXSDKInstance.getInstanceId()); mWXSDKInstance.getContext().startActivity(intent); if (callback != null) { callback.invoke(MSG_SUCCESS); } } } catch (Exception e) { WXLogUtils.eTag(TAG, e); if (callback != null) { callback.invoke(MSG_FAILED); } } } else if (callback != null) { callback.invoke(MSG_FAILED); } } }
WXNavigatorModule extends WXModule { @JSMethod(uiThread = true) public void push(String param, JSCallback callback) { if (!TextUtils.isEmpty(param)) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().push(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } try { JSONObject jsonObject = JSON.parseObject(param); String url = jsonObject.getString(URL); if (!TextUtils.isEmpty(url)) { Uri rawUri = Uri.parse(url); String scheme = rawUri.getScheme(); Uri.Builder builder = rawUri.buildUpon(); if (TextUtils.isEmpty(scheme)) { builder.scheme(Constants.Scheme.HTTP); } Intent intent = new Intent(Intent.ACTION_VIEW, builder.build()); intent.addCategory(WEEX); intent.putExtra(INSTANCE_ID, mWXSDKInstance.getInstanceId()); mWXSDKInstance.getContext().startActivity(intent); if (callback != null) { callback.invoke(MSG_SUCCESS); } } } catch (Exception e) { WXLogUtils.eTag(TAG, e); if (callback != null) { callback.invoke(MSG_FAILED); } } } else if (callback != null) { callback.invoke(MSG_FAILED); } } @JSMethod(uiThread = true) void open(JSONObject options, JSCallback success, JSCallback failure); @JSMethod(uiThread = true) void close(JSONObject options, JSCallback success, JSCallback failure); @JSMethod(uiThread = true) void push(String param, JSCallback callback); @JSMethod(uiThread = true) void pop(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarRightItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarRightItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarLeftItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarLeftItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarMoreItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarMoreItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarTitle(String param, JSCallback callback); @JSMethod void setNavBarHidden(String param, final String callback); }
WXNavigatorModule extends WXModule { @JSMethod(uiThread = true) public void push(String param, JSCallback callback) { if (!TextUtils.isEmpty(param)) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().push(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } try { JSONObject jsonObject = JSON.parseObject(param); String url = jsonObject.getString(URL); if (!TextUtils.isEmpty(url)) { Uri rawUri = Uri.parse(url); String scheme = rawUri.getScheme(); Uri.Builder builder = rawUri.buildUpon(); if (TextUtils.isEmpty(scheme)) { builder.scheme(Constants.Scheme.HTTP); } Intent intent = new Intent(Intent.ACTION_VIEW, builder.build()); intent.addCategory(WEEX); intent.putExtra(INSTANCE_ID, mWXSDKInstance.getInstanceId()); mWXSDKInstance.getContext().startActivity(intent); if (callback != null) { callback.invoke(MSG_SUCCESS); } } } catch (Exception e) { WXLogUtils.eTag(TAG, e); if (callback != null) { callback.invoke(MSG_FAILED); } } } else if (callback != null) { callback.invoke(MSG_FAILED); } } @JSMethod(uiThread = true) void open(JSONObject options, JSCallback success, JSCallback failure); @JSMethod(uiThread = true) void close(JSONObject options, JSCallback success, JSCallback failure); @JSMethod(uiThread = true) void push(String param, JSCallback callback); @JSMethod(uiThread = true) void pop(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarRightItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarRightItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarLeftItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarLeftItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarMoreItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarMoreItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarTitle(String param, JSCallback callback); @JSMethod void setNavBarHidden(String param, final String callback); static final String MSG_SUCCESS; static final String MSG_FAILED; static final String MSG_PARAM_ERR; static final String CALLBACK_RESULT; static final String CALLBACK_MESSAGE; }
@Test public void testPop() throws Exception { mockSetter(); module.pop("{}",callback); }
@JSMethod(uiThread = true) public void pop(String param, JSCallback callback) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().pop(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } if (mWXSDKInstance.getContext() instanceof Activity) { if (callback != null) { callback.invoke(MSG_SUCCESS); } ((Activity) mWXSDKInstance.getContext()).finish(); } }
WXNavigatorModule extends WXModule { @JSMethod(uiThread = true) public void pop(String param, JSCallback callback) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().pop(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } if (mWXSDKInstance.getContext() instanceof Activity) { if (callback != null) { callback.invoke(MSG_SUCCESS); } ((Activity) mWXSDKInstance.getContext()).finish(); } } }
WXNavigatorModule extends WXModule { @JSMethod(uiThread = true) public void pop(String param, JSCallback callback) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().pop(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } if (mWXSDKInstance.getContext() instanceof Activity) { if (callback != null) { callback.invoke(MSG_SUCCESS); } ((Activity) mWXSDKInstance.getContext()).finish(); } } }
WXNavigatorModule extends WXModule { @JSMethod(uiThread = true) public void pop(String param, JSCallback callback) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().pop(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } if (mWXSDKInstance.getContext() instanceof Activity) { if (callback != null) { callback.invoke(MSG_SUCCESS); } ((Activity) mWXSDKInstance.getContext()).finish(); } } @JSMethod(uiThread = true) void open(JSONObject options, JSCallback success, JSCallback failure); @JSMethod(uiThread = true) void close(JSONObject options, JSCallback success, JSCallback failure); @JSMethod(uiThread = true) void push(String param, JSCallback callback); @JSMethod(uiThread = true) void pop(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarRightItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarRightItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarLeftItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarLeftItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarMoreItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarMoreItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarTitle(String param, JSCallback callback); @JSMethod void setNavBarHidden(String param, final String callback); }
WXNavigatorModule extends WXModule { @JSMethod(uiThread = true) public void pop(String param, JSCallback callback) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().pop(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } if (mWXSDKInstance.getContext() instanceof Activity) { if (callback != null) { callback.invoke(MSG_SUCCESS); } ((Activity) mWXSDKInstance.getContext()).finish(); } } @JSMethod(uiThread = true) void open(JSONObject options, JSCallback success, JSCallback failure); @JSMethod(uiThread = true) void close(JSONObject options, JSCallback success, JSCallback failure); @JSMethod(uiThread = true) void push(String param, JSCallback callback); @JSMethod(uiThread = true) void pop(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarRightItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarRightItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarLeftItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarLeftItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarMoreItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarMoreItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarTitle(String param, JSCallback callback); @JSMethod void setNavBarHidden(String param, final String callback); static final String MSG_SUCCESS; static final String MSG_FAILED; static final String MSG_PARAM_ERR; static final String CALLBACK_RESULT; static final String CALLBACK_MESSAGE; }
@Test public void testSetNavBarRightItem() throws Exception { mockSetter(); module.setNavBarRightItem("{}",callback); }
@JSMethod(uiThread = true) public void setNavBarRightItem(String param, JSCallback callback) { if (!TextUtils.isEmpty(param)) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().setNavBarRightItem(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } } if (callback != null) { callback.invoke(MSG_FAILED); } }
WXNavigatorModule extends WXModule { @JSMethod(uiThread = true) public void setNavBarRightItem(String param, JSCallback callback) { if (!TextUtils.isEmpty(param)) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().setNavBarRightItem(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } } if (callback != null) { callback.invoke(MSG_FAILED); } } }
WXNavigatorModule extends WXModule { @JSMethod(uiThread = true) public void setNavBarRightItem(String param, JSCallback callback) { if (!TextUtils.isEmpty(param)) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().setNavBarRightItem(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } } if (callback != null) { callback.invoke(MSG_FAILED); } } }
WXNavigatorModule extends WXModule { @JSMethod(uiThread = true) public void setNavBarRightItem(String param, JSCallback callback) { if (!TextUtils.isEmpty(param)) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().setNavBarRightItem(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } } if (callback != null) { callback.invoke(MSG_FAILED); } } @JSMethod(uiThread = true) void open(JSONObject options, JSCallback success, JSCallback failure); @JSMethod(uiThread = true) void close(JSONObject options, JSCallback success, JSCallback failure); @JSMethod(uiThread = true) void push(String param, JSCallback callback); @JSMethod(uiThread = true) void pop(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarRightItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarRightItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarLeftItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarLeftItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarMoreItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarMoreItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarTitle(String param, JSCallback callback); @JSMethod void setNavBarHidden(String param, final String callback); }
WXNavigatorModule extends WXModule { @JSMethod(uiThread = true) public void setNavBarRightItem(String param, JSCallback callback) { if (!TextUtils.isEmpty(param)) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().setNavBarRightItem(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } } if (callback != null) { callback.invoke(MSG_FAILED); } } @JSMethod(uiThread = true) void open(JSONObject options, JSCallback success, JSCallback failure); @JSMethod(uiThread = true) void close(JSONObject options, JSCallback success, JSCallback failure); @JSMethod(uiThread = true) void push(String param, JSCallback callback); @JSMethod(uiThread = true) void pop(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarRightItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarRightItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarLeftItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarLeftItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarMoreItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarMoreItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarTitle(String param, JSCallback callback); @JSMethod void setNavBarHidden(String param, final String callback); static final String MSG_SUCCESS; static final String MSG_FAILED; static final String MSG_PARAM_ERR; static final String CALLBACK_RESULT; static final String CALLBACK_MESSAGE; }
@Test public void testClearNavBarRightItem() throws Exception { mockSetter(); module.clearNavBarRightItem("{}",callback); }
@JSMethod(uiThread = true) public void clearNavBarRightItem(String param, JSCallback callback) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().clearNavBarRightItem(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } if (callback != null) { callback.invoke(MSG_FAILED); } }
WXNavigatorModule extends WXModule { @JSMethod(uiThread = true) public void clearNavBarRightItem(String param, JSCallback callback) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().clearNavBarRightItem(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } if (callback != null) { callback.invoke(MSG_FAILED); } } }
WXNavigatorModule extends WXModule { @JSMethod(uiThread = true) public void clearNavBarRightItem(String param, JSCallback callback) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().clearNavBarRightItem(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } if (callback != null) { callback.invoke(MSG_FAILED); } } }
WXNavigatorModule extends WXModule { @JSMethod(uiThread = true) public void clearNavBarRightItem(String param, JSCallback callback) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().clearNavBarRightItem(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } if (callback != null) { callback.invoke(MSG_FAILED); } } @JSMethod(uiThread = true) void open(JSONObject options, JSCallback success, JSCallback failure); @JSMethod(uiThread = true) void close(JSONObject options, JSCallback success, JSCallback failure); @JSMethod(uiThread = true) void push(String param, JSCallback callback); @JSMethod(uiThread = true) void pop(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarRightItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarRightItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarLeftItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarLeftItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarMoreItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarMoreItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarTitle(String param, JSCallback callback); @JSMethod void setNavBarHidden(String param, final String callback); }
WXNavigatorModule extends WXModule { @JSMethod(uiThread = true) public void clearNavBarRightItem(String param, JSCallback callback) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().clearNavBarRightItem(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } if (callback != null) { callback.invoke(MSG_FAILED); } } @JSMethod(uiThread = true) void open(JSONObject options, JSCallback success, JSCallback failure); @JSMethod(uiThread = true) void close(JSONObject options, JSCallback success, JSCallback failure); @JSMethod(uiThread = true) void push(String param, JSCallback callback); @JSMethod(uiThread = true) void pop(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarRightItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarRightItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarLeftItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarLeftItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarMoreItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarMoreItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarTitle(String param, JSCallback callback); @JSMethod void setNavBarHidden(String param, final String callback); static final String MSG_SUCCESS; static final String MSG_FAILED; static final String MSG_PARAM_ERR; static final String CALLBACK_RESULT; static final String CALLBACK_MESSAGE; }
@Test public void testSetNavBarLeftItem() throws Exception { mockSetter(); module.setNavBarLeftItem("{}",callback); }
@JSMethod(uiThread = true) public void setNavBarLeftItem(String param, JSCallback callback) { if (!TextUtils.isEmpty(param)) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().setNavBarLeftItem(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } } if (callback != null) { callback.invoke(MSG_FAILED); } }
WXNavigatorModule extends WXModule { @JSMethod(uiThread = true) public void setNavBarLeftItem(String param, JSCallback callback) { if (!TextUtils.isEmpty(param)) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().setNavBarLeftItem(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } } if (callback != null) { callback.invoke(MSG_FAILED); } } }
WXNavigatorModule extends WXModule { @JSMethod(uiThread = true) public void setNavBarLeftItem(String param, JSCallback callback) { if (!TextUtils.isEmpty(param)) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().setNavBarLeftItem(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } } if (callback != null) { callback.invoke(MSG_FAILED); } } }
WXNavigatorModule extends WXModule { @JSMethod(uiThread = true) public void setNavBarLeftItem(String param, JSCallback callback) { if (!TextUtils.isEmpty(param)) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().setNavBarLeftItem(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } } if (callback != null) { callback.invoke(MSG_FAILED); } } @JSMethod(uiThread = true) void open(JSONObject options, JSCallback success, JSCallback failure); @JSMethod(uiThread = true) void close(JSONObject options, JSCallback success, JSCallback failure); @JSMethod(uiThread = true) void push(String param, JSCallback callback); @JSMethod(uiThread = true) void pop(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarRightItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarRightItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarLeftItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarLeftItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarMoreItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarMoreItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarTitle(String param, JSCallback callback); @JSMethod void setNavBarHidden(String param, final String callback); }
WXNavigatorModule extends WXModule { @JSMethod(uiThread = true) public void setNavBarLeftItem(String param, JSCallback callback) { if (!TextUtils.isEmpty(param)) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().setNavBarLeftItem(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } } if (callback != null) { callback.invoke(MSG_FAILED); } } @JSMethod(uiThread = true) void open(JSONObject options, JSCallback success, JSCallback failure); @JSMethod(uiThread = true) void close(JSONObject options, JSCallback success, JSCallback failure); @JSMethod(uiThread = true) void push(String param, JSCallback callback); @JSMethod(uiThread = true) void pop(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarRightItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarRightItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarLeftItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarLeftItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarMoreItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarMoreItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarTitle(String param, JSCallback callback); @JSMethod void setNavBarHidden(String param, final String callback); static final String MSG_SUCCESS; static final String MSG_FAILED; static final String MSG_PARAM_ERR; static final String CALLBACK_RESULT; static final String CALLBACK_MESSAGE; }
@Test public void testClearNavBarLeftItem() throws Exception { mockSetter(); module.clearNavBarLeftItem("{}",callback); }
@JSMethod(uiThread = true) public void clearNavBarLeftItem(String param, JSCallback callback) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().clearNavBarLeftItem(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } if (callback != null) { callback.invoke(MSG_FAILED); } }
WXNavigatorModule extends WXModule { @JSMethod(uiThread = true) public void clearNavBarLeftItem(String param, JSCallback callback) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().clearNavBarLeftItem(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } if (callback != null) { callback.invoke(MSG_FAILED); } } }
WXNavigatorModule extends WXModule { @JSMethod(uiThread = true) public void clearNavBarLeftItem(String param, JSCallback callback) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().clearNavBarLeftItem(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } if (callback != null) { callback.invoke(MSG_FAILED); } } }
WXNavigatorModule extends WXModule { @JSMethod(uiThread = true) public void clearNavBarLeftItem(String param, JSCallback callback) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().clearNavBarLeftItem(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } if (callback != null) { callback.invoke(MSG_FAILED); } } @JSMethod(uiThread = true) void open(JSONObject options, JSCallback success, JSCallback failure); @JSMethod(uiThread = true) void close(JSONObject options, JSCallback success, JSCallback failure); @JSMethod(uiThread = true) void push(String param, JSCallback callback); @JSMethod(uiThread = true) void pop(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarRightItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarRightItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarLeftItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarLeftItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarMoreItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarMoreItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarTitle(String param, JSCallback callback); @JSMethod void setNavBarHidden(String param, final String callback); }
WXNavigatorModule extends WXModule { @JSMethod(uiThread = true) public void clearNavBarLeftItem(String param, JSCallback callback) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().clearNavBarLeftItem(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } if (callback != null) { callback.invoke(MSG_FAILED); } } @JSMethod(uiThread = true) void open(JSONObject options, JSCallback success, JSCallback failure); @JSMethod(uiThread = true) void close(JSONObject options, JSCallback success, JSCallback failure); @JSMethod(uiThread = true) void push(String param, JSCallback callback); @JSMethod(uiThread = true) void pop(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarRightItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarRightItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarLeftItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarLeftItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarMoreItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarMoreItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarTitle(String param, JSCallback callback); @JSMethod void setNavBarHidden(String param, final String callback); static final String MSG_SUCCESS; static final String MSG_FAILED; static final String MSG_PARAM_ERR; static final String CALLBACK_RESULT; static final String CALLBACK_MESSAGE; }
@Test public void testSetNavBarMoreItem() throws Exception { mockSetter(); module.setNavBarMoreItem("{}",callback); }
@JSMethod(uiThread = true) public void setNavBarMoreItem(String param, JSCallback callback) { if (!TextUtils.isEmpty(param)) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().setNavBarMoreItem(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } } if (callback != null) { callback.invoke(MSG_FAILED); } }
WXNavigatorModule extends WXModule { @JSMethod(uiThread = true) public void setNavBarMoreItem(String param, JSCallback callback) { if (!TextUtils.isEmpty(param)) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().setNavBarMoreItem(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } } if (callback != null) { callback.invoke(MSG_FAILED); } } }
WXNavigatorModule extends WXModule { @JSMethod(uiThread = true) public void setNavBarMoreItem(String param, JSCallback callback) { if (!TextUtils.isEmpty(param)) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().setNavBarMoreItem(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } } if (callback != null) { callback.invoke(MSG_FAILED); } } }
WXNavigatorModule extends WXModule { @JSMethod(uiThread = true) public void setNavBarMoreItem(String param, JSCallback callback) { if (!TextUtils.isEmpty(param)) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().setNavBarMoreItem(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } } if (callback != null) { callback.invoke(MSG_FAILED); } } @JSMethod(uiThread = true) void open(JSONObject options, JSCallback success, JSCallback failure); @JSMethod(uiThread = true) void close(JSONObject options, JSCallback success, JSCallback failure); @JSMethod(uiThread = true) void push(String param, JSCallback callback); @JSMethod(uiThread = true) void pop(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarRightItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarRightItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarLeftItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarLeftItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarMoreItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarMoreItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarTitle(String param, JSCallback callback); @JSMethod void setNavBarHidden(String param, final String callback); }
WXNavigatorModule extends WXModule { @JSMethod(uiThread = true) public void setNavBarMoreItem(String param, JSCallback callback) { if (!TextUtils.isEmpty(param)) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().setNavBarMoreItem(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } } if (callback != null) { callback.invoke(MSG_FAILED); } } @JSMethod(uiThread = true) void open(JSONObject options, JSCallback success, JSCallback failure); @JSMethod(uiThread = true) void close(JSONObject options, JSCallback success, JSCallback failure); @JSMethod(uiThread = true) void push(String param, JSCallback callback); @JSMethod(uiThread = true) void pop(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarRightItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarRightItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarLeftItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarLeftItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarMoreItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarMoreItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarTitle(String param, JSCallback callback); @JSMethod void setNavBarHidden(String param, final String callback); static final String MSG_SUCCESS; static final String MSG_FAILED; static final String MSG_PARAM_ERR; static final String CALLBACK_RESULT; static final String CALLBACK_MESSAGE; }
@Test public void testClearNavBarMoreItem() throws Exception { mockSetter(); module.clearNavBarMoreItem("{}",callback); }
@JSMethod(uiThread = true) public void clearNavBarMoreItem(String param, JSCallback callback) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().clearNavBarMoreItem(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } if (callback != null) { callback.invoke(MSG_FAILED); } }
WXNavigatorModule extends WXModule { @JSMethod(uiThread = true) public void clearNavBarMoreItem(String param, JSCallback callback) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().clearNavBarMoreItem(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } if (callback != null) { callback.invoke(MSG_FAILED); } } }
WXNavigatorModule extends WXModule { @JSMethod(uiThread = true) public void clearNavBarMoreItem(String param, JSCallback callback) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().clearNavBarMoreItem(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } if (callback != null) { callback.invoke(MSG_FAILED); } } }
WXNavigatorModule extends WXModule { @JSMethod(uiThread = true) public void clearNavBarMoreItem(String param, JSCallback callback) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().clearNavBarMoreItem(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } if (callback != null) { callback.invoke(MSG_FAILED); } } @JSMethod(uiThread = true) void open(JSONObject options, JSCallback success, JSCallback failure); @JSMethod(uiThread = true) void close(JSONObject options, JSCallback success, JSCallback failure); @JSMethod(uiThread = true) void push(String param, JSCallback callback); @JSMethod(uiThread = true) void pop(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarRightItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarRightItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarLeftItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarLeftItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarMoreItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarMoreItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarTitle(String param, JSCallback callback); @JSMethod void setNavBarHidden(String param, final String callback); }
WXNavigatorModule extends WXModule { @JSMethod(uiThread = true) public void clearNavBarMoreItem(String param, JSCallback callback) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().clearNavBarMoreItem(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } if (callback != null) { callback.invoke(MSG_FAILED); } } @JSMethod(uiThread = true) void open(JSONObject options, JSCallback success, JSCallback failure); @JSMethod(uiThread = true) void close(JSONObject options, JSCallback success, JSCallback failure); @JSMethod(uiThread = true) void push(String param, JSCallback callback); @JSMethod(uiThread = true) void pop(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarRightItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarRightItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarLeftItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarLeftItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarMoreItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarMoreItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarTitle(String param, JSCallback callback); @JSMethod void setNavBarHidden(String param, final String callback); static final String MSG_SUCCESS; static final String MSG_FAILED; static final String MSG_PARAM_ERR; static final String CALLBACK_RESULT; static final String CALLBACK_MESSAGE; }
@Test public void testSetNavBarTitle() throws Exception { mockSetter(); module.setNavBarTitle("{}",callback); }
@JSMethod(uiThread = true) public void setNavBarTitle(String param, JSCallback callback) { if (!TextUtils.isEmpty(param)) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().setNavBarTitle(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } } if (callback != null) { callback.invoke(MSG_FAILED); } }
WXNavigatorModule extends WXModule { @JSMethod(uiThread = true) public void setNavBarTitle(String param, JSCallback callback) { if (!TextUtils.isEmpty(param)) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().setNavBarTitle(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } } if (callback != null) { callback.invoke(MSG_FAILED); } } }
WXNavigatorModule extends WXModule { @JSMethod(uiThread = true) public void setNavBarTitle(String param, JSCallback callback) { if (!TextUtils.isEmpty(param)) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().setNavBarTitle(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } } if (callback != null) { callback.invoke(MSG_FAILED); } } }
WXNavigatorModule extends WXModule { @JSMethod(uiThread = true) public void setNavBarTitle(String param, JSCallback callback) { if (!TextUtils.isEmpty(param)) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().setNavBarTitle(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } } if (callback != null) { callback.invoke(MSG_FAILED); } } @JSMethod(uiThread = true) void open(JSONObject options, JSCallback success, JSCallback failure); @JSMethod(uiThread = true) void close(JSONObject options, JSCallback success, JSCallback failure); @JSMethod(uiThread = true) void push(String param, JSCallback callback); @JSMethod(uiThread = true) void pop(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarRightItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarRightItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarLeftItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarLeftItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarMoreItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarMoreItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarTitle(String param, JSCallback callback); @JSMethod void setNavBarHidden(String param, final String callback); }
WXNavigatorModule extends WXModule { @JSMethod(uiThread = true) public void setNavBarTitle(String param, JSCallback callback) { if (!TextUtils.isEmpty(param)) { if (WXSDKEngine.getActivityNavBarSetter() != null) { if (WXSDKEngine.getActivityNavBarSetter().setNavBarTitle(param)) { if (callback != null) { callback.invoke(MSG_SUCCESS); } return; } } } if (callback != null) { callback.invoke(MSG_FAILED); } } @JSMethod(uiThread = true) void open(JSONObject options, JSCallback success, JSCallback failure); @JSMethod(uiThread = true) void close(JSONObject options, JSCallback success, JSCallback failure); @JSMethod(uiThread = true) void push(String param, JSCallback callback); @JSMethod(uiThread = true) void pop(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarRightItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarRightItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarLeftItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarLeftItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarMoreItem(String param, JSCallback callback); @JSMethod(uiThread = true) void clearNavBarMoreItem(String param, JSCallback callback); @JSMethod(uiThread = true) void setNavBarTitle(String param, JSCallback callback); @JSMethod void setNavBarHidden(String param, final String callback); static final String MSG_SUCCESS; static final String MSG_FAILED; static final String MSG_PARAM_ERR; static final String CALLBACK_RESULT; static final String CALLBACK_MESSAGE; }
@Test public void testSetSize() throws Exception { setupRoot(mInstance); mInstance.setSize(10,10); }
public void setSize(int width, int height) { if (width < 0 || height < 0 || isDestroy || !mRendered) { return; } float realWidth = WXViewUtils.getWebPxByWidth(width,getInstanceViewPortWidth()); float realHeight = WXViewUtils.getWebPxByWidth(height,getInstanceViewPortWidth()); View godView = mRenderContainer; if (godView != null) { ViewGroup.LayoutParams layoutParams = godView.getLayoutParams(); if (layoutParams != null) { if(godView.getWidth() != width || godView.getHeight() != height) { layoutParams.width = width; layoutParams.height = height; godView.setLayoutParams(layoutParams); } JSONObject style = new JSONObject(); WXComponent rootComponent = mRootComp; if(rootComponent == null){ return; } style.put(Constants.Name.DEFAULT_WIDTH, realWidth); style.put(Constants.Name.DEFAULT_HEIGHT, realHeight); updateRootComponentStyle(style); } } }
WXSDKInstance implements IWXActivityStateListener,DomContext, View.OnLayoutChangeListener { public void setSize(int width, int height) { if (width < 0 || height < 0 || isDestroy || !mRendered) { return; } float realWidth = WXViewUtils.getWebPxByWidth(width,getInstanceViewPortWidth()); float realHeight = WXViewUtils.getWebPxByWidth(height,getInstanceViewPortWidth()); View godView = mRenderContainer; if (godView != null) { ViewGroup.LayoutParams layoutParams = godView.getLayoutParams(); if (layoutParams != null) { if(godView.getWidth() != width || godView.getHeight() != height) { layoutParams.width = width; layoutParams.height = height; godView.setLayoutParams(layoutParams); } JSONObject style = new JSONObject(); WXComponent rootComponent = mRootComp; if(rootComponent == null){ return; } style.put(Constants.Name.DEFAULT_WIDTH, realWidth); style.put(Constants.Name.DEFAULT_HEIGHT, realHeight); updateRootComponentStyle(style); } } } }
WXSDKInstance implements IWXActivityStateListener,DomContext, View.OnLayoutChangeListener { public void setSize(int width, int height) { if (width < 0 || height < 0 || isDestroy || !mRendered) { return; } float realWidth = WXViewUtils.getWebPxByWidth(width,getInstanceViewPortWidth()); float realHeight = WXViewUtils.getWebPxByWidth(height,getInstanceViewPortWidth()); View godView = mRenderContainer; if (godView != null) { ViewGroup.LayoutParams layoutParams = godView.getLayoutParams(); if (layoutParams != null) { if(godView.getWidth() != width || godView.getHeight() != height) { layoutParams.width = width; layoutParams.height = height; godView.setLayoutParams(layoutParams); } JSONObject style = new JSONObject(); WXComponent rootComponent = mRootComp; if(rootComponent == null){ return; } style.put(Constants.Name.DEFAULT_WIDTH, realWidth); style.put(Constants.Name.DEFAULT_HEIGHT, realHeight); updateRootComponentStyle(style); } } } WXSDKInstance(Context context); WXSDKInstance(Context context,String id); }
WXSDKInstance implements IWXActivityStateListener,DomContext, View.OnLayoutChangeListener { public void setSize(int width, int height) { if (width < 0 || height < 0 || isDestroy || !mRendered) { return; } float realWidth = WXViewUtils.getWebPxByWidth(width,getInstanceViewPortWidth()); float realHeight = WXViewUtils.getWebPxByWidth(height,getInstanceViewPortWidth()); View godView = mRenderContainer; if (godView != null) { ViewGroup.LayoutParams layoutParams = godView.getLayoutParams(); if (layoutParams != null) { if(godView.getWidth() != width || godView.getHeight() != height) { layoutParams.width = width; layoutParams.height = height; godView.setLayoutParams(layoutParams); } JSONObject style = new JSONObject(); WXComponent rootComponent = mRootComp; if(rootComponent == null){ return; } style.put(Constants.Name.DEFAULT_WIDTH, realWidth); style.put(Constants.Name.DEFAULT_HEIGHT, realHeight); updateRootComponentStyle(style); } } } 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); }
WXSDKInstance implements IWXActivityStateListener,DomContext, View.OnLayoutChangeListener { public void setSize(int width, int height) { if (width < 0 || height < 0 || isDestroy || !mRendered) { return; } float realWidth = WXViewUtils.getWebPxByWidth(width,getInstanceViewPortWidth()); float realHeight = WXViewUtils.getWebPxByWidth(height,getInstanceViewPortWidth()); View godView = mRenderContainer; if (godView != null) { ViewGroup.LayoutParams layoutParams = godView.getLayoutParams(); if (layoutParams != null) { if(godView.getWidth() != width || godView.getHeight() != height) { layoutParams.width = width; layoutParams.height = height; godView.setLayoutParams(layoutParams); } JSONObject style = new JSONObject(); WXComponent rootComponent = mRootComp; if(rootComponent == null){ return; } style.put(Constants.Name.DEFAULT_WIDTH, realWidth); style.put(Constants.Name.DEFAULT_HEIGHT, realHeight); updateRootComponentStyle(style); } } } 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 testRenderByUrl() throws Exception { mInstance.renderByUrl(WXPerformance.DEFAULT,"file: mInstance.renderByUrl(WXPerformance.DEFAULT,"http: }
@Deprecated public void renderByUrl(String pageName, final String url, Map<String, Object> options, final String jsonInitData, final int width, final int height, final WXRenderStrategy flag){ renderByUrl(pageName,url,options,jsonInitData,flag); }
WXSDKInstance implements IWXActivityStateListener,DomContext, View.OnLayoutChangeListener { @Deprecated public void renderByUrl(String pageName, final String url, Map<String, Object> options, final String jsonInitData, final int width, final int height, final WXRenderStrategy flag){ renderByUrl(pageName,url,options,jsonInitData,flag); } }
WXSDKInstance implements IWXActivityStateListener,DomContext, View.OnLayoutChangeListener { @Deprecated public void renderByUrl(String pageName, final String url, Map<String, Object> options, final String jsonInitData, final int width, final int height, final WXRenderStrategy flag){ renderByUrl(pageName,url,options,jsonInitData,flag); } WXSDKInstance(Context context); WXSDKInstance(Context context,String id); }
WXSDKInstance implements IWXActivityStateListener,DomContext, View.OnLayoutChangeListener { @Deprecated public void renderByUrl(String pageName, final String url, Map<String, Object> options, final String jsonInitData, final int width, final int height, final WXRenderStrategy flag){ renderByUrl(pageName,url,options,jsonInitData,flag); } 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); }
WXSDKInstance implements IWXActivityStateListener,DomContext, View.OnLayoutChangeListener { @Deprecated public void renderByUrl(String pageName, final String url, Map<String, Object> options, final String jsonInitData, final int width, final int height, final WXRenderStrategy flag){ renderByUrl(pageName,url,options,jsonInitData,flag); } 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 testInit() throws Exception { assertFalse(WXSDKEngine.isInitialized()); WXSDKEngine.initialize(RuntimeEnvironment.application,null); assertTrue(WXSDKEngine.isInitialized()); WXSDKEngine.init(RuntimeEnvironment.application); WXSDKEngine.init(RuntimeEnvironment.application,null); WXSDKEngine.init(RuntimeEnvironment.application,null,null); WXSDKEngine.init(RuntimeEnvironment.application,null,null,null,null); }
@Deprecated public static void init(Application application) { init(application, null); }
WXSDKEngine { @Deprecated public static void init(Application application) { init(application, null); } }
WXSDKEngine { @Deprecated public static void init(Application application) { init(application, null); } }
WXSDKEngine { @Deprecated public static void init(Application application) { init(application, null); } @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(); }
WXSDKEngine { @Deprecated public static void init(Application application) { init(application, null); } @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 testRegisterComponent() throws Exception { assertFalse(WXSDKEngine.registerComponent(null,(Class<? extends WXComponent>) null,true)); assertTrue(WXSDKEngine.registerComponent("test", TestComponent.class,true)); assertTrue(WXSDKEngine.registerComponent("test1",TestComponent.class)); assertTrue(WXSDKEngine.registerComponent(TestComponent.class,false,"testA","testB","testC")); Map<String,Object> compInfo = new HashMap<>(); assertFalse(WXSDKEngine.registerComponent(compInfo,TestComponent.class)); }
public static boolean registerComponent(String type, Class<? extends WXComponent> clazz, boolean appendTree) throws WXException { return registerComponent(clazz, appendTree,type); }
WXSDKEngine { public static boolean registerComponent(String type, Class<? extends WXComponent> clazz, boolean appendTree) throws WXException { return registerComponent(clazz, appendTree,type); } }
WXSDKEngine { public static boolean registerComponent(String type, Class<? extends WXComponent> clazz, boolean appendTree) throws WXException { return registerComponent(clazz, appendTree,type); } }
WXSDKEngine { public static boolean registerComponent(String type, Class<? extends WXComponent> clazz, boolean appendTree) throws WXException { return registerComponent(clazz, appendTree,type); } @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(); }
WXSDKEngine { public static boolean registerComponent(String type, Class<? extends WXComponent> clazz, boolean appendTree) throws WXException { return registerComponent(clazz, appendTree,type); } @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 testRegisterModule() throws Exception { assertTrue(WXSDKEngine.registerModule("test", TestModule.class)); assertFalse(WXSDKEngine.registerModule(null,TestModule.class)); assertFalse(WXSDKEngine.registerModule("test",null)); assertFalse(WXSDKEngine.registerModuleWithFactory(null,new TestModuleFactory(TestModule.class),true)); assertTrue(WXSDKEngine.registerModuleWithFactory("test1",new TestModuleFactory(TestModule.class),true)); }
public static <T extends WXModule> boolean registerModule(String moduleName, Class<T> moduleClass,boolean global) throws WXException { return moduleClass != null && registerModule(moduleName, new TypeModuleFactory<>(moduleClass), global); }
WXSDKEngine { public static <T extends WXModule> boolean registerModule(String moduleName, Class<T> moduleClass,boolean global) throws WXException { return moduleClass != null && registerModule(moduleName, new TypeModuleFactory<>(moduleClass), global); } }
WXSDKEngine { public static <T extends WXModule> boolean registerModule(String moduleName, Class<T> moduleClass,boolean global) throws WXException { return moduleClass != null && registerModule(moduleName, new TypeModuleFactory<>(moduleClass), global); } }
WXSDKEngine { public static <T extends WXModule> boolean registerModule(String moduleName, Class<T> moduleClass,boolean global) throws WXException { return moduleClass != null && registerModule(moduleName, new TypeModuleFactory<>(moduleClass), global); } @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(); }
WXSDKEngine { public static <T extends WXModule> boolean registerModule(String moduleName, Class<T> moduleClass,boolean global) throws WXException { return moduleClass != null && registerModule(moduleName, new TypeModuleFactory<>(moduleClass), global); } @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)); }
public static boolean registerDomObject(String type, Class<? extends WXDomObject> clazz) throws WXException { return WXDomRegistry.registerDomObject(type, clazz); }
WXSDKEngine { public static boolean registerDomObject(String type, Class<? extends WXDomObject> clazz) throws WXException { return WXDomRegistry.registerDomObject(type, clazz); } }
WXSDKEngine { public static boolean registerDomObject(String type, Class<? extends WXDomObject> clazz) throws WXException { return WXDomRegistry.registerDomObject(type, clazz); } }
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(); }
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 testSetProperties() throws Exception { ComponentTest.setProperty(component,PROPS,VALUES); }
@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); }
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); } }
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); }
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); }
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 testIndicator() throws Exception { WXIndicator indicator = createIndicator(component); ComponentTest.create(indicator); component.addChild(indicator); ComponentTest.setProperty(indicator,IPROPS,IVALUES); }
@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); }
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); } }
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); }
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); }
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 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); }
@WXComponentProp(name = Constants.Name.OFFSET_X_ACCURACY) public void setOffsetXAccuracy(float accuracy) { this.offsetXAccuracy = accuracy; }
WXSlider extends WXVContainer<FrameLayout> { @WXComponentProp(name = Constants.Name.OFFSET_X_ACCURACY) public void setOffsetXAccuracy(float accuracy) { this.offsetXAccuracy = accuracy; } }
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); }
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); }
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 @PrepareForTest(WXImageView.class) public void testInitComponentHostView() throws Exception { ImageView imageView = mWXImage.initComponentHostView(Robolectric.setupActivity(TestActivity.class)); assertEquals(imageView.getClass(), WXImageView.class); }
@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; }
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; } }
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); }
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); }
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 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); }
@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; }
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; } }
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); }
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); }
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 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); }
@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); }
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); } }
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); }
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); }
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 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); }
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 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 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); }
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); }
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 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); }
@WXComponentProp(name = Constants.Name.RESIZE_MODE) public void setResizeMode(String resizeMode) { (getHostView()).setScaleType(getResizeMode(resizeMode)); }
WXImage extends WXComponent<ImageView> { @WXComponentProp(name = Constants.Name.RESIZE_MODE) public void setResizeMode(String resizeMode) { (getHostView()).setScaleType(getResizeMode(resizeMode)); } }
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); }
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); }
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 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); }
@WXComponentProp(name = Constants.Name.RESIZE) public void setResize(String resize) { (getHostView()).setScaleType(getResizeMode(resize)); }
WXImage extends WXComponent<ImageView> { @WXComponentProp(name = Constants.Name.RESIZE) public void setResize(String resize) { (getHostView()).setScaleType(getResizeMode(resize)); } }
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); }
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); }
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 testSetSrc() throws Exception { TestDomObject.setAttribute((WXDomObject)mWXImage.getDomObject(),PowerMockito.mock(WXAttr.class)); PowerMockito.when(mWXImage.getDomObject().getAttrs().getImageSharpen()).thenReturn(WXImageSharpen.SHARPEN); mWXImage.setSrc(""); }
@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); } }
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); } } }
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); }
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); }
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 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()); }
@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; }
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; } }
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); }
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); }
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 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)); }
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; } }
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; } } }
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); }
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); }
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 testAddEvent() throws Exception { component.addEvent(Constants.Event.FOCUS); }
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); } } }
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); } } } }
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); }
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); }
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 testAddChild() throws Exception { WXComponent child = WXDivTest.create(component); ComponentTest.create(child); component.addChild(child); child = WXHeaderTest.create(component); ComponentTest.create(child); component.addChild(child); }
@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()); } }
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()); } } }
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); }
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); }
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 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); }
@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()); } }
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()); } } }
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); }
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); }
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 testAppear() throws Exception { WXComponent child = WXDivTest.create(component); ComponentTest.create(child); component.addChild(child); component.bindAppearEvent(child); component.notifyAppearStateChange(0,0,0,10); }
@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()); } }
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()); } } }
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); }
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); }
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 onDragStart() throws Exception { WXComponent c = new WXCell(WXSDKInstanceTest.createInstance(),new TestDomObject(),null,false); mFakeDragHelper.onDragStart(c,3); verify(mockedEventTrigger).triggerEvent(eq("dragstart"),anyMap()); }
@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 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 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); }
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); }
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 testOnJSException() throws Exception { mInstance.onJSException(null,null,null); mInstance.onJSException("100","test","some error"); }
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 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 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); }
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); }
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 extractAnnotationSpans() throws Exception { System.out.println(AnnotationSpans.extractAnnotationSpans(jCas)); }
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 { 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 { 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); }
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(); }
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 @InSequence(5) public void delete() throws Exception { final Response response = webTarget.path("{id}") .resolveTemplate("id", 1) .request() .delete(); assertEquals(NO_CONTENT.getStatusCode(), response.getStatus()); }
@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(); }
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(); } }
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(); } }
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(); }
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 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-")); }
@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(); }
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(); } }
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(); } }
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(); }
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 @InSequence(1) public void findById() throws Exception { final Response response = webTarget.path("{id}").resolveTemplate("id", 0).request().get(); assertEquals(OK.getStatusCode(), response.getStatus()); }
@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(); }
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(); } }
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(); } }
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(); }
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(2) public void findAll() throws Exception { final Response response = webTarget.request().get(); assertEquals(OK.getStatusCode(), response.getStatus()); }
@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(); }
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(); } }
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(); } }
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(); }
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(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()); }
@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(); }
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(); } }
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(); } }
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(); }
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(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()); }
@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(); }
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(); } }
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(); } }
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(); }
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(5) public void delete() throws Exception { final Response response = webTarget.path("{id}") .resolveTemplate("id", 1) .request() .delete(); assertEquals(NO_CONTENT.getStatusCode(), response.getStatus()); }
@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(); }
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(); } }
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(); } }
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(); }
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 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-")); }
@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(); }
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(); } }
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(); } }
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(); }
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 @InSequence(2) public void findAll() throws Exception { final Response response = webTarget.request().get(); assertEquals(OK.getStatusCode(), response.getStatus()); }
@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(); }
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(); } }
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(); } }
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); }
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 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-")); }
@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(); }
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(); } }
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(); } }
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(); }
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 @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()); }
@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(); }
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(); } }
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(); } }
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); }
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(1) public void findById() throws Exception { final Response response = webTarget.path("{id}").resolveTemplate("id", 0).request().get(); assertEquals(OK.getStatusCode(), response.getStatus()); }
@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(); }
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(); } }
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(); } }
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); }
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(2) public void findAll() throws Exception { final Response response = webTarget.request().get(); assertEquals(OK.getStatusCode(), response.getStatus()); }
@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(); }
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(); } }
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(); } }
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); }
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(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()); }
@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(); }
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(); } }
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(); } }
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); }
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(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()); }
@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(); }
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(); } }
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(); } }
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); }
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()); }
@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(); }
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(); } }
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(); } }
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); }
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(5) public void delete() throws Exception { final Response response = webTarget.path("{id}") .resolveTemplate("id", 1) .request() .delete(); assertEquals(NO_CONTENT.getStatusCode(), response.getStatus()); }
@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(); }
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(); } }
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(); } }
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); }
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 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-")); }
@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(); }
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(); } }
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(); } }
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(); }
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 @InSequence(1) public void findById() throws Exception { final Response response = webTarget.path("{id}").resolveTemplate("id", 0).request().get(); assertEquals(OK.getStatusCode(), response.getStatus()); }
@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(); }
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(); } }
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(); } }
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); }
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(5) public void delete() throws Exception { final Response response = webTarget.path("{id}") .resolveTemplate("id", 1) .request() .delete(); assertEquals(NO_CONTENT.getStatusCode(), response.getStatus()); }
@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(); }
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(); } }
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(); } }
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); }
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 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-")); }
@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(); }
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(); } }
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(); } }
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(); }
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 @InSequence(1) public void findById() throws Exception { final Response response = webTarget.path("{id}").resolveTemplate("id", 0).request().get(); assertEquals(OK.getStatusCode(), response.getStatus()); }
@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(); }
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(); } }
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(); } }
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(); }
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(2) public void findAll() throws Exception { final Response response = webTarget.request().get(); assertEquals(OK.getStatusCode(), response.getStatus()); }
@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(); }
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(); } }
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(); } }
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(); }
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(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()); }
@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(); }
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(); } }
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(); } }
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(); }
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(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()); }
@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(); }
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(); } }
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(); } }
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(); }
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 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); }
public ResourceDto<AlbumDto> getAlbumsPage() { return getAlbumsPage(FIRST_PAGE_NUM); }
AlbumService implements PaginatedService { public ResourceDto<AlbumDto> getAlbumsPage() { return getAlbumsPage(FIRST_PAGE_NUM); } }
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); }
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); }
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 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(""); }
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); }
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); } }
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); }
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); }
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 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)); }
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 { 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 { 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); }
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); }
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 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)); }
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 { 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 { 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); }
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); }
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 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)); }
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 { 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 { 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); }
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); }
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 failsDuplicateAddCustomer() { SecKillGrabResult success = commandService.addCouponTo(1); assertThat(success, is(SecKillGrabResult.Success)); success = commandService.addCouponTo(1); assertThat(success, is(SecKillGrabResult.Duplicate)); }
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 { 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 { 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); }
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); }
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 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)); }
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 { 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 { 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); }
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); }
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 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")); }
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 { 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 { 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); }
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); }
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 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")); }
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 { 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 { 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); }
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); }
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 testStartActive() throws InterruptedException { try (ActiveSpan span = spanOps.startActive("hello sematextains")) { span.setTag("app", "console"); } Thread.sleep(2000); }
@Override public ActiveSpan startActive(String name) { return tracer.buildSpan(name) .startActive(); }
SpanTemplate implements SpanOperations { @Override public ActiveSpan startActive(String name) { return tracer.buildSpan(name) .startActive(); } }
SpanTemplate implements SpanOperations { @Override public ActiveSpan startActive(String name) { return tracer.buildSpan(name) .startActive(); } SpanTemplate(Tracer tracer); }
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); }
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 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); }
@Override public ActiveSpan startActive(String name) { return tracer.buildSpan(name) .startActive(); }
SpanTemplate implements SpanOperations { @Override public ActiveSpan startActive(String name) { return tracer.buildSpan(name) .startActive(); } }
SpanTemplate implements SpanOperations { @Override public ActiveSpan startActive(String name) { return tracer.buildSpan(name) .startActive(); } SpanTemplate(Tracer tracer); }
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); }
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 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); } }
@Override public void inject(SpanContext ctx, HttpHeaders headers) { HttpHeadersInjectAdapter injectAdapter = new HttpHeadersInjectAdapter(headers); tracer.inject(ctx, Format.Builtin.HTTP_HEADERS, injectAdapter); }
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 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); }
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); }
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 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); }
public static Executor capturingDecorator(final Executor executor) { if (stateCaptors.isEmpty() || executor instanceof CapturingExecutor) { return executor; } else { return new CapturingExecutor(executor); } }
StateCapture { public static Executor capturingDecorator(final Executor executor) { if (stateCaptors.isEmpty() || executor instanceof CapturingExecutor) { return executor; } else { return new CapturingExecutor(executor); } } }
StateCapture { public static Executor capturingDecorator(final Executor executor) { if (stateCaptors.isEmpty() || executor instanceof CapturingExecutor) { return executor; } else { return new CapturingExecutor(executor); } } private StateCapture(); }
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); }
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 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()); }
public void shutdown() { running.set(false); executor.shutdown(); try { executor.awaitTermination(SHUTDOWN_TIMEOUT, TimeUnit.SECONDS); } catch (InterruptedException e) { executor.shutdownNow(); Thread.currentThread().interrupt(); } }
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 { 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); }
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(); }
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 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))); } }
static boolean isValid(final Metric label) { final String str = label.toString(); return !(str.contains("\n") || str.contains(",") || str.contains(":") || str.contains("=")); }
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 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); }
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(); }
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 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()); }
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()); }
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()); } }
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); }
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); }
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 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()); }
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()); }
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()); } }
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); }
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); }
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 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()); }
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()); }
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()); } }
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); }
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); }
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 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()); }
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()); }
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()); } }
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); }
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); }
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 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]); }
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()); }
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()); } }
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); }
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); }
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 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); }
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()); }
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()); } }
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); }
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); }
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 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); }
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()); }
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()); } }
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); }
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); }
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 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); }
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()); }
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()); } }
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); }
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); }
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); }