src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
TimeUtils { public static String getSpecifiedDate(long time) { return simpleDateFormat_1.format(new Date(time)); } static String getMM_SS(long time); static String getYHM(long time); static String getHistoryTime(long timeInLong); static String getHistoryTime1(long timeInLong); static String getLiveTime(long timeInLong); static String getTimeSpecial(long time); static long getTodayStartTime(); static long getTodayEndTime(); static long getSpecificDayEndTime(long time); static long getSpecificDayStartTime(long time); static String getMediaPicTimeInString(final long time); static String getYMDHM(final long time); static String getMediaVideoTimeInString(final long time); static String getTodayString(); static String getDayString(long time); static String getUptime(long time); static String getDayInMonth(long time); static String getMM_DD(long time); static String getHH_MM(long time); static String getHH_MM_Remain(long timeMs); static String getTestTime(long time); static String getSpecifiedDate(long time); static String getDatePickFormat(long time, TimeZone timeZone); static int getWeekNum(long time, TimeZone timeZone); static long startOfDay(long time); static boolean isToday(long time); static String getSuperString(long time); static String getHomeItemTime(Context context, long time); static String getDay(long time); static String getMonthInYear(long time); static String getHHMMSS(long timeMs); static String AutoHHMMSS(long timeMs); static String getBellRecordTime(long time); static String getWonderTime(long time); static boolean isSameDay(long time1, long time2); static long wrapToLong(long time); static String get1224(long l); static final long DAY_TIME; static SimpleDateFormat simpleDateFormat_1; static final SimpleDateFormat simpleDateFormat1; static final SimpleDateFormat simpleDateFormat2; } | @Test public void getSpecifiedDate() throws Exception { } |
TimeUtils { public static long startOfDay(long time) { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(time); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); return cal.getTimeInMillis(); } static String getMM_SS(long time); static String getYHM(long time); static String getHistoryTime(long timeInLong); static String getHistoryTime1(long timeInLong); static String getLiveTime(long timeInLong); static String getTimeSpecial(long time); static long getTodayStartTime(); static long getTodayEndTime(); static long getSpecificDayEndTime(long time); static long getSpecificDayStartTime(long time); static String getMediaPicTimeInString(final long time); static String getYMDHM(final long time); static String getMediaVideoTimeInString(final long time); static String getTodayString(); static String getDayString(long time); static String getUptime(long time); static String getDayInMonth(long time); static String getMM_DD(long time); static String getHH_MM(long time); static String getHH_MM_Remain(long timeMs); static String getTestTime(long time); static String getSpecifiedDate(long time); static String getDatePickFormat(long time, TimeZone timeZone); static int getWeekNum(long time, TimeZone timeZone); static long startOfDay(long time); static boolean isToday(long time); static String getSuperString(long time); static String getHomeItemTime(Context context, long time); static String getDay(long time); static String getMonthInYear(long time); static String getHHMMSS(long timeMs); static String AutoHHMMSS(long timeMs); static String getBellRecordTime(long time); static String getWonderTime(long time); static boolean isSameDay(long time1, long time2); static long wrapToLong(long time); static String get1224(long l); static final long DAY_TIME; static SimpleDateFormat simpleDateFormat_1; static final SimpleDateFormat simpleDateFormat1; static final SimpleDateFormat simpleDateFormat2; } | @Test public void startOfDay() throws Exception { } |
TimeUtils { public static boolean isToday(long time) { Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date(time)); Calendar calendar1 = Calendar.getInstance(); calendar1.setTime(new Date(System.currentTimeMillis())); return calendar.get(Calendar.YEAR) == calendar1.get(Calendar.YEAR) && calendar.get(Calendar.DAY_OF_YEAR) == calendar1.get(Calendar.DAY_OF_YEAR); } static String getMM_SS(long time); static String getYHM(long time); static String getHistoryTime(long timeInLong); static String getHistoryTime1(long timeInLong); static String getLiveTime(long timeInLong); static String getTimeSpecial(long time); static long getTodayStartTime(); static long getTodayEndTime(); static long getSpecificDayEndTime(long time); static long getSpecificDayStartTime(long time); static String getMediaPicTimeInString(final long time); static String getYMDHM(final long time); static String getMediaVideoTimeInString(final long time); static String getTodayString(); static String getDayString(long time); static String getUptime(long time); static String getDayInMonth(long time); static String getMM_DD(long time); static String getHH_MM(long time); static String getHH_MM_Remain(long timeMs); static String getTestTime(long time); static String getSpecifiedDate(long time); static String getDatePickFormat(long time, TimeZone timeZone); static int getWeekNum(long time, TimeZone timeZone); static long startOfDay(long time); static boolean isToday(long time); static String getSuperString(long time); static String getHomeItemTime(Context context, long time); static String getDay(long time); static String getMonthInYear(long time); static String getHHMMSS(long timeMs); static String AutoHHMMSS(long timeMs); static String getBellRecordTime(long time); static String getWonderTime(long time); static boolean isSameDay(long time1, long time2); static long wrapToLong(long time); static String get1224(long l); static final long DAY_TIME; static SimpleDateFormat simpleDateFormat_1; static final SimpleDateFormat simpleDateFormat1; static final SimpleDateFormat simpleDateFormat2; } | @Test public void isToday() throws Exception { } |
JConstant { public static String assembleUrl(String id, String packageName) { return String.format(Locale.getDefault(), VERSION_URL, id, packageName); } static String getAIText(int[] objects); static String getRoot(); static int getNetTypeRes(int net); static int getMessageIcon(int pid); static int getOnlineIcon(int pid); static int getOfflineIcon(int pid); static String assembleUrl(String id, String packageName); static final String CYLAN_TAG; static final String KEY_NEW_HOME_ACTIVITY_BOTTOM_MENU_CONTAINER_ID; static final int AUTHORIZE_PHONE_SMS; static final int AUTHORIZE_MAIL; static final int GET_SMS_BACK; static final int CHECK_TIMEOUT; static final int CHECK_ACCOUNT; static final int THIS_ACCOUNT_NOT_REGISTERED; static final String KEY_TIME_TICK_; static final int TYPE_INVALID; static final int TYPE_PHONE; static final int TYPE_EMAIL; static final int TYPE_EMAIL_VERIFY; final static Pattern PHONE_REG; final static Pattern EMAIL_REG; static final Pattern MAC_REG; static final String EFAMILY_URL_PREFIX; static final int VALID_VERIFICATION_CODE_LEN; static final int PWD_LEN_MIN; static final int PWD_LEN_MAX; static final int USER_INPUT_LEN; static final int REGISTER_BY_PHONE; static final int REGISTER_BY_EMAIL; static final String KEY_ACTIVITY_FRAGMENT_CONTAINER_ID; static final String KEY_LOCALE; static final int LOCALE_SIMPLE_CN; static final int LOCALE_T_CN; static final long VERIFICATION_CODE_DEADLINE; static final String KEY_ACCOUNT_TO_SEND; static final String KEY_PWD_TO_SEND; static final String AUTO_LOGIN_ACCOUNT; static final String AUTO_LOGIN_PWD; static final String OPEN_LOGIN_TO_BIND_PHONE; static final String OPEN_LOGIN_USER_ICON; static final String OPEN_LOGIN_USER_ALIAS; static final String AUTO_SIGNIN_KEY; static final String TWITTER_INIT_KEY; static final String FACEBOOK_INIT_KEY; static final String FROM_LOG_OUT; static final String AUTO_lOGIN_PWD_ERR; static final String REG_SWITCH_BOX; static final String THIRD_RE_SHOW; static final String KEY_VCODE_TO_SEND; static final String KEY_SET_UP_PWD_TYPE; static final String KEY_SHOW_LOGIN_FRAGMENT; static final String KEY_SHOW_LOGIN_FRAGMENT_EXTRA; static final String KEY_FRESH; static final String KEY_HELP_GUIDE; static final String KEY_DELAY_RECORD_GUIDE; static final String VIEW_CALL_WAY; static final String VIEW_CALL_WAY_VIEWER; static final String VIEW_CALL_WAY_LISTEN; static final String VIEW_CALL_WAY_EXTRA; static final String KEY_WONDERFUL_GUIDE; static final String VIEW_CALL_WAY_TIME; static final String KEY_SIMPLE_STRING_ITEM; static final String KEY_CAM_SIGHT_SETTING; static final java.lang.String LAST_ENTER_TIME; static final String KEY_BIND_DEVICE_ALIAS; static final java.lang.String KEY_PANORAMA_POP_HINT; static final String BELL_HOME_LAST_ENTER_TIME; static final String KEY_COMPONENT_NAME; static final int REQ_CODE_ACTIVITY; static final int RESULT_CODE_FINISH; static final int RESULT_CODE_REMOVE_ITEM; static final String KEY_REMOVE_DEVICE; static final String KEY_REMOVE_ITEM_CID; static final String KEY_ACTIVITY_RESULT_CODE; static final String KEY_DEVICE_ITEM_BUNDLE; static final String KEY_DEVICE_ITEM_UUID; static final String KEY_DEVICE_TIME_ZONE; static final java.lang.String SHOW_PASSWORD_CHANGED; static final String KEY_CONFIG_FREE_CAM; static final java.lang.String PANORAMA_THUMB_PICTURE; static final java.lang.String SWITCH_MODE_POP; static final String ALERT_MOBILE; static final java.lang.String SHOW_VR_MODE_TIPS; static final java.lang.String KEY_SHOW_TIME_ZONE; static final java.lang.String FRIEND_LAST_VISABLE_TIME; static final String KEY_DEVICE_ITEM_IS_BELL; static final java.lang.String NEED_SHOW_BIND_ANIMATION; static final java.lang.String KEY_SHOW_HISTORY_WHEEL_CASE; static final String KEY_CAM_LIVE_PAGE_PLAY_HISTORY_INIT_WHEEL; static final String KEY_BIND_BACK_ACTIVITY; static final int OBJECT_MAN; static final int OBJECT_CAT; static final int OBJECT_DOG; static final int OBJECT_CAR; static final String IS_IN_BACKGROUND; static String KEY_BELL_CALL_PROCESS_ID; static String KEY_BELL_CALL_PROCESS_IS_FOREGROUND; static final int INVALID_PROCESS; static final String KEY_SHARE_ELEMENT_BYTE; static final String KEY_SHARED_ELEMENT_LIST; static final String KEY_SHARED_ELEMENT_BELL_LIST; static final String KEY_SHARED_ELEMENT_STARTED_POSITION; static final String EXTRA_STARTING_ALBUM_POSITION; static final String EXTRA_CURRENT_ALBUM_POSITION; static final String KEY_SHARED_ELEMENT_TRANSITION_NAME_SUFFIX; static final String KEY_DEVICE_NEW_VERSION; static final String ROOT_DIR; static final String UPDATE_FILE_PATH; static final String BLOCK_LOG_PATH; static final String CRASH_PATH; static final String DAEMON_DIR; static final String WORKER_PATH; static final String MEDIA_PATH; static final String SYSTEM_PHOTO_PATH; static final String MISC_PATH; static final String USER_IMAGE_HEAD_URL; static final String MEDIA_DETAIL_PICTURE_DOWNLOAD_DIR; static final String MEDIA_DETAIL_VIDEO_DOWNLOAD_DIR; static final String PREVIEW_CACHE; static final String RECEIVE_MESSAGE_NOTIFICATION; static final String OPEN_VOICE; static final String OPEN_SHAKE; static final String OPEN_DOOR_NOTIFY; static final String PAN_PATH; static final String KEY_REGISTER_SMS_TOKEN; static final String KEY_REGISTER_SMS_TOKEN_TIME; static final String KEY_FORGET_PWD_FRIST_GET_SMS; static final String KEY_FORGET_PWD_GET_SMS_COUNT; static final String KEY_REG_FRIST_GET_SMS; static final String KEY_REG_GET_SMS_COUNT; static final String KEY_BELL_LAST_ENTER_TIME_PREFIX; static final String KEY_BELL_LAST_LISTEN_TIME_PREFIX; static final int OS_SERVER; static final int OS_IOS_PHONE; static final int OS_PC; static final int OS_ANDROID_PHONE; static final int OS_CAMARA_ANDROID_SERVICE; static final int OS_CAMERA_ANDROID; static final int OS_CAMERA_UCOS; static final int OS_DOOR_BELL; static final int OS_CAMERA_UCOS_V2; static final int OS_EFAML; static final int OS_TEMP_HUMI; static final int OS_IR; static final int OS_MAGNET; static final int OS_AIR_DETECTOR; static final int OS_CAMERA_UCOS_V3; static final int OS_DOOR_BELL_CAM; static final int OS_DOOR_BELL_V2; static final int OS_CAMERA_ANDROID_4G; static final int OS_CAMERA_CC3200; static final int OS_CAMERA_PANORAMA_HAISI; static final int OS_CAMERA_PANORAMA_QIAOAN; static final int OS_CAMERA_PANORAMA_GUOKE; static final int PID_CAMERA_ANDROID_3_0; static final int OS_CAMERA_FXXX_LESHI; static final int PID_CAMERA_FXXX_LESHI_PID; static final int PID_CAMERA_VR_720; static final int PID_CAMERA_CLOUD; static final int PID_CAMERA_WIFI_G1; static final int PID_CAMERA_PANORAMA_HAISI_1080; static final int PID_CAMERA_PANORAMA_HAISI_960; static final int PID_BELL_G_1; static final int PID_BELL_G_2; static final String KEY_BIND_DEVICE; static final String BIND_DEVICE_CAM; static final String BIND_DEVICE_BELL; static final String BIND_DEVICE_CLOUD; static final String BIND_DEVICE_MAG; final static String KEY_ACCOUNT; final static String KEY_ACCOUNT_LOG_STATE; final static String KEY_NTP_INTERVAL; static final int PLAY_STATE_LOADING_FAILED; static final int PLAY_STATE_IDLE; static final int PLAY_STATE_PREPARE; static final int PLAY_STATE_PLAYING; static final int PLAY_STATE_STOP; static final int PLAY_STATE_NET_CHANGED; static final int CLOUD_OUT_CONNECT_TIME_OUT; static final int CLOUD_IN_CONNECT_TIME_OUT; static final int CLOUD_IN_CONNECT_OK; static final int CLOUD_IN_CONNECT_FAILED; static final int CLOUD_OUT_CONNECT_OK; static final int CLOUD_OUT_CONNECT_FAILED; static final String JUST_SEND_INFO; static final String KEY_CAM_LIVE_PAGE_PLAY_HISTORY_TIME; static final String KEY_JUMP_TO_CAM_DETAIL; static final String KEY_UUID_RESOLUTION; static final String KEY_UUID_PREVIEW_THUMBNAIL_TOKEN; static final String BINDING_DEVICE; static final String KEY_FIRMWARE_CONTENT; static final String KEY_FIRMWARE_POP_DIALOG_TIME; static final String KEY_CLIENT_NEW_VERSION_DIALOG; static final String PREF_NAME; static final String KEY_PHONE; static final String SESSIONID; static final String KEY_PSW; static final String UPDATAE_AUTO_LOGIN; static final String CLIENT_UPDATAE_TAB; static final String CLIENT_UPDATAE_TIME_TAB; static final String NEED_SHOW_COLLECT_USE_CASE; static final String NEED_SHOW_BIND_USE_CASE; static final String IS_FIRST_PAGE_VIS; static final String KEY_JUMP_TO_MESSAGE; static final String KEY_CLIENT_CHECK_VERSION_ID; static final String KEY_DEVICE_MAC; static final String KEY_ADD_DESC; static final int CODE_AD_FINISH; static final String KEY_NEED_LOGIN; static final String KEY_CLIENT_UPDATE_DESC; static final String KEY_LAST_TIME_CHECK_VERSION; static final String KEY_JUMP_TO_WONDER; static final String SHOW_GCM_DIALOG; static final String KEY_SHOW_SUGGESTION; static String KEY_CURRENT_PLAY_VIEW; static final String KEY_ANIM_GIF; static final String KEY_CONNECT_AP_GIF; static final String KEY_SSID_PREFIX; static final String KEY_ANIM_TITLE; static final String KEY_ANIM_SUB_TITLE; static final String KEY_NEXT_STEP; } | @Test public void testUrl() { String id = "VRJz6f"; String packageName = "hell"; System.out.println(assembleUrl(id, packageName)); } |
TimeUtils { public static String getSuperString(long time) { return getDateFormatSuper.get().format(new Date(time)); } static String getMM_SS(long time); static String getYHM(long time); static String getHistoryTime(long timeInLong); static String getHistoryTime1(long timeInLong); static String getLiveTime(long timeInLong); static String getTimeSpecial(long time); static long getTodayStartTime(); static long getTodayEndTime(); static long getSpecificDayEndTime(long time); static long getSpecificDayStartTime(long time); static String getMediaPicTimeInString(final long time); static String getYMDHM(final long time); static String getMediaVideoTimeInString(final long time); static String getTodayString(); static String getDayString(long time); static String getUptime(long time); static String getDayInMonth(long time); static String getMM_DD(long time); static String getHH_MM(long time); static String getHH_MM_Remain(long timeMs); static String getTestTime(long time); static String getSpecifiedDate(long time); static String getDatePickFormat(long time, TimeZone timeZone); static int getWeekNum(long time, TimeZone timeZone); static long startOfDay(long time); static boolean isToday(long time); static String getSuperString(long time); static String getHomeItemTime(Context context, long time); static String getDay(long time); static String getMonthInYear(long time); static String getHHMMSS(long timeMs); static String AutoHHMMSS(long timeMs); static String getBellRecordTime(long time); static String getWonderTime(long time); static boolean isSameDay(long time1, long time2); static long wrapToLong(long time); static String get1224(long l); static final long DAY_TIME; static SimpleDateFormat simpleDateFormat_1; static final SimpleDateFormat simpleDateFormat1; static final SimpleDateFormat simpleDateFormat2; } | @Test public void getSuperString() throws Exception { } |
TimeUtils { public static String getHomeItemTime(Context context, long time) { if (time == 0) return ""; if (System.currentTimeMillis() - time <= 5 * 60 * 1000L) return context.getString(R.string.JUST_NOW); if (startOfDay(System.currentTimeMillis()) < time) return getSimpleDateFormatHHMM.get().format(new Date(time)); return getSimpleDateFormatYYYYHHMM.get().format(new Date(time)); } static String getMM_SS(long time); static String getYHM(long time); static String getHistoryTime(long timeInLong); static String getHistoryTime1(long timeInLong); static String getLiveTime(long timeInLong); static String getTimeSpecial(long time); static long getTodayStartTime(); static long getTodayEndTime(); static long getSpecificDayEndTime(long time); static long getSpecificDayStartTime(long time); static String getMediaPicTimeInString(final long time); static String getYMDHM(final long time); static String getMediaVideoTimeInString(final long time); static String getTodayString(); static String getDayString(long time); static String getUptime(long time); static String getDayInMonth(long time); static String getMM_DD(long time); static String getHH_MM(long time); static String getHH_MM_Remain(long timeMs); static String getTestTime(long time); static String getSpecifiedDate(long time); static String getDatePickFormat(long time, TimeZone timeZone); static int getWeekNum(long time, TimeZone timeZone); static long startOfDay(long time); static boolean isToday(long time); static String getSuperString(long time); static String getHomeItemTime(Context context, long time); static String getDay(long time); static String getMonthInYear(long time); static String getHHMMSS(long timeMs); static String AutoHHMMSS(long timeMs); static String getBellRecordTime(long time); static String getWonderTime(long time); static boolean isSameDay(long time1, long time2); static long wrapToLong(long time); static String get1224(long l); static final long DAY_TIME; static SimpleDateFormat simpleDateFormat_1; static final SimpleDateFormat simpleDateFormat1; static final SimpleDateFormat simpleDateFormat2; } | @Test public void getHomeItemTime() throws Exception { } |
TimeUtils { public static String getMonthInYear(long time) { SimpleDateFormat format = (SimpleDateFormat) SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.FULL, SimpleDateFormat.FULL); format.applyPattern("MMMM"); return format.format(new Date(time)); } static String getMM_SS(long time); static String getYHM(long time); static String getHistoryTime(long timeInLong); static String getHistoryTime1(long timeInLong); static String getLiveTime(long timeInLong); static String getTimeSpecial(long time); static long getTodayStartTime(); static long getTodayEndTime(); static long getSpecificDayEndTime(long time); static long getSpecificDayStartTime(long time); static String getMediaPicTimeInString(final long time); static String getYMDHM(final long time); static String getMediaVideoTimeInString(final long time); static String getTodayString(); static String getDayString(long time); static String getUptime(long time); static String getDayInMonth(long time); static String getMM_DD(long time); static String getHH_MM(long time); static String getHH_MM_Remain(long timeMs); static String getTestTime(long time); static String getSpecifiedDate(long time); static String getDatePickFormat(long time, TimeZone timeZone); static int getWeekNum(long time, TimeZone timeZone); static long startOfDay(long time); static boolean isToday(long time); static String getSuperString(long time); static String getHomeItemTime(Context context, long time); static String getDay(long time); static String getMonthInYear(long time); static String getHHMMSS(long timeMs); static String AutoHHMMSS(long timeMs); static String getBellRecordTime(long time); static String getWonderTime(long time); static boolean isSameDay(long time1, long time2); static long wrapToLong(long time); static String get1224(long l); static final long DAY_TIME; static SimpleDateFormat simpleDateFormat_1; static final SimpleDateFormat simpleDateFormat1; static final SimpleDateFormat simpleDateFormat2; } | @Test public void getMonthInYear() throws Exception { } |
TimeUtils { public static String getBellRecordTime(long time) { Date today = new Date(); Date provide = new Date(time); SimpleDateFormat format = (SimpleDateFormat) SimpleDateFormat.getInstance(); if (today.getYear() > provide.getYear()) { format.applyPattern("yyyy.MM.dd"); return format.format(provide); } if (today.getMonth() == provide.getMonth()) { if (today.getDate() == provide.getDate()) { return ContextUtils.getContext().getString(R.string.DOOR_TODAY); } if (today.getDate() - provide.getDate() == 1) { return ContextUtils.getContext().getString(R.string.Yesterday); } } format.applyPattern("MM.dd"); return format.format(provide); } static String getMM_SS(long time); static String getYHM(long time); static String getHistoryTime(long timeInLong); static String getHistoryTime1(long timeInLong); static String getLiveTime(long timeInLong); static String getTimeSpecial(long time); static long getTodayStartTime(); static long getTodayEndTime(); static long getSpecificDayEndTime(long time); static long getSpecificDayStartTime(long time); static String getMediaPicTimeInString(final long time); static String getYMDHM(final long time); static String getMediaVideoTimeInString(final long time); static String getTodayString(); static String getDayString(long time); static String getUptime(long time); static String getDayInMonth(long time); static String getMM_DD(long time); static String getHH_MM(long time); static String getHH_MM_Remain(long timeMs); static String getTestTime(long time); static String getSpecifiedDate(long time); static String getDatePickFormat(long time, TimeZone timeZone); static int getWeekNum(long time, TimeZone timeZone); static long startOfDay(long time); static boolean isToday(long time); static String getSuperString(long time); static String getHomeItemTime(Context context, long time); static String getDay(long time); static String getMonthInYear(long time); static String getHHMMSS(long timeMs); static String AutoHHMMSS(long timeMs); static String getBellRecordTime(long time); static String getWonderTime(long time); static boolean isSameDay(long time1, long time2); static long wrapToLong(long time); static String get1224(long l); static final long DAY_TIME; static SimpleDateFormat simpleDateFormat_1; static final SimpleDateFormat simpleDateFormat1; static final SimpleDateFormat simpleDateFormat2; } | @Test public void getBellRecordTime() throws Exception { Date now = new Date(); SimpleDateFormat dateFormat = new SimpleDateFormat("EE", Locale.SIMPLIFIED_CHINESE); String asWeek = dateFormat.format(now); System.out.println(asWeek); System.out.println("星期缩写:"); for (Locale locale : JFGRules.CONST_LOCALE) { DateFormatSymbols symbols = new DateFormatSymbols(locale); String[] dayNames = symbols.getShortWeekdays(); System.out.print("" + locale.getCountry() + ":"); for (String s : dayNames) { System.out.print(s + " "); } System.out.println(""); } System.out.print("月份缩写:"); for (Locale locale : JFGRules.CONST_LOCALE) { DateFormatSymbols symbols = new DateFormatSymbols(locale); String[] dayNames = symbols.getShortMonths(); System.out.print("" + locale.getCountry() + ":"); for (String s : dayNames) { System.out.print(s + " "); } System.out.println(""); } } |
MiscUtils { public static List<JFGDPMsg> getCamDateVersionList(long startTime, int days) { ArrayList<JFGDPMsg> list = new ArrayList<>(); for (int i = 0; i < days; i++) { list.add(makeMsg(startTime - 24 * 3600 * 1000L * i, 222)); list.add(makeMsg(startTime - 24 * 3600 * 1000L * i, 505)); list.add(makeMsg(startTime - 24 * 3600 * 1000L * i, 512)); list.add(makeMsg(startTime - 24 * 3600 * 1000L * i, 401)); } return list; } static boolean isInRange(int start, int end, int dst); static boolean isBad(List<Integer> list, int level, int count); static int parseTime(String time); static String parse2Time(int value); static String getByteFromBitRate(long bitRate); static String getFlowResult(long byteData); static int getCount(int sum); static String getFileName(CamMessageBean bean, int index); static int getFileTime(CamMessageBean bean); static int getFileType(CamMessageBean bean); static CamWarnGlideURL getCamWarnUrl(String cid, CamMessageBean bean, int index); @SuppressWarnings("unchecked") static T cast(Object object, T defaultValue); static String bytesToHex(byte[] in); static Observable<List<TimeZoneBean>> loadTimeZoneList(); static T getValue(Object o, T t); static String getBeautifulString(String temp, int len); static ArrayList<String> getSharedList(List<Device> devices); static ArrayList<String> getNoneSharedList(List<Device> devices); static ArrayList<Long> createGetCameraWarnMsgDp(Device device); static boolean checkWriteExternalPermission(); static int setBit(int x, int n, int flag); static int getBit(int n, int k); static T safeGet(DpMsgDefine.DPPrimary<? extends T> value, T defaultValue); static long getVersion(List<T> set, boolean min); static JFGDPMsg getMessageByVersion(long id, long version); static boolean checkGpsAvailable(Context context); static T getObjectFromSP(String key, Class<T> tClass); static String FormatSdCardSize(long fileS); static String FormatSdCardSizeSpec(long fileS, String unit); static String getChaosTime(Context context, DpMsgDefine.DPAlarmInfo info, boolean off); static int getValueFrom(String content); static List<JFGDPMsg> getCamDateVersionList(long startTime, int days); static String makeFragmentName(int viewId, long id); static DPEntity getMaxVersionEntity(DPEntity... entities); static ArrayList<IDPEntity> msgList(DBAction dbAction, String uuid, String account, String server, List<JFGDPMsg> list); static List<IDPEntity> buildEntity(String uuid, long msgId, long version, boolean asc); static int getFileIndex(CamMessageBean camMessageBean); static long getVersion(CamMessageBean camMessageBean); static long getFinalVersion(CamMessageBean bean, int index); static void getDelta(CamMessageBean bean, long version); static String getErr(Throwable throwable); static boolean isLand(); static List<String> getUUidListFromItem(List<HomeItem> list); static List<HomeItem> getHomeItemListFromDevice(List<Device> list); static boolean insertImage(String filePath, String fileName); static String getFileNameWithoutExn(String url); static boolean isDeviceInWLAN(String uuid); static void recoveryWiFi(); static Observable<String> getAppVersionFromGooglePlay(); static boolean isGooglePlayServiceAvailable(); static boolean isAPDirect(String mac); static long getFileSizeFromUrl(String url); static String verticalString(String str); static void checkJFGLikeApp(); static void checkVPNState(); static String getValueFromUri(String url, String key); static int getSum(int num, int base); static boolean arrayContains(T[] array, T target); static boolean arrayContains(int[] array, int target); } | @Test public void getCamDateVersionList() throws Exception { SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd"); Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); List<JFGDPMsg> list = MiscUtils.getCamDateVersionList(calendar.getTimeInMillis(), 15); for (int i = 0; i < 45; i++) System.out.println("" + format.format(new Date(list.get(i).version))); } |
MiscUtils { public static int getSum(int num, int base) { float ret = (float) num / base; int count = num / base; if (ret > count) { return count + 1; } return 0; } static boolean isInRange(int start, int end, int dst); static boolean isBad(List<Integer> list, int level, int count); static int parseTime(String time); static String parse2Time(int value); static String getByteFromBitRate(long bitRate); static String getFlowResult(long byteData); static int getCount(int sum); static String getFileName(CamMessageBean bean, int index); static int getFileTime(CamMessageBean bean); static int getFileType(CamMessageBean bean); static CamWarnGlideURL getCamWarnUrl(String cid, CamMessageBean bean, int index); @SuppressWarnings("unchecked") static T cast(Object object, T defaultValue); static String bytesToHex(byte[] in); static Observable<List<TimeZoneBean>> loadTimeZoneList(); static T getValue(Object o, T t); static String getBeautifulString(String temp, int len); static ArrayList<String> getSharedList(List<Device> devices); static ArrayList<String> getNoneSharedList(List<Device> devices); static ArrayList<Long> createGetCameraWarnMsgDp(Device device); static boolean checkWriteExternalPermission(); static int setBit(int x, int n, int flag); static int getBit(int n, int k); static T safeGet(DpMsgDefine.DPPrimary<? extends T> value, T defaultValue); static long getVersion(List<T> set, boolean min); static JFGDPMsg getMessageByVersion(long id, long version); static boolean checkGpsAvailable(Context context); static T getObjectFromSP(String key, Class<T> tClass); static String FormatSdCardSize(long fileS); static String FormatSdCardSizeSpec(long fileS, String unit); static String getChaosTime(Context context, DpMsgDefine.DPAlarmInfo info, boolean off); static int getValueFrom(String content); static List<JFGDPMsg> getCamDateVersionList(long startTime, int days); static String makeFragmentName(int viewId, long id); static DPEntity getMaxVersionEntity(DPEntity... entities); static ArrayList<IDPEntity> msgList(DBAction dbAction, String uuid, String account, String server, List<JFGDPMsg> list); static List<IDPEntity> buildEntity(String uuid, long msgId, long version, boolean asc); static int getFileIndex(CamMessageBean camMessageBean); static long getVersion(CamMessageBean camMessageBean); static long getFinalVersion(CamMessageBean bean, int index); static void getDelta(CamMessageBean bean, long version); static String getErr(Throwable throwable); static boolean isLand(); static List<String> getUUidListFromItem(List<HomeItem> list); static List<HomeItem> getHomeItemListFromDevice(List<Device> list); static boolean insertImage(String filePath, String fileName); static String getFileNameWithoutExn(String url); static boolean isDeviceInWLAN(String uuid); static void recoveryWiFi(); static Observable<String> getAppVersionFromGooglePlay(); static boolean isGooglePlayServiceAvailable(); static boolean isAPDirect(String mac); static long getFileSizeFromUrl(String url); static String verticalString(String str); static void checkJFGLikeApp(); static void checkVPNState(); static String getValueFromUri(String url, String key); static int getSum(int num, int base); static boolean arrayContains(T[] array, T target); static boolean arrayContains(int[] array, int target); } | @Test public void testUrl() { long time = 1499670801000l; SimpleDateFormat format = new SimpleDateFormat("yyyyMMDD HH:mm:ss", Locale.getDefault()); format.setTimeZone(TimeZone.getTimeZone("GMT+8:00")); System.out.println(format.format(new Date(time))); format.setTimeZone(TimeZone.getTimeZone("GMT+0:00")); System.out.println(format.format(new Date(time))); System.out.println(MiscUtils.getSum(100, 200)); System.out.println(MiscUtils.getSum(199, 200)); System.out.println(MiscUtils.getSum(200, 200)); System.out.println(MiscUtils.getSum(201, 200)); } |
MapSubscription implements Subscription { @Override public boolean isUnsubscribed() { return unsubscribed; } MapSubscription(); @Override boolean isUnsubscribed(); void add(final Subscription s, String tag); void remove(final String tag); void clear(); @Override void unsubscribe(); boolean hasSubscriptions(); boolean hasSubscription(String tag); } | @Test public void isUnsubscribed() throws Exception { } |
MapSubscription implements Subscription { public void add(final Subscription s, String tag) { remove(tag); if (!unsubscribed) { synchronized (this) { if (!unsubscribed) { if (subscriptions == null) { subscriptions = new HashMap<>(4); } subscriptions.put(tag, s); AppLogger.d("add to sub:" + tag); return; } } } s.unsubscribe(); } MapSubscription(); @Override boolean isUnsubscribed(); void add(final Subscription s, String tag); void remove(final String tag); void clear(); @Override void unsubscribe(); boolean hasSubscriptions(); boolean hasSubscription(String tag); } | @Test public void add() throws Exception { MapSubscription mapSubscription = new MapSubscription(); mapSubscription.add(getTag(), "getTag"); mapSubscription.add(getTag(), "getTag"); Thread.sleep(50000); } |
MapSubscription implements Subscription { public void remove(final String tag) { if (!unsubscribed) { Subscription unsubscribe = null; synchronized (this) { if (unsubscribed || subscriptions == null) { return; } unsubscribe = subscriptions.remove(tag); } if (unsubscribe != null) { unsubscribe.unsubscribe(); } } } MapSubscription(); @Override boolean isUnsubscribed(); void add(final Subscription s, String tag); void remove(final String tag); void clear(); @Override void unsubscribe(); boolean hasSubscriptions(); boolean hasSubscription(String tag); } | @Test public void remove() throws Exception { } |
MapSubscription implements Subscription { public void clear() { if (!unsubscribed) { Collection<Map.Entry<String, Subscription>> unsubscribe = null; synchronized (this) { if (unsubscribed || subscriptions == null) { return; } else { unsubscribe = subscriptions.entrySet(); subscriptions = null; } unsubscribeFromAll(unsubscribe); } } } MapSubscription(); @Override boolean isUnsubscribed(); void add(final Subscription s, String tag); void remove(final String tag); void clear(); @Override void unsubscribe(); boolean hasSubscriptions(); boolean hasSubscription(String tag); } | @Test public void clear() throws Exception { } |
MapSubscription implements Subscription { @Override public void unsubscribe() { if (!unsubscribed) { Collection<Map.Entry<String, Subscription>> unsubscribe = null; synchronized (this) { if (unsubscribed || subscriptions == null) { return; } unsubscribed = true; unsubscribe = subscriptions.entrySet(); subscriptions = null; } unsubscribeFromAll(unsubscribe); } } MapSubscription(); @Override boolean isUnsubscribed(); void add(final Subscription s, String tag); void remove(final String tag); void clear(); @Override void unsubscribe(); boolean hasSubscriptions(); boolean hasSubscription(String tag); } | @Test public void unsubscribe() throws Exception { } |
MapSubscription implements Subscription { public boolean hasSubscriptions() { if (!unsubscribed) { synchronized (this) { return !unsubscribed && subscriptions != null && !subscriptions.isEmpty(); } } return false; } MapSubscription(); @Override boolean isUnsubscribed(); void add(final Subscription s, String tag); void remove(final String tag); void clear(); @Override void unsubscribe(); boolean hasSubscriptions(); boolean hasSubscription(String tag); } | @Test public void hasSubscriptions() throws Exception { } |
DeviceBean implements Parcelable { @Override public int hashCode() { return uuid != null ? uuid.hashCode() : 0; } DeviceBean(); protected DeviceBean(Parcel in); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override int describeContents(); @Override void writeToParcel(Parcel dest, int flags); public String uuid; public String sn; public String alias; public String shareAccount; public int pid; public int isChooseFlag; public int hasShareCount; static final Creator<DeviceBean> CREATOR; } | @Test public void testHashCode() { List<DeviceBean> beanList = new ArrayList<>(); for (int i = 0; i < 10; i++) { DeviceBean bean = new DeviceBean(); bean.alias = RandomUtils.getRandom(50) + ""; bean.uuid = i + ""; bean.uuid = i + ""; bean.sn = i + ""; beanList.add(bean); } for (int i = 8; i < 12; i++) { DeviceBean bean = new DeviceBean(); bean.alias = RandomUtils.getRandom(50) + ""; bean.uuid = i + ""; bean.uuid = i + ""; bean.sn = i + ""; beanList.add(bean); } beanList = new ArrayList<>(new HashSet<>(beanList)); assertTrue(beanList.size() == 12); } |
RxTask { @CheckReturnValue @NonNull public static <R> Single<R> single(@NonNull final Callable<Task<R>> callable) { return Single.fromCallable(callable).flatMap(new Function<Task<R>, SingleSource<? extends R>>() { @Override public SingleSource<? extends R> apply(Task<R> task) throws Exception { return single(task); } }); } @CheckReturnValue @NonNull static Single<R> single(@NonNull final Callable<Task<R>> callable); @CheckReturnValue @NonNull static Single<R> single(@NonNull final Task<R> task); @CheckReturnValue @NonNull static Completable completes(@NonNull final Callable<Task<R>> callable); @CheckReturnValue @NonNull static Completable completes(@NonNull final Task<R> task); @CheckReturnValue @NonNull static Maybe<R> maybe(@NonNull final Callable<Task<R>> callable); @CheckReturnValue @NonNull static Maybe<R> maybe(@NonNull final Task<R> task); @NonNull @CheckReturnValue static OnCompleteListener<R> listener(@NonNull final MaybeEmitter<R> emit); @NonNull @CheckReturnValue static OnCompleteListener<R> listener(@NonNull final CompletableEmitter emit); @NonNull @CheckReturnValue static OnCompleteListener<R> listener(@NonNull final SingleEmitter<R> emit); } | @Test public void testSingleSuccessful() { final String hello = "Hello, world!"; when(mockHelloTask.getResult()) .thenReturn(hello); when(mockHelloTask.isSuccessful()) .thenReturn(true); when(mockHelloTask.addOnCompleteListener(onComplete.capture())) .thenReturn(mockHelloTask); TestObserver<String> obs = TestObserver.create(); RxTask.single(mockHelloTask).subscribe(obs); verify(mockHelloTask).addOnCompleteListener(onComplete.capture()); onComplete.getValue().onComplete(mockHelloTask); obs.assertValue(hello) .assertNoErrors() .assertComplete(); verify(mockHelloTask).addOnCompleteListener(any(OnCompleteListener.class)); verify(mockHelloTask).getResult(); }
@Test public void testSingleFailure() { final String hello = "Hello, world!"; when(mockHelloTask.isSuccessful()) .thenReturn(false); when(mockHelloTask.getException()) .thenReturn(new RuntimeException(hello)); when(mockHelloTask.addOnCompleteListener(onComplete.capture())) .thenReturn(mockHelloTask); TestObserver<String> obs = TestObserver.create(); RxTask.single(mockHelloTask).subscribe(obs); verify(mockHelloTask).addOnCompleteListener(onComplete.capture()); onComplete.getValue().onComplete(mockHelloTask); obs.assertError(RuntimeException.class) .assertErrorMessage(hello) .dispose(); verify(mockHelloTask).addOnCompleteListener(any(OnCompleteListener.class)); verify(mockHelloTask).getException(); } |
RxTask { @CheckReturnValue @NonNull public static <R> Completable completes(@NonNull final Callable<Task<R>> callable) { return Single.fromCallable(callable).flatMapCompletable( new Function<Task<R>, Completable>() { @Override public Completable apply(Task<R> task) throws Exception { return completes(task); } }); } @CheckReturnValue @NonNull static Single<R> single(@NonNull final Callable<Task<R>> callable); @CheckReturnValue @NonNull static Single<R> single(@NonNull final Task<R> task); @CheckReturnValue @NonNull static Completable completes(@NonNull final Callable<Task<R>> callable); @CheckReturnValue @NonNull static Completable completes(@NonNull final Task<R> task); @CheckReturnValue @NonNull static Maybe<R> maybe(@NonNull final Callable<Task<R>> callable); @CheckReturnValue @NonNull static Maybe<R> maybe(@NonNull final Task<R> task); @NonNull @CheckReturnValue static OnCompleteListener<R> listener(@NonNull final MaybeEmitter<R> emit); @NonNull @CheckReturnValue static OnCompleteListener<R> listener(@NonNull final CompletableEmitter emit); @NonNull @CheckReturnValue static OnCompleteListener<R> listener(@NonNull final SingleEmitter<R> emit); } | @Test public void testCompleteSuccessful() { final String hello = "Hello, world!"; when(mockHelloTask.getResult()) .thenReturn(hello); when(mockHelloTask.isSuccessful()) .thenReturn(true); when(mockHelloTask.addOnCompleteListener(onComplete.capture())) .thenReturn(mockHelloTask); TestObserver<String> obs = TestObserver.create(); RxTask.completes(mockHelloTask).subscribe(obs); verify(mockHelloTask).addOnCompleteListener(onComplete.capture()); onComplete.getValue().onComplete(mockHelloTask); obs.assertNoErrors() .assertComplete(); verify(mockHelloTask).addOnCompleteListener(any(OnCompleteListener.class)); }
@Test public void testCompleteFailure() { final String hello = "Hello, world!"; when(mockHelloTask.isSuccessful()) .thenReturn(false); when(mockHelloTask.getException()) .thenReturn(new RuntimeException(hello)); when(mockHelloTask.addOnCompleteListener(onComplete.capture())) .thenReturn(mockHelloTask); TestObserver<String> obs = TestObserver.create(); RxTask.completes(mockHelloTask) .subscribe(obs); verify(mockHelloTask).addOnCompleteListener(onComplete.capture()); onComplete.getValue().onComplete(mockHelloTask); obs.dispose(); obs.assertError(RuntimeException.class) .assertErrorMessage(hello); verify(mockHelloTask).addOnCompleteListener(any(OnCompleteListener.class)); verify(mockHelloTask).getException(); } |
RxTask { @CheckReturnValue @NonNull public static <R> Maybe<R> maybe(@NonNull final Callable<Task<R>> callable) { return Single.fromCallable(callable).flatMapMaybe( new Function<Task<R>, MaybeSource<? extends R>>() { @Override public MaybeSource<? extends R> apply(Task<R> task) throws Exception { return maybe(task); } }); } @CheckReturnValue @NonNull static Single<R> single(@NonNull final Callable<Task<R>> callable); @CheckReturnValue @NonNull static Single<R> single(@NonNull final Task<R> task); @CheckReturnValue @NonNull static Completable completes(@NonNull final Callable<Task<R>> callable); @CheckReturnValue @NonNull static Completable completes(@NonNull final Task<R> task); @CheckReturnValue @NonNull static Maybe<R> maybe(@NonNull final Callable<Task<R>> callable); @CheckReturnValue @NonNull static Maybe<R> maybe(@NonNull final Task<R> task); @NonNull @CheckReturnValue static OnCompleteListener<R> listener(@NonNull final MaybeEmitter<R> emit); @NonNull @CheckReturnValue static OnCompleteListener<R> listener(@NonNull final CompletableEmitter emit); @NonNull @CheckReturnValue static OnCompleteListener<R> listener(@NonNull final SingleEmitter<R> emit); } | @Test public void testMaybe() { final String hello = "Hello, world!"; when(mockHelloTask.getResult()) .thenReturn(hello); when(mockHelloTask.isSuccessful()) .thenReturn(true); when(mockHelloTask.addOnCompleteListener(onComplete.capture())) .thenReturn(mockHelloTask); TestObserver<String> obs = TestObserver.create(); RxTask.maybe(mockHelloTask).subscribe(obs); verify(mockHelloTask).addOnCompleteListener(onComplete.capture()); onComplete.getValue().onComplete(mockHelloTask); obs.assertValue(hello) .assertNoErrors() .assertComplete(); verify(mockHelloTask).addOnCompleteListener(any(OnCompleteListener.class)); verify(mockHelloTask).getResult(); }
@Test public void testMaybeFailure() { final String hello = "Hello, world!"; when(mockHelloTask.isSuccessful()) .thenReturn(false); when(mockHelloTask.getException()) .thenReturn(new RuntimeException(hello)); when(mockHelloTask.addOnCompleteListener(onComplete.capture())) .thenReturn(mockHelloTask); TestObserver<String> obs = TestObserver.create(); RxTask.maybe(mockHelloTask).subscribe(obs); verify(mockHelloTask).addOnCompleteListener(onComplete.capture()); onComplete.getValue().onComplete(mockHelloTask); obs.assertError(RuntimeException.class) .assertErrorMessage(hello) .dispose(); verify(mockHelloTask).addOnCompleteListener(any(OnCompleteListener.class)); verify(mockHelloTask).getException(); } |
SimpleMemoryManager { public int malloc(final int size) { return malloc_internal(size + 16) + 16; } SimpleMemoryManager(final int totalMemory); int freeMemory(); int allocated(); int malloc(final int size); void free(final int position); void GC(); void printDebug(final PrintStream ps); } | @Test public void testMalloc() { final SimpleMemoryManager mm = new SimpleMemoryManager(1000); final int ptr = mm.malloc(100); assertEquals(16, ptr); assertEquals(884, mm.freeMemory()); assertEquals(116, mm.allocated()); assertEquals(132, mm.malloc(200)); assertEquals(348, mm.malloc(300)); mm.printDebug(System.out); } |
Module { public MemorySection getMems() { return mems; } Module(final String label, final String sourcemapFileName); void writeTo(final TextWriter writer, final boolean enableDebug); TypesSection getTypes(); GlobalsIndex globalsIndex(); EventIndex eventIndex(); FunctionIndex functionIndex(); void writeTo(final BinaryWriter writer, final boolean enableDebug); String getLabel(); MemorySection getMems(); FunctionsSection getFunctions(); ImportsSection getImports(); GlobalsSection getGlobals(); ExportsSection getExports(); TablesSection getTables(); EventSection getEvents(); } | @Test public void testWithExportedMemory() throws IOException { final StringWriter strWriter = new StringWriter(); final PrintWriter pw = new PrintWriter(strWriter); final Module module = new Module("mod", "mod.wasm.map"); final Memory memory = module.getMems().newMemory(10, 20); memory.exportAs("exported"); final Exporter exporter = new Exporter(debugOptions()); exporter.export(module, pw); Assert.assertEquals("(module $mod" + System.lineSeparator() + " (memory $mem0 10 20)" + System.lineSeparator() + " (export \"exported\" (memory $mem0))" + System.lineSeparator() + " )", strWriter.toString()); }
@Test public void testWithExportedMemoryBinary() throws IOException { final Module module = new Module("mod", "mod.wasm.map"); final Memory memory = module.getMems().newMemory(10, 20); memory.exportAs("exported"); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final StringWriter theSourceMap = new StringWriter(); final Exporter exporter = new Exporter(debugOptions()); exporter.export(module, bos, theSourceMap); final byte[] expected = IOUtils.toByteArray(getClass().getResource("testWithExportedMemory.wasm")); Assert.assertArrayEquals(expected, bos.toByteArray()); Assert.assertEquals("{\"version\":3,\"file\":\"mod.wasm\",\"sourceRoot\":\"\",\"names\":[],\"sources\":[],\"mappings\":\"\"}", theSourceMap.toString()); }
@Test public void testWithMemory() throws IOException { final StringWriter strWriter = new StringWriter(); final PrintWriter pw = new PrintWriter(strWriter); final Module module = new Module("mod", "mod.wasm.map"); final Memory memory = module.getMems().newMemory(10, 20); final Exporter exporter = new Exporter(debugOptions()); exporter.export(module, pw); Assert.assertEquals("(module $mod" + System.lineSeparator() + " (memory $mem0 10 20)" + System.lineSeparator() + " )", strWriter.toString()); }
@Test public void testWithMemoryBinary() throws IOException { final Module module = new Module("mod", "mod.wasm.map"); final Memory memory = module.getMems().newMemory(10, 20); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final StringWriter theSourceMap = new StringWriter(); final Exporter exporter = new Exporter(debugOptions()); exporter.export(module, bos, theSourceMap); final byte[] expected = IOUtils.toByteArray(getClass().getResource("testWithMemory.wasm")); Assert.assertArrayEquals(expected, bos.toByteArray()); Assert.assertEquals("{\"version\":3,\"file\":\"mod.wasm\",\"sourceRoot\":\"\",\"names\":[],\"sources\":[],\"mappings\":\"\"}", theSourceMap.toString()); } |
Module { public ImportsSection getImports() { return imports; } Module(final String label, final String sourcemapFileName); void writeTo(final TextWriter writer, final boolean enableDebug); TypesSection getTypes(); GlobalsIndex globalsIndex(); EventIndex eventIndex(); FunctionIndex functionIndex(); void writeTo(final BinaryWriter writer, final boolean enableDebug); String getLabel(); MemorySection getMems(); FunctionsSection getFunctions(); ImportsSection getImports(); GlobalsSection getGlobals(); ExportsSection getExports(); TablesSection getTables(); EventSection getEvents(); } | @Test public void testFunctionImportBinary() throws IOException { final Module module = new Module("mod", "mod.wasm.map"); final Function function = module.getImports().importFunction(new ImportReference("mod","obj"),"label", PrimitiveType.i32); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final StringWriter theSourceMap = new StringWriter(); final Exporter exporter = new Exporter(debugOptions()); exporter.export(module, bos, theSourceMap); final byte[] expected = IOUtils.toByteArray(getClass().getResource("testFunctionImport.wasm")); Assert.assertArrayEquals(expected, bos.toByteArray()); Assert.assertEquals("{\"version\":3,\"file\":\"mod.wasm\",\"sourceRoot\":\"\",\"names\":[],\"sources\":[],\"mappings\":\"\"}", theSourceMap.toString()); } |
Module { public FunctionsSection getFunctions() { return functions; } Module(final String label, final String sourcemapFileName); void writeTo(final TextWriter writer, final boolean enableDebug); TypesSection getTypes(); GlobalsIndex globalsIndex(); EventIndex eventIndex(); FunctionIndex functionIndex(); void writeTo(final BinaryWriter writer, final boolean enableDebug); String getLabel(); MemorySection getMems(); FunctionsSection getFunctions(); ImportsSection getImports(); GlobalsSection getGlobals(); ExportsSection getExports(); TablesSection getTables(); EventSection getEvents(); } | @Test public void testLocalAccess() throws IOException { final StringWriter strWriter = new StringWriter(); final PrintWriter pw = new PrintWriter(strWriter); final Module module = new Module("mod", "mod.wasm.map"); final FunctionsSection functionsContent = module.getFunctions(); final Param p1 = param("p1", PrimitiveType.i32); final Param p2 = param("p2", PrimitiveType.i32); final ExportableFunction function = functionsContent.newFunction("label", Arrays .asList(p1, p2), PrimitiveType.i32); final Local tempLocal = function.newLocal("loc", PrimitiveType.i32); function.flow.ret(getLocal(tempLocal, null), null); function.exportAs("expfunction"); final Exporter exporter = new Exporter(debugOptions()); exporter.export(module, pw); final String expected = "(module $mod" + System.lineSeparator() + " (type $t0 (func (param i32) (param i32) (result i32)))" + System.lineSeparator() + " (func $label (type $t0) (param $p1 i32) (param $p2 i32) (result i32)" + System.lineSeparator() + " (local $loc i32)" + System.lineSeparator() + " (return (get_local $loc))" + System.lineSeparator() + " )" + System.lineSeparator() + " (export \"expfunction\" (func $label))" + System.lineSeparator() + " )"; Assert.assertEquals(expected, strWriter.toString()); }
@Test public void testLocalAccessBinary() throws IOException { final Module module = new Module("mod", "mod.wasm.map"); final FunctionsSection functionsContent = module.getFunctions(); final Param p1 = param("p1", PrimitiveType.i32); final Param p2 = param("p2", PrimitiveType.i32); final ExportableFunction function = functionsContent.newFunction("label", Arrays .asList(p1, p2), PrimitiveType.i32); final Local tempLocal = function.newLocal("loc", PrimitiveType.i32); function.flow.ret(getLocal(tempLocal, null), null); function.exportAs("expfunction"); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final StringWriter theSourceMap = new StringWriter(); final Exporter exporter = new Exporter(debugOptions()); exporter.export(module, bos, theSourceMap); final byte[] expected = IOUtils.toByteArray(getClass().getResource("testLocalAccess.wasm")); Assert.assertArrayEquals(expected, bos.toByteArray()); Assert.assertEquals("{\"version\":3,\"file\":\"mod.wasm\",\"sourceRoot\":\"\",\"names\":[],\"sources\":[],\"mappings\":\"\"}", theSourceMap.toString()); }
@Test public void testBlock() throws IOException { final StringWriter strWriter = new StringWriter(); final PrintWriter pw = new PrintWriter(strWriter); final Module module = new Module("mod", "mod.wasm.map"); final FunctionsSection functionsContent = module.getFunctions(); final Param p1 = param("p1", PrimitiveType.i32); final Param p2 = param("p2", PrimitiveType.i32); final ExportableFunction function = functionsContent.newFunction("label", Arrays .asList(p1, p2), PrimitiveType.i32); final Local tempLocal = function.newLocal("loc", PrimitiveType.i32); final Block block = function.flow.block("outer", null); block.flow.ret(getLocal(tempLocal, null), null); function.flow.unreachable(null); function.exportAs("expfunction"); final Exporter exporter = new Exporter(debugOptions()); exporter.export(module, pw); final String expected = "(module $mod" + System.lineSeparator() + " (type $t0 (func (param i32) (param i32) (result i32)))" + System.lineSeparator() + " (func $label (type $t0) (param $p1 i32) (param $p2 i32) (result i32)" + System.lineSeparator() + " (local $loc i32)" + System.lineSeparator() + " (block $outer" + System.lineSeparator() + " (return (get_local $loc))" + System.lineSeparator() + " )" + System.lineSeparator() + " (unreachable))" + System.lineSeparator() + " (export \"expfunction\" (func $label))" + System.lineSeparator() + " )"; Assert.assertEquals(expected, strWriter.toString()); }
@Test public void testBlockBinary() throws IOException { final Module module = new Module("mod", "mod.wasm.map"); final FunctionsSection functionsContent = module.getFunctions(); final Param p1 = param("p1", PrimitiveType.i32); final Param p2 = param("p2", PrimitiveType.i32); final ExportableFunction function = functionsContent.newFunction("label", Arrays .asList(p1, p2), PrimitiveType.i32); final Local tempLocal = function.newLocal("loc", PrimitiveType.i32); final Block block = function.flow.block("outer", null); block.flow.ret(getLocal(tempLocal, null), null); function.flow.unreachable(null); function.exportAs("expfunction"); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final StringWriter theSourceMap = new StringWriter(); final Exporter exporter = new Exporter(debugOptions()); exporter.export(module, bos, theSourceMap); final byte[] expected = IOUtils.toByteArray(getClass().getResource("testBlockBinary.wasm")); Assert.assertArrayEquals(expected, bos.toByteArray()); Assert.assertEquals("{\"version\":3,\"file\":\"mod.wasm\",\"sourceRoot\":\"\",\"names\":[],\"sources\":[],\"mappings\":\"\"}", theSourceMap.toString()); }
@Test public void testIf() throws IOException { final StringWriter strWriter = new StringWriter(); final PrintWriter pw = new PrintWriter(strWriter); final Module module = new Module("mod", "mod.wasm.map"); final FunctionsSection functionsContent = module.getFunctions(); final Param p1 = param("p1", PrimitiveType.i32); final Param p2 = param("p2", PrimitiveType.i32); final ExportableFunction function = functionsContent.newFunction("label", Arrays .asList(p1, p2), PrimitiveType.i32); final Local tempLocal = function.newLocal("loc", PrimitiveType.i32); final Block block = function.flow.block("outer", null); function.flow.unreachable(null); final Iff ifExp = block.flow.iff("label", i32.eq(i32.c(10, null), i32.c(20, null), null), null); ifExp.flow.ret(getLocal(tempLocal, null), null); function.exportAs("expfunction"); final Exporter exporter = new Exporter(debugOptions()); exporter.export(module, pw); final String expected = "(module $mod" + System.lineSeparator() + " (type $t0 (func (param i32) (param i32) (result i32)))" + System.lineSeparator() + " (func $label (type $t0) (param $p1 i32) (param $p2 i32) (result i32)" + System.lineSeparator() + " (local $loc i32)" + System.lineSeparator() + " (block $outer" + System.lineSeparator() + " (if $label (i32.eq (i32.const 10) (i32.const 20))" + System.lineSeparator() + " (then" + System.lineSeparator() + " (return (get_local $loc))" + System.lineSeparator() + " ))" + System.lineSeparator() + " )" + System.lineSeparator() + " (unreachable))" + System.lineSeparator() + " (export \"expfunction\" (func $label))" + System.lineSeparator() + " )"; Assert.assertEquals(expected, strWriter.toString()); }
@Test public void testIfBinary() throws IOException { final Module module = new Module("mod", "mod.wasm.map"); final FunctionsSection functionsContent = module.getFunctions(); final Param p1 = param("p1", PrimitiveType.i32); final Param p2 = param("p2", PrimitiveType.i32); final ExportableFunction function = functionsContent.newFunction("label", Arrays .asList(p1, p2), PrimitiveType.i32); final Local tempLocal = function.newLocal("loc", PrimitiveType.i32); final Block block = function.flow.block("outer", null); function.flow.unreachable(null); final Iff ifExp = block.flow.iff("lab", i32.eq(i32.c(10, null), i32.c(20, null), null), null); ifExp.flow.branch(block, null); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final StringWriter theSourceMap = new StringWriter(); final Exporter exporter = new Exporter(debugOptions()); exporter.export(module, bos, theSourceMap); final byte[] expected = IOUtils.toByteArray(getClass().getResource("testIf.wasm")); Assert.assertArrayEquals(expected, bos.toByteArray()); Assert.assertEquals("{\"version\":3,\"file\":\"mod.wasm\",\"sourceRoot\":\"\",\"names\":[],\"sources\":[],\"mappings\":\"\"}", theSourceMap.toString()); }
@Test public void testBlockBranch() throws IOException { final StringWriter strWriter = new StringWriter(); final PrintWriter pw = new PrintWriter(strWriter); final Module module = new Module("mod", "mod.wasm.map"); final FunctionsSection functionsContent = module.getFunctions(); final Param p1 = param("p1", PrimitiveType.i32); final Param p2 = param("p2", PrimitiveType.i32); final ExportableFunction function = functionsContent.newFunction("label", Arrays .asList(p1, p2), PrimitiveType.i32); final Local tempLocal = function.newLocal("loc", PrimitiveType.i32); final Block block = function.flow.block("outer", null); block.flow.branch(block, null); function.flow.unreachable(null); function.exportAs("expfunction"); final Exporter exporter = new Exporter(debugOptions()); exporter.export(module, pw); final String expected = "(module $mod" + System.lineSeparator() + " (type $t0 (func (param i32) (param i32) (result i32)))" + System.lineSeparator() + " (func $label (type $t0) (param $p1 i32) (param $p2 i32) (result i32)" + System.lineSeparator() + " (local $loc i32)" + System.lineSeparator() + " (block $outer" + System.lineSeparator() + " (br $outer))" + System.lineSeparator() + " (unreachable))" + System.lineSeparator() + " (export \"expfunction\" (func $label))" + System.lineSeparator() + " )"; Assert.assertEquals(expected, strWriter.toString()); }
@Test public void testBlockBranchBinary() throws IOException { final Module module = new Module("mod", "mod.wasm.map"); final FunctionsSection functionsContent = module.getFunctions(); final Param p1 = param("p1", PrimitiveType.i32); final Param p2 = param("p2", PrimitiveType.i32); final ExportableFunction function = functionsContent.newFunction("label", Arrays .asList(p1, p2), PrimitiveType.i32); final Local tempLocal = function.newLocal("loc", PrimitiveType.i32); final Block block = function.flow.block("outer", null); block.flow.branch(block, null); function.flow.unreachable(null); function.exportAs("expfunction"); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final StringWriter theSourceMap = new StringWriter(); final Exporter exporter = new Exporter(debugOptions()); exporter.export(module, bos, theSourceMap); final byte[] expected = IOUtils.toByteArray(getClass().getResource("testBlockBranch.wasm")); Assert.assertArrayEquals(expected, bos.toByteArray()); Assert.assertEquals("{\"version\":3,\"file\":\"mod.wasm\",\"sourceRoot\":\"\",\"names\":[],\"sources\":[],\"mappings\":\"\"}", theSourceMap.toString()); }
@Test public void testBlockBranchIf() throws IOException { final StringWriter strWriter = new StringWriter(); final PrintWriter pw = new PrintWriter(strWriter); final Module module = new Module("mod", "mod.wasm.map"); final FunctionsSection functionsContent = module.getFunctions(); final Param p1 = param("p1", PrimitiveType.i32); final Param p2 = param("p2", PrimitiveType.i32); final ExportableFunction function = functionsContent.newFunction("label", Arrays .asList(p1, p2), PrimitiveType.i32); final Local tempLocal = function.newLocal("loc", PrimitiveType.i32); final Block block = function.flow.block("outer", null); block.flow.branchIff(block, i32.c(42, null), null); function.flow.unreachable(null); function.exportAs("expfunction"); final Exporter exporter = new Exporter(debugOptions()); exporter.export(module, pw); final String expected = "(module $mod" + System.lineSeparator() + " (type $t0 (func (param i32) (param i32) (result i32)))" + System.lineSeparator() + " (func $label (type $t0) (param $p1 i32) (param $p2 i32) (result i32)" + System.lineSeparator() + " (local $loc i32)" + System.lineSeparator() + " (block $outer" + System.lineSeparator() + " (br_if $outer" + System.lineSeparator() + " (i32.const 42))" + System.lineSeparator() + " )" + System.lineSeparator() + " (unreachable))" + System.lineSeparator() + " (export \"expfunction\" (func $label))" + System.lineSeparator() + " )"; Assert.assertEquals(expected, strWriter.toString()); }
@Test public void testBlockBranchIfBinary() throws IOException { final Module module = new Module("mod", "mod.wasm.map"); final FunctionsSection functionsContent = module.getFunctions(); final Param p1 = param("p1", PrimitiveType.i32); final Param p2 = param("p2", PrimitiveType.i32); final ExportableFunction function = functionsContent.newFunction("label", Arrays .asList(p1, p2), PrimitiveType.i32); final Local tempLocal = function.newLocal("loc", PrimitiveType.i32); final Block block = function.flow.block("outer", null); block.flow.branchIff(block, i32.c(42, null), null); function.flow.unreachable(null); function.exportAs("expfunction"); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final StringWriter theSourceMap = new StringWriter(); final Exporter exporter = new Exporter(debugOptions()); exporter.export(module, bos, theSourceMap); final byte[] expected = IOUtils.toByteArray(getClass().getResource("testBlockBranchIf.wasm")); Assert.assertArrayEquals(expected, bos.toByteArray()); Assert.assertEquals("{\"version\":3,\"file\":\"mod.wasm\",\"sourceRoot\":\"\",\"names\":[],\"sources\":[],\"mappings\":\"\"}", theSourceMap.toString()); }
@Test public void testTableWithFunction() throws IOException { final StringWriter strWriter = new StringWriter(); final PrintWriter pw = new PrintWriter(strWriter); final Module module = new Module("mod", "mod.wasm.map"); final FunctionsSection functionsContent = module.getFunctions(); final Param p1 = param("p1", PrimitiveType.i32); final Param p2 = param("p2", PrimitiveType.i32); final ExportableFunction function = functionsContent.newFunction("label", Arrays .asList(p1, p2), PrimitiveType.i32); function.flow.unreachable(null); function.toTable(); final Exporter exporter = new Exporter(debugOptions()); exporter.export(module, pw); final String expected = "(module $mod" + System.lineSeparator() + " (type $t0 (func (param i32) (param i32) (result i32)))" + System.lineSeparator() + " (table 1 anyfunc)" + System.lineSeparator() + " (elem (i32.const 0) $label)" + System.lineSeparator() + " (func $label (type $t0) (param $p1 i32) (param $p2 i32) (result i32)" + System.lineSeparator() + " (unreachable))" + System.lineSeparator() + " )"; Assert.assertEquals(expected, strWriter.toString()); }
@Test public void testTableWithFunctionBinary() throws IOException { final Module module = new Module("mod", "mod.wasm.map"); final FunctionsSection functionsContent = module.getFunctions(); final Param p1 = param("p1", PrimitiveType.i32); final Param p2 = param("p2", PrimitiveType.i32); final ExportableFunction function = functionsContent.newFunction("label", Arrays .asList(p1, p2), PrimitiveType.i32); function.flow.unreachable(null); function.toTable(); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final StringWriter theSourceMap = new StringWriter(); final Exporter exporter = new Exporter(debugOptions()); exporter.export(module, bos, theSourceMap); final byte[] expected = IOUtils.toByteArray(getClass().getResource("testTableWithFunction.wasm")); Assert.assertArrayEquals(expected, bos.toByteArray()); Assert.assertEquals("{\"version\":3,\"file\":\"mod.wasm\",\"sourceRoot\":\"\",\"names\":[],\"sources\":[],\"mappings\":\"\"}", theSourceMap.toString()); }
@Test public void testIntegerMath() throws IOException { final StringWriter strWriter = new StringWriter(); final PrintWriter pw = new PrintWriter(strWriter); final Module module = new Module("mod", "mod.wasm.map"); final FunctionsSection functionsContent = module.getFunctions(); final Param p1 = param("p1", PrimitiveType.i32); final Param p2 = param("p2", PrimitiveType.i32); final ExportableFunction function = functionsContent.newFunction("label", Arrays .asList(p1, p2), PrimitiveType.i32); final Local loc1 = function.newLocal("local1", PrimitiveType.i32); function.flow.setLocal(loc1, i32.c(100, null), null); function.flow.ret(i32.add(getLocal(loc1, null), i32.c(200, null), null), null); final Exporter exporter = new Exporter(debugOptions()); exporter.export(module, pw); final String expected = "(module $mod" + System.lineSeparator() + " (type $t0 (func (param i32) (param i32) (result i32)))" + System.lineSeparator() + " (func $label (type $t0) (param $p1 i32) (param $p2 i32) (result i32)" + System.lineSeparator() + " (local $local1 i32)" + System.lineSeparator() + " (set_local $local1 (i32.const 100))" + System.lineSeparator() + " (return (i32.add (get_local $local1) (i32.const 200)))" + System.lineSeparator() + " )" + System.lineSeparator() + " )"; Assert.assertEquals(expected, strWriter.toString()); }
@Test public void testIntegerMathBinary() throws IOException { final Module module = new Module("mod", "mod.wasm.map"); final FunctionsSection functionsContent = module.getFunctions(); final Param p1 = param("p1", PrimitiveType.i32); final Param p2 = param("p2", PrimitiveType.i32); final ExportableFunction function = functionsContent.newFunction("label", Arrays .asList(p1, p2), PrimitiveType.i32); final Local loc1 = function.newLocal("local1", PrimitiveType.i32); function.flow.setLocal(loc1, i32.c(100, null), null); function.flow.ret(i32.add(getLocal(loc1, null), i32.c(200, null), null), null); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final StringWriter theSourceMap = new StringWriter(); final Exporter exporter = new Exporter(debugOptions()); exporter.export(module, bos, theSourceMap); final byte[] expected = IOUtils.toByteArray(getClass().getResource("testIntegerMath.wasm")); Assert.assertArrayEquals(expected, bos.toByteArray()); Assert.assertEquals("{\"version\":3,\"file\":\"mod.wasm\",\"sourceRoot\":\"\",\"names\":[],\"sources\":[],\"mappings\":\"\"}", theSourceMap.toString()); }
@Test public void testCall() throws IOException { final StringWriter strWriter = new StringWriter(); final PrintWriter pw = new PrintWriter(strWriter); final Module module = new Module("mod", "mod.wasm.map"); final FunctionsSection functionsContent = module.getFunctions(); final Param p1 = param("p1", PrimitiveType.i32); final Param p2 = param("p2", PrimitiveType.i32); final ExportableFunction function = functionsContent.newFunction("label", Arrays .asList(p1, p2), PrimitiveType.i32); final Local loc1 = function.newLocal("local1", PrimitiveType.i32); function.flow.ret(call(function, Arrays.asList(getLocal(p1, null), getLocal(p2, null)), null), null); final Exporter exporter = new Exporter(debugOptions()); exporter.export(module, pw); final String expected = "(module $mod" + System.lineSeparator() + " (type $t0 (func (param i32) (param i32) (result i32)))" + System.lineSeparator() + " (func $label (type $t0) (param $p1 i32) (param $p2 i32) (result i32)" + System.lineSeparator() + " (local $local1 i32)" + System.lineSeparator() + " (return (call $label (get_local $p1) (get_local $p2)))" + System.lineSeparator() + " )" + System.lineSeparator() + " )"; Assert.assertEquals(expected, strWriter.toString()); }
@Test public void testCallBinary() throws IOException { final Module module = new Module("mod", "mod.wasm.map"); final FunctionsSection functionsContent = module.getFunctions(); final Param p1 = param("p1", PrimitiveType.i32); final Param p2 = param("p2", PrimitiveType.i32); final ExportableFunction function = functionsContent.newFunction("label", Arrays .asList(p1, p2), PrimitiveType.i32); final Local loc1 = function.newLocal("local1", PrimitiveType.i32); function.flow.ret(call(function, Arrays.asList(getLocal(p1, null), getLocal(p2, null)), null), null); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final StringWriter theSourceMap = new StringWriter(); final Exporter exporter = new Exporter(debugOptions()); exporter.export(module, bos, theSourceMap); final byte[] expected = IOUtils.toByteArray(getClass().getResource("testCall.wasm")); Assert.assertArrayEquals(expected, bos.toByteArray()); Assert.assertEquals("{\"version\":3,\"file\":\"mod.wasm\",\"sourceRoot\":\"\",\"names\":[],\"sources\":[],\"mappings\":\"\"}", theSourceMap.toString()); }
@Test public void testSimpleF32() throws IOException { final StringWriter strWriter = new StringWriter(); final PrintWriter pw = new PrintWriter(strWriter); final Module module = new Module("mod", "mod.wasm.map"); final Param p1 = param("p1", PrimitiveType.f32); final Param p2 = param("p2", PrimitiveType.f32); final ExportableFunction compareValueF32 = module.getFunctions().newFunction("compareValueF32", Arrays.asList(p1, p2), PrimitiveType.i32); final Block b1 = compareValueF32.flow.block("b1", null); b1.flow.branchIff(b1, ConstExpressions.f32.ne(getLocal(p1, null), getLocal(p2, null), null), null); b1.flow.ret(i32.c(0, null), null); final Block b2 = compareValueF32.flow.block("b2", null); b2.flow.branchIff(b2, ConstExpressions.f32.ge(getLocal(p1, null), getLocal(p2, null), null), null); b2.flow.ret(i32.c(-1, null), null); compareValueF32.flow.ret(i32.c(1, null), null); final Exporter exporter = new Exporter(debugOptions()); exporter.export(module, pw); final String expected = "(module $mod" + System.lineSeparator() + " (type $t0 (func (param f32) (param f32) (result i32)))" + System.lineSeparator() + " (func $compareValueF32 (type $t0) (param $p1 f32) (param $p2 f32) (result i32)" + System.lineSeparator() + " (block $b1" + System.lineSeparator() + " (br_if $b1" + System.lineSeparator() + " (f32.ne (get_local $p1) (get_local $p2)))" + System.lineSeparator() + " (return (i32.const 0))" + System.lineSeparator() + " )" + System.lineSeparator() + " (block $b2" + System.lineSeparator() + " (br_if $b2" + System.lineSeparator() + " (f32.ge (get_local $p1) (get_local $p2)))" + System.lineSeparator() + " (return (i32.const -1))" + System.lineSeparator() + " )" + System.lineSeparator() + " (return (i32.const 1))" + System.lineSeparator() + " )" + System.lineSeparator() + " )"; Assert.assertEquals(expected, strWriter.toString()); }
@Test public void testSimpleF32Binary() throws IOException { final Module module = new Module("mod", "mod.wasm.map"); final Param p1 = param("p1", PrimitiveType.f32); final Param p2 = param("p2", PrimitiveType.f32); final ExportableFunction compareValueF32 = module.getFunctions().newFunction("compareValueF32", Arrays.asList(p1, p2), PrimitiveType.i32); final Block b1 = compareValueF32.flow.block("b1", null); b1.flow.branchIff(b1, ConstExpressions.f32.ne(getLocal(p1, null), getLocal(p2, null), null), null); b1.flow.ret(i32.c(0, null), null); final Block b2 = compareValueF32.flow.block("b2", null); b2.flow.branchIff(b2, ConstExpressions.f32.ge(getLocal(p1, null), getLocal(p2, null), null), null); b2.flow.ret(i32.c(-1, null), null); compareValueF32.flow.ret(i32.c(1, null), null); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final StringWriter theSourceMap = new StringWriter(); final Exporter exporter = new Exporter(debugOptions()); exporter.export(module, bos, theSourceMap); final byte[] expected = IOUtils.toByteArray(getClass().getResource("testSimpleF32.wasm")); Assert.assertArrayEquals(expected, bos.toByteArray()); Assert.assertEquals("{\"version\":3,\"file\":\"mod.wasm\",\"sourceRoot\":\"\",\"names\":[],\"sources\":[],\"mappings\":\"\"}", theSourceMap.toString()); }
@Test public void testIntegerMathComplete() throws IOException { final StringWriter strWriter = new StringWriter(); final PrintWriter pw = new PrintWriter(strWriter); final Module module = new Module("mod", "mod.wasm.map"); final ExportableFunction testFunction = module.getFunctions().newFunction("testFunction", Collections.emptyList()); final Local local = testFunction.newLocal("loc1", PrimitiveType.i32); testFunction.flow.setLocal(local, i32.add(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.and(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.clz(i32.c(10,null),null),null); testFunction.flow.setLocal(local, i32.ctz(i32.c(10,null),null),null); testFunction.flow.setLocal(local, i32.div_s(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.div_u(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.eq(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.eqz(i32.c(10,null),null),null); testFunction.flow.setLocal(local, i32.ge_s(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.ge_u(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.gt_s(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.gt_u(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.le_s(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.le_u(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.lt_s(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.lt_u(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.mul(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.ne(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.or(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.popcount(i32.c(10,null),null),null); testFunction.flow.setLocal(local, i32.reinterpretF32(f32.c(10.0f,null),null),null); testFunction.flow.setLocal(local, i32.rem_s(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.rem_u(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.rotl(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.rotr(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.shl(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.shr_s(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.shr_u(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.sub(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.trunc_sF32(f32.c(10.2f,null),null),null); testFunction.flow.setLocal(local, i32.trunc_uF32(f32.c(10.2f,null),null),null); testFunction.flow.setLocal(local, i32.xor(i32.c(10,null), i32.c(20,null),null),null); final Exporter exporter = new Exporter(debugOptions()); exporter.export(module, pw); final String expected = "(module $mod" + System.lineSeparator() + " (type $t0 (func))" + System.lineSeparator() + " (func $testFunction (type $t0)" + System.lineSeparator() + " (local $loc1 i32)" + System.lineSeparator() + " (set_local $loc1 (i32.add (i32.const 10) (i32.const 20)))" + System.lineSeparator() + " (set_local $loc1 (i32.and (i32.const 10) (i32.const 20)))" + System.lineSeparator() + " (set_local $loc1 (i32.clz (i32.const 10)))" + System.lineSeparator() + " (set_local $loc1 (i32.ctz (i32.const 10)))" + System.lineSeparator() + " (set_local $loc1 (i32.div_s (i32.const 10) (i32.const 20)))" + System.lineSeparator() + " (set_local $loc1 (i32.div_u (i32.const 10) (i32.const 20)))" + System.lineSeparator() + " (set_local $loc1 (i32.eq (i32.const 10) (i32.const 20)))" + System.lineSeparator() + " (set_local $loc1 (i32.eqz (i32.const 10)))" + System.lineSeparator() + " (set_local $loc1 (i32.ge_s (i32.const 10) (i32.const 20)))" + System.lineSeparator() + " (set_local $loc1 (i32.ge_u (i32.const 10) (i32.const 20)))" + System.lineSeparator() + " (set_local $loc1 (i32.gt_s (i32.const 10) (i32.const 20)))" + System.lineSeparator() + " (set_local $loc1 (i32.gt_u (i32.const 10) (i32.const 20)))" + System.lineSeparator() + " (set_local $loc1 (i32.le_s (i32.const 10) (i32.const 20)))" + System.lineSeparator() + " (set_local $loc1 (i32.le_u (i32.const 10) (i32.const 20)))" + System.lineSeparator() + " (set_local $loc1 (i32.lt_s (i32.const 10) (i32.const 20)))" + System.lineSeparator() + " (set_local $loc1 (i32.lt_u (i32.const 10) (i32.const 20)))" + System.lineSeparator() + " (set_local $loc1 (i32.mul (i32.const 10) (i32.const 20)))" + System.lineSeparator() + " (set_local $loc1 (i32.ne (i32.const 10) (i32.const 20)))" + System.lineSeparator() + " (set_local $loc1 (i32.or (i32.const 10) (i32.const 20)))" + System.lineSeparator() + " (set_local $loc1 (i32.popcnt (i32.const 10)))" + System.lineSeparator() + " (set_local $loc1 (i32.reinterpret/f32 (f32.const 10.0)))" + System.lineSeparator() + " (set_local $loc1 (i32.rem_s (i32.const 10) (i32.const 20)))" + System.lineSeparator() + " (set_local $loc1 (i32.rem_u (i32.const 10) (i32.const 20)))" + System.lineSeparator() + " (set_local $loc1 (i32.rotl (i32.const 10) (i32.const 20)))" + System.lineSeparator() + " (set_local $loc1 (i32.rotr (i32.const 10) (i32.const 20)))" + System.lineSeparator() + " (set_local $loc1 (i32.shl (i32.const 10) (i32.const 20)))" + System.lineSeparator() + " (set_local $loc1 (i32.shr_s (i32.const 10) (i32.const 20)))" + System.lineSeparator() + " (set_local $loc1 (i32.shr_u (i32.const 10) (i32.const 20)))" + System.lineSeparator() + " (set_local $loc1 (i32.sub (i32.const 10) (i32.const 20)))" + System.lineSeparator() + " (set_local $loc1 (i32.trunc_s/f32 (f32.const 10.2)))" + System.lineSeparator() + " (set_local $loc1 (i32.trunc_u/f32 (f32.const 10.2)))" + System.lineSeparator() + " (set_local $loc1 (i32.xor (i32.const 10) (i32.const 20)))" + System.lineSeparator() + " )" + System.lineSeparator() + " )"; Assert.assertEquals(expected, strWriter.toString()); }
@Test public void testIntegerMathCompleteBinary() throws IOException { final Module module = new Module("mod", "mod.wasm.map"); final ExportableFunction testFunction = module.getFunctions().newFunction("testFunction", Collections.emptyList()); final Local local = testFunction.newLocal("loc1", PrimitiveType.i32); testFunction.flow.setLocal(local, i32.add(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.and(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.clz(i32.c(10,null),null),null); testFunction.flow.setLocal(local, i32.ctz(i32.c(10,null),null),null); testFunction.flow.setLocal(local, i32.div_s(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.div_u(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.eq(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.eqz(i32.c(10,null),null),null); testFunction.flow.setLocal(local, i32.ge_s(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.ge_u(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.gt_s(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.gt_u(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.le_s(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.le_u(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.lt_s(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.lt_u(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.mul(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.ne(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.or(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.popcount(i32.c(10,null),null),null); testFunction.flow.setLocal(local, i32.reinterpretF32(f32.c(10.0f,null),null),null); testFunction.flow.setLocal(local, i32.rem_s(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.rem_u(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.rotl(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.rotr(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.shl(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.shr_s(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.shr_u(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.sub(i32.c(10,null), i32.c(20,null),null),null); testFunction.flow.setLocal(local, i32.trunc_sF32(f32.c(10.2f,null),null),null); testFunction.flow.setLocal(local, i32.trunc_uF32(f32.c(10.2f,null),null),null); testFunction.flow.setLocal(local, i32.xor(i32.c(10,null), i32.c(20,null),null),null); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final StringWriter theSourceMap = new StringWriter(); final Exporter exporter = new Exporter(debugOptions()); exporter.export(module, bos, theSourceMap); final byte[] expected = IOUtils.toByteArray(getClass().getResource("testIntegerMathComplete.wasm")); Assert.assertArrayEquals(expected, bos.toByteArray()); Assert.assertEquals("{\"version\":3,\"file\":\"mod.wasm\",\"sourceRoot\":\"\",\"names\":[],\"sources\":[],\"mappings\":\"\"}", theSourceMap.toString()); }
@Test public void testFloatMathComplete() throws IOException { final StringWriter strWriter = new StringWriter(); final PrintWriter pw = new PrintWriter(strWriter); final Module module = new Module("mod", "mod.wasm.map"); final ExportableFunction testFunction = module.getFunctions().newFunction("testFunction", Collections.emptyList()); final Local locali32 = testFunction.newLocal("loc1", PrimitiveType.i32); final Local localf32 = testFunction.newLocal("loc2", PrimitiveType.f32); testFunction.flow.setLocal(localf32, f32.abs(f32.c(-10.4f,null),null),null); testFunction.flow.setLocal(localf32, f32.add(f32.c(10f,null), f32.c(20f,null),null),null); testFunction.flow.setLocal(localf32, f32.ceil(f32.c(-10.4f,null),null),null); testFunction.flow.setLocal(localf32, f32.convert_sI32(i32.c(10,null),null),null); testFunction.flow.setLocal(localf32, f32.convert_uI32(i32.c(10,null),null),null); testFunction.flow.setLocal(localf32, f32.copysign(f32.c(10f,null), f32.c(20f,null),null),null); testFunction.flow.setLocal(localf32, f32.div(f32.c(10f,null), f32.c(20f,null),null),null); testFunction.flow.setLocal(locali32, f32.eq(f32.c(10f,null), f32.c(20f,null),null),null); testFunction.flow.setLocal(localf32, f32.floor(f32.c(-10.4f,null),null),null); testFunction.flow.setLocal(locali32, f32.gt(f32.c(10f,null), f32.c(20f,null),null),null); testFunction.flow.setLocal(locali32, f32.le(f32.c(10f,null), f32.c(20f,null),null),null); testFunction.flow.setLocal(locali32, f32.lt(f32.c(10f,null), f32.c(20f,null),null),null); testFunction.flow.setLocal(localf32, f32.max(f32.c(10f,null), f32.c(20f,null),null),null); testFunction.flow.setLocal(localf32, f32.min(f32.c(10f,null), f32.c(20f,null),null),null); testFunction.flow.setLocal(localf32, f32.mul(f32.c(10f,null), f32.c(20f,null),null),null); testFunction.flow.setLocal(locali32, f32.ne(f32.c(10f,null), f32.c(20f,null),null),null); testFunction.flow.setLocal(localf32, f32.nearest(f32.c(-10.4f,null),null),null); testFunction.flow.setLocal(localf32, f32.neg(f32.c(-10.4f,null),null),null); testFunction.flow.setLocal(localf32, f32.sqrt(f32.c(-10.4f,null),null),null); testFunction.flow.setLocal(localf32, f32.sub(f32.c(10f,null), f32.c(20f,null),null),null); testFunction.flow.setLocal(localf32, f32.trunc(f32.c(-10.4f,null),null),null); final Exporter exporter = new Exporter(debugOptions()); exporter.export(module, pw); final String expected = "(module $mod" + System.lineSeparator() + " (type $t0 (func))" + System.lineSeparator() + " (func $testFunction (type $t0)" + System.lineSeparator() + " (local $loc1 i32)" + System.lineSeparator() + " (local $loc2 f32)" + System.lineSeparator() + " (set_local $loc2 (f32.abs (f32.const -10.4)))" + System.lineSeparator() + " (set_local $loc2 (f32.add (f32.const 10.0) (f32.const 20.0)))" + System.lineSeparator() + " (set_local $loc2 (f32.ceil (f32.const -10.4)))" + System.lineSeparator() + " (set_local $loc2 (f32.convert_s/i32 (i32.const 10)))" + System.lineSeparator() + " (set_local $loc2 (f32.convert_u/i32 (i32.const 10)))" + System.lineSeparator() + " (set_local $loc2 (f32.copysign (f32.const 10.0) (f32.const 20.0)))" + System.lineSeparator() + " (set_local $loc2 (f32.div (f32.const 10.0) (f32.const 20.0)))" + System.lineSeparator() + " (set_local $loc1 (f32.eq (f32.const 10.0) (f32.const 20.0)))" + System.lineSeparator() + " (set_local $loc2 (f32.floor (f32.const -10.4)))" + System.lineSeparator() + " (set_local $loc1 (f32.gt (f32.const 10.0) (f32.const 20.0)))" + System.lineSeparator() + " (set_local $loc1 (f32.le (f32.const 10.0) (f32.const 20.0)))" + System.lineSeparator() + " (set_local $loc1 (f32.lt (f32.const 10.0) (f32.const 20.0)))" + System.lineSeparator() + " (set_local $loc2 (f32.max (f32.const 10.0) (f32.const 20.0)))" + System.lineSeparator() + " (set_local $loc2 (f32.min (f32.const 10.0) (f32.const 20.0)))" + System.lineSeparator() + " (set_local $loc2 (f32.mul (f32.const 10.0) (f32.const 20.0)))" + System.lineSeparator() + " (set_local $loc1 (f32.ne (f32.const 10.0) (f32.const 20.0)))" + System.lineSeparator() + " (set_local $loc2 (f32.nearest (f32.const -10.4)))" + System.lineSeparator() + " (set_local $loc2 (f32.neg (f32.const -10.4)))" + System.lineSeparator() + " (set_local $loc2 (f32.sqrt (f32.const -10.4)))" + System.lineSeparator() + " (set_local $loc2 (f32.sub (f32.const 10.0) (f32.const 20.0)))" + System.lineSeparator() + " (set_local $loc2 (f32.trunc (f32.const -10.4)))" + System.lineSeparator() + " )" + System.lineSeparator() + " )"; Assert.assertEquals(expected, strWriter.toString()); }
@Test public void testFloatMathCompleteBinary() throws IOException { final Module module = new Module("mod", "mod.wasm.map"); final ExportableFunction testFunction = module.getFunctions().newFunction("testFunction", Collections.emptyList()); final Local locali32 = testFunction.newLocal("loc1", PrimitiveType.i32); final Local localf32 = testFunction.newLocal("loc2", PrimitiveType.f32); testFunction.flow.setLocal(localf32, f32.abs(f32.c(-10.4f,null),null),null); testFunction.flow.setLocal(localf32, f32.add(f32.c(10f,null), f32.c(20f,null),null),null); testFunction.flow.setLocal(localf32, f32.ceil(f32.c(-10.4f,null),null),null); testFunction.flow.setLocal(localf32, f32.convert_sI32(i32.c(10,null),null),null); testFunction.flow.setLocal(localf32, f32.convert_uI32(i32.c(10,null),null),null); testFunction.flow.setLocal(localf32, f32.copysign(f32.c(10f,null), f32.c(20f,null),null),null); testFunction.flow.setLocal(localf32, f32.div(f32.c(10f,null), f32.c(20f,null),null),null); testFunction.flow.setLocal(locali32, f32.eq(f32.c(10f,null), f32.c(20f,null),null),null); testFunction.flow.setLocal(localf32, f32.floor(f32.c(-10.4f,null),null),null); testFunction.flow.setLocal(locali32, f32.gt(f32.c(10f,null), f32.c(20f,null),null),null); testFunction.flow.setLocal(locali32, f32.le(f32.c(10f,null), f32.c(20f,null),null),null); testFunction.flow.setLocal(locali32, f32.lt(f32.c(10f,null), f32.c(20f,null),null),null); testFunction.flow.setLocal(localf32, f32.max(f32.c(10f,null), f32.c(20f,null),null),null); testFunction.flow.setLocal(localf32, f32.min(f32.c(10f,null), f32.c(20f,null),null),null); testFunction.flow.setLocal(localf32, f32.mul(f32.c(10f,null), f32.c(20f,null),null),null); testFunction.flow.setLocal(locali32, f32.ne(f32.c(10f,null), f32.c(20f,null),null),null); testFunction.flow.setLocal(localf32, f32.nearest(f32.c(-10.4f,null),null),null); testFunction.flow.setLocal(localf32, f32.neg(f32.c(-10.4f,null),null),null); testFunction.flow.setLocal(localf32, f32.sqrt(f32.c(-10.4f,null),null),null); testFunction.flow.setLocal(localf32, f32.sub(f32.c(10f,null), f32.c(20f,null),null),null); testFunction.flow.setLocal(localf32, f32.trunc(f32.c(-10.4f,null),null),null); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final StringWriter theSourceMap = new StringWriter(); final Exporter exporter = new Exporter(debugOptions()); exporter.export(module, bos, theSourceMap); final byte[] expected = IOUtils.toByteArray(getClass().getResource("testFloatMathComplete.wasm")); Assert.assertArrayEquals(expected, bos.toByteArray()); Assert.assertEquals("{\"version\":3,\"file\":\"mod.wasm\",\"sourceRoot\":\"\",\"names\":[],\"sources\":[],\"mappings\":\"\"}", theSourceMap.toString()); }
@Test public void testTeeNopDropSelect() throws IOException { final StringWriter strWriter = new StringWriter(); final PrintWriter pw = new PrintWriter(strWriter); final Module module = new Module("mod", "mod.wasm.map"); final ExportableFunction testFunction = module.getFunctions().newFunction("testFunction", Collections.emptyList()); final Local locali32 = testFunction.newLocal("loc1", PrimitiveType.i32); final Loop loop = testFunction.flow.loop("lp1",null); loop.flow.nop(null); final Block block = loop.flow.block("bl1",null); block.flow.nop(null); block.flow.setLocal(locali32, select(i32.c(10,null), i32.c(20,null), i32.eq(i32.c(30,null), i32.c(40,null),null),null),null); block.flow.drop(teeLocal(locali32, i32.c(100,null),null),null); block.flow.voidCallIndirect(testFunction.getFunctionType(), Collections.emptyList(), i32.c(0,null),null); block.flow.branch(block,null); loop.flow.branch(loop,null); testFunction.toTable(); final Exporter exporter = new Exporter(debugOptions()); exporter.export(module, pw); final String expected = "(module $mod" + System.lineSeparator() + " (type $t0 (func))" + System.lineSeparator() + " (table 1 anyfunc)" + System.lineSeparator() + " (elem (i32.const 0) $testFunction)" + System.lineSeparator() + " (func $testFunction (type $t0)" + System.lineSeparator() + " (local $loc1 i32)" + System.lineSeparator() + " (loop $lp1" + System.lineSeparator() + " (nop)" + System.lineSeparator() + " (block $bl1" + System.lineSeparator() + " (nop)" + System.lineSeparator() + " (set_local $loc1 (select (i32.const 10) (i32.const 20) (i32.eq (i32.const 30) (i32.const 40))))" + System.lineSeparator() + " (drop (tee_local $loc1 (i32.const 100)))" + System.lineSeparator() + " (call_indirect (type $t0) (i32.const 0))" + System.lineSeparator() + " (br $bl1))" + System.lineSeparator() + " (br $lp1))" + System.lineSeparator() + " )" + System.lineSeparator() + " )"; Assert.assertEquals(expected, strWriter.toString()); }
@Test public void testTeeNopDropSelectBinary() throws IOException { final Module module = new Module("mod", "mod.wasm.map"); final ExportableFunction testFunction = module.getFunctions().newFunction("testFunction", Collections.emptyList()); final Local locali32 = testFunction.newLocal("loc1", PrimitiveType.i32); final Loop loop = testFunction.flow.loop("lp1",null); loop.flow.nop(null); final Block block = loop.flow.block("bl1",null); block.flow.nop(null); block.flow.setLocal(locali32, select(i32.c(10,null), i32.c(20,null), i32.eq(i32.c(30,null), i32.c(40,null),null),null),null); block.flow.drop(teeLocal(locali32, i32.c(100,null),null),null); block.flow.voidCallIndirect(testFunction.getFunctionType(), Collections.emptyList(), i32.c(0,null),null); block.flow.branch(block,null); loop.flow.branch(loop,null); testFunction.toTable(); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final StringWriter theSourceMap = new StringWriter(); final Exporter exporter = new Exporter(debugOptions()); exporter.export(module, bos, theSourceMap); final byte[] expected = IOUtils.toByteArray(getClass().getResource("testTeeNopDropSelect.wasm")); Assert.assertArrayEquals(expected, bos.toByteArray()); Assert.assertEquals("{\"version\":3,\"file\":\"mod.wasm\",\"sourceRoot\":\"\",\"names\":[],\"sources\":[],\"mappings\":\"\"}", theSourceMap.toString()); }
@Test public void testSimpleFunction() throws IOException { final StringWriter strWriter = new StringWriter(); final PrintWriter pw = new PrintWriter(strWriter); final Module module = new Module("mod", "mod.wasm.map"); final FunctionsSection functionsContent = module.getFunctions(); final ExportableFunction function = functionsContent.newFunction("label", Collections.singletonList(param("p1", PrimitiveType.i32)), PrimitiveType.i32); function.flow.ret(i32.c(42, null), null); function.exportAs("expfunction"); final Exporter exporter = new Exporter(debugOptions()); exporter.export(module, pw); final String expected = "(module $mod" + System.lineSeparator() + " (type $t0 (func (param i32) (result i32)))" + System.lineSeparator() + " (func $label (type $t0) (param $p1 i32) (result i32)" + System.lineSeparator() + " (return (i32.const 42))" + System.lineSeparator() + " )" + System.lineSeparator() + " (export \"expfunction\" (func $label))" + System.lineSeparator() + " )"; Assert.assertEquals(expected, strWriter.toString()); }
@Test public void testSimpleFunctionBinary() throws IOException { final Module module = new Module("mod", "mod.wasm.map"); final FunctionsSection functionsContent = module.getFunctions(); final ExportableFunction function = functionsContent.newFunction("label", Collections.singletonList(param("p1", PrimitiveType.i32)), PrimitiveType.i32); function.flow.ret(i32.c(42, null), null); function.exportAs("expfunction"); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final Exporter exporter = new Exporter(debugOptions()); final StringWriter theSourceMap = new StringWriter(); exporter.export(module, bos, theSourceMap); final byte[] expected = IOUtils.toByteArray(getClass().getResource("testSimpleFunction.wasm")); Assert.assertArrayEquals(expected, bos.toByteArray()); Assert.assertEquals("{\"version\":3,\"file\":\"mod.wasm\",\"sourceRoot\":\"\",\"names\":[],\"sources\":[],\"mappings\":\"\"}", theSourceMap.toString()); } |
SimpleMemoryManager { public void GC() { Chunk current = allocatedList; while (current != null) { final Chunk next = current.next; free_internal(current.position); current = next; } } SimpleMemoryManager(final int totalMemory); int freeMemory(); int allocated(); int malloc(final int size); void free(final int position); void GC(); void printDebug(final PrintStream ps); } | @Test public void testGC() { final SimpleMemoryManager mm = new SimpleMemoryManager(1000); final int a = mm.malloc(100); final int b = mm.malloc(200); final int c = mm.malloc(300); mm.GC(); mm.printDebug(System.out); assertEquals(1000, mm.freeMemory()); assertEquals(0, mm.allocated()); } |
VLQ { public static int[] decode(final String aData) { final List<Integer> theResult = new ArrayList<>(); int theShift = 0; int theValue = 0; for (int i=0;i<aData.length();i++) { int theInteger = CHARACTERS.indexOf(aData.charAt(i)); final int hasContinuationBit = theInteger & 32; theInteger &= 31; theValue += theInteger << theShift; if (hasContinuationBit > 0) { theShift += 5; } else { final int shouldNegate = theValue & 1; theValue >>= 1; theResult.add( shouldNegate > 0 ? -theValue : theValue ); theValue = theShift = 0; } } final int[] theResultArray = new int[theResult.size()]; for (int i=0;i<theResult.size();i++) { theResultArray[i] = theResult.get(i); } return theResultArray; } private VLQ(); static int[] decode(final String aData); static String encode(final int[] aData); } | @Test public void testDecode() { final int[] theResult = VLQ.decode("IAAM"); Assert.assertEquals(4, theResult.length); Assert.assertEquals(4, theResult[0]); Assert.assertEquals(0, theResult[1]); Assert.assertEquals(0, theResult[2]); Assert.assertEquals(6, theResult[3]); } |
Partitioning { public List<Set<T>> partitions() { return partitions; } Partitioning(final Set<T> nodes, final Predicate<Edge<EdgeType, T>> edgeFilter); List<Set<T>> partitions(); } | @Test public void testEmptyGraph() { final Partitioning thePartitioning = new Partitioning(new HashSet(), t -> true); final List<Set<Node>> thePartitions = thePartitioning.partitions(); assertTrue(thePartitions.isEmpty()); }
@Test public void testSingleNodeGraph() { final Set<Node> theNodes = new HashSet<>(); final Node node1 = new Node(); theNodes.add(node1); final Partitioning thePartitioning = new Partitioning(theNodes, t -> true); final List<Set<Node>> thePartitions = thePartitioning.partitions(); assertEquals(1, thePartitions.size()); assertEquals(1, thePartitions.get(0).size()); assertTrue(thePartitions.get(0).contains(node1)); }
@Test public void testSinglePartitionGraph() { final Set<Node> theNodes = new HashSet<>(); final Node node1 = new Node(); theNodes.add(node1); final Node node2 = new Node(); theNodes.add(node2); node1.addEdgeTo(ControlFlowEdgeType.forward, node2); final Partitioning thePartitioning = new Partitioning(theNodes, t -> true); final List<Set<Node>> thePartitions = thePartitioning.partitions(); assertEquals(1, thePartitions.size()); assertEquals(2, thePartitions.get(0).size()); assertTrue(thePartitions.get(0).contains(node1)); assertTrue(thePartitions.get(0).contains(node2)); }
@Test public void testMultiPartitionGraph() { final Set<Node> theNodes = new HashSet<>(); final Node node1 = new Node(); theNodes.add(node1); final Node node2 = new Node(); theNodes.add(node2); final Partitioning thePartitioning = new Partitioning(theNodes, t -> true); final List<Set<Node>> thePartitions = thePartitioning.partitions(); assertEquals(2, thePartitions.size()); assertEquals(1, thePartitions.get(0).size()); assertEquals(1, thePartitions.get(1).size()); } |
VLQ { public static String encode(final int[] aData) { final StringBuilder theResult = new StringBuilder(); for (int i = 0; i < aData.length; i += 1 ) { theResult.append(encodeInteger(aData[i])); } return theResult.toString(); } private VLQ(); static int[] decode(final String aData); static String encode(final int[] aData); } | @Test public void testEncode() { Assert.assertEquals("IAAM", VLQ.encode(new int[] {4,0,0,6})); } |
BytecodeLoader { public BytecodeClass loadByteCode(final BytecodeObjectTypeRef aTypeRef) throws IOException, ClassNotFoundException { return loadByteCode(aTypeRef, bytecodeReplacer); } BytecodeLoader(final ClassLoader aClassLoader); BytecodeSignatureParser getSignatureParser(); BytecodeClass loadByteCode(final BytecodeObjectTypeRef aTypeRef); BytecodeClass loadByteCode(final BytecodeObjectTypeRef aTypeRef, final BytecodeReplacer aDefaultReplacer); } | @Test public void testLoadInterface() throws IOException, ClassNotFoundException { BytecodeLoader theLoader = new BytecodeLoader(getClass().getClassLoader()); theLoader.loadByteCode(new BytecodeObjectTypeRef(SimpleInterface.class.getName())); } |
Stackifier { public void writeStructuredControlFlow(final StackifierStructuredControlFlowWriter writer) { flow.writeStructuredControlFlow(writer); } Stackifier(final ControlFlowGraph controlFlowGraph); void writeStructuredControlFlow(final StackifierStructuredControlFlowWriter writer); void printDebug(final PrintWriter printWriter); } | @Test public void testOnlyOneNode() throws HeadToHeadControlFlowException { final Program p = new Program(DebugInformation.empty(), null); final ControlFlowGraph g = new ControlFlowGraph(p); final RegionNode startNode = g.createAt(BytecodeOpcodeAddress.START_AT_ZERO, RegionNode.BlockType.NORMAL); g.calculateReachabilityAndMarkBackEdges(); final Stackifier stackifier = new Stackifier(g); final StringWriter sw = new StringWriter(); stackifier.writeStructuredControlFlow(new DebugStructurecControlFlowWriter(stackifier, new PrintWriter(sw))); assertEquals("RegionNode{startAddress=BytecodeOpcodeAddress{address=0}}" + System.lineSeparator(), sw.toString()); }
@Test public void testSimpleSequence() throws HeadToHeadControlFlowException { final Program p = new Program(DebugInformation.empty(), null); final ControlFlowGraph g = new ControlFlowGraph(p); final RegionNode startNode = g.createAt(BytecodeOpcodeAddress.START_AT_ZERO, RegionNode.BlockType.NORMAL); startNode.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(0), new BytecodeOpcodeAddress(10))); final RegionNode node1 = g.createAt(new BytecodeOpcodeAddress(10), RegionNode.BlockType.NORMAL); node1.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(1), new BytecodeOpcodeAddress(20))); final RegionNode node2 = g.createAt(new BytecodeOpcodeAddress(20), RegionNode.BlockType.NORMAL); startNode.addEdgeTo(ControlFlowEdgeType.forward, node1); node1.addEdgeTo(ControlFlowEdgeType.forward, node2); g.calculateReachabilityAndMarkBackEdges(); final Stackifier stackifier = new Stackifier(g); final StringWriter sw = new StringWriter(); stackifier.writeStructuredControlFlow(new DebugStructurecControlFlowWriter(stackifier, new PrintWriter(sw))); assertEquals("RegionNode{startAddress=BytecodeOpcodeAddress{address=0}}" + System.lineSeparator() + "RegionNode{startAddress=BytecodeOpcodeAddress{address=10}}" + System.lineSeparator() + "RegionNode{startAddress=BytecodeOpcodeAddress{address=20}}" + System.lineSeparator(), sw.toString()); }
@Test public void testSimpleSequenceWithoutGotos() throws HeadToHeadControlFlowException { final Program p = new Program(DebugInformation.empty(), null); final ControlFlowGraph g = new ControlFlowGraph(p); final RegionNode startNode = g.createAt(BytecodeOpcodeAddress.START_AT_ZERO, RegionNode.BlockType.NORMAL); final RegionNode node1 = g.createAt(new BytecodeOpcodeAddress(10), RegionNode.BlockType.NORMAL); final RegionNode node2 = g.createAt(new BytecodeOpcodeAddress(20), RegionNode.BlockType.NORMAL); startNode.addEdgeTo(ControlFlowEdgeType.forward, node1); node1.addEdgeTo(ControlFlowEdgeType.forward, node2); g.calculateReachabilityAndMarkBackEdges(); final Stackifier stackifier = new Stackifier(g); final StringWriter sw = new StringWriter(); stackifier.writeStructuredControlFlow(new DebugStructurecControlFlowWriter(stackifier, new PrintWriter(sw))); assertEquals("RegionNode{startAddress=BytecodeOpcodeAddress{address=0}}" + System.lineSeparator() + "RegionNode{startAddress=BytecodeOpcodeAddress{address=10}}" + System.lineSeparator() + "RegionNode{startAddress=BytecodeOpcodeAddress{address=20}}" + System.lineSeparator(), sw.toString()); }
@Test public void testIfThenElse() throws HeadToHeadControlFlowException { final Program p = new Program(DebugInformation.empty(), null); final ControlFlowGraph g = new ControlFlowGraph(p); final RegionNode startNode = g.createAt(BytecodeOpcodeAddress.START_AT_ZERO, RegionNode.BlockType.NORMAL); startNode.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(0), new BytecodeOpcodeAddress(10))); startNode.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(1), new BytecodeOpcodeAddress(20))); final RegionNode a = g.createAt(new BytecodeOpcodeAddress(10), RegionNode.BlockType.NORMAL); a.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(0), new BytecodeOpcodeAddress(30))); final RegionNode b = g.createAt(new BytecodeOpcodeAddress(20), RegionNode.BlockType.NORMAL); b.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(2), new BytecodeOpcodeAddress(30))); final RegionNode c = g.createAt(new BytecodeOpcodeAddress(30), RegionNode.BlockType.NORMAL); startNode.addEdgeTo(ControlFlowEdgeType.forward, a); startNode.addEdgeTo(ControlFlowEdgeType.forward, b); a.addEdgeTo(ControlFlowEdgeType.forward, c); b.addEdgeTo(ControlFlowEdgeType.forward, c); g.calculateReachabilityAndMarkBackEdges(); final Stackifier stackifier = new Stackifier(g); final StringWriter sw = new StringWriter(); stackifier.writeStructuredControlFlow(new DebugStructurecControlFlowWriter(stackifier, new PrintWriter(sw))); assertEquals("BLOCK $B_0_3: {" + System.lineSeparator() + " BLOCK $B_0_2: {" + System.lineSeparator() + " BLOCK $B_0_1: {" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=0}}" + System.lineSeparator() + " break $B_0_1" + System.lineSeparator() + " break $B_0_2" + System.lineSeparator() + " } ; Closing block $B_0_1" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=10}}" + System.lineSeparator() + " break $B_0_3" + System.lineSeparator() + " } ; Closing block $B_0_2" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=20}}" + System.lineSeparator() + " break $B_0_3" + System.lineSeparator() + "} ; Closing block $B_0_3" + System.lineSeparator() + "RegionNode{startAddress=BytecodeOpcodeAddress{address=30}}" + System.lineSeparator(), sw.toString()); }
@Test public void testSimpleLoop() throws HeadToHeadControlFlowException { final Program p = new Program(DebugInformation.empty(), null); final ControlFlowGraph g = new ControlFlowGraph(p); final RegionNode startNode = g.createAt(BytecodeOpcodeAddress.START_AT_ZERO, RegionNode.BlockType.NORMAL); startNode.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(0), new BytecodeOpcodeAddress(10))); final RegionNode node1 = g.createAt(new BytecodeOpcodeAddress(10), RegionNode.BlockType.NORMAL); node1.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(1), new BytecodeOpcodeAddress(0))); startNode.addEdgeTo(ControlFlowEdgeType.forward, node1); node1.addEdgeTo(ControlFlowEdgeType.forward, startNode); g.calculateReachabilityAndMarkBackEdges(); final Stackifier stackifier = new Stackifier(g); final StringWriter sw = new StringWriter(); stackifier.writeStructuredControlFlow(new DebugStructurecControlFlowWriter(stackifier, new PrintWriter(sw))); assertEquals("LOOP $L_0_1: {" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=0}}" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=10}}" + System.lineSeparator() + " continue $L_0_1" + System.lineSeparator() + "} ; Closing block $L_0_1" + System.lineSeparator(), sw.toString()); }
@Test public void testSimpleLoopWithSuccessor1() throws HeadToHeadControlFlowException { final Program p = new Program(DebugInformation.empty(), null); final ControlFlowGraph g = new ControlFlowGraph(p); final RegionNode startNode = g.createAt(BytecodeOpcodeAddress.START_AT_ZERO, RegionNode.BlockType.NORMAL); startNode.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(0), new BytecodeOpcodeAddress(20))); final RegionNode node1 = g.createAt(new BytecodeOpcodeAddress(10), RegionNode.BlockType.NORMAL); node1.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(1), new BytecodeOpcodeAddress(0))); final RegionNode node2 = g.createAt(new BytecodeOpcodeAddress(20), RegionNode.BlockType.NORMAL); startNode.addEdgeTo(ControlFlowEdgeType.forward, node1); startNode.addEdgeTo(ControlFlowEdgeType.forward, node2); node1.addEdgeTo(ControlFlowEdgeType.forward, startNode); g.calculateReachabilityAndMarkBackEdges(); final Stackifier stackifier = new Stackifier(g); final StringWriter sw = new StringWriter(); stackifier.writeStructuredControlFlow(new DebugStructurecControlFlowWriter(stackifier, new PrintWriter(sw))); assertEquals("LOOP $L_0_2: {" + System.lineSeparator() + " BLOCK $B_0_2: {" + System.lineSeparator() + " BLOCK $B_0_1: {" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=0}}" + System.lineSeparator() + " break $B_0_2" + System.lineSeparator() + " } ; Closing block $B_0_1" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=10}}" + System.lineSeparator() + " continue $L_0_2" + System.lineSeparator() + " } ; Closing block $B_0_2" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=20}}" + System.lineSeparator() + "} ; Closing block $L_0_2" + System.lineSeparator(), sw.toString()); }
@Test public void testSimpleLoopWithSuccessor2() throws HeadToHeadControlFlowException { final Program p = new Program(DebugInformation.empty(), null); final ControlFlowGraph g = new ControlFlowGraph(p); final RegionNode startNode = g.createAt(BytecodeOpcodeAddress.START_AT_ZERO, RegionNode.BlockType.NORMAL); startNode.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(0), new BytecodeOpcodeAddress(0))); final RegionNode node1 = g.createAt(new BytecodeOpcodeAddress(10), RegionNode.BlockType.NORMAL); node1.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(1), new BytecodeOpcodeAddress(20))); final RegionNode node2 = g.createAt(new BytecodeOpcodeAddress(20), RegionNode.BlockType.NORMAL); startNode.addEdgeTo(ControlFlowEdgeType.forward, node1); startNode.addEdgeTo(ControlFlowEdgeType.forward, node2); node1.addEdgeTo(ControlFlowEdgeType.forward, startNode); g.calculateReachabilityAndMarkBackEdges(); final Stackifier stackifier = new Stackifier(g); final StringWriter sw = new StringWriter(); stackifier.writeStructuredControlFlow(new DebugStructurecControlFlowWriter(stackifier, new PrintWriter(sw))); assertEquals("LOOP $L_0_2: {" + System.lineSeparator() + " BLOCK $B_0_2: {" + System.lineSeparator() + " BLOCK $B_0_1: {" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=0}}" + System.lineSeparator() + " continue $L_0_2" + System.lineSeparator() + " } ; Closing block $B_0_1" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=10}}" + System.lineSeparator() + " break $B_0_2" + System.lineSeparator() + " } ; Closing block $B_0_2" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=20}}" + System.lineSeparator() + "} ; Closing block $L_0_2" + System.lineSeparator(), sw.toString()); }
@Test public void testSimpleLoopDoubleExit() throws HeadToHeadControlFlowException { final Program p = new Program(DebugInformation.empty(), null); final ControlFlowGraph g = new ControlFlowGraph(p); final RegionNode startNode = g.createAt(BytecodeOpcodeAddress.START_AT_ZERO, RegionNode.BlockType.NORMAL); startNode.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(0), new BytecodeOpcodeAddress(20))); final RegionNode node1 = g.createAt(new BytecodeOpcodeAddress(10), RegionNode.BlockType.NORMAL); node1.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(1), new BytecodeOpcodeAddress(20))); node1.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(1), new BytecodeOpcodeAddress(0))); final RegionNode node2 = g.createAt(new BytecodeOpcodeAddress(20), RegionNode.BlockType.NORMAL); startNode.addEdgeTo(ControlFlowEdgeType.forward, node1); startNode.addEdgeTo(ControlFlowEdgeType.forward, node2); node1.addEdgeTo(ControlFlowEdgeType.forward, startNode); g.calculateReachabilityAndMarkBackEdges(); final Stackifier stackifier = new Stackifier(g); final StringWriter sw = new StringWriter(); stackifier.writeStructuredControlFlow(new DebugStructurecControlFlowWriter(stackifier, new PrintWriter(sw))); assertEquals("LOOP $L_0_2: {" + System.lineSeparator() + " BLOCK $B_0_2: {" + System.lineSeparator() + " BLOCK $B_0_1: {" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=0}}" + System.lineSeparator() + " break $B_0_2" + System.lineSeparator() + " } ; Closing block $B_0_1" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=10}}" + System.lineSeparator() + " break $B_0_2" + System.lineSeparator() + " continue $L_0_2" + System.lineSeparator() + " } ; Closing block $B_0_2" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=20}}" + System.lineSeparator() + "} ; Closing block $L_0_2" + System.lineSeparator(), sw.toString()); }
@Test public void testSimpleLoopDoubleContinue() throws HeadToHeadControlFlowException { final Program p = new Program(DebugInformation.empty(), null); final ControlFlowGraph g = new ControlFlowGraph(p); final RegionNode startNode = g.createAt(BytecodeOpcodeAddress.START_AT_ZERO, RegionNode.BlockType.NORMAL); startNode.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(0), new BytecodeOpcodeAddress(0))); final RegionNode node1 = g.createAt(new BytecodeOpcodeAddress(10), RegionNode.BlockType.NORMAL); node1.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(1), new BytecodeOpcodeAddress(20))); node1.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(1), new BytecodeOpcodeAddress(0))); final RegionNode node2 = g.createAt(new BytecodeOpcodeAddress(20), RegionNode.BlockType.NORMAL); startNode.addEdgeTo(ControlFlowEdgeType.forward, node1); startNode.addEdgeTo(ControlFlowEdgeType.forward, node2); node1.addEdgeTo(ControlFlowEdgeType.forward, startNode); g.calculateReachabilityAndMarkBackEdges(); final Stackifier stackifier = new Stackifier(g); final StringWriter sw = new StringWriter(); stackifier.writeStructuredControlFlow(new DebugStructurecControlFlowWriter(stackifier, new PrintWriter(sw))); assertEquals("LOOP $L_0_2: {" + System.lineSeparator() + " BLOCK $B_0_2: {" + System.lineSeparator() + " BLOCK $B_0_1: {" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=0}}" + System.lineSeparator() + " continue $L_0_2" + System.lineSeparator() + " } ; Closing block $B_0_1" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=10}}" + System.lineSeparator() + " break $B_0_2" + System.lineSeparator() + " continue $L_0_2" + System.lineSeparator() + " } ; Closing block $B_0_2" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=20}}" + System.lineSeparator() + "} ; Closing block $L_0_2" + System.lineSeparator(), sw.toString()); }
@Test public void testMoreComplexExample() throws HeadToHeadControlFlowException { final Program p = new Program(DebugInformation.empty(), null); final ControlFlowGraph g = new ControlFlowGraph(p); final RegionNode startNode = g.createAt(BytecodeOpcodeAddress.START_AT_ZERO, RegionNode.BlockType.NORMAL); final RegionNode node10 = g.createAt(new BytecodeOpcodeAddress(10), RegionNode.BlockType.NORMAL); final RegionNode node16 = g.createAt(new BytecodeOpcodeAddress(16), RegionNode.BlockType.NORMAL); final RegionNode node31 = g.createAt(new BytecodeOpcodeAddress(31), RegionNode.BlockType.NORMAL); final RegionNode node35= g.createAt(new BytecodeOpcodeAddress(35), RegionNode.BlockType.NORMAL); final RegionNode node41= g.createAt(new BytecodeOpcodeAddress(41), RegionNode.BlockType.NORMAL); final RegionNode node51= g.createAt(new BytecodeOpcodeAddress(51), RegionNode.BlockType.NORMAL); final RegionNode node57= g.createAt(new BytecodeOpcodeAddress(57), RegionNode.BlockType.NORMAL); final RegionNode node72= g.createAt(new BytecodeOpcodeAddress(72), RegionNode.BlockType.NORMAL); final RegionNode node76= g.createAt(new BytecodeOpcodeAddress(76), RegionNode.BlockType.NORMAL); final RegionNode node82= g.createAt(new BytecodeOpcodeAddress(82), RegionNode.BlockType.NORMAL); final RegionNode node95= g.createAt(new BytecodeOpcodeAddress(95), RegionNode.BlockType.NORMAL); final RegionNode node99= g.createAt(new BytecodeOpcodeAddress(99), RegionNode.BlockType.NORMAL); final RegionNode node112= g.createAt(new BytecodeOpcodeAddress(112), RegionNode.BlockType.NORMAL); final RegionNode node116= g.createAt(new BytecodeOpcodeAddress(116), RegionNode.BlockType.NORMAL); startNode.addEdgeTo(ControlFlowEdgeType.forward, node10); startNode.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(0), new BytecodeOpcodeAddress(10))); node10.addEdgeTo(ControlFlowEdgeType.forward, node16); node10.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(10), new BytecodeOpcodeAddress(16))); node10.addEdgeTo(ControlFlowEdgeType.forward, node41); node10.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(11), new BytecodeOpcodeAddress(41))); node16.addEdgeTo(ControlFlowEdgeType.forward, node35); node16.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(16), new BytecodeOpcodeAddress(35))); node16.addEdgeTo(ControlFlowEdgeType.forward, node31); node16.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(17), new BytecodeOpcodeAddress(31))); node35.addEdgeTo(ControlFlowEdgeType.forward, node10); node35.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(35), new BytecodeOpcodeAddress(10))); node41.addEdgeTo(ControlFlowEdgeType.forward, node51); node41.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(41), new BytecodeOpcodeAddress(51))); node51.addEdgeTo(ControlFlowEdgeType.forward, node57); node51.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(51), new BytecodeOpcodeAddress(57))); node51.addEdgeTo(ControlFlowEdgeType.forward, node82); node51.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(52), new BytecodeOpcodeAddress(82))); node57.addEdgeTo(ControlFlowEdgeType.forward, node72); node57.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(57), new BytecodeOpcodeAddress(72))); node57.addEdgeTo(ControlFlowEdgeType.forward, node76); node57.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(58), new BytecodeOpcodeAddress(76))); node76.addEdgeTo(ControlFlowEdgeType.forward, node51); node76.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(76), new BytecodeOpcodeAddress(51))); node82.addEdgeTo(ControlFlowEdgeType.forward, node95); node82.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(82), new BytecodeOpcodeAddress(95))); node82.addEdgeTo(ControlFlowEdgeType.forward, node99); node82.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(83), new BytecodeOpcodeAddress(99))); node99.addEdgeTo(ControlFlowEdgeType.forward, node112); node99.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(99), new BytecodeOpcodeAddress(112))); node99.addEdgeTo(ControlFlowEdgeType.forward, node116); node99.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(100), new BytecodeOpcodeAddress(116))); g.calculateReachabilityAndMarkBackEdges(); final Stackifier stackifier = new Stackifier(g); final StringWriter sw = new StringWriter(); stackifier.writeStructuredControlFlow(new DebugStructurecControlFlowWriter(stackifier, new PrintWriter(sw))); assertEquals("RegionNode{startAddress=BytecodeOpcodeAddress{address=0}}" + System.lineSeparator() + "LOOP $L_1_14: {" + System.lineSeparator() + " BLOCK $B_1_5: {" + System.lineSeparator() + " BLOCK $B_1_2: {" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=10}}" + System.lineSeparator() + " break $B_1_2" + System.lineSeparator() + " break $B_1_5" + System.lineSeparator() + " } ; Closing block $B_1_2" + System.lineSeparator() + " BLOCK $B_2_4: {" + System.lineSeparator() + " BLOCK $B_2_3: {" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=16}}" + System.lineSeparator() + " break $B_2_4" + System.lineSeparator() + " break $B_2_3" + System.lineSeparator() + " } ; Closing block $B_2_3" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=31}}" + System.lineSeparator() + " } ; Closing block $B_2_4" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=35}}" + System.lineSeparator() + " continue $L_1_14" + System.lineSeparator() + " } ; Closing block $B_1_5" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=41}}" + System.lineSeparator() + " LOOP $L_6_14: {" + System.lineSeparator() + " BLOCK $B_6_10: {" + System.lineSeparator() + " BLOCK $B_6_7: {" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=51}}" + System.lineSeparator() + " break $B_6_7" + System.lineSeparator() + " break $B_6_10" + System.lineSeparator() + " } ; Closing block $B_6_7" + System.lineSeparator() + " BLOCK $B_7_9: {" + System.lineSeparator() + " BLOCK $B_7_8: {" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=57}}" + System.lineSeparator() + " break $B_7_8" + System.lineSeparator() + " break $B_7_9" + System.lineSeparator() + " } ; Closing block $B_7_8" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=72}}" + System.lineSeparator() + " } ; Closing block $B_7_9" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=76}}" + System.lineSeparator() + " continue $L_6_14" + System.lineSeparator() + " } ; Closing block $B_6_10" + System.lineSeparator() + " BLOCK $B_10_12: {" + System.lineSeparator() + " BLOCK $B_10_11: {" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=82}}" + System.lineSeparator() + " break $B_10_11" + System.lineSeparator() + " break $B_10_12" + System.lineSeparator() + " } ; Closing block $B_10_11" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=95}}" + System.lineSeparator() + " } ; Closing block $B_10_12" + System.lineSeparator() + " BLOCK $B_12_14: {" + System.lineSeparator() + " BLOCK $B_12_13: {" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=99}}" + System.lineSeparator() + " break $B_12_13" + System.lineSeparator() + " break $B_12_14" + System.lineSeparator() + " } ; Closing block $B_12_13" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=112}}" + System.lineSeparator() + " } ; Closing block $B_12_14" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=116}}" + System.lineSeparator() + " } ; Closing block $L_6_14" + System.lineSeparator() + "} ; Closing block $L_1_14" + System.lineSeparator(), sw.toString()); }
@Test public void testComplexExampleWithLoopAsLastElement() throws HeadToHeadControlFlowException { final Program p = new Program(DebugInformation.empty(), null); final ControlFlowGraph g = new ControlFlowGraph(p); final RegionNode startNode = g.createAt(BytecodeOpcodeAddress.START_AT_ZERO, RegionNode.BlockType.NORMAL); final RegionNode node10 = g.createAt(new BytecodeOpcodeAddress(10), RegionNode.BlockType.NORMAL); final RegionNode node23 = g.createAt(new BytecodeOpcodeAddress(23), RegionNode.BlockType.NORMAL); final RegionNode node25 = g.createAt(new BytecodeOpcodeAddress(25), RegionNode.BlockType.NORMAL); final RegionNode node62 = g.createAt(new BytecodeOpcodeAddress(62), RegionNode.BlockType.NORMAL); final RegionNode node65 = g.createAt(new BytecodeOpcodeAddress(65), RegionNode.BlockType.NORMAL); final RegionNode node74 = g.createAt(new BytecodeOpcodeAddress(74), RegionNode.BlockType.NORMAL); final RegionNode node81 = g.createAt(new BytecodeOpcodeAddress(81), RegionNode.BlockType.NORMAL); final RegionNode node109 = g.createAt(new BytecodeOpcodeAddress(109), RegionNode.BlockType.NORMAL); final RegionNode node103 = g.createAt(new BytecodeOpcodeAddress(103), RegionNode.BlockType.NORMAL); final RegionNode node100 = g.createAt(new BytecodeOpcodeAddress(100), RegionNode.BlockType.NORMAL); startNode.addEdgeTo(ControlFlowEdgeType.forward, node10); startNode.addEdgeTo(ControlFlowEdgeType.forward, node74); node10.addEdgeTo(ControlFlowEdgeType.forward, node23); node10.addEdgeTo(ControlFlowEdgeType.forward, node25); node25.addEdgeTo(ControlFlowEdgeType.forward, node62); node25.addEdgeTo(ControlFlowEdgeType.forward, node65); node65.addEdgeTo(ControlFlowEdgeType.forward, node74); node74.addEdgeTo(ControlFlowEdgeType.forward, node81); node74.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(74), new BytecodeOpcodeAddress(109))); node74.addEdgeTo(ControlFlowEdgeType.forward, node109); node81.addEdgeTo(ControlFlowEdgeType.forward, node103); node81.addEdgeTo(ControlFlowEdgeType.forward, node100); node100.addEdgeTo(ControlFlowEdgeType.forward, node74); node100.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(100), new BytecodeOpcodeAddress(74))); g.calculateReachabilityAndMarkBackEdges(); final Stackifier stackifier = new Stackifier(g); final StringWriter sw = new StringWriter(); stackifier.writeStructuredControlFlow(new DebugStructurecControlFlowWriter(stackifier, new PrintWriter(sw))); assertEquals("BLOCK $B_0_6: {" + System.lineSeparator() + " BLOCK $B_0_1: {" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=0}}" + System.lineSeparator() + " } ; Closing block $B_0_1" + System.lineSeparator() + " BLOCK $B_1_3: {" + System.lineSeparator() + " BLOCK $B_1_2: {" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=10}}" + System.lineSeparator() + " } ; Closing block $B_1_2" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=23}}" + System.lineSeparator() + " } ; Closing block $B_1_3" + System.lineSeparator() + " BLOCK $B_3_5: {" + System.lineSeparator() + " BLOCK $B_3_4: {" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=25}}" + System.lineSeparator() + " } ; Closing block $B_3_4" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=62}}" + System.lineSeparator() + " } ; Closing block $B_3_5" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=65}}" + System.lineSeparator() + "} ; Closing block $B_0_6" + System.lineSeparator() + "LOOP $L_6_10: {" + System.lineSeparator() + " BLOCK $B_6_10: {" + System.lineSeparator() + " BLOCK $B_6_7: {" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=74}}" + System.lineSeparator() + " break $B_6_10" + System.lineSeparator() + " } ; Closing block $B_6_7" + System.lineSeparator() + " BLOCK $B_7_9: {" + System.lineSeparator() + " BLOCK $B_7_8: {" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=81}}" + System.lineSeparator() + " } ; Closing block $B_7_8" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=100}}" + System.lineSeparator() + " continue $L_6_10" + System.lineSeparator() + " } ; Closing block $B_7_9" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=103}}" + System.lineSeparator() + " } ; Closing block $B_6_10" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=109}}" + System.lineSeparator() + "} ; Closing block $L_6_10" + System.lineSeparator(), sw.toString()); }
@Test public void testAnotherComplexExample() throws HeadToHeadControlFlowException { final Program p = new Program(DebugInformation.empty(), null); final ControlFlowGraph g = new ControlFlowGraph(p); final RegionNode node0 = g.createAt(BytecodeOpcodeAddress.START_AT_ZERO, RegionNode.BlockType.NORMAL); node0.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(0), new BytecodeOpcodeAddress(2))); final RegionNode node1 = g.createAt(new BytecodeOpcodeAddress(2), RegionNode.BlockType.NORMAL); node1.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(2), new BytecodeOpcodeAddress(13))); node1.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(3), new BytecodeOpcodeAddress(11))); final RegionNode node2 = g.createAt(new BytecodeOpcodeAddress(11), RegionNode.BlockType.NORMAL); final RegionNode node3 = g.createAt(new BytecodeOpcodeAddress(13), RegionNode.BlockType.NORMAL); node3.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(13), new BytecodeOpcodeAddress(2))); node0.addEdgeTo(ControlFlowEdgeType.forward, node1); node1.addEdgeTo(ControlFlowEdgeType.forward, node2); node1.addEdgeTo(ControlFlowEdgeType.forward, node3); node3.addEdgeTo(ControlFlowEdgeType.forward, node1); g.calculateReachabilityAndMarkBackEdges(); final Stackifier stackifier = new Stackifier(g); final StringWriter sw = new StringWriter(); stackifier.writeStructuredControlFlow(new DebugStructurecControlFlowWriter(stackifier, new PrintWriter(sw))); assertEquals("RegionNode{startAddress=BytecodeOpcodeAddress{address=0}}" + System.lineSeparator() + "LOOP $L_1_3: {" + System.lineSeparator() + " BLOCK $B_1_3: {" + System.lineSeparator() + " BLOCK $B_1_2: {" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=2}}" + System.lineSeparator() + " break $B_1_3" + System.lineSeparator() + " break $B_1_2" + System.lineSeparator() + " } ; Closing block $B_1_2" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=11}}" + System.lineSeparator() + " } ; Closing block $B_1_3" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=13}}" + System.lineSeparator() + " continue $L_1_3" + System.lineSeparator() + "} ; Closing block $L_1_3" + System.lineSeparator(), sw.toString()); }
@Test public void testCondition() throws HeadToHeadControlFlowException { final Program p = new Program(DebugInformation.empty(), null); final ControlFlowGraph g = new ControlFlowGraph(p); final RegionNode startNode = g.createAt(BytecodeOpcodeAddress.START_AT_ZERO, RegionNode.BlockType.NORMAL); startNode.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(0), new BytecodeOpcodeAddress(10))); final RegionNode node1 = g.createAt(new BytecodeOpcodeAddress(10), RegionNode.BlockType.NORMAL); final ExpressionList e = new ExpressionList(); e.add(new GotoExpression(p, new BytecodeOpcodeAddress(0), new BytecodeOpcodeAddress(20))); node1.getExpressions().add(new IFExpression(p, new BytecodeOpcodeAddress(0), new BytecodeOpcodeAddress(20), new IntegerValue(0), e)); node1.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(0), new BytecodeOpcodeAddress(30))); final RegionNode node2 = g.createAt(new BytecodeOpcodeAddress(20), RegionNode.BlockType.NORMAL); node2.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(0), new BytecodeOpcodeAddress(30))); final RegionNode node3 = g.createAt(new BytecodeOpcodeAddress(30), RegionNode.BlockType.NORMAL); startNode.addEdgeTo(ControlFlowEdgeType.forward, node1); node1.addEdgeTo(ControlFlowEdgeType.forward, node2); node1.addEdgeTo(ControlFlowEdgeType.forward, node3); node2.addEdgeTo(ControlFlowEdgeType.forward, node3); g.calculateReachabilityAndMarkBackEdges(); final Stackifier stackifier = new Stackifier(g); final StringWriter sw = new StringWriter(); stackifier.writeStructuredControlFlow(new DebugStructurecControlFlowWriter(stackifier, new PrintWriter(sw))); assertEquals("RegionNode{startAddress=BytecodeOpcodeAddress{address=0}}" + System.lineSeparator() + "BLOCK $B_1_3: {" + System.lineSeparator() + " BLOCK $B_1_2: {" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=10}}" + System.lineSeparator() + " if " + System.lineSeparator() + " break $B_1_2" + System.lineSeparator() + " else " + System.lineSeparator() + " break $B_1_3" + System.lineSeparator() + " } ; Closing block $B_1_2" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=20}}" + System.lineSeparator() + " break $B_1_3" + System.lineSeparator() + "} ; Closing block $B_1_3" + System.lineSeparator() + "RegionNode{startAddress=BytecodeOpcodeAddress{address=30}}" + System.lineSeparator(), sw.toString()); }
@Test public void testCompleteInitLoopBoundaries() throws HeadToHeadControlFlowException { final Program p = new Program(DebugInformation.empty(), null); final ControlFlowGraph g = new ControlFlowGraph(p); final RegionNode node0 = g.createAt(BytecodeOpcodeAddress.START_AT_ZERO, RegionNode.BlockType.NORMAL); final RegionNode node1 = g.createAt(new BytecodeOpcodeAddress(13), RegionNode.BlockType.NORMAL); final RegionNode node2 = g.createAt(new BytecodeOpcodeAddress(17), RegionNode.BlockType.NORMAL); final RegionNode node3 = g.createAt(new BytecodeOpcodeAddress(20), RegionNode.BlockType.NORMAL); final RegionNode node4 = g.createAt(new BytecodeOpcodeAddress(27), RegionNode.BlockType.NORMAL); final RegionNode node5 = g.createAt(new BytecodeOpcodeAddress(33), RegionNode.BlockType.NORMAL); final RegionNode node6 = g.createAt(new BytecodeOpcodeAddress(39), RegionNode.BlockType.NORMAL); final RegionNode node7 = g.createAt(new BytecodeOpcodeAddress(46), RegionNode.BlockType.NORMAL); final RegionNode node8 = g.createAt(new BytecodeOpcodeAddress(53), RegionNode.BlockType.NORMAL); final RegionNode node9 = g.createAt(new BytecodeOpcodeAddress(66), RegionNode.BlockType.NORMAL); node0.addEdgeTo(ControlFlowEdgeType.forward, node1); node0.addEdgeTo(ControlFlowEdgeType.forward, node2); node1.addEdgeTo(ControlFlowEdgeType.forward, node3); node2.addEdgeTo(ControlFlowEdgeType.forward, node3); node3.addEdgeTo(ControlFlowEdgeType.forward, node4); node3.addEdgeTo(ControlFlowEdgeType.forward, node9); node4.addEdgeTo(ControlFlowEdgeType.forward, node5); node4.addEdgeTo(ControlFlowEdgeType.forward, node9); node5.addEdgeTo(ControlFlowEdgeType.forward, node9); node5.addEdgeTo(ControlFlowEdgeType.forward, node6); node6.addEdgeTo(ControlFlowEdgeType.forward, node7); node7.addEdgeTo(ControlFlowEdgeType.forward, node8); node7.addEdgeTo(ControlFlowEdgeType.forward, node9); node8.addEdgeTo(ControlFlowEdgeType.forward, node7); g.calculateReachabilityAndMarkBackEdges(); final Stackifier stackifier = new Stackifier(g); final StringWriter sw = new StringWriter(); stackifier.writeStructuredControlFlow(new DebugStructurecControlFlowWriter(stackifier, new PrintWriter(sw))); assertEquals("BLOCK $B_0_3: {" + System.lineSeparator() + " BLOCK $B_0_2: {" + System.lineSeparator() + " BLOCK $B_0_1: {" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=0}}" + System.lineSeparator() + " } ; Closing block $B_0_1" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=13}}" + System.lineSeparator() + " } ; Closing block $B_0_2" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=17}}" + System.lineSeparator() + "} ; Closing block $B_0_3" + System.lineSeparator() + "BLOCK $B_3_9: {" + System.lineSeparator() + " BLOCK $B_3_4: {" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=20}}" + System.lineSeparator() + " } ; Closing block $B_3_4" + System.lineSeparator() + " BLOCK $B_4_9: {" + System.lineSeparator() + " BLOCK $B_4_5: {" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=27}}" + System.lineSeparator() + " } ; Closing block $B_4_5" + System.lineSeparator() + " BLOCK $B_5_9: {" + System.lineSeparator() + " BLOCK $B_5_6: {" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=33}}" + System.lineSeparator() + " } ; Closing block $B_5_6" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=39}}" + System.lineSeparator() + " LOOP $L_7_8: {" + System.lineSeparator() + " BLOCK $B_7_8: {" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=46}}" + System.lineSeparator() + " } ; Closing block $B_7_8" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=53}}" + System.lineSeparator() + " } ; Closing block $L_7_8" + System.lineSeparator() + " } ; Closing block $B_5_9" + System.lineSeparator() + " } ; Closing block $B_4_9" + System.lineSeparator() + "} ; Closing block $B_3_9" + System.lineSeparator() + "RegionNode{startAddress=BytecodeOpcodeAddress{address=66}}" + System.lineSeparator(), sw.toString()); }
@Test public void testIfShoulNotExitLoop() throws HeadToHeadControlFlowException { final Program p = new Program(DebugInformation.empty(), null); final ControlFlowGraph g = new ControlFlowGraph(p); final RegionNode node0 = g.createAt(BytecodeOpcodeAddress.START_AT_ZERO, RegionNode.BlockType.NORMAL); node0.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(0), new BytecodeOpcodeAddress(79))); node0.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(1), new BytecodeOpcodeAddress(138))); final RegionNode node1 = g.createAt(new BytecodeOpcodeAddress(79), RegionNode.BlockType.NORMAL); final RegionNode node2 = g.createAt(new BytecodeOpcodeAddress(90), RegionNode.BlockType.NORMAL); final ExpressionList e = new ExpressionList(); e.add(new GotoExpression(p, new BytecodeOpcodeAddress(0), new BytecodeOpcodeAddress(138))); node2.getExpressions().add(new IFExpression(p, new BytecodeOpcodeAddress(90), new BytecodeOpcodeAddress(138), new IntegerValue(0), e)); node2.getExpressions().add(new GotoExpression(p, new BytecodeOpcodeAddress(0), new BytecodeOpcodeAddress(96))); final RegionNode node3 = g.createAt(new BytecodeOpcodeAddress(96), RegionNode.BlockType.NORMAL); final RegionNode node4 = g.createAt(new BytecodeOpcodeAddress(138), RegionNode.BlockType.NORMAL); final RegionNode node5 = g.createAt(new BytecodeOpcodeAddress(147), RegionNode.BlockType.NORMAL); final RegionNode node6 = g.createAt(new BytecodeOpcodeAddress(190), RegionNode.BlockType.NORMAL); final RegionNode node7 = g.createAt(new BytecodeOpcodeAddress(197), RegionNode.BlockType.NORMAL); final RegionNode node8 = g.createAt(new BytecodeOpcodeAddress(205), RegionNode.BlockType.NORMAL); final RegionNode node9 = g.createAt(new BytecodeOpcodeAddress(219), RegionNode.BlockType.NORMAL); final RegionNode node10 = g.createAt(new BytecodeOpcodeAddress(247), RegionNode.BlockType.NORMAL); node0.addEdgeTo(ControlFlowEdgeType.forward, node1); node0.addEdgeTo(ControlFlowEdgeType.forward, node4); node1.addEdgeTo(ControlFlowEdgeType.forward, node2); node2.addEdgeTo(ControlFlowEdgeType.forward, node3); node2.addEdgeTo(ControlFlowEdgeType.forward, node4); node3.addEdgeTo(ControlFlowEdgeType.forward, node2); node4.addEdgeTo(ControlFlowEdgeType.forward, node5); node4.addEdgeTo(ControlFlowEdgeType.forward, node10); node5.addEdgeTo(ControlFlowEdgeType.forward, node6); node6.addEdgeTo(ControlFlowEdgeType.forward, node10); node6.addEdgeTo(ControlFlowEdgeType.forward, node7); node7.addEdgeTo(ControlFlowEdgeType.forward, node9); node7.addEdgeTo(ControlFlowEdgeType.forward, node8); node8.addEdgeTo(ControlFlowEdgeType.forward, node9); node9.addEdgeTo(ControlFlowEdgeType.forward, node6); g.calculateReachabilityAndMarkBackEdges(); final Stackifier stackifier = new Stackifier(g); final StringWriter sw = new StringWriter(); stackifier.writeStructuredControlFlow(new DebugStructurecControlFlowWriter(stackifier, new PrintWriter(sw))); assertEquals("BLOCK $B_0_4: {" + System.lineSeparator() + " BLOCK $B_0_1: {" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=0}}" + System.lineSeparator() + " break $B_0_1" + System.lineSeparator() + " break $B_0_4" + System.lineSeparator() + " } ; Closing block $B_0_1" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=79}}" + System.lineSeparator() + " LOOP $L_2_3: {" + System.lineSeparator() + " BLOCK $B_2_3: {" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=90}}" + System.lineSeparator() + " if " + System.lineSeparator() + " break $B_0_4" + System.lineSeparator() + " else " + System.lineSeparator() + " break $B_2_3" + System.lineSeparator() + " } ; Closing block $B_2_3" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=96}}" + System.lineSeparator() + " } ; Closing block $L_2_3" + System.lineSeparator() + "} ; Closing block $B_0_4" + System.lineSeparator() + "BLOCK $B_4_10: {" + System.lineSeparator() + " BLOCK $B_4_5: {" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=138}}" + System.lineSeparator() + " } ; Closing block $B_4_5" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=147}}" + System.lineSeparator() + " LOOP $L_6_9: {" + System.lineSeparator() + " BLOCK $B_6_7: {" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=190}}" + System.lineSeparator() + " } ; Closing block $B_6_7" + System.lineSeparator() + " BLOCK $B_7_9: {" + System.lineSeparator() + " BLOCK $B_7_8: {" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=197}}" + System.lineSeparator() + " } ; Closing block $B_7_8" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=205}}" + System.lineSeparator() + " } ; Closing block $B_7_9" + System.lineSeparator() + " RegionNode{startAddress=BytecodeOpcodeAddress{address=219}}" + System.lineSeparator() + " } ; Closing block $L_6_9" + System.lineSeparator() + "} ; Closing block $B_4_10" + System.lineSeparator() + "RegionNode{startAddress=BytecodeOpcodeAddress{address=247}}" + System.lineSeparator() , sw.toString()); } |
Function extends Container implements Importable, Callable { @Override public void writeTo(final TextWriter textWriter, final Module aModule) throws IOException { textWriter.opening(); textWriter.write("func"); textWriter.space(); textWriter.writeLabel(label); textWriter.space(); functionType.writeRefTo(textWriter); textWriter.closing(); } Function(final Module aModule, final WASMType functionType, final String label, final List<Param> params, final PrimitiveType result); Function(final Module aModule, final WASMType functionType, final String label, final List<Param> params); Function(final Module aModule, final WASMType functionType, final String label, final PrimitiveType result); @Override void writeTo(final TextWriter textWriter, final Module aModule); WASMType getFunctionType(); String getLabel(); List<Param> getParams(); PrimitiveType getResultType(); Function toTable(); @Override PrimitiveType resolveResultType(final WASMValue.ExportContext context); @Override int resolveIndex(final WASMValue.ExportContext context); } | @Test public void testSimpleCase() throws IOException { final StringWriter strWriter = new StringWriter(); final PrintWriter pw = new PrintWriter(strWriter); final Module module = new Module("mod", "mod.wasm.map"); final FunctionsSection functionsContent = module.getFunctions(); final ExportableFunction function = functionsContent.newFunction("label", Collections.singletonList(param("p1", PrimitiveType.i32)), PrimitiveType.i32); function.flow.ret(i32.c(42, null), null); try (final TextWriter writer = new TextWriter(pw)) { function.writeTo(writer, module); } Assert.assertEquals("(func $label (type $t0) (param $p1 i32) (result i32)" + System.lineSeparator() + " (return (i32.const 42))" + System.lineSeparator() + " )", strWriter.toString()); }
@Test public void testNoReturnValue() throws IOException { final StringWriter strWriter = new StringWriter(); final PrintWriter pw = new PrintWriter(strWriter); final Module module = new Module("mod", "mod.wasm.map"); final FunctionsSection functionsContent = module.getFunctions(); final ExportableFunction function = functionsContent.newFunction("label", Collections.singletonList(param("p1", PrimitiveType.i32))); function.flow.ret(null); try (final TextWriter writer = new TextWriter(pw)) { function.writeTo(writer, module); } Assert.assertEquals("(func $label (type $t0) (param $p1 i32)" + System.lineSeparator() + " (return)" + System.lineSeparator() + " )", strWriter.toString()); } |
StructuredControlFlow { public void printDebug(final PrintWriter pw) { pw.println("Original:"); printDebug(pw, false); for (final JumpArrow<T> arrow : knownJumpArrows) { pw.println(String.format(" %s %d -> %d", arrow.getEdgeType(), indexOf(arrow.getTail()), indexOf(arrow.getHead()))); } pw.println(); pw.println("Stackified:"); printDebug(pw, true); for (final JumpArrow<T> arrow : knownJumpArrows) { pw.println(String.format(" %s %d -> %d", arrow.getEdgeType(), indexOf(arrow.getNewTail()), indexOf(arrow.getHead()))); } pw.println(); pw.println("Data:"); for (int i=0;i<nodesInOrder.size();i++) { pw.println(String.format(" %d %s", i, nodesInOrder.get(i))); } pw.flush(); } StructuredControlFlow(final List<JumpArrow<T>> knownJumpArrows, final List<T> nodesInOrder); int indexOf(final T aValue); int indexOf(final JumpArrow<T> arrow); void printDebug(final PrintWriter pw); void writeStructuredControlFlow(final StructuredControlFlowWriter<T> writer); void writeStructuredControlFlow(final StructuredControlFlowWriter<T> writer, final List<T> nodes); } | @Test public void testHeadToHead() throws HeadToHeadControlFlowException { expectedException.expect(HeadToHeadControlFlowException.class); expectedException.expectMessage("{2,3} are head to head"); final StructuredControlFlowBuilder<Integer> builder = new StructuredControlFlowBuilder<>(Arrays.asList(0, 1, 2, 3)); builder.add(ControlFlowEdgeType.forward,0, 2); builder.add(ControlFlowEdgeType.back, 3, 1); final StructuredControlFlow<Integer> graph = builder.build(); graph.printDebug(new PrintWriter(System.out)); } |
AnnotationBasedExpiration implements BeanFactoryAware, CustomExpiry<K, V> { protected ExpirationAttributes getDefaultExpirationAttributes() { return this.defaultExpirationAttributes; } AnnotationBasedExpiration(); AnnotationBasedExpiration(ExpirationAttributes defaultExpirationAttributes); static AnnotationBasedExpiration<K, V> forIdleTimeout(); static AnnotationBasedExpiration<K, V> forIdleTimeout(ExpirationAttributes defaultExpirationAttributes); static AnnotationBasedExpiration<K, V> forTimeToLive(); static AnnotationBasedExpiration<K, V> forTimeToLive(ExpirationAttributes defaultExpirationAttributes); @Override void setBeanFactory(BeanFactory beanFactory); void setDefaultExpirationAttributes(ExpirationAttributes defaultExpirationAttributes); @Override ExpirationAttributes getExpiry(Region.Entry<K, V> entry); @Override void close(); } | @Test public void constructUninitializedAnnotationBasedExpirationInstance() { AnnotationBasedExpiration expiration = new AnnotationBasedExpiration(); assertThat(expiration.getDefaultExpirationAttributes(), is(nullValue())); }
@Test public void constructInitializedAnnotationBasedExpirationInstance() { AnnotationBasedExpiration expiration = new AnnotationBasedExpiration(ExpirationAttributes.DEFAULT); assertThat(expiration.getDefaultExpirationAttributes(), is(equalTo(ExpirationAttributes.DEFAULT))); } |
PartitionedRegionFactoryBean extends PeerRegionFactoryBean<K, V> { @Override protected void resolveDataPolicy(RegionFactory<K, V> regionFactory, Boolean persistent, DataPolicy dataPolicy) { if (dataPolicy == null) { dataPolicy = isPersistent() ? DataPolicy.PERSISTENT_PARTITION : DataPolicy.PARTITION; } else { Assert.isTrue(dataPolicy.withPartitioning(), String.format( "Data Policy [%s] is not supported in Partitioned Regions.", dataPolicy)); } RegionUtils.assertDataPolicyAndPersistentAttributeAreCompatible(dataPolicy, persistent); regionFactory.setDataPolicy(dataPolicy); setDataPolicy(dataPolicy); } } | @Test public void testResolveDataPolicyWhenPersistentUnspecifiedAndPartitionDataPolicy() { RegionFactory mockRegionFactory = createMockRegionFactory(); factoryBean.resolveDataPolicy(mockRegionFactory, null, "PARTITION"); verify(mockRegionFactory).setDataPolicy(eq(DataPolicy.PARTITION)); }
@Test public void testResolveDataPolicyWhenNotPersistentAndPartitionDataPolicy() { RegionFactory mockRegionFactory = createMockRegionFactory(); factoryBean.setPersistent(false); factoryBean.resolveDataPolicy(mockRegionFactory, false, "PARTITION"); verify(mockRegionFactory).setDataPolicy(eq(DataPolicy.PARTITION)); }
@Test(expected = IllegalArgumentException.class) public void testResolveDataPolicyWhenPersistentAndPartitionDataPolicy() { RegionFactory mockRegionFactory = createMockRegionFactory(); try { factoryBean.setPersistent(true); factoryBean.resolveDataPolicy(mockRegionFactory, true, "PARTITION"); } catch (IllegalArgumentException e) { assertEquals("Data Policy [PARTITION] is not valid when persistent is true", e.getMessage()); throw e; } finally { verify(mockRegionFactory, never()).setDataPolicy(null); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.PARTITION)); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.PERSISTENT_PARTITION)); } }
@Test public void testResolveDataPolicyWhenPersistentUnspecifiedAndPersistentPartitionDataPolicy() { RegionFactory mockRegionFactory = createMockRegionFactory(); factoryBean.resolveDataPolicy(mockRegionFactory, null, "PERSISTENT_PARTITION"); verify(mockRegionFactory).setDataPolicy(eq(DataPolicy.PERSISTENT_PARTITION)); }
@Test(expected = IllegalArgumentException.class) public void testResolveDataPolicyWhenNotPersistentAndPersistentPartitionedDataPolicy() { RegionFactory mockRegionFactory = createMockRegionFactory(); try { factoryBean.setPersistent(false); factoryBean.resolveDataPolicy(mockRegionFactory, false, "PERSISTENT_PARTITION"); } catch (IllegalArgumentException e) { assertEquals("Data Policy [PERSISTENT_PARTITION] is not valid when persistent is false", e.getMessage()); throw e; } finally { verify(mockRegionFactory, never()).setDataPolicy(null); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.PARTITION)); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.PERSISTENT_PARTITION)); } }
@Test public void testResolveDataPolicyWhenPersistentAndPersistentPartitionedDataPolicy() { RegionFactory mockRegionFactory = createMockRegionFactory(); factoryBean.setPersistent(true); factoryBean.resolveDataPolicy(mockRegionFactory, true, "PERSISTENT_PARTITION"); verify(mockRegionFactory).setDataPolicy(eq(DataPolicy.PERSISTENT_PARTITION)); }
@Test public void testResolveDataPolicyWithPersistentUnspecifiedAndDataPolicyUnspecified() { RegionFactory mockRegionFactory = createMockRegionFactory(); factoryBean.resolveDataPolicy(mockRegionFactory, null, (String) null); verify(mockRegionFactory).setDataPolicy(eq(DataPolicy.PARTITION)); }
@Test public void testResolveDataPolicyWhenNotPersistentAndDataPolicyUnspecified() { RegionFactory mockRegionFactory = createMockRegionFactory(); factoryBean.setPersistent(false); factoryBean.resolveDataPolicy(mockRegionFactory, false, (String) null); verify(mockRegionFactory).setDataPolicy(eq(DataPolicy.PARTITION)); }
@Test public void testResolveDataPolicyWhenPersistentAndDataPolicyUnspecified() { RegionFactory mockRegionFactory = createMockRegionFactory(); factoryBean.setPersistent(true); factoryBean.resolveDataPolicy(mockRegionFactory, true, (String) null); verify(mockRegionFactory).setDataPolicy(eq(DataPolicy.PERSISTENT_PARTITION)); }
@Test(expected = IllegalArgumentException.class) public void testResolveDataPolicyWithBlankDataPolicy() { RegionFactory mockRegionFactory = createMockRegionFactory(); try { factoryBean.resolveDataPolicy(mockRegionFactory, null, " "); } catch (IllegalArgumentException e) { assertEquals("Data Policy [ ] is invalid.", e.getMessage()); throw e; } finally { verify(mockRegionFactory, never()).setDataPolicy(null); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.NORMAL)); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.PERSISTENT_REPLICATE)); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.PRELOADED)); } }
@Test(expected = IllegalArgumentException.class) public void testResolveDataPolicyWithEmptyDataPolicy() { RegionFactory mockRegionFactory = createMockRegionFactory(); try { factoryBean.resolveDataPolicy(mockRegionFactory, null, ""); } catch (IllegalArgumentException e) { assertEquals("Data Policy [] is invalid.", e.getMessage()); throw e; } finally { verify(mockRegionFactory, never()).setDataPolicy(null); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.NORMAL)); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.PERSISTENT_REPLICATE)); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.PRELOADED)); } }
@Test(expected = IllegalArgumentException.class) public void testResolveDataPolicyWithInvalidDataPolicyName() { RegionFactory mockRegionFactory = createMockRegionFactory(); try { factoryBean.resolveDataPolicy(mockRegionFactory, null, "INVALID_DATA_POLICY_NAME"); } catch (IllegalArgumentException e) { assertEquals("Data Policy [INVALID_DATA_POLICY_NAME] is invalid.", e.getMessage()); throw e; } finally { verify(mockRegionFactory, never()).setDataPolicy(null); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.PARTITION)); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.PERSISTENT_PARTITION)); } }
@Test(expected = IllegalArgumentException.class) public void testResolveDataPolicyWithInvalidDataPolicyType() { RegionFactory mockRegionFactory = createMockRegionFactory(); try { factoryBean.resolveDataPolicy(mockRegionFactory, null, "REPLICATE"); } catch (IllegalArgumentException e) { assertEquals("Data Policy [REPLICATE] is not supported in Partitioned Regions.", e.getMessage()); throw e; } finally { verify(mockRegionFactory, never()).setDataPolicy(null); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.REPLICATE)); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.PARTITION)); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.PERSISTENT_PARTITION)); } } |
ReplicatedRegionFactoryBean extends PeerRegionFactoryBean<K, V> { @Override protected void resolveDataPolicy(RegionFactory<K, V> regionFactory, Boolean persistent, DataPolicy dataPolicy) { if (dataPolicy == null) { dataPolicy = isPersistent() ? DataPolicy.PERSISTENT_REPLICATE : DataPolicy.REPLICATE; } else if (DataPolicy.EMPTY.equals(dataPolicy)) { dataPolicy = DataPolicy.EMPTY; } else { Assert.isTrue(dataPolicy.withReplication(), String.format( "Data Policy [%s] is not supported in Replicated Regions.", dataPolicy)); } RegionUtils.assertDataPolicyAndPersistentAttributeAreCompatible(dataPolicy, persistent); regionFactory.setDataPolicy(dataPolicy); setDataPolicy(dataPolicy); } } | @Test public void testResolveDataPolicyWithPersistentUnspecifiedAndDataPolicyUnspecified() { RegionFactory mockRegionFactory = createMockRegionFactory(); factoryBean.resolveDataPolicy(mockRegionFactory, null, (String) null); verify(mockRegionFactory).setDataPolicy(eq(DataPolicy.REPLICATE)); }
@Test public void testResolveDataPolicyWhenNotPersistentAndDataPolicyUnspecified() { RegionFactory mockRegionFactory = createMockRegionFactory(); factoryBean.setPersistent(false); factoryBean.resolveDataPolicy(mockRegionFactory, false, (String) null); verify(mockRegionFactory).setDataPolicy(eq(DataPolicy.REPLICATE)); }
@Test public void testResolveDataPolicyWhenPersistentAndDataPolicyUnspecified() { RegionFactory mockRegionFactory = createMockRegionFactory(); factoryBean.setPersistent(true); factoryBean.resolveDataPolicy(mockRegionFactory, true, (String) null); verify(mockRegionFactory).setDataPolicy(eq(DataPolicy.PERSISTENT_REPLICATE)); }
@Test(expected = IllegalArgumentException.class) public void testResolveDataPolicyWithBlankDataPolicy() { RegionFactory mockRegionFactory = createMockRegionFactory(); try { factoryBean.resolveDataPolicy(mockRegionFactory, null, " "); } catch (IllegalArgumentException e) { assertEquals("Data Policy [ ] is invalid.", e.getMessage()); throw e; } finally { verify(mockRegionFactory, never()).setDataPolicy(null); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.NORMAL)); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.PERSISTENT_REPLICATE)); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.PRELOADED)); } }
@Test(expected = IllegalArgumentException.class) public void testResolveDataPolicyWithEmptyDataPolicy() { RegionFactory mockRegionFactory = createMockRegionFactory(); try { factoryBean.resolveDataPolicy(mockRegionFactory, null, ""); } catch (IllegalArgumentException e) { assertEquals("Data Policy [] is invalid.", e.getMessage()); throw e; } finally { verify(mockRegionFactory, never()).setDataPolicy(null); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.NORMAL)); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.PERSISTENT_REPLICATE)); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.PRELOADED)); } }
@Test(expected = IllegalArgumentException.class) public void testResolveDataPolicyWhenPersistentUnspecifiedAndInvalidDataPolicyName() { RegionFactory mockRegionFactory = createMockRegionFactory(); try { factoryBean.resolveDataPolicy(mockRegionFactory, null, "INVALID_DATA_POLICY_NAME"); } catch (IllegalArgumentException e) { assertEquals("Data Policy [INVALID_DATA_POLICY_NAME] is invalid.", e.getMessage()); throw e; } finally { verify(mockRegionFactory, never()).setDataPolicy(null); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.EMPTY)); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.REPLICATE)); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.PERSISTENT_REPLICATE)); } }
@Test(expected = IllegalArgumentException.class) public void testResolveDataPolicyWhenPersistentUnspecifiedAndInvalidDataPolicyType() { RegionFactory mockRegionFactory = createMockRegionFactory(); try { factoryBean.resolveDataPolicy(mockRegionFactory, null, "PARTITION"); } catch (IllegalArgumentException e) { assertEquals("Data Policy [PARTITION] is not supported in Replicated Regions.", e.getMessage()); throw e; } finally { verify(mockRegionFactory, never()).setDataPolicy(null); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.PARTITION)); } }
@Test public void testResolveDataPolicyWhenPersistentUnspecifiedAndEmptyDataPolicy() { RegionFactory mockRegionFactory = createMockRegionFactory(); factoryBean.resolveDataPolicy(mockRegionFactory, null, "EMPTY"); verify(mockRegionFactory).setDataPolicy(eq(DataPolicy.EMPTY)); }
@Test public void testResolveDataPolicyWhenNotPersistentAndEmptyDataPolicy() { RegionFactory mockRegionFactory = createMockRegionFactory(); factoryBean.setPersistent(false); factoryBean.resolveDataPolicy(mockRegionFactory, false, "empty"); verify(mockRegionFactory).setDataPolicy(eq(DataPolicy.EMPTY)); }
@Test(expected = IllegalArgumentException.class) public void testResolveDataPolicyWhenPersistentAndEmptyDataPolicy() { RegionFactory mockRegionFactory = createMockRegionFactory(); try { factoryBean.setPersistent(true); factoryBean.resolveDataPolicy(mockRegionFactory, true, "empty"); } catch (IllegalArgumentException e) { assertEquals("Data Policy [EMPTY] is not valid when persistent is true", e.getMessage()); throw e; } finally { verify(mockRegionFactory, never()).setDataPolicy(null); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.EMPTY)); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.PERSISTENT_REPLICATE)); } }
@Test public void testResolveDataPolicyWhenPersistentUnspecifiedAndReplicateDataPolicy() { RegionFactory mockRegionFactory = createMockRegionFactory(); factoryBean.resolveDataPolicy(mockRegionFactory, null, "REPLICATE"); verify(mockRegionFactory).setDataPolicy(eq(DataPolicy.REPLICATE)); }
@Test public void testResolveDataPolicyWhenNotPersistentAndReplicateDataPolicy() { RegionFactory mockRegionFactory = createMockRegionFactory(); factoryBean.setPersistent(false); factoryBean.resolveDataPolicy(mockRegionFactory, false, "REPLICATE"); verify(mockRegionFactory).setDataPolicy(eq(DataPolicy.REPLICATE)); }
@Test(expected = IllegalArgumentException.class) public void testResolveDataPolicyWhenPersistentAndReplicateDataPolicy() { RegionFactory mockRegionFactory = createMockRegionFactory(); try { factoryBean.setPersistent(true); factoryBean.resolveDataPolicy(mockRegionFactory, true, "REPLICATE"); } catch (IllegalArgumentException e) { assertEquals("Data Policy [REPLICATE] is not valid when persistent is true", e.getMessage()); throw e; } finally { verify(mockRegionFactory, never()).setDataPolicy(null); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.REPLICATE)); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.PERSISTENT_REPLICATE)); } }
@Test public void testResolveDataPolicyWhenPersistentUnspecifiedAndPersistentReplicateDataPolicy() { RegionFactory mockRegionFactory = createMockRegionFactory(); factoryBean.resolveDataPolicy(mockRegionFactory, null, "PERSISTENT_REPLICATE"); verify(mockRegionFactory).setDataPolicy(eq(DataPolicy.PERSISTENT_REPLICATE)); }
@Test(expected = IllegalArgumentException.class) public void testResolveDataPolicyWhenNotPersistentAndPersistentReplicateDataPolicy() { RegionFactory mockRegionFactory = createMockRegionFactory(); try { factoryBean.setPersistent(false); factoryBean.resolveDataPolicy(mockRegionFactory, false, "PERSISTENT_REPLICATE"); } catch (IllegalArgumentException e) { assertEquals("Data Policy [PERSISTENT_REPLICATE] is not valid when persistent is false", e.getMessage()); throw e; } finally { verify(mockRegionFactory, never()).setDataPolicy(null); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.REPLICATE)); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.PERSISTENT_REPLICATE)); } }
@Test public void testResolveDataPolicyWhenPersistentAndPersistentReplicateDataPolicy() { RegionFactory mockRegionFactory = createMockRegionFactory(); factoryBean.setPersistent(true); factoryBean.resolveDataPolicy(mockRegionFactory, true, "PERSISTENT_REPLICATE"); verify(mockRegionFactory).setDataPolicy(eq(DataPolicy.PERSISTENT_REPLICATE)); } |
AnnotationBasedExpiration implements BeanFactoryAware, CustomExpiry<K, V> { protected Expiration getExpiration(Region.Entry<K, V> entry) { return getExpiration(entry.getValue()); } AnnotationBasedExpiration(); AnnotationBasedExpiration(ExpirationAttributes defaultExpirationAttributes); static AnnotationBasedExpiration<K, V> forIdleTimeout(); static AnnotationBasedExpiration<K, V> forIdleTimeout(ExpirationAttributes defaultExpirationAttributes); static AnnotationBasedExpiration<K, V> forTimeToLive(); static AnnotationBasedExpiration<K, V> forTimeToLive(ExpirationAttributes defaultExpirationAttributes); @Override void setBeanFactory(BeanFactory beanFactory); void setDefaultExpirationAttributes(ExpirationAttributes defaultExpirationAttributes); @Override ExpirationAttributes getExpiry(Region.Entry<K, V> entry); @Override void close(); } | @Test public void getExpirationWithNoGenericExpirationRegionEntry() { Region.Entry mockRegionEntry = mock(Region.Entry.class, "MockRegionEntry"); when(mockRegionEntry.getValue()).thenReturn(new RegionEntryValueWithTimeToLiveIdleTimeoutExpiration()); assertThat(noDefaultExpiration.getExpiration(mockRegionEntry), is(nullValue())); when(mockRegionEntry.getValue()).thenReturn(new RegionEntryValueWithNoExpiration()); assertThat(noDefaultExpiration.getExpiration(mockRegionEntry), is(nullValue())); verify(mockRegionEntry, times(2)).getValue(); }
@Test public void getExpirationWithGenericExpirationBasedRegionEntry() { Region.Entry mockRegionEntry = mock(Region.Entry.class, "MockRegionEntry"); when(mockRegionEntry.getValue()).thenReturn(new RegionEntryValueWithGenericExpiration()); assertThat(noDefaultExpiration.getExpiration(mockRegionEntry), isA(Expiration.class)); when(mockRegionEntry.getValue()).thenReturn(new RegionEntryValueWithTimeToLiveIdleTimeoutGenericExpiration()); assertThat(noDefaultExpiration.getExpiration(mockRegionEntry), isA(Expiration.class)); verify(mockRegionEntry, times(2)).getValue(); } |
AnnotationBasedExpiration implements BeanFactoryAware, CustomExpiry<K, V> { protected IdleTimeoutExpiration getIdleTimeout(Region.Entry<K, V> entry) { return getIdleTimeout(entry.getValue()); } AnnotationBasedExpiration(); AnnotationBasedExpiration(ExpirationAttributes defaultExpirationAttributes); static AnnotationBasedExpiration<K, V> forIdleTimeout(); static AnnotationBasedExpiration<K, V> forIdleTimeout(ExpirationAttributes defaultExpirationAttributes); static AnnotationBasedExpiration<K, V> forTimeToLive(); static AnnotationBasedExpiration<K, V> forTimeToLive(ExpirationAttributes defaultExpirationAttributes); @Override void setBeanFactory(BeanFactory beanFactory); void setDefaultExpirationAttributes(ExpirationAttributes defaultExpirationAttributes); @Override ExpirationAttributes getExpiry(Region.Entry<K, V> entry); @Override void close(); } | @Test public void getIdleTimeoutWithIdleTimeoutExpirationBasedRegionEntry() { Region.Entry mockRegionEntry = mock(Region.Entry.class, "MockRegionEntry"); when(mockRegionEntry.getValue()).thenReturn(new RegionEntryValueWithIdleTimeoutExpiration()); assertThat(noDefaultExpiration.getIdleTimeout(mockRegionEntry), isA(IdleTimeoutExpiration.class)); when(mockRegionEntry.getValue()).thenReturn(new RegionEntryValueWithTimeToLiveIdleTimeoutGenericExpiration()); assertThat(noDefaultExpiration.getIdleTimeout(mockRegionEntry), isA(IdleTimeoutExpiration.class)); verify(mockRegionEntry, times(2)).getValue(); }
@Test public void getIdleTimeoutWithNoIdleTimeoutExpirationRegionEntry() { Region.Entry mockRegionEntry = mock(Region.Entry.class, "MockRegionEntry"); when(mockRegionEntry.getValue()).thenReturn(new RegionEntryValueWithTimeToLiveGenericExpiration()); assertThat(noDefaultExpiration.getIdleTimeout(mockRegionEntry), is(nullValue())); when(mockRegionEntry.getValue()).thenReturn(new RegionEntryValueWithNoExpiration()); assertThat(noDefaultExpiration.getIdleTimeout(mockRegionEntry), is(nullValue())); verify(mockRegionEntry, times(2)).getValue(); } |
RegionShortcutConverter implements Converter<String, RegionShortcut> { protected static String toUpperCase(final String value) { return (value != null ? value.toUpperCase().trim() : String.valueOf(value)); } @Override RegionShortcut convert(final String source); } | @Test public void testToUpperCase() { assertEquals("TEST", RegionShortcutConverter.toUpperCase("test")); assertEquals("TEST", RegionShortcutConverter.toUpperCase(" Test ")); assertEquals("", RegionShortcutConverter.toUpperCase("")); assertEquals("", RegionShortcutConverter.toUpperCase(" ")); assertEquals("NULL", RegionShortcutConverter.toUpperCase("null")); assertEquals("null", RegionShortcutConverter.toUpperCase(null)); } |
RegionShortcutConverter implements Converter<String, RegionShortcut> { @Override public RegionShortcut convert(final String source) { return RegionShortcut.valueOf(toUpperCase(source)); } @Override RegionShortcut convert(final String source); } | @Test public void testConvert() { for (RegionShortcut shortcut : RegionShortcut.values()) { assertEquals(shortcut, converter.convert(shortcut.name())); } assertEquals(RegionShortcut.PARTITION_PROXY, converter.convert("Partition_Proxy")); assertEquals(RegionShortcut.REPLICATE_OVERFLOW, converter.convert("replicate_overflow")); assertEquals(RegionShortcut.LOCAL_HEAP_LRU, converter.convert("local_Heap_LRU")); }
@Test(expected = IllegalArgumentException.class) public void testConvertWithIllegalEnumeratedValue() { converter.convert("localPersistentOverflow"); } |
ClientCacheFactoryBean extends CacheFactoryBean implements ApplicationListener<ContextRefreshedEvent> { @Override @SuppressWarnings({ "rawtypes", "unchecked" }) public Class<? extends GemFireCache> getObjectType() { return Optional.ofNullable(getCache()).map(Object::getClass).orElse((Class) ClientCache.class); } @Override void onApplicationEvent(ContextRefreshedEvent event); @Override @SuppressWarnings({ "rawtypes", "unchecked" }) Class<? extends GemFireCache> getObjectType(); void addLocators(ConnectionEndpoint... locators); void addLocators(Iterable<ConnectionEndpoint> locators); void addServers(ConnectionEndpoint... servers); void addServers(Iterable<ConnectionEndpoint> servers); void setClientCacheConfigurers(ClientCacheConfigurer... clientCacheConfigurers); void setClientCacheConfigurers(List<ClientCacheConfigurer> peerCacheConfigurers); ClientCacheConfigurer getCompositeClientCacheConfigurer(); void setDurableClientId(String durableClientId); String getDurableClientId(); void setDurableClientTimeout(Integer durableClientTimeout); Integer getDurableClientTimeout(); @Override final void setEnableAutoReconnect(Boolean enableAutoReconnect); @Override final Boolean getEnableAutoReconnect(); void setFreeConnectionTimeout(Integer freeConnectionTimeout); Integer getFreeConnectionTimeout(); void setIdleTimeout(Long idleTimeout); Long getIdleTimeout(); void setKeepAlive(Boolean keepAlive); Boolean getKeepAlive(); boolean isKeepAlive(); void setLoadConditioningInterval(Integer loadConditioningInterval); Integer getLoadConditioningInterval(); void setLocators(ConnectionEndpoint[] locators); void setLocators(Iterable<ConnectionEndpoint> locators); void setMaxConnections(Integer maxConnections); Integer getMaxConnections(); void setMinConnections(Integer minConnections); Integer getMinConnections(); void setMultiUserAuthentication(Boolean multiUserAuthentication); Boolean getMultiUserAuthentication(); void setPool(@Nullable Pool pool); @Nullable Pool getPool(); void setPoolName(@Nullable String poolName); @Nullable String getPoolName(); void setPoolResolver(@Nullable PoolResolver poolResolver); @NonNull PoolResolver getPoolResolver(); void setPingInterval(Long pingInterval); Long getPingInterval(); void setPrSingleHopEnabled(Boolean prSingleHopEnabled); Boolean getPrSingleHopEnabled(); void setReadTimeout(Integer readTimeout); Integer getReadTimeout(); void setReadyForEvents(Boolean readyForEvents); Boolean getReadyForEvents(); boolean isReadyForEvents(); void setRetryAttempts(Integer retryAttempts); Integer getRetryAttempts(); void setServerConnectionTimeout(Integer serverConnectionTimeout); Integer getServerConnectionTimeout(); void setServerGroup(String serverGroup); String getServerGroup(); void setServers(ConnectionEndpoint[] servers); void setServers(Iterable<ConnectionEndpoint> servers); void setSocketBufferSize(Integer socketBufferSize); Integer getSocketBufferSize(); void setSocketConnectTimeout(Integer socketConnectTimeout); Integer getSocketConnectTimeout(); void setSocketFactory(@Nullable SocketFactory socketFactory); @NonNull SocketFactory getSocketFactory(); void setStatisticsInterval(Integer statisticsInterval); Integer getStatisticsInterval(); void setSubscriptionAckInterval(Integer subscriptionAckInterval); Integer getSubscriptionAckInterval(); void setSubscriptionEnabled(Boolean subscriptionEnabled); Boolean getSubscriptionEnabled(); void setSubscriptionMessageTrackingTimeout(Integer subscriptionMessageTrackingTimeout); Integer getSubscriptionMessageTrackingTimeout(); void setSubscriptionRedundancy(Integer subscriptionRedundancy); Integer getSubscriptionRedundancy(); void setThreadLocalConnections(Boolean threadLocalConnections); Boolean getThreadLocalConnections(); @Override final void setUseClusterConfiguration(Boolean useClusterConfiguration); @Override final Boolean getUseClusterConfiguration(); } | @Test public void getObjectTypeEqualsClientCacheClass() { assertThat(new ClientCacheFactoryBean().getObjectType()).isEqualTo(ClientCache.class); } |
ClientCacheFactoryBean extends CacheFactoryBean implements ApplicationListener<ContextRefreshedEvent> { @Override protected Object createFactory(Properties gemfireProperties) { return new ClientCacheFactory(gemfireProperties); } @Override void onApplicationEvent(ContextRefreshedEvent event); @Override @SuppressWarnings({ "rawtypes", "unchecked" }) Class<? extends GemFireCache> getObjectType(); void addLocators(ConnectionEndpoint... locators); void addLocators(Iterable<ConnectionEndpoint> locators); void addServers(ConnectionEndpoint... servers); void addServers(Iterable<ConnectionEndpoint> servers); void setClientCacheConfigurers(ClientCacheConfigurer... clientCacheConfigurers); void setClientCacheConfigurers(List<ClientCacheConfigurer> peerCacheConfigurers); ClientCacheConfigurer getCompositeClientCacheConfigurer(); void setDurableClientId(String durableClientId); String getDurableClientId(); void setDurableClientTimeout(Integer durableClientTimeout); Integer getDurableClientTimeout(); @Override final void setEnableAutoReconnect(Boolean enableAutoReconnect); @Override final Boolean getEnableAutoReconnect(); void setFreeConnectionTimeout(Integer freeConnectionTimeout); Integer getFreeConnectionTimeout(); void setIdleTimeout(Long idleTimeout); Long getIdleTimeout(); void setKeepAlive(Boolean keepAlive); Boolean getKeepAlive(); boolean isKeepAlive(); void setLoadConditioningInterval(Integer loadConditioningInterval); Integer getLoadConditioningInterval(); void setLocators(ConnectionEndpoint[] locators); void setLocators(Iterable<ConnectionEndpoint> locators); void setMaxConnections(Integer maxConnections); Integer getMaxConnections(); void setMinConnections(Integer minConnections); Integer getMinConnections(); void setMultiUserAuthentication(Boolean multiUserAuthentication); Boolean getMultiUserAuthentication(); void setPool(@Nullable Pool pool); @Nullable Pool getPool(); void setPoolName(@Nullable String poolName); @Nullable String getPoolName(); void setPoolResolver(@Nullable PoolResolver poolResolver); @NonNull PoolResolver getPoolResolver(); void setPingInterval(Long pingInterval); Long getPingInterval(); void setPrSingleHopEnabled(Boolean prSingleHopEnabled); Boolean getPrSingleHopEnabled(); void setReadTimeout(Integer readTimeout); Integer getReadTimeout(); void setReadyForEvents(Boolean readyForEvents); Boolean getReadyForEvents(); boolean isReadyForEvents(); void setRetryAttempts(Integer retryAttempts); Integer getRetryAttempts(); void setServerConnectionTimeout(Integer serverConnectionTimeout); Integer getServerConnectionTimeout(); void setServerGroup(String serverGroup); String getServerGroup(); void setServers(ConnectionEndpoint[] servers); void setServers(Iterable<ConnectionEndpoint> servers); void setSocketBufferSize(Integer socketBufferSize); Integer getSocketBufferSize(); void setSocketConnectTimeout(Integer socketConnectTimeout); Integer getSocketConnectTimeout(); void setSocketFactory(@Nullable SocketFactory socketFactory); @NonNull SocketFactory getSocketFactory(); void setStatisticsInterval(Integer statisticsInterval); Integer getStatisticsInterval(); void setSubscriptionAckInterval(Integer subscriptionAckInterval); Integer getSubscriptionAckInterval(); void setSubscriptionEnabled(Boolean subscriptionEnabled); Boolean getSubscriptionEnabled(); void setSubscriptionMessageTrackingTimeout(Integer subscriptionMessageTrackingTimeout); Integer getSubscriptionMessageTrackingTimeout(); void setSubscriptionRedundancy(Integer subscriptionRedundancy); Integer getSubscriptionRedundancy(); void setThreadLocalConnections(Boolean threadLocalConnections); Boolean getThreadLocalConnections(); @Override final void setUseClusterConfiguration(Boolean useClusterConfiguration); @Override final Boolean getUseClusterConfiguration(); } | @Test public void createClientCacheFactory() { Properties gemfireProperties = new Properties(); Object clientCacheFactoryReference = new ClientCacheFactoryBean().createFactory(gemfireProperties); assertThat(clientCacheFactoryReference).isInstanceOf(ClientCacheFactory.class); assertThat(gemfireProperties.isEmpty()).isTrue(); ClientCacheFactory clientCacheFactory = (ClientCacheFactory) clientCacheFactoryReference; clientCacheFactory.set("testCase", "TestCreateClientCacheFactory"); assertThat(gemfireProperties.containsKey("testCase")).isTrue(); assertThat(gemfireProperties.getProperty("testCase")).isEqualTo("TestCreateClientCacheFactory"); } |
ClientCacheFactoryBean extends CacheFactoryBean implements ApplicationListener<ContextRefreshedEvent> { ClientCacheFactory configurePdx(ClientCacheFactory clientCacheFactory) { Optional.ofNullable(getPdxSerializer()).ifPresent(clientCacheFactory::setPdxSerializer); Optional.ofNullable(getPdxDiskStoreName()).filter(StringUtils::hasText) .ifPresent(clientCacheFactory::setPdxDiskStore); Optional.ofNullable(getPdxIgnoreUnreadFields()).ifPresent(clientCacheFactory::setPdxIgnoreUnreadFields); Optional.ofNullable(getPdxPersistent()).ifPresent(clientCacheFactory::setPdxPersistent); Optional.ofNullable(getPdxReadSerialized()).ifPresent(clientCacheFactory::setPdxReadSerialized); return clientCacheFactory; } @Override void onApplicationEvent(ContextRefreshedEvent event); @Override @SuppressWarnings({ "rawtypes", "unchecked" }) Class<? extends GemFireCache> getObjectType(); void addLocators(ConnectionEndpoint... locators); void addLocators(Iterable<ConnectionEndpoint> locators); void addServers(ConnectionEndpoint... servers); void addServers(Iterable<ConnectionEndpoint> servers); void setClientCacheConfigurers(ClientCacheConfigurer... clientCacheConfigurers); void setClientCacheConfigurers(List<ClientCacheConfigurer> peerCacheConfigurers); ClientCacheConfigurer getCompositeClientCacheConfigurer(); void setDurableClientId(String durableClientId); String getDurableClientId(); void setDurableClientTimeout(Integer durableClientTimeout); Integer getDurableClientTimeout(); @Override final void setEnableAutoReconnect(Boolean enableAutoReconnect); @Override final Boolean getEnableAutoReconnect(); void setFreeConnectionTimeout(Integer freeConnectionTimeout); Integer getFreeConnectionTimeout(); void setIdleTimeout(Long idleTimeout); Long getIdleTimeout(); void setKeepAlive(Boolean keepAlive); Boolean getKeepAlive(); boolean isKeepAlive(); void setLoadConditioningInterval(Integer loadConditioningInterval); Integer getLoadConditioningInterval(); void setLocators(ConnectionEndpoint[] locators); void setLocators(Iterable<ConnectionEndpoint> locators); void setMaxConnections(Integer maxConnections); Integer getMaxConnections(); void setMinConnections(Integer minConnections); Integer getMinConnections(); void setMultiUserAuthentication(Boolean multiUserAuthentication); Boolean getMultiUserAuthentication(); void setPool(@Nullable Pool pool); @Nullable Pool getPool(); void setPoolName(@Nullable String poolName); @Nullable String getPoolName(); void setPoolResolver(@Nullable PoolResolver poolResolver); @NonNull PoolResolver getPoolResolver(); void setPingInterval(Long pingInterval); Long getPingInterval(); void setPrSingleHopEnabled(Boolean prSingleHopEnabled); Boolean getPrSingleHopEnabled(); void setReadTimeout(Integer readTimeout); Integer getReadTimeout(); void setReadyForEvents(Boolean readyForEvents); Boolean getReadyForEvents(); boolean isReadyForEvents(); void setRetryAttempts(Integer retryAttempts); Integer getRetryAttempts(); void setServerConnectionTimeout(Integer serverConnectionTimeout); Integer getServerConnectionTimeout(); void setServerGroup(String serverGroup); String getServerGroup(); void setServers(ConnectionEndpoint[] servers); void setServers(Iterable<ConnectionEndpoint> servers); void setSocketBufferSize(Integer socketBufferSize); Integer getSocketBufferSize(); void setSocketConnectTimeout(Integer socketConnectTimeout); Integer getSocketConnectTimeout(); void setSocketFactory(@Nullable SocketFactory socketFactory); @NonNull SocketFactory getSocketFactory(); void setStatisticsInterval(Integer statisticsInterval); Integer getStatisticsInterval(); void setSubscriptionAckInterval(Integer subscriptionAckInterval); Integer getSubscriptionAckInterval(); void setSubscriptionEnabled(Boolean subscriptionEnabled); Boolean getSubscriptionEnabled(); void setSubscriptionMessageTrackingTimeout(Integer subscriptionMessageTrackingTimeout); Integer getSubscriptionMessageTrackingTimeout(); void setSubscriptionRedundancy(Integer subscriptionRedundancy); Integer getSubscriptionRedundancy(); void setThreadLocalConnections(Boolean threadLocalConnections); Boolean getThreadLocalConnections(); @Override final void setUseClusterConfiguration(Boolean useClusterConfiguration); @Override final Boolean getUseClusterConfiguration(); } | @Test public void initializePdxWithAllPdxOptions() { ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean(); PdxSerializer mockPdxSerializer = mock(PdxSerializer.class); clientCacheFactoryBean.setPdxDiskStoreName("MockPdxDiskStoreName"); clientCacheFactoryBean.setPdxIgnoreUnreadFields(false); clientCacheFactoryBean.setPdxPersistent(true); clientCacheFactoryBean.setPdxReadSerialized(false); clientCacheFactoryBean.setPdxSerializer(mockPdxSerializer); assertThat(clientCacheFactoryBean.getPdxDiskStoreName()).isEqualTo("MockPdxDiskStoreName"); assertThat(clientCacheFactoryBean.getPdxIgnoreUnreadFields()).isFalse(); assertThat(clientCacheFactoryBean.getPdxPersistent()).isTrue(); assertThat(clientCacheFactoryBean.getPdxReadSerialized()).isFalse(); assertThat(clientCacheFactoryBean.getPdxSerializer()).isSameAs(mockPdxSerializer); ClientCacheFactory mockClientCacheFactory = mock(ClientCacheFactory.class); assertThat(clientCacheFactoryBean.configurePdx(mockClientCacheFactory)).isSameAs(mockClientCacheFactory); verify(mockClientCacheFactory, times(1)).setPdxSerializer(eq(mockPdxSerializer)); verify(mockClientCacheFactory, times(1)).setPdxDiskStore(eq("MockPdxDiskStoreName")); verify(mockClientCacheFactory, times(1)).setPdxIgnoreUnreadFields(eq(false)); verify(mockClientCacheFactory, times(1)).setPdxPersistent(eq(true)); verify(mockClientCacheFactory, times(1)).setPdxReadSerialized(eq(false)); }
@Test public void initializePdxWithPartialPdxOptions() { ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean(); clientCacheFactoryBean.setPdxReadSerialized(true); clientCacheFactoryBean.setPdxIgnoreUnreadFields(true); assertThat(clientCacheFactoryBean.getPdxDiskStoreName()).isNull(); assertThat(clientCacheFactoryBean.getPdxIgnoreUnreadFields()).isTrue(); assertThat(clientCacheFactoryBean.getPdxPersistent()).isNull(); assertThat(clientCacheFactoryBean.getPdxReadSerialized()).isTrue(); assertThat(clientCacheFactoryBean.getPdxSerializer()).isNull(); ClientCacheFactory mockClientCacheFactory = mock(ClientCacheFactory.class); assertThat(clientCacheFactoryBean.configurePdx(mockClientCacheFactory)).isSameAs(mockClientCacheFactory); verify(mockClientCacheFactory, never()).setPdxDiskStore(anyString()); verify(mockClientCacheFactory, times(1)).setPdxIgnoreUnreadFields(eq(true)); verify(mockClientCacheFactory, never()).setPdxPersistent(anyBoolean()); verify(mockClientCacheFactory, times(1)).setPdxReadSerialized(eq(true)); verify(mockClientCacheFactory, never()).setPdxSerializer(any(PdxSerializer.class)); }
@Test public void initializePdxWithNoPdxOptions() { ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean(); assertThat(clientCacheFactoryBean.getPdxDiskStoreName()).isNull(); assertThat(clientCacheFactoryBean.getPdxIgnoreUnreadFields()).isNull(); assertThat(clientCacheFactoryBean.getPdxPersistent()).isNull(); assertThat(clientCacheFactoryBean.getPdxReadSerialized()).isNull(); assertThat(clientCacheFactoryBean.getPdxSerializer()).isNull(); ClientCacheFactory mockClientCacheFactory = mock(ClientCacheFactory.class); assertThat(clientCacheFactoryBean.configurePdx(mockClientCacheFactory)).isSameAs(mockClientCacheFactory); verifyNoInteractions(mockClientCacheFactory); } |
ClientCacheFactoryBean extends CacheFactoryBean implements ApplicationListener<ContextRefreshedEvent> { @Override @SuppressWarnings("unchecked") protected <T extends GemFireCache> T createCache(Object factory) { return (T) ((ClientCacheFactory) factory).create(); } @Override void onApplicationEvent(ContextRefreshedEvent event); @Override @SuppressWarnings({ "rawtypes", "unchecked" }) Class<? extends GemFireCache> getObjectType(); void addLocators(ConnectionEndpoint... locators); void addLocators(Iterable<ConnectionEndpoint> locators); void addServers(ConnectionEndpoint... servers); void addServers(Iterable<ConnectionEndpoint> servers); void setClientCacheConfigurers(ClientCacheConfigurer... clientCacheConfigurers); void setClientCacheConfigurers(List<ClientCacheConfigurer> peerCacheConfigurers); ClientCacheConfigurer getCompositeClientCacheConfigurer(); void setDurableClientId(String durableClientId); String getDurableClientId(); void setDurableClientTimeout(Integer durableClientTimeout); Integer getDurableClientTimeout(); @Override final void setEnableAutoReconnect(Boolean enableAutoReconnect); @Override final Boolean getEnableAutoReconnect(); void setFreeConnectionTimeout(Integer freeConnectionTimeout); Integer getFreeConnectionTimeout(); void setIdleTimeout(Long idleTimeout); Long getIdleTimeout(); void setKeepAlive(Boolean keepAlive); Boolean getKeepAlive(); boolean isKeepAlive(); void setLoadConditioningInterval(Integer loadConditioningInterval); Integer getLoadConditioningInterval(); void setLocators(ConnectionEndpoint[] locators); void setLocators(Iterable<ConnectionEndpoint> locators); void setMaxConnections(Integer maxConnections); Integer getMaxConnections(); void setMinConnections(Integer minConnections); Integer getMinConnections(); void setMultiUserAuthentication(Boolean multiUserAuthentication); Boolean getMultiUserAuthentication(); void setPool(@Nullable Pool pool); @Nullable Pool getPool(); void setPoolName(@Nullable String poolName); @Nullable String getPoolName(); void setPoolResolver(@Nullable PoolResolver poolResolver); @NonNull PoolResolver getPoolResolver(); void setPingInterval(Long pingInterval); Long getPingInterval(); void setPrSingleHopEnabled(Boolean prSingleHopEnabled); Boolean getPrSingleHopEnabled(); void setReadTimeout(Integer readTimeout); Integer getReadTimeout(); void setReadyForEvents(Boolean readyForEvents); Boolean getReadyForEvents(); boolean isReadyForEvents(); void setRetryAttempts(Integer retryAttempts); Integer getRetryAttempts(); void setServerConnectionTimeout(Integer serverConnectionTimeout); Integer getServerConnectionTimeout(); void setServerGroup(String serverGroup); String getServerGroup(); void setServers(ConnectionEndpoint[] servers); void setServers(Iterable<ConnectionEndpoint> servers); void setSocketBufferSize(Integer socketBufferSize); Integer getSocketBufferSize(); void setSocketConnectTimeout(Integer socketConnectTimeout); Integer getSocketConnectTimeout(); void setSocketFactory(@Nullable SocketFactory socketFactory); @NonNull SocketFactory getSocketFactory(); void setStatisticsInterval(Integer statisticsInterval); Integer getStatisticsInterval(); void setSubscriptionAckInterval(Integer subscriptionAckInterval); Integer getSubscriptionAckInterval(); void setSubscriptionEnabled(Boolean subscriptionEnabled); Boolean getSubscriptionEnabled(); void setSubscriptionMessageTrackingTimeout(Integer subscriptionMessageTrackingTimeout); Integer getSubscriptionMessageTrackingTimeout(); void setSubscriptionRedundancy(Integer subscriptionRedundancy); Integer getSubscriptionRedundancy(); void setThreadLocalConnections(Boolean threadLocalConnections); Boolean getThreadLocalConnections(); @Override final void setUseClusterConfiguration(Boolean useClusterConfiguration); @Override final Boolean getUseClusterConfiguration(); } | @Test public void createCache() { ClientCache mockClientCache = mock(ClientCache.class); ClientCacheFactory mockClientCacheFactory = mock(ClientCacheFactory.class); when(mockClientCacheFactory.create()).thenReturn(mockClientCache); ClientCacheFactoryBean clientCacheFactoryBean = new ClientCacheFactoryBean(); assertThat(clientCacheFactoryBean.<GemFireCache>createCache(mockClientCacheFactory)).isSameAs(mockClientCache); verify(mockClientCacheFactory, times(1)).create(); verifyNoInteractions(mockClientCache); } |
ClientCacheFactoryBean extends CacheFactoryBean implements ApplicationListener<ContextRefreshedEvent> { @Override public final Boolean getEnableAutoReconnect() { return Boolean.FALSE; } @Override void onApplicationEvent(ContextRefreshedEvent event); @Override @SuppressWarnings({ "rawtypes", "unchecked" }) Class<? extends GemFireCache> getObjectType(); void addLocators(ConnectionEndpoint... locators); void addLocators(Iterable<ConnectionEndpoint> locators); void addServers(ConnectionEndpoint... servers); void addServers(Iterable<ConnectionEndpoint> servers); void setClientCacheConfigurers(ClientCacheConfigurer... clientCacheConfigurers); void setClientCacheConfigurers(List<ClientCacheConfigurer> peerCacheConfigurers); ClientCacheConfigurer getCompositeClientCacheConfigurer(); void setDurableClientId(String durableClientId); String getDurableClientId(); void setDurableClientTimeout(Integer durableClientTimeout); Integer getDurableClientTimeout(); @Override final void setEnableAutoReconnect(Boolean enableAutoReconnect); @Override final Boolean getEnableAutoReconnect(); void setFreeConnectionTimeout(Integer freeConnectionTimeout); Integer getFreeConnectionTimeout(); void setIdleTimeout(Long idleTimeout); Long getIdleTimeout(); void setKeepAlive(Boolean keepAlive); Boolean getKeepAlive(); boolean isKeepAlive(); void setLoadConditioningInterval(Integer loadConditioningInterval); Integer getLoadConditioningInterval(); void setLocators(ConnectionEndpoint[] locators); void setLocators(Iterable<ConnectionEndpoint> locators); void setMaxConnections(Integer maxConnections); Integer getMaxConnections(); void setMinConnections(Integer minConnections); Integer getMinConnections(); void setMultiUserAuthentication(Boolean multiUserAuthentication); Boolean getMultiUserAuthentication(); void setPool(@Nullable Pool pool); @Nullable Pool getPool(); void setPoolName(@Nullable String poolName); @Nullable String getPoolName(); void setPoolResolver(@Nullable PoolResolver poolResolver); @NonNull PoolResolver getPoolResolver(); void setPingInterval(Long pingInterval); Long getPingInterval(); void setPrSingleHopEnabled(Boolean prSingleHopEnabled); Boolean getPrSingleHopEnabled(); void setReadTimeout(Integer readTimeout); Integer getReadTimeout(); void setReadyForEvents(Boolean readyForEvents); Boolean getReadyForEvents(); boolean isReadyForEvents(); void setRetryAttempts(Integer retryAttempts); Integer getRetryAttempts(); void setServerConnectionTimeout(Integer serverConnectionTimeout); Integer getServerConnectionTimeout(); void setServerGroup(String serverGroup); String getServerGroup(); void setServers(ConnectionEndpoint[] servers); void setServers(Iterable<ConnectionEndpoint> servers); void setSocketBufferSize(Integer socketBufferSize); Integer getSocketBufferSize(); void setSocketConnectTimeout(Integer socketConnectTimeout); Integer getSocketConnectTimeout(); void setSocketFactory(@Nullable SocketFactory socketFactory); @NonNull SocketFactory getSocketFactory(); void setStatisticsInterval(Integer statisticsInterval); Integer getStatisticsInterval(); void setSubscriptionAckInterval(Integer subscriptionAckInterval); Integer getSubscriptionAckInterval(); void setSubscriptionEnabled(Boolean subscriptionEnabled); Boolean getSubscriptionEnabled(); void setSubscriptionMessageTrackingTimeout(Integer subscriptionMessageTrackingTimeout); Integer getSubscriptionMessageTrackingTimeout(); void setSubscriptionRedundancy(Integer subscriptionRedundancy); Integer getSubscriptionRedundancy(); void setThreadLocalConnections(Boolean threadLocalConnections); Boolean getThreadLocalConnections(); @Override final void setUseClusterConfiguration(Boolean useClusterConfiguration); @Override final Boolean getUseClusterConfiguration(); } | @Test public void autoReconnectDisabled() { assertThat(new ClientCacheFactoryBean().getEnableAutoReconnect()).isFalse(); } |
ClientCacheFactoryBean extends CacheFactoryBean implements ApplicationListener<ContextRefreshedEvent> { @Override public final void setEnableAutoReconnect(Boolean enableAutoReconnect) { throw new UnsupportedOperationException("Auto-reconnect does not apply to clients"); } @Override void onApplicationEvent(ContextRefreshedEvent event); @Override @SuppressWarnings({ "rawtypes", "unchecked" }) Class<? extends GemFireCache> getObjectType(); void addLocators(ConnectionEndpoint... locators); void addLocators(Iterable<ConnectionEndpoint> locators); void addServers(ConnectionEndpoint... servers); void addServers(Iterable<ConnectionEndpoint> servers); void setClientCacheConfigurers(ClientCacheConfigurer... clientCacheConfigurers); void setClientCacheConfigurers(List<ClientCacheConfigurer> peerCacheConfigurers); ClientCacheConfigurer getCompositeClientCacheConfigurer(); void setDurableClientId(String durableClientId); String getDurableClientId(); void setDurableClientTimeout(Integer durableClientTimeout); Integer getDurableClientTimeout(); @Override final void setEnableAutoReconnect(Boolean enableAutoReconnect); @Override final Boolean getEnableAutoReconnect(); void setFreeConnectionTimeout(Integer freeConnectionTimeout); Integer getFreeConnectionTimeout(); void setIdleTimeout(Long idleTimeout); Long getIdleTimeout(); void setKeepAlive(Boolean keepAlive); Boolean getKeepAlive(); boolean isKeepAlive(); void setLoadConditioningInterval(Integer loadConditioningInterval); Integer getLoadConditioningInterval(); void setLocators(ConnectionEndpoint[] locators); void setLocators(Iterable<ConnectionEndpoint> locators); void setMaxConnections(Integer maxConnections); Integer getMaxConnections(); void setMinConnections(Integer minConnections); Integer getMinConnections(); void setMultiUserAuthentication(Boolean multiUserAuthentication); Boolean getMultiUserAuthentication(); void setPool(@Nullable Pool pool); @Nullable Pool getPool(); void setPoolName(@Nullable String poolName); @Nullable String getPoolName(); void setPoolResolver(@Nullable PoolResolver poolResolver); @NonNull PoolResolver getPoolResolver(); void setPingInterval(Long pingInterval); Long getPingInterval(); void setPrSingleHopEnabled(Boolean prSingleHopEnabled); Boolean getPrSingleHopEnabled(); void setReadTimeout(Integer readTimeout); Integer getReadTimeout(); void setReadyForEvents(Boolean readyForEvents); Boolean getReadyForEvents(); boolean isReadyForEvents(); void setRetryAttempts(Integer retryAttempts); Integer getRetryAttempts(); void setServerConnectionTimeout(Integer serverConnectionTimeout); Integer getServerConnectionTimeout(); void setServerGroup(String serverGroup); String getServerGroup(); void setServers(ConnectionEndpoint[] servers); void setServers(Iterable<ConnectionEndpoint> servers); void setSocketBufferSize(Integer socketBufferSize); Integer getSocketBufferSize(); void setSocketConnectTimeout(Integer socketConnectTimeout); Integer getSocketConnectTimeout(); void setSocketFactory(@Nullable SocketFactory socketFactory); @NonNull SocketFactory getSocketFactory(); void setStatisticsInterval(Integer statisticsInterval); Integer getStatisticsInterval(); void setSubscriptionAckInterval(Integer subscriptionAckInterval); Integer getSubscriptionAckInterval(); void setSubscriptionEnabled(Boolean subscriptionEnabled); Boolean getSubscriptionEnabled(); void setSubscriptionMessageTrackingTimeout(Integer subscriptionMessageTrackingTimeout); Integer getSubscriptionMessageTrackingTimeout(); void setSubscriptionRedundancy(Integer subscriptionRedundancy); Integer getSubscriptionRedundancy(); void setThreadLocalConnections(Boolean threadLocalConnections); Boolean getThreadLocalConnections(); @Override final void setUseClusterConfiguration(Boolean useClusterConfiguration); @Override final Boolean getUseClusterConfiguration(); } | @Test(expected = UnsupportedOperationException.class) public void autoReconnectEnabled() { new ClientCacheFactoryBean().setEnableAutoReconnect(true); } |
ClientCacheFactoryBean extends CacheFactoryBean implements ApplicationListener<ContextRefreshedEvent> { @Override public final Boolean getUseClusterConfiguration() { return Boolean.FALSE; } @Override void onApplicationEvent(ContextRefreshedEvent event); @Override @SuppressWarnings({ "rawtypes", "unchecked" }) Class<? extends GemFireCache> getObjectType(); void addLocators(ConnectionEndpoint... locators); void addLocators(Iterable<ConnectionEndpoint> locators); void addServers(ConnectionEndpoint... servers); void addServers(Iterable<ConnectionEndpoint> servers); void setClientCacheConfigurers(ClientCacheConfigurer... clientCacheConfigurers); void setClientCacheConfigurers(List<ClientCacheConfigurer> peerCacheConfigurers); ClientCacheConfigurer getCompositeClientCacheConfigurer(); void setDurableClientId(String durableClientId); String getDurableClientId(); void setDurableClientTimeout(Integer durableClientTimeout); Integer getDurableClientTimeout(); @Override final void setEnableAutoReconnect(Boolean enableAutoReconnect); @Override final Boolean getEnableAutoReconnect(); void setFreeConnectionTimeout(Integer freeConnectionTimeout); Integer getFreeConnectionTimeout(); void setIdleTimeout(Long idleTimeout); Long getIdleTimeout(); void setKeepAlive(Boolean keepAlive); Boolean getKeepAlive(); boolean isKeepAlive(); void setLoadConditioningInterval(Integer loadConditioningInterval); Integer getLoadConditioningInterval(); void setLocators(ConnectionEndpoint[] locators); void setLocators(Iterable<ConnectionEndpoint> locators); void setMaxConnections(Integer maxConnections); Integer getMaxConnections(); void setMinConnections(Integer minConnections); Integer getMinConnections(); void setMultiUserAuthentication(Boolean multiUserAuthentication); Boolean getMultiUserAuthentication(); void setPool(@Nullable Pool pool); @Nullable Pool getPool(); void setPoolName(@Nullable String poolName); @Nullable String getPoolName(); void setPoolResolver(@Nullable PoolResolver poolResolver); @NonNull PoolResolver getPoolResolver(); void setPingInterval(Long pingInterval); Long getPingInterval(); void setPrSingleHopEnabled(Boolean prSingleHopEnabled); Boolean getPrSingleHopEnabled(); void setReadTimeout(Integer readTimeout); Integer getReadTimeout(); void setReadyForEvents(Boolean readyForEvents); Boolean getReadyForEvents(); boolean isReadyForEvents(); void setRetryAttempts(Integer retryAttempts); Integer getRetryAttempts(); void setServerConnectionTimeout(Integer serverConnectionTimeout); Integer getServerConnectionTimeout(); void setServerGroup(String serverGroup); String getServerGroup(); void setServers(ConnectionEndpoint[] servers); void setServers(Iterable<ConnectionEndpoint> servers); void setSocketBufferSize(Integer socketBufferSize); Integer getSocketBufferSize(); void setSocketConnectTimeout(Integer socketConnectTimeout); Integer getSocketConnectTimeout(); void setSocketFactory(@Nullable SocketFactory socketFactory); @NonNull SocketFactory getSocketFactory(); void setStatisticsInterval(Integer statisticsInterval); Integer getStatisticsInterval(); void setSubscriptionAckInterval(Integer subscriptionAckInterval); Integer getSubscriptionAckInterval(); void setSubscriptionEnabled(Boolean subscriptionEnabled); Boolean getSubscriptionEnabled(); void setSubscriptionMessageTrackingTimeout(Integer subscriptionMessageTrackingTimeout); Integer getSubscriptionMessageTrackingTimeout(); void setSubscriptionRedundancy(Integer subscriptionRedundancy); Integer getSubscriptionRedundancy(); void setThreadLocalConnections(Boolean threadLocalConnections); Boolean getThreadLocalConnections(); @Override final void setUseClusterConfiguration(Boolean useClusterConfiguration); @Override final Boolean getUseClusterConfiguration(); } | @Test public void clusterConfigurationNotUsed() { assertThat(new ClientCacheFactoryBean().getUseClusterConfiguration()).isFalse(); } |
ClientCacheFactoryBean extends CacheFactoryBean implements ApplicationListener<ContextRefreshedEvent> { @Override public final void setUseClusterConfiguration(Boolean useClusterConfiguration) { throw new UnsupportedOperationException("Cluster-based Configuration is not applicable for clients"); } @Override void onApplicationEvent(ContextRefreshedEvent event); @Override @SuppressWarnings({ "rawtypes", "unchecked" }) Class<? extends GemFireCache> getObjectType(); void addLocators(ConnectionEndpoint... locators); void addLocators(Iterable<ConnectionEndpoint> locators); void addServers(ConnectionEndpoint... servers); void addServers(Iterable<ConnectionEndpoint> servers); void setClientCacheConfigurers(ClientCacheConfigurer... clientCacheConfigurers); void setClientCacheConfigurers(List<ClientCacheConfigurer> peerCacheConfigurers); ClientCacheConfigurer getCompositeClientCacheConfigurer(); void setDurableClientId(String durableClientId); String getDurableClientId(); void setDurableClientTimeout(Integer durableClientTimeout); Integer getDurableClientTimeout(); @Override final void setEnableAutoReconnect(Boolean enableAutoReconnect); @Override final Boolean getEnableAutoReconnect(); void setFreeConnectionTimeout(Integer freeConnectionTimeout); Integer getFreeConnectionTimeout(); void setIdleTimeout(Long idleTimeout); Long getIdleTimeout(); void setKeepAlive(Boolean keepAlive); Boolean getKeepAlive(); boolean isKeepAlive(); void setLoadConditioningInterval(Integer loadConditioningInterval); Integer getLoadConditioningInterval(); void setLocators(ConnectionEndpoint[] locators); void setLocators(Iterable<ConnectionEndpoint> locators); void setMaxConnections(Integer maxConnections); Integer getMaxConnections(); void setMinConnections(Integer minConnections); Integer getMinConnections(); void setMultiUserAuthentication(Boolean multiUserAuthentication); Boolean getMultiUserAuthentication(); void setPool(@Nullable Pool pool); @Nullable Pool getPool(); void setPoolName(@Nullable String poolName); @Nullable String getPoolName(); void setPoolResolver(@Nullable PoolResolver poolResolver); @NonNull PoolResolver getPoolResolver(); void setPingInterval(Long pingInterval); Long getPingInterval(); void setPrSingleHopEnabled(Boolean prSingleHopEnabled); Boolean getPrSingleHopEnabled(); void setReadTimeout(Integer readTimeout); Integer getReadTimeout(); void setReadyForEvents(Boolean readyForEvents); Boolean getReadyForEvents(); boolean isReadyForEvents(); void setRetryAttempts(Integer retryAttempts); Integer getRetryAttempts(); void setServerConnectionTimeout(Integer serverConnectionTimeout); Integer getServerConnectionTimeout(); void setServerGroup(String serverGroup); String getServerGroup(); void setServers(ConnectionEndpoint[] servers); void setServers(Iterable<ConnectionEndpoint> servers); void setSocketBufferSize(Integer socketBufferSize); Integer getSocketBufferSize(); void setSocketConnectTimeout(Integer socketConnectTimeout); Integer getSocketConnectTimeout(); void setSocketFactory(@Nullable SocketFactory socketFactory); @NonNull SocketFactory getSocketFactory(); void setStatisticsInterval(Integer statisticsInterval); Integer getStatisticsInterval(); void setSubscriptionAckInterval(Integer subscriptionAckInterval); Integer getSubscriptionAckInterval(); void setSubscriptionEnabled(Boolean subscriptionEnabled); Boolean getSubscriptionEnabled(); void setSubscriptionMessageTrackingTimeout(Integer subscriptionMessageTrackingTimeout); Integer getSubscriptionMessageTrackingTimeout(); void setSubscriptionRedundancy(Integer subscriptionRedundancy); Integer getSubscriptionRedundancy(); void setThreadLocalConnections(Boolean threadLocalConnections); Boolean getThreadLocalConnections(); @Override final void setUseClusterConfiguration(Boolean useClusterConfiguration); @Override final Boolean getUseClusterConfiguration(); } | @Test(expected = UnsupportedOperationException.class) public void usesClusterConfiguration() { new ClientCacheFactoryBean().setUseClusterConfiguration(true); } |
ClientRegionFactoryBean extends ConfigurableRegionFactoryBean<K, V> implements SmartLifecycleSupport, EvictingRegionFactoryBean, ExpiringRegionFactoryBean<K, V>, DisposableBean { protected ClientRegionFactory<K, V> createClientRegionFactory(ClientCache clientCache, ClientRegionShortcut clientRegionShortcut) { return clientCache.createClientRegionFactory(clientRegionShortcut); } @Override void start(); @Override void destroy(); void setAttributes(RegionAttributes<K, V> attributes); void setCacheListeners(CacheListener<K, V>[] cacheListeners); void setCacheLoader(CacheLoader<K, V> cacheLoader); void setCacheWriter(CacheWriter<K, V> cacheWriter); void setCloningEnabled(Boolean cloningEnabled); void setClose(boolean close); void setCompressor(Compressor compressor); void setConcurrencyChecksEnabled(Boolean concurrencyChecksEnabled); void setConcurrencyLevel(Integer concurrencyLevel); void setCustomEntryIdleTimeout(CustomExpiry<K, V> customEntryIdleTimeout); void setCustomEntryTimeToLive(CustomExpiry<K, V> customEntryTimeToLive); void setDataPolicy(DataPolicy dataPolicy); void setDestroy(boolean destroy); void setDiskStoreName(String diskStoreName); void setDiskSynchronous(Boolean diskSynchronous); void setEntryIdleTimeout(ExpirationAttributes entryIdleTimeout); void setEntryTimeToLive(ExpirationAttributes entryTimeToLive); void setEvictionAttributes(EvictionAttributes evictionAttributes); void setInitialCapacity(Integer initialCapacity); void setInterests(Interest<K>[] interests); void setKeyConstraint(Class<K> keyConstraint); void setLoadFactor(Float loadFactor); void setPersistent(boolean persistent); void setPool(Pool pool); void setPoolName(String poolName); Optional<String> getPoolName(); void setPoolResolver(@Nullable PoolResolver poolResolver); @NonNull PoolResolver getPoolResolver(); void setRegionIdleTimeout(ExpirationAttributes regionIdleTimeout); void setRegionTimeToLive(ExpirationAttributes regionTimeToLive); void setShortcut(ClientRegionShortcut shortcut); void setStatisticsEnabled(Boolean statisticsEnabled); Boolean getStatisticsEnabled(); boolean isStatisticsEnabled(); void setValueConstraint(Class<V> valueConstraint); static final String DEFAULT_POOL_NAME; static final String GEMFIRE_POOL_NAME; } | @Test @SuppressWarnings("unchecked") public void createClientRegionFactoryFromClientCache() { ClientCache mockClientCache = mock(ClientCache.class); ClientRegionFactory mockClientRegionFactory = mock(ClientRegionFactory.class); when(mockClientCache.createClientRegionFactory(any(ClientRegionShortcut.class))) .thenReturn(mockClientRegionFactory); assertThat(factoryBean.createClientRegionFactory(mockClientCache, ClientRegionShortcut.CACHING_PROXY)) .isEqualTo(mockClientRegionFactory); verify(mockClientCache, times(1)) .createClientRegionFactory(eq(ClientRegionShortcut.CACHING_PROXY)); } |
ClientRegionFactoryBean extends ConfigurableRegionFactoryBean<K, V> implements SmartLifecycleSupport, EvictingRegionFactoryBean, ExpiringRegionFactoryBean<K, V>, DisposableBean { ClientRegionShortcut resolveClientRegionShortcut() { ClientRegionShortcut resolvedShortcut = this.shortcut; if (resolvedShortcut == null) { DataPolicy dataPolicy = this.dataPolicy; if (dataPolicy != null) { RegionUtils.assertDataPolicyAndPersistentAttributeAreCompatible(dataPolicy, this.persistent); if (DataPolicy.EMPTY.equals(dataPolicy)) { resolvedShortcut = ClientRegionShortcut.PROXY; } else if (DataPolicy.NORMAL.equals(dataPolicy)) { resolvedShortcut = ClientRegionShortcut.CACHING_PROXY; } else if (DataPolicy.PERSISTENT_REPLICATE.equals(dataPolicy)) { resolvedShortcut = ClientRegionShortcut.LOCAL_PERSISTENT; } else { throw newIllegalArgumentException("Data Policy [%s] is not valid for a client Region", dataPolicy); } } else { resolvedShortcut = isPersistent() ? ClientRegionShortcut.LOCAL_PERSISTENT : ClientRegionShortcut.LOCAL; } } RegionUtils.assertClientRegionShortcutAndPersistentAttributeAreCompatible(resolvedShortcut, this.persistent); return resolvedShortcut; } @Override void start(); @Override void destroy(); void setAttributes(RegionAttributes<K, V> attributes); void setCacheListeners(CacheListener<K, V>[] cacheListeners); void setCacheLoader(CacheLoader<K, V> cacheLoader); void setCacheWriter(CacheWriter<K, V> cacheWriter); void setCloningEnabled(Boolean cloningEnabled); void setClose(boolean close); void setCompressor(Compressor compressor); void setConcurrencyChecksEnabled(Boolean concurrencyChecksEnabled); void setConcurrencyLevel(Integer concurrencyLevel); void setCustomEntryIdleTimeout(CustomExpiry<K, V> customEntryIdleTimeout); void setCustomEntryTimeToLive(CustomExpiry<K, V> customEntryTimeToLive); void setDataPolicy(DataPolicy dataPolicy); void setDestroy(boolean destroy); void setDiskStoreName(String diskStoreName); void setDiskSynchronous(Boolean diskSynchronous); void setEntryIdleTimeout(ExpirationAttributes entryIdleTimeout); void setEntryTimeToLive(ExpirationAttributes entryTimeToLive); void setEvictionAttributes(EvictionAttributes evictionAttributes); void setInitialCapacity(Integer initialCapacity); void setInterests(Interest<K>[] interests); void setKeyConstraint(Class<K> keyConstraint); void setLoadFactor(Float loadFactor); void setPersistent(boolean persistent); void setPool(Pool pool); void setPoolName(String poolName); Optional<String> getPoolName(); void setPoolResolver(@Nullable PoolResolver poolResolver); @NonNull PoolResolver getPoolResolver(); void setRegionIdleTimeout(ExpirationAttributes regionIdleTimeout); void setRegionTimeToLive(ExpirationAttributes regionTimeToLive); void setShortcut(ClientRegionShortcut shortcut); void setStatisticsEnabled(Boolean statisticsEnabled); Boolean getStatisticsEnabled(); boolean isStatisticsEnabled(); void setValueConstraint(Class<V> valueConstraint); static final String DEFAULT_POOL_NAME; static final String GEMFIRE_POOL_NAME; } | @Test public void testResolveClientRegionShortcut() throws Exception { assertNull(TestUtils.readField("dataPolicy", factoryBean)); assertNull(TestUtils.readField("persistent", factoryBean)); assertNull(TestUtils.readField("shortcut", factoryBean)); assertEquals(ClientRegionShortcut.LOCAL, factoryBean.resolveClientRegionShortcut()); } |
ClientRegionFactoryBean extends ConfigurableRegionFactoryBean<K, V> implements SmartLifecycleSupport, EvictingRegionFactoryBean, ExpiringRegionFactoryBean<K, V>, DisposableBean { @Override public void destroy() throws Exception { Optional.ofNullable(getObject()).ifPresent(region -> { if (isClose() && RegionUtils.isCloseable(region)) { RegionUtils.close(region); } if (isDestroy()) { region.destroyRegion(); } }); } @Override void start(); @Override void destroy(); void setAttributes(RegionAttributes<K, V> attributes); void setCacheListeners(CacheListener<K, V>[] cacheListeners); void setCacheLoader(CacheLoader<K, V> cacheLoader); void setCacheWriter(CacheWriter<K, V> cacheWriter); void setCloningEnabled(Boolean cloningEnabled); void setClose(boolean close); void setCompressor(Compressor compressor); void setConcurrencyChecksEnabled(Boolean concurrencyChecksEnabled); void setConcurrencyLevel(Integer concurrencyLevel); void setCustomEntryIdleTimeout(CustomExpiry<K, V> customEntryIdleTimeout); void setCustomEntryTimeToLive(CustomExpiry<K, V> customEntryTimeToLive); void setDataPolicy(DataPolicy dataPolicy); void setDestroy(boolean destroy); void setDiskStoreName(String diskStoreName); void setDiskSynchronous(Boolean diskSynchronous); void setEntryIdleTimeout(ExpirationAttributes entryIdleTimeout); void setEntryTimeToLive(ExpirationAttributes entryTimeToLive); void setEvictionAttributes(EvictionAttributes evictionAttributes); void setInitialCapacity(Integer initialCapacity); void setInterests(Interest<K>[] interests); void setKeyConstraint(Class<K> keyConstraint); void setLoadFactor(Float loadFactor); void setPersistent(boolean persistent); void setPool(Pool pool); void setPoolName(String poolName); Optional<String> getPoolName(); void setPoolResolver(@Nullable PoolResolver poolResolver); @NonNull PoolResolver getPoolResolver(); void setRegionIdleTimeout(ExpirationAttributes regionIdleTimeout); void setRegionTimeToLive(ExpirationAttributes regionTimeToLive); void setShortcut(ClientRegionShortcut shortcut); void setStatisticsEnabled(Boolean statisticsEnabled); Boolean getStatisticsEnabled(); boolean isStatisticsEnabled(); void setValueConstraint(Class<V> valueConstraint); static final String DEFAULT_POOL_NAME; static final String GEMFIRE_POOL_NAME; } | @Test @SuppressWarnings("unchecked") public void destroyDoesNothingWhenClientRegionFactoryBeanCloseAndDestroyAreFalse() throws Exception { Region mockRegion = mock(Region.class, "MockRegion"); doReturn(mockRegion).when(factoryBean).getObject(); factoryBean.destroy(); verify(factoryBean, times(1)).getObject(); verify(mockRegion, never()).getRegionService(); verify(mockRegion, never()).close(); verify(mockRegion, never()).destroyRegion(); verify(mockRegion, never()).unregisterInterest(any()); verify(mockRegion, never()).unregisterInterestRegex(anyString()); }
@Test public void destroyDoesNothingWhenRegionIsNull() throws Exception { doReturn(null).when(factoryBean).getObject(); factoryBean.destroy(); verify(factoryBean, times(1)).getObject(); } |
ListRegionsOnServerFunction implements Function { @Override @SuppressWarnings("unchecked") public void execute(FunctionContext functionContext) { List<String> regionNames = new ArrayList<>(); for (Region<?, ?> region : getCache().rootRegions()) { regionNames.add(region.getName()); } functionContext.getResultSender().lastResult(regionNames); } @Override @SuppressWarnings("unchecked") void execute(FunctionContext functionContext); @Override String getId(); @Override boolean hasResult(); @Override boolean isHA(); @Override boolean optimizeForWrite(); static final String ID; } | @Test @SuppressWarnings("unchecked") public void executeReturnsRootRegionNames() { final Cache mockCache = mock(Cache.class, "MockGemFireCache"); Region mockRegionOne = mock(Region.class, "MockGemFireRegionOne"); Region mockRegionTwo = mock(Region.class, "MockGemFireRegionTwo"); Region mockRegionThree = mock(Region.class, "MockGemFireRegionThree"); FunctionContext mockFunctionContext = mock(FunctionContext.class, "MockGemFireFunctionContext"); ResultSender<Object> mockResultSender = mock(ResultSender.class, "MockGemFireResultSender"); when(mockCache.rootRegions()).thenReturn(new HashSet<>( Arrays.<Region<?, ?>>asList(mockRegionOne, mockRegionTwo, mockRegionThree))); when(mockRegionOne.getName()).thenReturn("One"); when(mockRegionTwo.getName()).thenReturn("Two"); when(mockRegionThree.getName()).thenReturn("Three"); when(mockFunctionContext.getResultSender()).thenReturn(mockResultSender); final AtomicReference<List<String>> regionNames = new AtomicReference<>(null); doAnswer(new Answer<Void>() { @Override public Void answer(final InvocationOnMock invocation) throws Throwable { regionNames.compareAndSet(null, invocation.getArgument(0)); return null; } }).when(mockResultSender).lastResult(any(List.class)); ListRegionsOnServerFunction function = new ListRegionsOnServerFunction() { @Override Cache getCache() { return mockCache; } }; function.execute(mockFunctionContext); List<String> actualRegionNames = regionNames.get(); assertThat(actualRegionNames, is(not(nullValue()))); assertThat(actualRegionNames.isEmpty(), is(false)); assertThat(actualRegionNames.size(), is(equalTo(3))); assertThat(actualRegionNames.containsAll(Arrays.asList("One", "Two", "Three")), is(true)); verify(mockCache, times(1)).rootRegions(); verify(mockRegionOne, times(1)).getName(); verify(mockRegionTwo, times(1)).getName(); verify(mockRegionThree, times(1)).getName(); verify(mockFunctionContext, times(1)).getResultSender(); verify(mockResultSender, times(1)).lastResult(any(List.class)); }
@Test @SuppressWarnings("unchecked") public void executeWithNoRegions() { final Cache mockCache = mock(Cache.class, "MockGemFireCache"); FunctionContext mockFunctionContext = mock(FunctionContext.class, "MockGemFireFunctionContext"); ResultSender<Object> mockResultSender = mock(ResultSender.class, "MockGemFireResultSender"); when(mockCache.rootRegions()).thenReturn(Collections.emptySet()); when(mockFunctionContext.getResultSender()).thenReturn(mockResultSender); final AtomicReference<List<String>> regionNames = new AtomicReference<>(null); doAnswer(new Answer<Void>() { @Override public Void answer(final InvocationOnMock invocation) throws Throwable { regionNames.compareAndSet(null, invocation.getArgument(0)); return null; } }).when(mockResultSender).lastResult(any(List.class)); ListRegionsOnServerFunction function = new ListRegionsOnServerFunction() { @Override Cache getCache() { return mockCache; } }; function.execute(mockFunctionContext); List<String> actualRegionNames = regionNames.get(); assertThat(actualRegionNames, is(not(nullValue()))); assertThat(actualRegionNames.isEmpty(), is(true)); verify(mockCache, times(1)).rootRegions(); verify(mockFunctionContext, times(1)).getResultSender(); verify(mockResultSender, times(1)).lastResult(any(List.class)); } |
AnnotationBasedExpiration implements BeanFactoryAware, CustomExpiry<K, V> { protected TimeToLiveExpiration getTimeToLive(Region.Entry<K, V> entry) { return getTimeToLive(entry.getValue()); } AnnotationBasedExpiration(); AnnotationBasedExpiration(ExpirationAttributes defaultExpirationAttributes); static AnnotationBasedExpiration<K, V> forIdleTimeout(); static AnnotationBasedExpiration<K, V> forIdleTimeout(ExpirationAttributes defaultExpirationAttributes); static AnnotationBasedExpiration<K, V> forTimeToLive(); static AnnotationBasedExpiration<K, V> forTimeToLive(ExpirationAttributes defaultExpirationAttributes); @Override void setBeanFactory(BeanFactory beanFactory); void setDefaultExpirationAttributes(ExpirationAttributes defaultExpirationAttributes); @Override ExpirationAttributes getExpiry(Region.Entry<K, V> entry); @Override void close(); } | @Test public void getTimeToLiveWithTimeToLiveExpirationBasedRegionEntry() { Region.Entry mockRegionEntry = mock(Region.Entry.class, "MockRegionEntry"); when(mockRegionEntry.getValue()).thenReturn(new RegionEntryValueWithTimeToLiveExpiration()); assertThat(noDefaultExpiration.getTimeToLive(mockRegionEntry), isA(TimeToLiveExpiration.class)); when(mockRegionEntry.getValue()).thenReturn(new RegionEntryValueWithTimeToLiveIdleTimeoutGenericExpiration()); assertThat(noDefaultExpiration.getTimeToLive(mockRegionEntry), isA(TimeToLiveExpiration.class)); verify(mockRegionEntry, times(2)).getValue(); }
@Test public void getTimeToLiveWithNoTimeToLiveExpirationRegionEntry() { Region.Entry mockRegionEntry = mock(Region.Entry.class, "MockRegionEntry"); when(mockRegionEntry.getValue()).thenReturn(new RegionEntryValueWithIdleTimeoutGenericExpiration()); assertThat(noDefaultExpiration.getTimeToLive(mockRegionEntry), is(nullValue())); when(mockRegionEntry.getValue()).thenReturn(new RegionEntryValueWithNoExpiration()); assertThat(noDefaultExpiration.getTimeToLive(mockRegionEntry), is(nullValue())); verify(mockRegionEntry, times(2)).getValue(); } |
ListRegionsOnServerFunction implements Function { @Override public String getId() { return this.getClass().getName(); } @Override @SuppressWarnings("unchecked") void execute(FunctionContext functionContext); @Override String getId(); @Override boolean hasResult(); @Override boolean isHA(); @Override boolean optimizeForWrite(); static final String ID; } | @Test public void getIdIsFullyQualifiedClassName() { assertThat(function.getId(), is(equalTo(ListRegionsOnServerFunction.class.getName()))); } |
ListRegionsOnServerFunction implements Function { @Override public boolean hasResult() { return true; } @Override @SuppressWarnings("unchecked") void execute(FunctionContext functionContext); @Override String getId(); @Override boolean hasResult(); @Override boolean isHA(); @Override boolean optimizeForWrite(); static final String ID; } | @Test public void hasResultIsTrue() { assertThat(function.hasResult(), is(true)); } |
ClientRegionShortcutConverter implements Converter<String, ClientRegionShortcut> { protected static String toUpperCase(final String value) { return (value != null ? value.toUpperCase().trim() : String.valueOf(value)); } @Override ClientRegionShortcut convert(final String source); } | @Test public void testToUpperCase() { assertEquals("TEST", ClientRegionShortcutConverter.toUpperCase("test")); assertEquals("TEST", ClientRegionShortcutConverter.toUpperCase(" Test ")); assertEquals("", ClientRegionShortcutConverter.toUpperCase("")); assertEquals("", ClientRegionShortcutConverter.toUpperCase(" ")); assertEquals("NULL", ClientRegionShortcutConverter.toUpperCase("null")); assertEquals("null", ClientRegionShortcutConverter.toUpperCase(null)); } |
ClientRegionShortcutConverter implements Converter<String, ClientRegionShortcut> { @Override public ClientRegionShortcut convert(final String source) { return ClientRegionShortcut.valueOf(toUpperCase(source)); } @Override ClientRegionShortcut convert(final String source); } | @Test public void testConvert() { for (ClientRegionShortcut shortcut : ClientRegionShortcut.values()) { assertEquals(shortcut, converter.convert(shortcut.name())); } assertEquals(ClientRegionShortcut.PROXY, converter.convert("Proxy")); assertEquals(ClientRegionShortcut.CACHING_PROXY, converter.convert("caching_proxy")); assertEquals(ClientRegionShortcut.LOCAL_HEAP_LRU, converter.convert("local_Heap_LRU")); }
@Test(expected = IllegalArgumentException.class) public void testConvertWithIllegalEnumeratedValue() { converter.convert("LOCAL Persistent OverFlow"); } |
GemfireDataSourcePostProcessor implements BeanFactoryAware, BeanPostProcessor { @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { if (beanFactory instanceof ConfigurableBeanFactory) { this.beanFactory = (ConfigurableBeanFactory) beanFactory; } else { throw new TypeMismatchException(beanFactory, ConfigurableBeanFactory.class); } } @Override void setBeanFactory(BeanFactory beanFactory); Optional<ConfigurableBeanFactory> getBeanFactory(); void setClientRegionShortcut(ClientRegionShortcut clientRegionShortcut); Optional<ClientRegionShortcut> getClientRegionShortcut(); @Nullable @Override Object postProcessAfterInitialization(Object bean, String beanName); GemfireDataSourcePostProcessor using(ClientRegionShortcut clientRegionShortcut); GemfireDataSourcePostProcessor using(BeanFactory beanFactory); } | @Test(expected = TypeMismatchException.class) public void setBeanFactoryToIncompatibleTypeThrowsBeansException() { new GemfireDataSourcePostProcessor().setBeanFactory(mock(BeanFactory.class)); }
@Test(expected = TypeMismatchException.class) public void setBeanFactoryToNullThrowsBeansException() { new GemfireDataSourcePostProcessor().setBeanFactory(null); } |
GemfireDataSourcePostProcessor implements BeanFactoryAware, BeanPostProcessor { boolean containsRegionInformation(Object results) { return results instanceof Object[] && ((Object[]) results).length > 0 && ((Object[]) results)[0] instanceof RegionInformation; } @Override void setBeanFactory(BeanFactory beanFactory); Optional<ConfigurableBeanFactory> getBeanFactory(); void setClientRegionShortcut(ClientRegionShortcut clientRegionShortcut); Optional<ClientRegionShortcut> getClientRegionShortcut(); @Nullable @Override Object postProcessAfterInitialization(Object bean, String beanName); GemfireDataSourcePostProcessor using(ClientRegionShortcut clientRegionShortcut); GemfireDataSourcePostProcessor using(BeanFactory beanFactory); } | @Test public void containsRegionInformationIsTrue() { assertThat(new GemfireDataSourcePostProcessor() .containsRegionInformation(new Object[] { newRegionInformation(mockRegion("Example")) })) .isTrue(); }
@Test public void containsRegionInformationWithEmptyArrayIsFalse() { assertThat(new GemfireDataSourcePostProcessor().containsRegionInformation(new Object[0])).isFalse(); }
@Test public void containsRegionInformationWithListOfRegionInformationIsFalse() { assertThat(new GemfireDataSourcePostProcessor() .containsRegionInformation(Collections.singletonList(newRegionInformation(mockRegion("Example"))))) .isFalse(); }
@Test public void containsRegionInformationWithNonEmptyArrayContainingNonRegionInformationIsFalse() { assertThat(new GemfireDataSourcePostProcessor().containsRegionInformation(new Object[] { "TEST" })).isFalse(); }
@Test public void containsRegionInformationWithNullIsFalse() { assertThat(new GemfireDataSourcePostProcessor().containsRegionInformation(null)).isFalse(); } |
GemfireDataSourcePostProcessor implements BeanFactoryAware, BeanPostProcessor { void createClientProxyRegions(ConfigurableBeanFactory beanFactory, ClientCache clientCache, Iterable<String> regionNames) { if (regionNames.iterator().hasNext()) { ClientRegionShortcut resolvedClientRegionShortcut = resolveClientRegionShortcut(); ClientRegionFactory<?, ?> clientRegionFactory = clientCache.createClientRegionFactory(resolvedClientRegionShortcut); for (String regionName : regionNames) { if (beanFactory.containsBean(regionName)) { Object bean = beanFactory.getBean(regionName); logWarn("Cannot create a client {} Region bean named {}; A bean with name {} having type {} already exists", resolvedClientRegionShortcut.name(), regionName, regionName, ObjectUtils.nullSafeClassName(bean)); } else { logInfo("Creating Region bean with name {}...", regionName); beanFactory.registerSingleton(regionName, clientRegionFactory.create(regionName)); } } } } @Override void setBeanFactory(BeanFactory beanFactory); Optional<ConfigurableBeanFactory> getBeanFactory(); void setClientRegionShortcut(ClientRegionShortcut clientRegionShortcut); Optional<ClientRegionShortcut> getClientRegionShortcut(); @Nullable @Override Object postProcessAfterInitialization(Object bean, String beanName); GemfireDataSourcePostProcessor using(ClientRegionShortcut clientRegionShortcut); GemfireDataSourcePostProcessor using(BeanFactory beanFactory); } | @Test @SuppressWarnings("unchecked") public void createClientProxyRegionsIsSuccessful() { ClientRegionFactory mockClientRegionFactory = mock(ClientRegionFactory.class); when(this.mockClientCache.createClientRegionFactory(eq(ClientRegionShortcut.PROXY))) .thenReturn(mockClientRegionFactory); Region mockRegionOne = mock(Region.class, "MockGemFireRegionOne"); Region mockRegionTwo = mock(Region.class, "MockGemFireRegionTwo"); Map<String, Region<?, ?>> regionMap = new HashMap<>(2); regionMap.put("RegionOne", mockRegionOne); regionMap.put("RegionTwo", mockRegionTwo); doAnswer(invocation -> { String regionName = invocation.getArgument(0); assertThat(regionMap.containsKey(regionName)).isTrue(); return regionMap.get(regionName); }).when(mockClientRegionFactory).create(any(String.class)); when(mockBeanFactory.containsBean(any(String.class))).thenReturn(false); GemfireDataSourcePostProcessor postProcessor = new GemfireDataSourcePostProcessor(); postProcessor.createClientProxyRegions(this.mockBeanFactory, this.mockClientCache, regionMap.keySet()); verify(this.mockClientCache, times(1)).createClientRegionFactory(eq(ClientRegionShortcut.PROXY)); verify(mockClientRegionFactory, times(1)).create(eq("RegionOne")); verify(mockClientRegionFactory, times(1)).create(eq("RegionTwo")); verify(this.mockBeanFactory, times(1)).registerSingleton(eq("RegionOne"), same(mockRegionOne)); verify(this.mockBeanFactory, times(1)).registerSingleton(eq("RegionTwo"), same(mockRegionTwo)); }
@Test @SuppressWarnings("unchecked") public void createClientProxyRegionsWhenRegionBeanExists() { ClientRegionFactory mockClientRegionFactory = mock(ClientRegionFactory.class); when(this.mockClientCache.createClientRegionFactory(eq(ClientRegionShortcut.PROXY))) .thenReturn(mockClientRegionFactory); Region mockRegion = mock(Region.class); when(this.mockBeanFactory.containsBean(any(String.class))).thenReturn(true); when(this.mockBeanFactory.getBean(eq("Example"))).thenReturn(mockRegion); GemfireDataSourcePostProcessor postProcessor = new GemfireDataSourcePostProcessor(); postProcessor.createClientProxyRegions(this.mockBeanFactory, this.mockClientCache, Collections.singletonList("Example")); verify(this.mockClientCache, times(1)).createClientRegionFactory(eq(ClientRegionShortcut.PROXY)); verify(mockClientRegionFactory, never()).create(any(String.class)); verify(this.mockBeanFactory, never()).registerSingleton(any(String.class), any(Region.class)); } |
FactoryDefaultsPoolAdapter extends PoolAdapter { @Override public List<InetSocketAddress> getLocators() { return Collections.emptyList(); } @Override int getFreeConnectionTimeout(); @Override long getIdleTimeout(); @Override int getLoadConditioningInterval(); @Override List<InetSocketAddress> getLocators(); @Override int getMaxConnections(); @Override int getMinConnections(); @Override boolean getMultiuserAuthentication(); @Override String getName(); @Override List<InetSocketAddress> getOnlineLocators(); @Override long getPingInterval(); @Override boolean getPRSingleHopEnabled(); @Override QueryService getQueryService(); @Override int getReadTimeout(); @Override int getRetryAttempts(); @Override int getServerConnectionTimeout(); @Override String getServerGroup(); @Override List<InetSocketAddress> getServers(); @Override int getSocketBufferSize(); @Override int getSocketConnectTimeout(); @Override SocketFactory getSocketFactory(); @Override int getStatisticInterval(); @Override int getSubscriptionAckInterval(); @Override boolean getSubscriptionEnabled(); @Override int getSubscriptionMessageTrackingTimeout(); @Override int getSubscriptionRedundancy(); @Override int getSubscriptionTimeoutMultiplier(); @Override boolean getThreadLocalConnections(); void destroy(); } | @Test public void locatorsReturnsEmptyList() { assertThat(this.poolAdapter.getLocators()).isEqualTo(Collections.<InetSocketAddress>emptyList()); } |
FactoryDefaultsPoolAdapter extends PoolAdapter { @Override public String getName() { return DEFAULT_POOL_NAME; } @Override int getFreeConnectionTimeout(); @Override long getIdleTimeout(); @Override int getLoadConditioningInterval(); @Override List<InetSocketAddress> getLocators(); @Override int getMaxConnections(); @Override int getMinConnections(); @Override boolean getMultiuserAuthentication(); @Override String getName(); @Override List<InetSocketAddress> getOnlineLocators(); @Override long getPingInterval(); @Override boolean getPRSingleHopEnabled(); @Override QueryService getQueryService(); @Override int getReadTimeout(); @Override int getRetryAttempts(); @Override int getServerConnectionTimeout(); @Override String getServerGroup(); @Override List<InetSocketAddress> getServers(); @Override int getSocketBufferSize(); @Override int getSocketConnectTimeout(); @Override SocketFactory getSocketFactory(); @Override int getStatisticInterval(); @Override int getSubscriptionAckInterval(); @Override boolean getSubscriptionEnabled(); @Override int getSubscriptionMessageTrackingTimeout(); @Override int getSubscriptionRedundancy(); @Override int getSubscriptionTimeoutMultiplier(); @Override boolean getThreadLocalConnections(); void destroy(); } | @Test public void nameReturnsDefault() { assertThat(this.poolAdapter.getName()).isEqualTo(FactoryDefaultsPoolAdapter.DEFAULT_POOL_NAME); } |
FactoryDefaultsPoolAdapter extends PoolAdapter { @Override public List<InetSocketAddress> getOnlineLocators() { return Collections.emptyList(); } @Override int getFreeConnectionTimeout(); @Override long getIdleTimeout(); @Override int getLoadConditioningInterval(); @Override List<InetSocketAddress> getLocators(); @Override int getMaxConnections(); @Override int getMinConnections(); @Override boolean getMultiuserAuthentication(); @Override String getName(); @Override List<InetSocketAddress> getOnlineLocators(); @Override long getPingInterval(); @Override boolean getPRSingleHopEnabled(); @Override QueryService getQueryService(); @Override int getReadTimeout(); @Override int getRetryAttempts(); @Override int getServerConnectionTimeout(); @Override String getServerGroup(); @Override List<InetSocketAddress> getServers(); @Override int getSocketBufferSize(); @Override int getSocketConnectTimeout(); @Override SocketFactory getSocketFactory(); @Override int getStatisticInterval(); @Override int getSubscriptionAckInterval(); @Override boolean getSubscriptionEnabled(); @Override int getSubscriptionMessageTrackingTimeout(); @Override int getSubscriptionRedundancy(); @Override int getSubscriptionTimeoutMultiplier(); @Override boolean getThreadLocalConnections(); void destroy(); } | @Test public void onlineLocatorsIsEmptyList() { assertThat(this.poolAdapter.getOnlineLocators()).isEqualTo(Collections.EMPTY_LIST); } |
FactoryDefaultsPoolAdapter extends PoolAdapter { @Override public QueryService getQueryService() { return null; } @Override int getFreeConnectionTimeout(); @Override long getIdleTimeout(); @Override int getLoadConditioningInterval(); @Override List<InetSocketAddress> getLocators(); @Override int getMaxConnections(); @Override int getMinConnections(); @Override boolean getMultiuserAuthentication(); @Override String getName(); @Override List<InetSocketAddress> getOnlineLocators(); @Override long getPingInterval(); @Override boolean getPRSingleHopEnabled(); @Override QueryService getQueryService(); @Override int getReadTimeout(); @Override int getRetryAttempts(); @Override int getServerConnectionTimeout(); @Override String getServerGroup(); @Override List<InetSocketAddress> getServers(); @Override int getSocketBufferSize(); @Override int getSocketConnectTimeout(); @Override SocketFactory getSocketFactory(); @Override int getStatisticInterval(); @Override int getSubscriptionAckInterval(); @Override boolean getSubscriptionEnabled(); @Override int getSubscriptionMessageTrackingTimeout(); @Override int getSubscriptionRedundancy(); @Override int getSubscriptionTimeoutMultiplier(); @Override boolean getThreadLocalConnections(); void destroy(); } | @Test public void queryServiceIsNull() { assertThat(this.poolAdapter.getQueryService()).isNull(); } |
FactoryDefaultsPoolAdapter extends PoolAdapter { @Override public List<InetSocketAddress> getServers() { return Collections.singletonList(new InetSocketAddress(LOCALHOST, GemfireUtils.DEFAULT_CACHE_SERVER_PORT)); } @Override int getFreeConnectionTimeout(); @Override long getIdleTimeout(); @Override int getLoadConditioningInterval(); @Override List<InetSocketAddress> getLocators(); @Override int getMaxConnections(); @Override int getMinConnections(); @Override boolean getMultiuserAuthentication(); @Override String getName(); @Override List<InetSocketAddress> getOnlineLocators(); @Override long getPingInterval(); @Override boolean getPRSingleHopEnabled(); @Override QueryService getQueryService(); @Override int getReadTimeout(); @Override int getRetryAttempts(); @Override int getServerConnectionTimeout(); @Override String getServerGroup(); @Override List<InetSocketAddress> getServers(); @Override int getSocketBufferSize(); @Override int getSocketConnectTimeout(); @Override SocketFactory getSocketFactory(); @Override int getStatisticInterval(); @Override int getSubscriptionAckInterval(); @Override boolean getSubscriptionEnabled(); @Override int getSubscriptionMessageTrackingTimeout(); @Override int getSubscriptionRedundancy(); @Override int getSubscriptionTimeoutMultiplier(); @Override boolean getThreadLocalConnections(); void destroy(); } | @Test public void serversReturnsLocalhostListeningOnDefaultCacheServerPort() { assertThat(this.poolAdapter.getServers()).isEqualTo(Collections.singletonList( newSocketAddress("localhost", DEFAULT_CACHE_SERVER_PORT))); } |
AnnotationBasedExpiration implements BeanFactoryAware, CustomExpiry<K, V> { private <T extends Annotation> T getAnnotation(Object obj, Class<T> annotationType) { return AnnotationUtils.getAnnotation(obj.getClass(), annotationType); } AnnotationBasedExpiration(); AnnotationBasedExpiration(ExpirationAttributes defaultExpirationAttributes); static AnnotationBasedExpiration<K, V> forIdleTimeout(); static AnnotationBasedExpiration<K, V> forIdleTimeout(ExpirationAttributes defaultExpirationAttributes); static AnnotationBasedExpiration<K, V> forTimeToLive(); static AnnotationBasedExpiration<K, V> forTimeToLive(ExpirationAttributes defaultExpirationAttributes); @Override void setBeanFactory(BeanFactory beanFactory); void setDefaultExpirationAttributes(ExpirationAttributes defaultExpirationAttributes); @Override ExpirationAttributes getExpiry(Region.Entry<K, V> entry); @Override void close(); } | @Test public void fromExpiration() { ExpirationMetaData expirationMetaData = ExpirationMetaData.from( RegionEntryValueWithGenericExpiration.class.getAnnotation(Expiration.class)); assertExpiration(expirationMetaData, 60, ExpirationActionType.INVALIDATE); }
@Test public void fromExpirationIdleTimeout() { ExpirationMetaData expirationMetaData = ExpirationMetaData.from( RegionEntryValueWithIdleTimeoutExpiration.class.getAnnotation(IdleTimeoutExpiration.class)); assertExpiration(expirationMetaData, 120, ExpirationActionType.LOCAL_INVALIDATE); }
@Test public void fromExpirationTimeToLive() { ExpirationMetaData expirationMetaData = ExpirationMetaData.from( RegionEntryValueWithTimeToLiveExpiration.class.getAnnotation(TimeToLiveExpiration.class)); assertExpiration(expirationMetaData, 300, ExpirationActionType.LOCAL_DESTROY); } |
FactoryDefaultsPoolAdapter extends PoolAdapter { public void destroy() { destroy(DEFAULT_KEEP_ALIVE); } @Override int getFreeConnectionTimeout(); @Override long getIdleTimeout(); @Override int getLoadConditioningInterval(); @Override List<InetSocketAddress> getLocators(); @Override int getMaxConnections(); @Override int getMinConnections(); @Override boolean getMultiuserAuthentication(); @Override String getName(); @Override List<InetSocketAddress> getOnlineLocators(); @Override long getPingInterval(); @Override boolean getPRSingleHopEnabled(); @Override QueryService getQueryService(); @Override int getReadTimeout(); @Override int getRetryAttempts(); @Override int getServerConnectionTimeout(); @Override String getServerGroup(); @Override List<InetSocketAddress> getServers(); @Override int getSocketBufferSize(); @Override int getSocketConnectTimeout(); @Override SocketFactory getSocketFactory(); @Override int getStatisticInterval(); @Override int getSubscriptionAckInterval(); @Override boolean getSubscriptionEnabled(); @Override int getSubscriptionMessageTrackingTimeout(); @Override int getSubscriptionRedundancy(); @Override int getSubscriptionTimeoutMultiplier(); @Override boolean getThreadLocalConnections(); void destroy(); } | @Test(expected = UnsupportedOperationException.class) public void destroyedIsUnsupported() { testPoolOperationIsUnsupported(() -> { this.poolAdapter.destroy(); return null; }); }
@Test(expected = UnsupportedOperationException.class) public void destroyedWithKeepAliveIsUnsupported() { testPoolOperationIsUnsupported(() -> { this.poolAdapter.destroy(false); return null; }); } |
DefaultableDelegatingPoolAdapter { protected Pool getDelegate() { return this.delegate; } protected DefaultableDelegatingPoolAdapter(Pool delegate); static DefaultableDelegatingPoolAdapter from(Pool delegate); DefaultableDelegatingPoolAdapter preferDefault(); DefaultableDelegatingPoolAdapter preferPool(); boolean isDestroyed(); int getFreeConnectionTimeout(Integer defaultFreeConnectionTimeout); long getIdleTimeout(Long defaultIdleTimeout); int getLoadConditioningInterval(Integer defaultLoadConditioningInterval); List<InetSocketAddress> getLocators(List<InetSocketAddress> defaultLocators); int getMaxConnections(Integer defaultMaxConnections); int getMinConnections(Integer defaultMinConnections); boolean getMultiuserAuthentication(Boolean defaultMultiUserAuthentication); String getName(); int getPendingEventCount(); long getPingInterval(Long defaultPingInterval); boolean getPRSingleHopEnabled(Boolean defaultPrSingleHopEnabled); QueryService getQueryService(QueryService defaultQueryService); int getReadTimeout(Integer defaultReadTimeout); int getRetryAttempts(Integer defaultRetryAttempts); int getServerConnectionTimeout(Integer defaultServerConnectionTimeout); String getServerGroup(String defaultServerGroup); List<InetSocketAddress> getServers(List<InetSocketAddress> defaultServers); int getSocketBufferSize(Integer defaultSocketBufferSize); int getSocketConnectTimeout(Integer defaultSocketConnectTimeout); SocketFactory getSocketFactory(SocketFactory defaultSocketFactory); int getStatisticInterval(Integer defaultStatisticInterval); int getSubscriptionAckInterval(Integer defaultSubscriptionAckInterval); boolean getSubscriptionEnabled(Boolean defaultSubscriptionEnabled); int getSubscriptionMessageTrackingTimeout(Integer defaultSubscriptionMessageTrackingTimeout); int getSubscriptionRedundancy(Integer defaultSubscriptionRedundancy); int getSubscriptionTimeoutMultiplier(Integer defaultSubscriptionTimeoutMultiplier); boolean getThreadLocalConnections(Boolean defaultThreadLocalConnections); void destroy(); void destroy(boolean keepAlive); void releaseThreadLocalConnection(); } | @Test public void fromMockPool() { assertThat(this.poolAdapter.getDelegate()).isSameAs(this.mockPool); } |
DefaultableDelegatingPoolAdapter { public static DefaultableDelegatingPoolAdapter from(Pool delegate) { return new DefaultableDelegatingPoolAdapter(delegate) {}; } protected DefaultableDelegatingPoolAdapter(Pool delegate); static DefaultableDelegatingPoolAdapter from(Pool delegate); DefaultableDelegatingPoolAdapter preferDefault(); DefaultableDelegatingPoolAdapter preferPool(); boolean isDestroyed(); int getFreeConnectionTimeout(Integer defaultFreeConnectionTimeout); long getIdleTimeout(Long defaultIdleTimeout); int getLoadConditioningInterval(Integer defaultLoadConditioningInterval); List<InetSocketAddress> getLocators(List<InetSocketAddress> defaultLocators); int getMaxConnections(Integer defaultMaxConnections); int getMinConnections(Integer defaultMinConnections); boolean getMultiuserAuthentication(Boolean defaultMultiUserAuthentication); String getName(); int getPendingEventCount(); long getPingInterval(Long defaultPingInterval); boolean getPRSingleHopEnabled(Boolean defaultPrSingleHopEnabled); QueryService getQueryService(QueryService defaultQueryService); int getReadTimeout(Integer defaultReadTimeout); int getRetryAttempts(Integer defaultRetryAttempts); int getServerConnectionTimeout(Integer defaultServerConnectionTimeout); String getServerGroup(String defaultServerGroup); List<InetSocketAddress> getServers(List<InetSocketAddress> defaultServers); int getSocketBufferSize(Integer defaultSocketBufferSize); int getSocketConnectTimeout(Integer defaultSocketConnectTimeout); SocketFactory getSocketFactory(SocketFactory defaultSocketFactory); int getStatisticInterval(Integer defaultStatisticInterval); int getSubscriptionAckInterval(Integer defaultSubscriptionAckInterval); boolean getSubscriptionEnabled(Boolean defaultSubscriptionEnabled); int getSubscriptionMessageTrackingTimeout(Integer defaultSubscriptionMessageTrackingTimeout); int getSubscriptionRedundancy(Integer defaultSubscriptionRedundancy); int getSubscriptionTimeoutMultiplier(Integer defaultSubscriptionTimeoutMultiplier); boolean getThreadLocalConnections(Boolean defaultThreadLocalConnections); void destroy(); void destroy(boolean keepAlive); void releaseThreadLocalConnection(); } | @Test(expected = IllegalArgumentException.class) public void fromNull() { try { DefaultableDelegatingPoolAdapter.from(null); } catch (IllegalArgumentException expected) { assertThat(expected).hasMessage("Pool delegate must not be null"); assertThat(expected).hasNoCause(); throw expected; } } |
LocalRegionFactoryBean extends PeerRegionFactoryBean<K, V> { @Override protected void resolveDataPolicy(RegionFactory<K, V> regionFactory, Boolean persistent, DataPolicy dataPolicy) { if (dataPolicy == null || DataPolicy.NORMAL.equals(dataPolicy)) { DataPolicy resolvedDataPolicy = (isPersistent() ? DataPolicy.PERSISTENT_REPLICATE : DataPolicy.NORMAL); regionFactory.setDataPolicy(resolvedDataPolicy); setDataPolicy(resolvedDataPolicy); } else if (DataPolicy.PRELOADED.equals(dataPolicy)) { DataPolicy resolvedDataPolicy = (isPersistent() ? DataPolicy.PERSISTENT_REPLICATE : DataPolicy.PRELOADED); regionFactory.setDataPolicy(resolvedDataPolicy); setDataPolicy(resolvedDataPolicy); } else if (DataPolicy.PERSISTENT_REPLICATE.equals(dataPolicy) && RegionShortcutWrapper.valueOf(getShortcut()).isPersistent()) { regionFactory.setDataPolicy(dataPolicy); setDataPolicy(dataPolicy); } else { throw newIllegalArgumentException("Data Policy [%s] is not supported for Local Regions", dataPolicy); } } @Override void setScope(Scope scope); @Override void afterPropertiesSet(); } | @Test public void testResolveDataPolicyWhenPersistentUnspecifiedAndDataPolicyUnspecified() { RegionFactory mockRegionFactory = createMockRegionFactory(); factoryBean.resolveDataPolicy(mockRegionFactory, null, (String) null); verify(mockRegionFactory).setDataPolicy(eq(DataPolicy.NORMAL)); }
@Test public void testResolveDataPolicyWhenNotPersistentAndDataPolicyUnspecified() { RegionFactory mockRegionFactory = createMockRegionFactory(); factoryBean.setPersistent(false); factoryBean.resolveDataPolicy(mockRegionFactory, false, (String) null); verify(mockRegionFactory).setDataPolicy(eq(DataPolicy.NORMAL)); }
@Test public void testResolveDataPolicyWhenPersistentAndDataPolicyUnspecified() { RegionFactory mockRegionFactory = createMockRegionFactory(); factoryBean.setPersistent(true); factoryBean.resolveDataPolicy(mockRegionFactory, true, (String) null); verify(mockRegionFactory).setDataPolicy(eq(DataPolicy.PERSISTENT_REPLICATE)); }
@Test(expected = IllegalArgumentException.class) public void testResolveDataPolicyWithBlankDataPolicy() { RegionFactory mockRegionFactory = createMockRegionFactory(); try { factoryBean.resolveDataPolicy(mockRegionFactory, null, " "); } catch (IllegalArgumentException e) { assertEquals("Data Policy [ ] is invalid", e.getMessage()); throw e; } finally { verify(mockRegionFactory, never()).setDataPolicy(null); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.NORMAL)); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.PERSISTENT_REPLICATE)); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.PRELOADED)); } }
@Test(expected = IllegalArgumentException.class) public void testResolveDataPolicyWithEmptyDataPolicy() { RegionFactory mockRegionFactory = createMockRegionFactory(); try { factoryBean.resolveDataPolicy(mockRegionFactory, null, ""); } catch (IllegalArgumentException e) { assertEquals("Data Policy [] is invalid", e.getMessage()); throw e; } finally { verify(mockRegionFactory, never()).setDataPolicy(null); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.NORMAL)); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.PERSISTENT_REPLICATE)); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.PRELOADED)); } }
@Test(expected = IllegalArgumentException.class) public void testResolveDataPolicyWithInvalidDataPolicyName() { RegionFactory mockRegionFactory = createMockRegionFactory(); try { factoryBean.resolveDataPolicy(mockRegionFactory, null, "INVALID_DATA_POLICY_NAME"); } catch (IllegalArgumentException e) { assertEquals("Data Policy [INVALID_DATA_POLICY_NAME] is invalid", e.getMessage()); throw e; } finally { verify(mockRegionFactory, never()).setDataPolicy(null); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.NORMAL)); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.PERSISTENT_REPLICATE)); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.PRELOADED)); } }
@Test(expected = IllegalArgumentException.class) public void testResolveDataPolicyWithInvalidDataPolicyType() { RegionFactory mockRegionFactory = createMockRegionFactory(); try { factoryBean.resolveDataPolicy(mockRegionFactory, null, "PARTITION"); } catch (IllegalArgumentException e) { assertEquals("Data Policy [PARTITION] is not supported for Local Regions", e.getMessage()); throw e; } finally { verify(mockRegionFactory, never()).setDataPolicy(null); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.NORMAL)); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.PERSISTENT_REPLICATE)); verify(mockRegionFactory, never()).setDataPolicy(eq(DataPolicy.PRELOADED)); } }
@Test public void testResolveDataPolicyWhenPersistentUnspecifiedAndNormalDataPolicy() { RegionFactory mockRegionFactory = createMockRegionFactory(); factoryBean.resolveDataPolicy(mockRegionFactory, null, "Normal"); verify(mockRegionFactory).setDataPolicy(eq(DataPolicy.NORMAL)); }
@Test public void testResolveDataPolicyWhenNotPersistentAndNormalDataPolicy() { RegionFactory mockRegionFactory = createMockRegionFactory(); factoryBean.setPersistent(false); factoryBean.resolveDataPolicy(mockRegionFactory, false, "NORMAL"); verify(mockRegionFactory).setDataPolicy(eq(DataPolicy.NORMAL)); }
@Test public void testResolveDataPolicyWhenPersistentAndNormalDataPolicy() { RegionFactory mockRegionFactory = createMockRegionFactory(); factoryBean.setPersistent(true); factoryBean.resolveDataPolicy(mockRegionFactory, true, "NORMAL"); verify(mockRegionFactory).setDataPolicy(eq(DataPolicy.PERSISTENT_REPLICATE)); }
@Test public void testResolveDataPolicyWhenPersistentUnspecifiedAndPreloadedDataPolicy() { RegionFactory mockRegionFactory = createMockRegionFactory(); factoryBean.resolveDataPolicy(mockRegionFactory, null, "preloaded"); verify(mockRegionFactory).setDataPolicy(eq(DataPolicy.PRELOADED)); }
@Test public void testResolveDataPolicyWhenNotPersistentAndPreloadedDataPolicy() { RegionFactory mockRegionFactory = createMockRegionFactory(); factoryBean.setPersistent(false); factoryBean.resolveDataPolicy(mockRegionFactory, false, "PreLoaded"); verify(mockRegionFactory).setDataPolicy(eq(DataPolicy.PRELOADED)); }
@Test public void testResolveDataPolicyWhenPersistentAndPreloadedDataPolicy() { RegionFactory mockRegionFactory = createMockRegionFactory(); factoryBean.setPersistent(true); factoryBean.resolveDataPolicy(mockRegionFactory, true, "PRELOADED"); verify(mockRegionFactory).setDataPolicy(eq(DataPolicy.PERSISTENT_REPLICATE)); }
@Test(expected = IllegalArgumentException.class) public void testResolveDataPolicyWhenShortcutIsNullAndPersistentReplicateDataPolicy() { RegionFactory mockRegionFactory = createMockRegionFactory(); try { factoryBean.setShortcut(null); factoryBean.resolveDataPolicy(mockRegionFactory, null, DataPolicy.PERSISTENT_REPLICATE); } catch (IllegalArgumentException expected) { assertEquals("Data Policy [PERSISTENT_REPLICATE] is not supported for Local Regions", expected.getMessage()); throw expected; } finally { verify(mockRegionFactory, never()).setDataPolicy(null); verify(mockRegionFactory, never()).setDataPolicy(DataPolicy.NORMAL); verify(mockRegionFactory, never()).setDataPolicy(DataPolicy.PRELOADED); verify(mockRegionFactory, never()).setDataPolicy(DataPolicy.PERSISTENT_REPLICATE); } }
@Test(expected = IllegalArgumentException.class) public void testResolveDataPolicyWhenShortcutNotPersistentAndPersistentReplicateDataPolicy() { RegionFactory mockRegionFactory = createMockRegionFactory(); try { factoryBean.setShortcut(RegionShortcut.LOCAL_OVERFLOW); factoryBean.resolveDataPolicy(mockRegionFactory, true, DataPolicy.PERSISTENT_REPLICATE); } catch (IllegalArgumentException expected) { assertEquals("Data Policy [PERSISTENT_REPLICATE] is not supported for Local Regions", expected.getMessage()); throw expected; } finally { verify(mockRegionFactory, never()).setDataPolicy(null); verify(mockRegionFactory, never()).setDataPolicy(DataPolicy.NORMAL); verify(mockRegionFactory, never()).setDataPolicy(DataPolicy.PRELOADED); verify(mockRegionFactory, never()).setDataPolicy(DataPolicy.PERSISTENT_REPLICATE); } }
@Test public void testResolveDataPolicyWhenPersistentPersistentReplicateDataPolicy() { RegionFactory mockRegionFactory = createMockRegionFactory(); factoryBean.setShortcut(RegionShortcut.LOCAL_PERSISTENT_OVERFLOW); factoryBean.resolveDataPolicy(mockRegionFactory, false, DataPolicy.PERSISTENT_REPLICATE); verify(mockRegionFactory).setDataPolicy(DataPolicy.PERSISTENT_REPLICATE); } |
BatchingResultSender { public void sendArrayResults(Object result) { Assert.isTrue(ObjectUtils.isArray(result), () -> String.format("Object must be an array; was [%s]", ObjectUtils.nullSafeClassName(result))); int arrayLength = Array.getLength(result); ResultSender<Object> resultSender = getResultSender(); if (doNotSendChunks(arrayLength == 0)) { resultSender.lastResult(result); } else { int batchSize = getBatchSize(); for (int from = 0; from < arrayLength; from += batchSize) { int to = Math.min(arrayLength, from + batchSize); Object chunk = copyOfRange(result, from, to); if (to == arrayLength) { resultSender.lastResult(chunk); } else { resultSender.sendResult(chunk); } } } } BatchingResultSender(int batchSize, ResultSender<Object> resultSender); int getBatchSize(); ResultSender<Object> getResultSender(); void sendResults(Iterable<?> result); void sendArrayResults(Object result); } | @SuppressWarnings("unchecked") @Test(expected = IllegalArgumentException.class) public void sendArrayResultsWithNonArrayThrowIllegalArgumentException() { try { new BatchingResultSender(20, mock(ResultSender.class)).sendArrayResults(new Object()); } catch (IllegalArgumentException expected) { assertThat(expected).hasMessage("Object must be an array; was [java.lang.Object]"); assertThat(expected).hasNoCause(); throw expected; } } |
AbstractFunctionExecution { <T> T executeAndExtract() { Iterable<T> results = execute(); if (isEmpty(results)) { return null; } T result = results.iterator().next(); return throwOnExceptionOrReturn(result); } @SuppressWarnings("rawtypes") AbstractFunctionExecution(Function function, Object... arguments); AbstractFunctionExecution(String functionId, Object... arguments); AbstractFunctionExecution(); } | @Test public void executeAndExtractWithSingleResult() { List<String> results = Collections.singletonList("test"); AbstractFunctionExecution functionExecution = new AbstractFunctionExecution() { @Override protected Execution getExecution() { return mockExecution; } @SuppressWarnings("unchecked") @Override <T> Iterable<T> execute() { return (Iterable<T>) results; } }; assertThat(functionExecution.<String>executeAndExtract()).isEqualTo("test"); }
@Test public void executeAndExtractWithMultipleResults() { List<String> results = Arrays.asList("one", "two", "three"); AbstractFunctionExecution functionExecution = new AbstractFunctionExecution() { @Override protected Execution getExecution() { return mockExecution; } @SuppressWarnings("unchecked") @Override <T> Iterable<T> execute() { return (Iterable<T>) results; } }; assertThat(functionExecution.<String>executeAndExtract()).isEqualTo("one"); }
@Test public void executeAndExtractWithNullResults() { AbstractFunctionExecution functionExecution = new AbstractFunctionExecution() { @Override protected Execution getExecution() { return mockExecution; } @Override <T> Iterable<T> execute() { return null; } }; assertThat((Object) functionExecution.executeAndExtract()).isNull(); }
@Test public void executeAndExtractWithNoResults() { AbstractFunctionExecution functionExecution = new AbstractFunctionExecution() { @Override protected Execution getExecution() { return mockExecution; } @Override <T> Iterable<T> execute() { return Collections.emptyList(); } }; assertThat((Object) functionExecution.executeAndExtract()).isNull(); } |
PdxFunctionArgumentResolver extends DefaultFunctionArgumentResolver { @Override public Object[] resolveFunctionArguments(final FunctionContext functionContext) { Object[] functionArguments = super.resolveFunctionArguments(functionContext); if (isPdxSerializerConfigured()) { int index = 0; for (Object functionArgument : functionArguments) { if (functionArgument instanceof PdxInstance) { String className = ((PdxInstance) functionArgument).getClassName(); if (isDeserializationNecessary(className)) { functionArguments[index] = ((PdxInstance) functionArgument).getObject(); } } index++; } } return functionArguments; } @Override Object[] resolveFunctionArguments(final FunctionContext functionContext); @Override Method getFunctionAnnotatedMethod(); } | @Test public void testResolveSimpleFunctionArguments() { functionArgumentResolver = new PdxFunctionArgumentResolver() { @Override public Method getFunctionAnnotatedMethod() { return getMethod(FunctionExecutions.class, "simpleMethod", Boolean.class, Character.class, Integer.class, Double.class, String.class); } }; Object[] expectedArguments = { Boolean.TRUE, 'C', 123, Math.PI, "TEST" }; FunctionContext mockFunctionContext = mock(FunctionContext.class, "testResolveSimpleFunctionArguments"); when(mockFunctionContext.getArguments()).thenReturn(expectedArguments); Object[] actualArguments = functionArgumentResolver.resolveFunctionArguments(mockFunctionContext); assertArguments(expectedArguments, actualArguments); }
@Test public void testResolveNonSerializedApplicationDomainTypeFunctionArguments() { functionArgumentResolver = new PdxFunctionArgumentResolver() { @Override public Method getFunctionAnnotatedMethod() { return getMethod(FunctionExecutions.class, "nonSerializedMethod", Boolean.class, Person.class, Character.class, Person.class, Integer.class, Double.class, Gender.class, String.class); } }; Object[] expectedArguments = { Boolean.TRUE, createPerson("Jon", "Doe", Gender.MALE), 'C', createPerson("Jane", "Doe", Gender.FEMALE), 123, Math.PI, Gender.FEMALE, "test" }; FunctionContext mockFunctionContext = mock(FunctionContext.class, "testResolveNonSerializedApplicationDomainTypeFunctionArguments"); when(mockFunctionContext.getArguments()).thenReturn(expectedArguments); Object[] actualArguments = functionArgumentResolver.resolveFunctionArguments(mockFunctionContext); assertArguments(expectedArguments, actualArguments); }
@Test public void testResolveSerializedApplicationDomainTypeFunctionArguments() { functionArgumentResolver = new PdxFunctionArgumentResolver() { @Override public Method getFunctionAnnotatedMethod() { return getMethod(FunctionExecutions.class, "serializedMethod", Boolean.class, Person.class, String.class, Gender.class); } }; Person jackHandy = createPerson("Jack", "Handy", Gender.MALE); Object[] serializedArguments = { Boolean.TRUE, toPdxInstance(jackHandy), "test", toPdxInstance(Gender.MALE) }; Object[] expectedArguments = { Boolean.TRUE, jackHandy, "test", Gender.MALE }; FunctionContext mockFunctionContext = mock(FunctionContext.class, "testResolveSerializedApplicationDomainTypeFunctionArguments"); when(mockFunctionContext.getArguments()).thenReturn(serializedArguments); Object[] actualArguments = functionArgumentResolver.resolveFunctionArguments(mockFunctionContext); assertArguments(expectedArguments, actualArguments); }
@Test public void testResolveUnnecessaryDeserializationFunctionArguments() { functionArgumentResolver = new PdxFunctionArgumentResolver() { @Override public Method getFunctionAnnotatedMethod() { return getMethod(FunctionExecutions.class, "unnecessaryDeserializationMethod", Boolean.class, Object.class, String.class, PdxInstanceEnum.class); } }; Person sandyHandy = createPerson("Sandy", "Handy", Gender.FEMALE); Object[] expectedArguments = { Boolean.TRUE, toPdxInstance(sandyHandy), "test", toPdxInstance(Gender.FEMALE) }; FunctionContext mockFunctionContext = mock(FunctionContext.class, "testResolveUnnecessaryDeserializationFunctionArguments"); when(mockFunctionContext.getArguments()).thenReturn(expectedArguments); Object[] actualArguments = functionArgumentResolver.resolveFunctionArguments(mockFunctionContext); assertArguments(expectedArguments, actualArguments); }
@Test public void testResolveUnresolvableApplicationDomainTypeFunctionArguments() { functionArgumentResolver = new PdxFunctionArgumentResolver() { @Override public Method getFunctionAnnotatedMethod() { return getMethod(FunctionExecutions.class, "unresolvableMethod", String.class, Object.class); } }; Map<String, Object> addressData = new HashMap<>(5); addressData.put("@type", "org.example.Address"); addressData.put("street", "100 Main St."); addressData.put("city", "Portland"); addressData.put("state", "OR"); addressData.put("zip", "12345"); Object[] expectedArguments = { "test", toPdxInstance(addressData) }; FunctionContext mockFunctionContext = mock(FunctionContext.class, "testResolveUnresolvableApplicationDomainTypeFunctionArguments"); when(mockFunctionContext.getArguments()).thenReturn(expectedArguments); Object[] actualArguments = functionArgumentResolver.resolveFunctionArguments(mockFunctionContext); assertArguments(expectedArguments, actualArguments); } |
ExpirationAttributesFactoryBean implements FactoryBean<ExpirationAttributes>, InitializingBean { @Override public boolean isSingleton() { return true; } @Override ExpirationAttributes getObject(); @Override Class<?> getObjectType(); @Override boolean isSingleton(); void setAction(final ExpirationAction action); ExpirationAction getAction(); void setTimeout(final Integer timeout); int getTimeout(); @Override void afterPropertiesSet(); } | @Test public void testIsSingleton() { assertTrue(new ExpirationAttributesFactoryBean().isSingleton()); } |
CallableCacheLoaderAdapter implements Callable<V>, CacheLoader<K, V> { public void close() { getCacheLoader().close(); } CallableCacheLoaderAdapter(CacheLoader<K, V> delegate); CallableCacheLoaderAdapter(CacheLoader<K, V> delegate, K key, Region<K, V> region); CallableCacheLoaderAdapter(CacheLoader<K, V> delegate, K key, Region<K, V> region, Object argument); final V call(); void close(); V load(LoaderHelper<K, V> loaderHelper); } | @Test public void closeDelegatesToCacheLoaderClose() { new CallableCacheLoaderAdapter<>(mockCacheLoader).close(); verify(mockCacheLoader, times(1)).close(); } |
CallableCacheLoaderAdapter implements Callable<V>, CacheLoader<K, V> { public V load(LoaderHelper<K, V> loaderHelper) throws CacheLoaderException { return getCacheLoader().load(loaderHelper); } CallableCacheLoaderAdapter(CacheLoader<K, V> delegate); CallableCacheLoaderAdapter(CacheLoader<K, V> delegate, K key, Region<K, V> region); CallableCacheLoaderAdapter(CacheLoader<K, V> delegate, K key, Region<K, V> region, Object argument); final V call(); void close(); V load(LoaderHelper<K, V> loaderHelper); } | @Test public void loadDelegatesToCacheLoaderLoad() { CallableCacheLoaderAdapter<String, Object> instance = new CallableCacheLoaderAdapter<>(mockCacheLoader); when(mockCacheLoader.load(eq(mockLoaderHelper))).thenReturn("test"); assertThat(instance.load(mockLoaderHelper), is(equalTo("test"))); verify(mockCacheLoader, times(1)).load(eq(mockLoaderHelper)); } |
DiskStoreFactoryBean extends AbstractFactoryBeanSupport<DiskStore> implements InitializingBean { protected void validateCompactionThreshold(Integer compactionThreshold) { Assert.isTrue(compactionThreshold == null || (compactionThreshold >= 0 && compactionThreshold <= 100), String.format("The DiskStore's (%1$s) compaction threshold (%2$d) must be an integer value between 0 and 100 inclusive.", resolveDiskStoreName(), compactionThreshold)); } @Override void afterPropertiesSet(); @Override DiskStore getObject(); @Override Class<?> getObjectType(); void setCache(GemFireCache cache); void setAllowForceCompaction(Boolean allowForceCompaction); void setAutoCompact(Boolean autoCompact); void setCompactionThreshold(Integer compactionThreshold); void setDiskDirs(List<DiskDir> diskDirs); void setDiskStoreConfigurers(DiskStoreConfigurer... diskStoreConfigurers); void setDiskStoreConfigurers(List<DiskStoreConfigurer> diskStoreConfigurers); void setDiskUsageCriticalPercentage(Float diskUsageCriticalPercentage); void setDiskUsageWarningPercentage(Float diskUsageWarningPercentage); void setMaxOplogSize(Long maxOplogSize); void setQueueSize(Integer queueSize); void setTimeInterval(Long timeInterval); void setWriteBufferSize(Integer writeBufferSize); } | @Test public void testValidateCompactionThresholdWhenNull() { factoryBean.validateCompactionThreshold(null); }
@Test public void testValidateCompactionThresholdWhenValid() { factoryBean.validateCompactionThreshold(0); factoryBean.validateCompactionThreshold(50); factoryBean.validateCompactionThreshold(100); } |
DiskStoreFactoryBean extends AbstractFactoryBeanSupport<DiskStore> implements InitializingBean { public void setCompactionThreshold(Integer compactionThreshold) { validateCompactionThreshold(compactionThreshold); this.compactionThreshold = compactionThreshold; } @Override void afterPropertiesSet(); @Override DiskStore getObject(); @Override Class<?> getObjectType(); void setCache(GemFireCache cache); void setAllowForceCompaction(Boolean allowForceCompaction); void setAutoCompact(Boolean autoCompact); void setCompactionThreshold(Integer compactionThreshold); void setDiskDirs(List<DiskDir> diskDirs); void setDiskStoreConfigurers(DiskStoreConfigurer... diskStoreConfigurers); void setDiskStoreConfigurers(List<DiskStoreConfigurer> diskStoreConfigurers); void setDiskUsageCriticalPercentage(Float diskUsageCriticalPercentage); void setDiskUsageWarningPercentage(Float diskUsageWarningPercentage); void setMaxOplogSize(Long maxOplogSize); void setQueueSize(Integer queueSize); void setTimeInterval(Long timeInterval); void setWriteBufferSize(Integer writeBufferSize); } | @Test public void testSetCompactionThreshold() { factoryBean.setCompactionThreshold(75); } |
DiskStoreFactoryBean extends AbstractFactoryBeanSupport<DiskStore> implements InitializingBean { @Override public void afterPropertiesSet() throws Exception { String diskStoreName = resolveDiskStoreName(); applyDiskStoreConfigurers(diskStoreName); GemFireCache cache = resolveCache(diskStoreName); DiskStoreFactory diskStoreFactory = postProcess(configure(createDiskStoreFactory(cache))); this.diskStore = postProcess(newDiskStore(diskStoreFactory, diskStoreName)); } @Override void afterPropertiesSet(); @Override DiskStore getObject(); @Override Class<?> getObjectType(); void setCache(GemFireCache cache); void setAllowForceCompaction(Boolean allowForceCompaction); void setAutoCompact(Boolean autoCompact); void setCompactionThreshold(Integer compactionThreshold); void setDiskDirs(List<DiskDir> diskDirs); void setDiskStoreConfigurers(DiskStoreConfigurer... diskStoreConfigurers); void setDiskStoreConfigurers(List<DiskStoreConfigurer> diskStoreConfigurers); void setDiskUsageCriticalPercentage(Float diskUsageCriticalPercentage); void setDiskUsageWarningPercentage(Float diskUsageWarningPercentage); void setMaxOplogSize(Long maxOplogSize); void setQueueSize(Integer queueSize); void setTimeInterval(Long timeInterval); void setWriteBufferSize(Integer writeBufferSize); } | @Test(expected = IllegalStateException.class) public void testAfterPropertiesSetWithNoCacheReference() throws Exception { try { factoryBean.afterPropertiesSet(); } catch (IllegalStateException expected) { assertEquals("Cache is required to create DiskStore [testDiskStore]", expected.getMessage()); throw expected; } } |
Regions implements Iterable<Region<?, ?>> { @SuppressWarnings("unchecked") public <T> Region<?, T> getRegion(Class<T> entityType) { Assert.notNull(entityType, "Entity type must not be null"); String regionName = Optional.ofNullable(this.mappingContext.getPersistentEntity(entityType)) .map(entity -> entity.getRegionName()) .orElseGet(entityType::getSimpleName); return (Region<?, T>) this.regions.get(regionName); } Regions(Iterable<Region<?, ?>> regions,
MappingContext<? extends GemfirePersistentEntity<?>, ?> mappingContext); @SuppressWarnings("unchecked") Region<?, T> getRegion(Class<T> entityType); @SuppressWarnings("unchecked") Region<S, T> getRegion(String namePath); @Override Iterator<Region<?, ?>> iterator(); } | @Test public void getRegionByEntityTypeReturnsRegionForEntityRegionName() { GemfirePersistentEntity<User> mockPersistentEntity = mock(GemfirePersistentEntity.class); when(mockPersistentEntity.getRegionName()).thenReturn("Users"); when(mockMappingContext.getPersistentEntity(eq(User.class))).thenReturn(mockPersistentEntity); assertThat(regions.getRegion(User.class)).isEqualTo(mockUsers); }
@Test public void getRegionByEntityTypeReturnsRegionForEntityTypeSimpleName() { when(mockMappingContext.getPersistentEntity(any(Class.class))).thenReturn(null); assertThat(regions.getRegion(Users.class)).isEqualTo(mockUsers); }
@Test public void getRegionByEntityTypeReturnsNull() { when(mockMappingContext.getPersistentEntity(any(Class.class))).thenReturn(null); assertThat(regions.getRegion(Object.class)).isNull(); }
@Test public void getRegionWithNullEntityTypeThrowsIllegalArgumentException() { exception.expect(IllegalArgumentException.class); exception.expectCause(is(nullValue(Throwable.class))); exception.expectMessage("Entity type must not be null"); regions.getRegion((Class) null); }
@Test public void getRegionWithNameReturnsRegion() { assertThat(regions.getRegion("Users")).isSameAs(mockUsers); assertThat(regions.getRegion("Admin")).isSameAs(mockAdminUsers); assertThat(regions.getRegion("Guest")).isSameAs(mockGuestUsers); }
@Test public void getRegionWithPathReturnsRegion() { assertThat(regions.getRegion("/Users")).isSameAs(mockUsers); assertThat(regions.getRegion("/Users/Admin")).isSameAs(mockAdminUsers); assertThat(regions.getRegion("/Users/Guest")).isSameAs(mockGuestUsers); }
@Test public void getRegionWithNonExistingNameReturnsNull() { assertThat(regions.getRegion("NonExistingRegionName")).isNull(); }
@Test public void getRegionWithNonExistingPathReturnsNull() { assertThat(regions.getRegion("/Non/Existing/Region/Path")).isNull(); }
@Test public void getRegionWithNullNameNullPathThrowsIllegalArgumentException() { exception.expect(IllegalArgumentException.class); exception.expectCause(is(nullValue(Throwable.class))); exception.expectMessage("Region name/path is required"); regions.getRegion((String) null); } |
ExpirationAttributesFactoryBean implements FactoryBean<ExpirationAttributes>, InitializingBean { @Override public void afterPropertiesSet() throws Exception { expirationAttributes = new ExpirationAttributes(getTimeout(), getAction()); } @Override ExpirationAttributes getObject(); @Override Class<?> getObjectType(); @Override boolean isSingleton(); void setAction(final ExpirationAction action); ExpirationAction getAction(); void setTimeout(final Integer timeout); int getTimeout(); @Override void afterPropertiesSet(); } | @Test public void testAfterPropertiesSet() throws Exception { ExpirationAttributesFactoryBean expirationAttributesFactoryBean = new ExpirationAttributesFactoryBean(); assertNull(expirationAttributesFactoryBean.getObject()); assertEquals(ExpirationAttributes.class, expirationAttributesFactoryBean.getObjectType()); expirationAttributesFactoryBean.setAction(ExpirationAction.DESTROY); expirationAttributesFactoryBean.setTimeout(8192); expirationAttributesFactoryBean.afterPropertiesSet(); ExpirationAttributes expirationAttributes = expirationAttributesFactoryBean.getObject(); assertNotNull(expirationAttributes); assertEquals(ExpirationAction.DESTROY, expirationAttributes.getAction()); assertEquals(8192, expirationAttributes.getTimeout()); assertEquals(expirationAttributes.getClass(), expirationAttributesFactoryBean.getObjectType()); } |
DataPolicyConverter implements Converter<String, DataPolicy> { @Override public DataPolicy convert(String policyValue) { Policy policy = Policy.getValue(policyValue); return (policy == null ? null : policy.toDataPolicy()); } @Override DataPolicy convert(String policyValue); } | @Test public void convertDataPolicyStrings() { assertEquals(DataPolicy.EMPTY, converter.convert("empty")); assertEquals(DataPolicy.PARTITION, converter.convert("Partition")); assertEquals(DataPolicy.PERSISTENT_REPLICATE, converter.convert("PERSISTENT_REPLICATE")); assertNull(converter.convert("invalid")); assertNull(converter.convert(null)); } |
CacheServerFactoryBean extends AbstractFactoryBeanSupport<CacheServer> implements DisposableBean, InitializingBean, SmartLifecycle { @Override public CacheServer getObject() { return this.cacheServer; } @Override void afterPropertiesSet(); @Override CacheServer getObject(); @Override Class<?> getObjectType(); boolean isAutoStartup(); boolean isRunning(); int getPhase(); void destroy(); @Override void start(); void stop(); @Override void stop(Runnable callback); void setAutoStartup(boolean autoStartup); void setBindAddress(String bindAddress); void setCache(Cache cache); void setCacheServerConfigurers(CacheServerConfigurer... cacheServerConfigurers); void setCacheServerConfigurers(List<CacheServerConfigurer> cacheServerConfigurers); void setHostNameForClients(String hostNameForClients); void setListeners(Set<InterestRegistrationListener> listeners); void setLoadPollInterval(long loadPollInterval); void setMaxConnections(int maxConnections); void setMaxMessageCount(int maxMessageCount); void setMaxThreads(int maxThreads); void setMaxTimeBetweenPings(int maxTimeBetweenPings); void setMessageTimeToLive(int messageTimeToLive); void setNotifyBySubscription(boolean notifyBySubscription); void setPort(int port); void setServerGroups(String[] serverGroups); void setServerLoadProbe(ServerLoadProbe serverLoadProbe); void setSocketBufferSize(int socketBufferSize); void setSubscriptionCapacity(int subscriptionCapacity); void setSubscriptionDiskStore(String diskStoreName); void setSubscriptionEvictionPolicy(SubscriptionEvictionPolicy evictionPolicy); void setTcpNoDelay(boolean tcpNoDelay); } | @Test public void testGetObjectUninitialized() { assertNull(new CacheServerFactoryBean().getObject()); } |
CacheServerFactoryBean extends AbstractFactoryBeanSupport<CacheServer> implements DisposableBean, InitializingBean, SmartLifecycle { @Override public Class<?> getObjectType() { return this.cacheServer != null ? this.cacheServer.getClass() : CacheServer.class; } @Override void afterPropertiesSet(); @Override CacheServer getObject(); @Override Class<?> getObjectType(); boolean isAutoStartup(); boolean isRunning(); int getPhase(); void destroy(); @Override void start(); void stop(); @Override void stop(Runnable callback); void setAutoStartup(boolean autoStartup); void setBindAddress(String bindAddress); void setCache(Cache cache); void setCacheServerConfigurers(CacheServerConfigurer... cacheServerConfigurers); void setCacheServerConfigurers(List<CacheServerConfigurer> cacheServerConfigurers); void setHostNameForClients(String hostNameForClients); void setListeners(Set<InterestRegistrationListener> listeners); void setLoadPollInterval(long loadPollInterval); void setMaxConnections(int maxConnections); void setMaxMessageCount(int maxMessageCount); void setMaxThreads(int maxThreads); void setMaxTimeBetweenPings(int maxTimeBetweenPings); void setMessageTimeToLive(int messageTimeToLive); void setNotifyBySubscription(boolean notifyBySubscription); void setPort(int port); void setServerGroups(String[] serverGroups); void setServerLoadProbe(ServerLoadProbe serverLoadProbe); void setSocketBufferSize(int socketBufferSize); void setSubscriptionCapacity(int subscriptionCapacity); void setSubscriptionDiskStore(String diskStoreName); void setSubscriptionEvictionPolicy(SubscriptionEvictionPolicy evictionPolicy); void setTcpNoDelay(boolean tcpNoDelay); } | @Test public void testGetObjectType() { assertEquals(CacheServer.class, new CacheServerFactoryBean().getObjectType()); } |
CacheServerFactoryBean extends AbstractFactoryBeanSupport<CacheServer> implements DisposableBean, InitializingBean, SmartLifecycle { @Override public void afterPropertiesSet() throws IOException { applyCacheServerConfigurers(); Cache cache = resolveCache(); this.cacheServer = postProcess(configure(addCacheServer(cache))); } @Override void afterPropertiesSet(); @Override CacheServer getObject(); @Override Class<?> getObjectType(); boolean isAutoStartup(); boolean isRunning(); int getPhase(); void destroy(); @Override void start(); void stop(); @Override void stop(Runnable callback); void setAutoStartup(boolean autoStartup); void setBindAddress(String bindAddress); void setCache(Cache cache); void setCacheServerConfigurers(CacheServerConfigurer... cacheServerConfigurers); void setCacheServerConfigurers(List<CacheServerConfigurer> cacheServerConfigurers); void setHostNameForClients(String hostNameForClients); void setListeners(Set<InterestRegistrationListener> listeners); void setLoadPollInterval(long loadPollInterval); void setMaxConnections(int maxConnections); void setMaxMessageCount(int maxMessageCount); void setMaxThreads(int maxThreads); void setMaxTimeBetweenPings(int maxTimeBetweenPings); void setMessageTimeToLive(int messageTimeToLive); void setNotifyBySubscription(boolean notifyBySubscription); void setPort(int port); void setServerGroups(String[] serverGroups); void setServerLoadProbe(ServerLoadProbe serverLoadProbe); void setSocketBufferSize(int socketBufferSize); void setSubscriptionCapacity(int subscriptionCapacity); void setSubscriptionDiskStore(String diskStoreName); void setSubscriptionEvictionPolicy(SubscriptionEvictionPolicy evictionPolicy); void setTcpNoDelay(boolean tcpNoDelay); } | @Test @SuppressWarnings("deprecation") public void testAfterPropertiesSet() throws IOException { Cache mockCache = mock(Cache.class, "testAfterPropertiesSet.MockCache"); CacheServer mockCacheServer = mock(CacheServer.class, "testAfterPropertiesSet.MockCacheServer"); ClientSubscriptionConfig mockClientSubscriptionConfig = mock(ClientSubscriptionConfig.class, "testAfterPropertiesSet.MockClientSubscriptionConfig"); InterestRegistrationListener mockInterestRegistrationListenerOne = mock(InterestRegistrationListener.class, "testAfterPropertiesSet.MockInterestRegistrationListener.One"); InterestRegistrationListener mockInterestRegistrationListenerTwo = mock(InterestRegistrationListener.class, "testAfterPropertiesSet.MockInterestRegistrationListener.Two"); ServerLoadProbe mockServerLoadProbe = mock(ServerLoadProbe.class, "testAfterPropertiesSet.MockServerLoadProbe"); when(mockCache.addCacheServer()).thenReturn(mockCacheServer); when(mockCacheServer.getClientSubscriptionConfig()).thenReturn(mockClientSubscriptionConfig); CacheServerFactoryBean factoryBean = new CacheServerFactoryBean(); factoryBean.setCache(mockCache); factoryBean.setBindAddress("10.124.62.5"); factoryBean.setHostNameForClients("skullbox"); factoryBean.setListeners(new HashSet<InterestRegistrationListener>(Arrays.asList( mockInterestRegistrationListenerOne, mockInterestRegistrationListenerTwo))); factoryBean.setLoadPollInterval(500l); factoryBean.setMaxConnections(200); factoryBean.setMaxMessageCount(1024); factoryBean.setMaxTimeBetweenPings(2000); factoryBean.setMaxThreads(50); factoryBean.setMessageTimeToLive(8192); factoryBean.setNotifyBySubscription(true); factoryBean.setPort(54321); factoryBean.setServerGroups(new String[] { "testGroup" }); factoryBean.setServerLoadProbe(mockServerLoadProbe); factoryBean.setSocketBufferSize(4096); factoryBean.setSubscriptionCapacity(8196); factoryBean.setSubscriptionEvictionPolicy(SubscriptionEvictionPolicy.ENTRY); factoryBean.setSubscriptionDiskStore("toTheVoid"); factoryBean.afterPropertiesSet(); assertSame(mockCacheServer, factoryBean.getObject()); assertEquals(mockCacheServer.getClass(), factoryBean.getObjectType()); verify(mockCache, times(1)).addCacheServer(); verify(mockCacheServer, times(1)).setBindAddress(eq("10.124.62.5")); verify(mockCacheServer, times(1)).setGroups(eq(new String[] { "testGroup" })); verify(mockCacheServer, times(1)).setHostnameForClients(eq("skullbox")); verify(mockCacheServer, times(1)).setLoadPollInterval(eq(500l)); verify(mockCacheServer, times(1)).setLoadProbe(same(mockServerLoadProbe)); verify(mockCacheServer, times(1)).setMaxConnections(eq(200)); verify(mockCacheServer, times(1)).setMaximumMessageCount(eq(1024)); verify(mockCacheServer, times(1)).setMaximumTimeBetweenPings(eq(2000)); verify(mockCacheServer, times(1)).setMaxThreads(eq(50)); verify(mockCacheServer, times(1)).setMessageTimeToLive(eq(8192)); verify(mockCacheServer, times(1)).setNotifyBySubscription(eq(true)); verify(mockCacheServer, times(1)).setPort(eq(54321)); verify(mockCacheServer, times(1)).setSocketBufferSize(eq(4096)); verify(mockCacheServer, times(1)).registerInterestRegistrationListener( same(mockInterestRegistrationListenerOne)); verify(mockCacheServer, times(1)).registerInterestRegistrationListener( same(mockInterestRegistrationListenerTwo)); verify(mockCacheServer, times(1)).getClientSubscriptionConfig(); verify(mockClientSubscriptionConfig, times(1)).setCapacity(eq(8196)); verify(mockClientSubscriptionConfig, times(1)).setDiskStoreName(eq("toTheVoid")); verify(mockClientSubscriptionConfig, times(1)).setEvictionPolicy("entry"); }
@Test(expected = IllegalArgumentException.class) public void testAfterPropertiesSetWithNullCache() throws IOException { try { new CacheServerFactoryBean().afterPropertiesSet(); } catch (IllegalArgumentException expected) { assertEquals("Cache is required", expected.getMessage()); throw expected; } } |
CacheFactoryBean extends AbstractFactoryBeanSupport<GemFireCache> implements DisposableBean, InitializingBean, PersistenceExceptionTranslator, Phased { @Override public GemFireCache getObject() throws Exception { return Optional.<GemFireCache>ofNullable(getCache()).orElseGet(this::init); } @Override void afterPropertiesSet(); @Override void destroy(); @Override DataAccessException translateExceptionIfPossible(RuntimeException exception); GemfireBeanFactoryLocator getBeanFactoryLocator(); void setCacheXml(Resource cacheXml); Resource getCacheXml(); @Override GemFireCache getObject(); @Override Class<? extends GemFireCache> getObjectType(); @SuppressWarnings("rawtypes") void setCacheFactoryInitializer(CacheFactoryInitializer cacheFactoryInitializer); @SuppressWarnings("rawtypes") CacheFactoryInitializer getCacheFactoryInitializer(); void setProperties(Properties properties); Properties getProperties(); void setClose(boolean close); boolean isClose(); PeerCacheConfigurer getCompositePeerCacheConfigurer(); void setCopyOnRead(Boolean copyOnRead); Boolean getCopyOnRead(); void setCriticalHeapPercentage(Float criticalHeapPercentage); Float getCriticalHeapPercentage(); void setCriticalOffHeapPercentage(Float criticalOffHeapPercentage); Float getCriticalOffHeapPercentage(); void setEnableAutoReconnect(Boolean enableAutoReconnect); Boolean getEnableAutoReconnect(); void setEvictionHeapPercentage(Float evictionHeapPercentage); Float getEvictionHeapPercentage(); void setEvictionOffHeapPercentage(Float evictionOffHeapPercentage); Float getEvictionOffHeapPercentage(); void setGatewayConflictResolver(GatewayConflictResolver gatewayConflictResolver); GatewayConflictResolver getGatewayConflictResolver(); void setJndiDataSources(List<JndiDataSource> jndiDataSources); List<JndiDataSource> getJndiDataSources(); void setLockLease(Integer lockLease); Integer getLockLease(); void setLockTimeout(Integer lockTimeout); Integer getLockTimeout(); void setMessageSyncInterval(Integer messageSyncInterval); Integer getMessageSyncInterval(); @Override int getPhase(); void setPdxDiskStoreName(String pdxDiskStoreName); String getPdxDiskStoreName(); void setPdxIgnoreUnreadFields(Boolean pdxIgnoreUnreadFields); Boolean getPdxIgnoreUnreadFields(); void setPdxPersistent(Boolean pdxPersistent); Boolean getPdxPersistent(); void setPdxReadSerialized(Boolean pdxReadSerialized); Boolean getPdxReadSerialized(); void setPdxSerializer(PdxSerializer serializer); PdxSerializer getPdxSerializer(); void setPeerCacheConfigurers(PeerCacheConfigurer... peerCacheConfigurers); void setPeerCacheConfigurers(List<PeerCacheConfigurer> peerCacheConfigurers); void setSearchTimeout(Integer searchTimeout); Integer getSearchTimeout(); void setSecurityManager(SecurityManager securityManager); SecurityManager getSecurityManager(); void setTransactionListeners(List<TransactionListener> transactionListeners); List<TransactionListener> getTransactionListeners(); void setTransactionWriter(TransactionWriter transactionWriter); TransactionWriter getTransactionWriter(); void setUseBeanFactoryLocator(boolean use); boolean isUseBeanFactoryLocator(); void setUseClusterConfiguration(Boolean useSharedConfiguration); Boolean getUseClusterConfiguration(); } | @Test public void getObjectCallsInit() throws Exception { AtomicBoolean initCalled = new AtomicBoolean(false); Cache mockCache = mock(Cache.class); CacheFactoryBean cacheFactoryBean = new CacheFactoryBean() { @Override Cache init() { initCalled.set(true); return mockCache; } }; assertThat(cacheFactoryBean.getObject(), is(sameInstance(mockCache))); assertThat(initCalled.get(), is(true)); verifyZeroInteractions(mockCache); } |
ComposableSnapshotFilter implements SnapshotFilter<K, V> { @SuppressWarnings("unchecked") protected static <K, V> SnapshotFilter<K, V> compose(Operator operator, SnapshotFilter<K, V>... snapshotFilters) { SnapshotFilter<K, V> composedSnapshotFilter = null; for (SnapshotFilter<K, V> snapshotFilter : nullSafeArray(snapshotFilters, SnapshotFilter.class)) { composedSnapshotFilter = (composedSnapshotFilter == null ? snapshotFilter : new ComposableSnapshotFilter<K, V>(snapshotFilter, operator, composedSnapshotFilter)); } return composedSnapshotFilter; } private ComposableSnapshotFilter(SnapshotFilter<K, V> leftOperand, Operator operator, SnapshotFilter<K, V> rightOperand); static SnapshotFilter<K, V> and(SnapshotFilter<K, V>... snapshotFilters); static SnapshotFilter<K, V> or(SnapshotFilter<K, V>... snapshotFilters); @Override boolean accept(final Map.Entry<K, V> entry); } | @Test public void composeSingle() { SnapshotFilter mockSnapshotFilter = mockSnapshotFilter(false); SnapshotFilter composedFilter = ComposableSnapshotFilter.compose(Operator.AND, mockSnapshotFilter); assertThat(composedFilter, is(sameInstance(mockSnapshotFilter))); }
@Test public void composeMultiple() throws Exception { SnapshotFilter mockSnapshotFilterOne = mockSnapshotFilter(false); SnapshotFilter mockSnapshotFilterTwo = mockSnapshotFilter(true); SnapshotFilter composedFilter = ComposableSnapshotFilter.compose(Operator.AND, mockSnapshotFilterOne, mockSnapshotFilterTwo); assertThat(composedFilter, is(not(sameInstance(mockSnapshotFilterOne)))); assertThat(composedFilter, is(not(sameInstance(mockSnapshotFilterTwo)))); assertThat((ComposableSnapshotFilter) composedFilter, isA(ComposableSnapshotFilter.class)); assertThat((SnapshotFilter) TestUtils.readField("leftOperand", composedFilter), is(equalTo(mockSnapshotFilterTwo))); assertThat((Operator) TestUtils.readField("operator", composedFilter), is(equalTo(Operator.AND))); assertThat((SnapshotFilter) TestUtils.readField("rightOperand", composedFilter), is(equalTo(mockSnapshotFilterOne))); } |
SnapshotServiceFactoryBean extends AbstractFactoryBeanSupport<SnapshotServiceAdapter<K, V>> implements InitializingBean, DisposableBean, ApplicationListener<SnapshotApplicationEvent<K, V>> { static boolean nullSafeIsDirectory(File file) { return file != null && file.isDirectory(); } @Override @SuppressWarnings("unchecked") void afterPropertiesSet(); void setCache(Cache cache); void setExports(SnapshotMetadata<K, V>[] exports); void setImports(SnapshotMetadata<K, V>[] imports); void setRegion(Region<K, V> region); void setSuppressImportOnInit(Boolean suppressImportOnInit); @Override SnapshotServiceAdapter<K, V> getObject(); @Override @SuppressWarnings("unchecked") Class<?> getObjectType(); @Override boolean isSingleton(); @Override @SuppressWarnings("all") void destroy(); @Override @SuppressWarnings("all") void onApplicationEvent(SnapshotApplicationEvent<K, V> event); } | @Test public void nullSafeIsDirectoryWithDirectory() { assertThat(SnapshotServiceFactoryBean.nullSafeIsDirectory(new File(System.getProperty("user.dir"))), is(true)); }
@Test public void nullSafeIsDirectoryWithNonDirectories() { assertThat(SnapshotServiceFactoryBean.nullSafeIsDirectory(new File("path/to/non-existing/directory")), is(false)); assertThat(SnapshotServiceFactoryBean.nullSafeIsDirectory(FileSystemUtils.JAVA_EXE), is(false)); } |
SnapshotServiceFactoryBean extends AbstractFactoryBeanSupport<SnapshotServiceAdapter<K, V>> implements InitializingBean, DisposableBean, ApplicationListener<SnapshotApplicationEvent<K, V>> { static boolean nullSafeIsFile(File file) { return file != null && file.isFile(); } @Override @SuppressWarnings("unchecked") void afterPropertiesSet(); void setCache(Cache cache); void setExports(SnapshotMetadata<K, V>[] exports); void setImports(SnapshotMetadata<K, V>[] imports); void setRegion(Region<K, V> region); void setSuppressImportOnInit(Boolean suppressImportOnInit); @Override SnapshotServiceAdapter<K, V> getObject(); @Override @SuppressWarnings("unchecked") Class<?> getObjectType(); @Override boolean isSingleton(); @Override @SuppressWarnings("all") void destroy(); @Override @SuppressWarnings("all") void onApplicationEvent(SnapshotApplicationEvent<K, V> event); } | @Test public void nullSafeIsFileWithFile() { assertThat(SnapshotServiceFactoryBean.nullSafeIsFile(FileSystemUtils.JAVA_EXE), is(FileSystemUtils.JAVA_EXE.isFile())); }
@Test public void nullSafeIsFileWithNonFiles() { assertThat(SnapshotServiceFactoryBean.nullSafeIsFile(new File("/path/to/non-existing/file.ext")), is(false)); assertThat(SnapshotServiceFactoryBean.nullSafeIsFile(new File(System.getProperty("user.dir"))), is(false)); } |
SnapshotServiceFactoryBean extends AbstractFactoryBeanSupport<SnapshotServiceAdapter<K, V>> implements InitializingBean, DisposableBean, ApplicationListener<SnapshotApplicationEvent<K, V>> { public void setCache(Cache cache) { this.cache = Optional.ofNullable(cache) .orElseThrow(() -> newIllegalArgumentException("The GemFire Cache must not be null")); } @Override @SuppressWarnings("unchecked") void afterPropertiesSet(); void setCache(Cache cache); void setExports(SnapshotMetadata<K, V>[] exports); void setImports(SnapshotMetadata<K, V>[] imports); void setRegion(Region<K, V> region); void setSuppressImportOnInit(Boolean suppressImportOnInit); @Override SnapshotServiceAdapter<K, V> getObject(); @Override @SuppressWarnings("unchecked") Class<?> getObjectType(); @Override boolean isSingleton(); @Override @SuppressWarnings("all") void destroy(); @Override @SuppressWarnings("all") void onApplicationEvent(SnapshotApplicationEvent<K, V> event); } | @Test public void setCacheToNull() { exception.expect(IllegalArgumentException.class); exception.expectCause(is(nullValue(Throwable.class))); exception.expectMessage("The GemFire Cache must not be null"); factoryBean.setCache(null); } |
SnapshotServiceFactoryBean extends AbstractFactoryBeanSupport<SnapshotServiceAdapter<K, V>> implements InitializingBean, DisposableBean, ApplicationListener<SnapshotApplicationEvent<K, V>> { protected Cache getCache() { return Optional.ofNullable(this.cache) .orElseThrow(() -> newIllegalStateException("The GemFire Cache was not properly initialized")); } @Override @SuppressWarnings("unchecked") void afterPropertiesSet(); void setCache(Cache cache); void setExports(SnapshotMetadata<K, V>[] exports); void setImports(SnapshotMetadata<K, V>[] imports); void setRegion(Region<K, V> region); void setSuppressImportOnInit(Boolean suppressImportOnInit); @Override SnapshotServiceAdapter<K, V> getObject(); @Override @SuppressWarnings("unchecked") Class<?> getObjectType(); @Override boolean isSingleton(); @Override @SuppressWarnings("all") void destroy(); @Override @SuppressWarnings("all") void onApplicationEvent(SnapshotApplicationEvent<K, V> event); } | @Test public void getCacheWhenUninitialized() { exception.expect(IllegalStateException.class); exception.expectCause(is(nullValue(Throwable.class))); exception.expectMessage("The GemFire Cache was not properly initialized"); factoryBean.getCache(); } |
SnapshotServiceFactoryBean extends AbstractFactoryBeanSupport<SnapshotServiceAdapter<K, V>> implements InitializingBean, DisposableBean, ApplicationListener<SnapshotApplicationEvent<K, V>> { @Override public boolean isSingleton() { return true; } @Override @SuppressWarnings("unchecked") void afterPropertiesSet(); void setCache(Cache cache); void setExports(SnapshotMetadata<K, V>[] exports); void setImports(SnapshotMetadata<K, V>[] imports); void setRegion(Region<K, V> region); void setSuppressImportOnInit(Boolean suppressImportOnInit); @Override SnapshotServiceAdapter<K, V> getObject(); @Override @SuppressWarnings("unchecked") Class<?> getObjectType(); @Override boolean isSingleton(); @Override @SuppressWarnings("all") void destroy(); @Override @SuppressWarnings("all") void onApplicationEvent(SnapshotApplicationEvent<K, V> event); } | @Test public void isSingletonIsTrue() { assertThat(factoryBean.isSingleton(), is(true)); } |
SnapshotServiceFactoryBean extends AbstractFactoryBeanSupport<SnapshotServiceAdapter<K, V>> implements InitializingBean, DisposableBean, ApplicationListener<SnapshotApplicationEvent<K, V>> { protected SnapshotServiceAdapter<Object, Object> wrap(CacheSnapshotService cacheSnapshotService) { return new CacheSnapshotServiceAdapter(cacheSnapshotService); } @Override @SuppressWarnings("unchecked") void afterPropertiesSet(); void setCache(Cache cache); void setExports(SnapshotMetadata<K, V>[] exports); void setImports(SnapshotMetadata<K, V>[] imports); void setRegion(Region<K, V> region); void setSuppressImportOnInit(Boolean suppressImportOnInit); @Override SnapshotServiceAdapter<K, V> getObject(); @Override @SuppressWarnings("unchecked") Class<?> getObjectType(); @Override boolean isSingleton(); @Override @SuppressWarnings("all") void destroy(); @Override @SuppressWarnings("all") void onApplicationEvent(SnapshotApplicationEvent<K, V> event); } | @Test public void wrapNullCacheSnapshotService() { exception.expect(IllegalArgumentException.class); exception.expectCause(is(nullValue(Throwable.class))); exception.expectMessage("The backing CacheSnapshotService must not be null"); factoryBean.wrap((CacheSnapshotService) null); }
@Test public void wrapNullRegionSnapshotService() { exception.expect(IllegalArgumentException.class); exception.expectCause(is(nullValue(Throwable.class))); exception.expectMessage("The backing RegionSnapshotService must not be null"); factoryBean.wrap((RegionSnapshotService) null); } |
CacheFactoryBean extends AbstractFactoryBeanSupport<GemFireCache> implements DisposableBean, InitializingBean, PersistenceExceptionTranslator, Phased { @SuppressWarnings("deprecation") GemFireCache init() { ClassLoader currentThreadContextClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(getBeanClassLoader()); setCache(postProcess(resolveCache())); Optional.<GemFireCache>ofNullable(getCache()).ifPresent(cache -> { Optional.ofNullable(cache.getDistributedSystem()) .map(DistributedSystem::getDistributedMember) .ifPresent(member -> logInfo(() -> String.format("Connected to Distributed System [%1$s] as Member [%2$s]" .concat(" in Group(s) [%3$s] with Role(s) [%4$s] on Host [%5$s] having PID [%6$d]"), cache.getDistributedSystem().getName(), member.getId(), member.getGroups(), member.getRoles(), member.getHost(), member.getProcessId()))); logInfo(() -> String.format("%1$s %2$s version [%3$s] Cache [%4$s]", this.cacheResolutionMessagePrefix, apacheGeodeProductName(), apacheGeodeVersion(), cache.getName())); }); return getCache(); } catch (Exception cause) { throw newRuntimeException(cause, "Error occurred when initializing peer cache"); } finally { Thread.currentThread().setContextClassLoader(currentThreadContextClassLoader); } } @Override void afterPropertiesSet(); @Override void destroy(); @Override DataAccessException translateExceptionIfPossible(RuntimeException exception); GemfireBeanFactoryLocator getBeanFactoryLocator(); void setCacheXml(Resource cacheXml); Resource getCacheXml(); @Override GemFireCache getObject(); @Override Class<? extends GemFireCache> getObjectType(); @SuppressWarnings("rawtypes") void setCacheFactoryInitializer(CacheFactoryInitializer cacheFactoryInitializer); @SuppressWarnings("rawtypes") CacheFactoryInitializer getCacheFactoryInitializer(); void setProperties(Properties properties); Properties getProperties(); void setClose(boolean close); boolean isClose(); PeerCacheConfigurer getCompositePeerCacheConfigurer(); void setCopyOnRead(Boolean copyOnRead); Boolean getCopyOnRead(); void setCriticalHeapPercentage(Float criticalHeapPercentage); Float getCriticalHeapPercentage(); void setCriticalOffHeapPercentage(Float criticalOffHeapPercentage); Float getCriticalOffHeapPercentage(); void setEnableAutoReconnect(Boolean enableAutoReconnect); Boolean getEnableAutoReconnect(); void setEvictionHeapPercentage(Float evictionHeapPercentage); Float getEvictionHeapPercentage(); void setEvictionOffHeapPercentage(Float evictionOffHeapPercentage); Float getEvictionOffHeapPercentage(); void setGatewayConflictResolver(GatewayConflictResolver gatewayConflictResolver); GatewayConflictResolver getGatewayConflictResolver(); void setJndiDataSources(List<JndiDataSource> jndiDataSources); List<JndiDataSource> getJndiDataSources(); void setLockLease(Integer lockLease); Integer getLockLease(); void setLockTimeout(Integer lockTimeout); Integer getLockTimeout(); void setMessageSyncInterval(Integer messageSyncInterval); Integer getMessageSyncInterval(); @Override int getPhase(); void setPdxDiskStoreName(String pdxDiskStoreName); String getPdxDiskStoreName(); void setPdxIgnoreUnreadFields(Boolean pdxIgnoreUnreadFields); Boolean getPdxIgnoreUnreadFields(); void setPdxPersistent(Boolean pdxPersistent); Boolean getPdxPersistent(); void setPdxReadSerialized(Boolean pdxReadSerialized); Boolean getPdxReadSerialized(); void setPdxSerializer(PdxSerializer serializer); PdxSerializer getPdxSerializer(); void setPeerCacheConfigurers(PeerCacheConfigurer... peerCacheConfigurers); void setPeerCacheConfigurers(List<PeerCacheConfigurer> peerCacheConfigurers); void setSearchTimeout(Integer searchTimeout); Integer getSearchTimeout(); void setSecurityManager(SecurityManager securityManager); SecurityManager getSecurityManager(); void setTransactionListeners(List<TransactionListener> transactionListeners); List<TransactionListener> getTransactionListeners(); void setTransactionWriter(TransactionWriter transactionWriter); TransactionWriter getTransactionWriter(); void setUseBeanFactoryLocator(boolean use); boolean isUseBeanFactoryLocator(); void setUseClusterConfiguration(Boolean useSharedConfiguration); Boolean getUseClusterConfiguration(); } | @Test @SuppressWarnings("deprecation") public void init() throws Exception { BeanFactory mockBeanFactory = mock(BeanFactory.class); Cache mockCache = mock(Cache.class); CacheTransactionManager mockCacheTransactionManager = mock(CacheTransactionManager.class); DistributedMember mockDistributedMember = mock(DistributedMember.class, withSettings().lenient()); DistributedSystem mockDistributedSystem = mock(DistributedSystem.class, withSettings().lenient()); GatewayConflictResolver mockGatewayConflictResolver = mock(GatewayConflictResolver.class); PdxSerializer mockPdxSerializer = mock(PdxSerializer.class); Resource mockCacheXml = mock(Resource.class); ResourceManager mockResourceManager = mock(ResourceManager.class); TransactionListener mockTransactionLister = mock(TransactionListener.class); TransactionWriter mockTransactionWriter = mock(TransactionWriter.class); CacheFactory mockCacheFactory = mock(CacheFactory.class); when(mockBeanFactory.getAliases(anyString())).thenReturn(new String[0]); when(mockCacheFactory.create()).thenReturn(mockCache); when(mockCache.getCacheTransactionManager()).thenReturn(mockCacheTransactionManager); when(mockCache.getDistributedSystem()).thenReturn(mockDistributedSystem); when(mockCache.getResourceManager()).thenReturn(mockResourceManager); when(mockCacheXml.getInputStream()).thenReturn(mock(InputStream.class)); when(mockDistributedSystem.getDistributedMember()).thenReturn(mockDistributedMember); when(mockDistributedSystem.getName()).thenReturn("MockDistributedSystem"); when(mockDistributedMember.getId()).thenReturn("MockDistributedMember"); when(mockDistributedMember.getGroups()).thenReturn(Collections.emptyList()); when(mockDistributedMember.getRoles()).thenReturn(Collections.emptySet()); when(mockDistributedMember.getHost()).thenReturn("skullbox"); when(mockDistributedMember.getProcessId()).thenReturn(12345); ClassLoader expectedThreadContextClassLoader = Thread.currentThread().getContextClassLoader(); Properties gemfireProperties = new Properties(); CacheFactoryBean cacheFactoryBean = new CacheFactoryBean() { @Override protected Object createFactory(Properties actualGemfireProperties) { assertThat(actualGemfireProperties, is(equalTo(gemfireProperties))); assertThat(getBeanClassLoader(), is(equalTo(ClassLoader.getSystemClassLoader()))); return mockCacheFactory; } }; cacheFactoryBean.setBeanClassLoader(ClassLoader.getSystemClassLoader()); cacheFactoryBean.setBeanFactory(mockBeanFactory); cacheFactoryBean.setBeanName("TestGemFireCache"); cacheFactoryBean.setCacheXml(mockCacheXml); cacheFactoryBean.setCopyOnRead(true); cacheFactoryBean.setCriticalHeapPercentage(0.90f); cacheFactoryBean.setCriticalOffHeapPercentage(0.95f); cacheFactoryBean.setEnableAutoReconnect(false); cacheFactoryBean.setEvictionHeapPercentage(0.75f); cacheFactoryBean.setEvictionOffHeapPercentage(0.90f); cacheFactoryBean.setGatewayConflictResolver(mockGatewayConflictResolver); cacheFactoryBean.setJndiDataSources(null); cacheFactoryBean.setLockLease(15000); cacheFactoryBean.setLockTimeout(5000); cacheFactoryBean.setMessageSyncInterval(20000); cacheFactoryBean.setPdxDiskStoreName("TestPdxDiskStore"); cacheFactoryBean.setPdxIgnoreUnreadFields(false); cacheFactoryBean.setPdxPersistent(true); cacheFactoryBean.setPdxReadSerialized(true); cacheFactoryBean.setPdxSerializer(mockPdxSerializer); cacheFactoryBean.setProperties(gemfireProperties); cacheFactoryBean.setSearchTimeout(45000); cacheFactoryBean.setTransactionListeners(Collections.singletonList(mockTransactionLister)); cacheFactoryBean.setTransactionWriter(mockTransactionWriter); cacheFactoryBean.setUseBeanFactoryLocator(true); cacheFactoryBean.afterPropertiesSet(); cacheFactoryBean.init(); assertThat(Thread.currentThread().getContextClassLoader(), is(sameInstance(expectedThreadContextClassLoader))); GemfireBeanFactoryLocator beanFactoryLocator = cacheFactoryBean.getBeanFactoryLocator(); assertThat(beanFactoryLocator, is(notNullValue())); BeanFactory beanFactoryReference = beanFactoryLocator.useBeanFactory("TestGemFireCache"); assertThat(beanFactoryReference, is(sameInstance(mockBeanFactory))); verify(mockBeanFactory, times(1)).getAliases(anyString()); verify(mockCacheFactory, times(1)).setPdxDiskStore(eq("TestPdxDiskStore")); verify(mockCacheFactory, times(1)).setPdxIgnoreUnreadFields(eq(false)); verify(mockCacheFactory, times(1)).setPdxPersistent(eq(true)); verify(mockCacheFactory, times(1)).setPdxReadSerialized(eq(true)); verify(mockCacheFactory, times(1)).setPdxSerializer(eq(mockPdxSerializer)); verify(mockCacheFactory, times(1)).create(); verify(mockCache, times(2)).getCacheTransactionManager(); verify(mockCache, times(1)).loadCacheXml(any(InputStream.class)); verify(mockCache, times(1)).setCopyOnRead(eq(true)); verify(mockCache, times(1)).setGatewayConflictResolver(same(mockGatewayConflictResolver)); verify(mockCache, times(1)).setLockLease(eq(15000)); verify(mockCache, times(1)).setLockTimeout(eq(5000)); verify(mockCache, times(1)).setMessageSyncInterval(eq(20000)); verify(mockCache, times(4)).getResourceManager(); verify(mockCache, times(1)).setSearchTimeout(eq(45000)); verify(mockCacheTransactionManager, times(1)).addListener(same(mockTransactionLister)); verify(mockCacheTransactionManager, times(1)).setWriter(same(mockTransactionWriter)); verify(mockResourceManager, times(1)).setCriticalHeapPercentage(eq(0.90f)); verify(mockResourceManager, times(1)).setCriticalOffHeapPercentage(eq(0.95f)); verify(mockResourceManager, times(1)).setEvictionHeapPercentage(eq(0.75f)); verify(mockResourceManager, times(1)).setEvictionOffHeapPercentage(eq(0.90f)); } |
SnapshotApplicationEvent extends ApplicationEvent { public boolean matches(Region region) { return (region != null && matches(region.getFullPath())); } SnapshotApplicationEvent(Object source, SnapshotMetadata<K, V>... snapshotMetadata); SnapshotApplicationEvent(Object source, String regionPath, SnapshotMetadata<K, V>... snapshotMetadata); String getRegionPath(); SnapshotMetadata<K, V>[] getSnapshotMetadata(); boolean isCacheSnapshotEvent(); boolean isRegionSnapshotEvent(); boolean matches(Region region); boolean matches(String regionPath); } | @Test public void matchesNullRegionIsFalse() { assertThat(new TestSnapshotApplicationEvent(this).matches((Region) null), is(false)); }
@Test public void matchesNonMatchingRegionIsFalse() { Region mockRegion = mock(Region.class, "MockRegion"); when(mockRegion.getFullPath()).thenReturn("/Example"); assertThat(new TestSnapshotApplicationEvent(this, "/Prototype").matches(mockRegion), is(false)); verify(mockRegion, times(1)).getFullPath(); }
@Test public void matchesMatchingRegionIsTrue() { Region mockRegion = mock(Region.class, "MockRegion"); when(mockRegion.getFullPath()).thenReturn("/Example"); assertThat(new TestSnapshotApplicationEvent(this, "/Example").matches(mockRegion), is(true)); verify(mockRegion, times(1)).getFullPath(); }
@Test public void matchesMatchingRegionPathsIsTrue() { assertThat(new TestSnapshotApplicationEvent(this, "/Example").matches("/Example"), is(true)); assertThat(new TestSnapshotApplicationEvent(this, "/").matches("/"), is(true)); assertThat(new TestSnapshotApplicationEvent(this, " ").matches(" "), is(true)); assertThat(new TestSnapshotApplicationEvent(this, "").matches(" "), is(true)); assertThat(new TestSnapshotApplicationEvent(this, "").matches(""), is(true)); assertThat(new TestSnapshotApplicationEvent(this, (String) null).matches((String) null), is(true)); } |
SpringServerLauncherCacheProvider implements ServerLauncherCacheProvider { @Override public Cache createCache(Properties gemfireProperties, ServerLauncher serverLauncher) { Cache cache = null; if (serverLauncher.isSpringXmlLocationSpecified()) { System.setProperty(gemfireName(), serverLauncher.getMemberName()); newSpringContextBootstrappingInitializer().init(createParameters(serverLauncher)); cache = SpringContextBootstrappingInitializer.getApplicationContext().getBean(Cache.class); } return cache; } @Override Cache createCache(Properties gemfireProperties, ServerLauncher serverLauncher); } | @Test public void createsCacheWhenSpringXmlLocationIsSpecified() { Cache mockCache = mock(Cache.class); ConfigurableApplicationContext mockApplicationContext = mock(ConfigurableApplicationContext.class); ServerLauncher mockServerLauncher = mock(ServerLauncher.class); SpringContextBootstrappingInitializer.applicationContext = mockApplicationContext; when(mockServerLauncher.isSpringXmlLocationSpecified()).thenReturn(true); when(mockServerLauncher.getSpringXmlLocation()).thenReturn("test-context.xml"); when(mockServerLauncher.getMemberName()).thenReturn("TEST"); when(mockApplicationContext.getBean(eq(Cache.class))).thenReturn(mockCache); final SpringContextBootstrappingInitializer initializer = mock(SpringContextBootstrappingInitializer.class); SpringServerLauncherCacheProvider provider = new SpringServerLauncherCacheProvider() { @Override public SpringContextBootstrappingInitializer newSpringContextBootstrappingInitializer() { return initializer; } }; Properties expectedParameters = singletonProperties( SpringContextBootstrappingInitializer.CONTEXT_CONFIG_LOCATIONS_PARAMETER, "test-context.xml"); assertThat(provider.createCache(null, mockServerLauncher), is(equalTo(mockCache))); verify(mockServerLauncher, times(1)).isSpringXmlLocationSpecified(); verify(mockServerLauncher, times(1)).getSpringXmlLocation(); verify(mockServerLauncher, times(1)).getMemberName(); verify(mockApplicationContext, times(1)).getBean(eq(Cache.class)); verify(initializer).init(eq(expectedParameters)); }
@Test public void doesNothingWhenSpringXmlLocationNotSpecified() { ServerLauncher launcher = mock(ServerLauncher.class); when(launcher.isSpringXmlLocationSpecified()).thenReturn(false); assertThat(new SpringServerLauncherCacheProvider().createCache(null, launcher), is(nullValue())); verify(launcher, times(1)).isSpringXmlLocationSpecified(); } |
ConnectionEndpointList extends AbstractList<ConnectionEndpoint> { public static ConnectionEndpointList parse(int defaultPort, String... hostsPorts) { List<ConnectionEndpoint> connectionEndpoints = new ArrayList<ConnectionEndpoint>( ArrayUtils.length(hostsPorts)); for (String hostPort : ArrayUtils.nullSafeArray(hostsPorts, String.class)) { connectionEndpoints.add(ConnectionEndpoint.parse(hostPort, defaultPort)); } return new ConnectionEndpointList(connectionEndpoints); } ConnectionEndpointList(); ConnectionEndpointList(ConnectionEndpoint... connectionEndpoints); ConnectionEndpointList(Iterable<ConnectionEndpoint> connectionEndpoints); static ConnectionEndpointList from(ConnectionEndpoint... connectionEndpoints); static ConnectionEndpointList from(InetSocketAddress... socketAddresses); static ConnectionEndpointList from(Iterable<InetSocketAddress> socketAddresses); static ConnectionEndpointList parse(int defaultPort, String... hostsPorts); @Override boolean add(ConnectionEndpoint connectionEndpoint); final ConnectionEndpointList add(ConnectionEndpoint... connectionEndpoints); final ConnectionEndpointList add(Iterable<ConnectionEndpoint> connectionEndpoints); @Override void clear(); ConnectionEndpointList findBy(String host); ConnectionEndpointList findBy(int port); ConnectionEndpoint findOne(String host); ConnectionEndpoint findOne(int port); @Override ConnectionEndpoint get(int index); @Override ConnectionEndpoint set(int index, ConnectionEndpoint element); @Override boolean isEmpty(); @Override @SuppressWarnings("all") Iterator<ConnectionEndpoint> iterator(); @Override int size(); @Override @SuppressWarnings("all") ConnectionEndpoint[] toArray(); List<InetSocketAddress> toInetSocketAddresses(); @Override String toString(); } | @Test public void parse() { ConnectionEndpointList list = ConnectionEndpointList.parse(24842, "mercury[11235]", "venus", "[12480]", "[]", "jupiter[]", "saturn[1, 2-Hundred and 34.zero5]", "neptune[four]"); String[] expectedHostPorts = { "mercury[11235]", "venus[24842]", "localhost[12480]", "localhost[24842]", "jupiter[24842]", "saturn[12345]", "neptune[24842]" }; assertThat(list, is(notNullValue())); assertThat(list.size(), is(equalTo(expectedHostPorts.length))); int index = 0; for (ConnectionEndpoint connectionEndpoint : list) { assertThat(connectionEndpoint.toString(), is(equalTo(expectedHostPorts[index++]))); } } |
ConnectionEndpointList extends AbstractList<ConnectionEndpoint> { @Override @SuppressWarnings("all") public ConnectionEndpoint[] toArray() { return connectionEndpoints.toArray(new ConnectionEndpoint[connectionEndpoints.size()]); } ConnectionEndpointList(); ConnectionEndpointList(ConnectionEndpoint... connectionEndpoints); ConnectionEndpointList(Iterable<ConnectionEndpoint> connectionEndpoints); static ConnectionEndpointList from(ConnectionEndpoint... connectionEndpoints); static ConnectionEndpointList from(InetSocketAddress... socketAddresses); static ConnectionEndpointList from(Iterable<InetSocketAddress> socketAddresses); static ConnectionEndpointList parse(int defaultPort, String... hostsPorts); @Override boolean add(ConnectionEndpoint connectionEndpoint); final ConnectionEndpointList add(ConnectionEndpoint... connectionEndpoints); final ConnectionEndpointList add(Iterable<ConnectionEndpoint> connectionEndpoints); @Override void clear(); ConnectionEndpointList findBy(String host); ConnectionEndpointList findBy(int port); ConnectionEndpoint findOne(String host); ConnectionEndpoint findOne(int port); @Override ConnectionEndpoint get(int index); @Override ConnectionEndpoint set(int index, ConnectionEndpoint element); @Override boolean isEmpty(); @Override @SuppressWarnings("all") Iterator<ConnectionEndpoint> iterator(); @Override int size(); @Override @SuppressWarnings("all") ConnectionEndpoint[] toArray(); List<InetSocketAddress> toInetSocketAddresses(); @Override String toString(); } | @Test public void toArrayFromEmptyList() { ConnectionEndpoint[] connectionEndpoints = new ConnectionEndpointList().toArray(); assertThat(connectionEndpoints, is(notNullValue())); assertThat(connectionEndpoints.length, is(equalTo(0))); } |
ConnectionEndpointList extends AbstractList<ConnectionEndpoint> { @Override public String toString() { return connectionEndpoints.toString(); } ConnectionEndpointList(); ConnectionEndpointList(ConnectionEndpoint... connectionEndpoints); ConnectionEndpointList(Iterable<ConnectionEndpoint> connectionEndpoints); static ConnectionEndpointList from(ConnectionEndpoint... connectionEndpoints); static ConnectionEndpointList from(InetSocketAddress... socketAddresses); static ConnectionEndpointList from(Iterable<InetSocketAddress> socketAddresses); static ConnectionEndpointList parse(int defaultPort, String... hostsPorts); @Override boolean add(ConnectionEndpoint connectionEndpoint); final ConnectionEndpointList add(ConnectionEndpoint... connectionEndpoints); final ConnectionEndpointList add(Iterable<ConnectionEndpoint> connectionEndpoints); @Override void clear(); ConnectionEndpointList findBy(String host); ConnectionEndpointList findBy(int port); ConnectionEndpoint findOne(String host); ConnectionEndpoint findOne(int port); @Override ConnectionEndpoint get(int index); @Override ConnectionEndpoint set(int index, ConnectionEndpoint element); @Override boolean isEmpty(); @Override @SuppressWarnings("all") Iterator<ConnectionEndpoint> iterator(); @Override int size(); @Override @SuppressWarnings("all") ConnectionEndpoint[] toArray(); List<InetSocketAddress> toInetSocketAddresses(); @Override String toString(); } | @Test public void toStringFromEmptyList() { assertThat(new ConnectionEndpointList().toString(), is(equalTo("[]"))); } |
CacheFactoryBean extends AbstractFactoryBeanSupport<GemFireCache> implements DisposableBean, InitializingBean, PersistenceExceptionTranslator, Phased { @SuppressWarnings("unchecked") protected <T extends GemFireCache> T resolveCache() { try { this.cacheResolutionMessagePrefix = "Found existing"; return (T) fetchCache(); } catch (CacheClosedException cause) { this.cacheResolutionMessagePrefix = "Created new"; return (T) createCache(postProcess(configureFactory(initializeFactory(createFactory(resolveProperties()))))); } } @Override void afterPropertiesSet(); @Override void destroy(); @Override DataAccessException translateExceptionIfPossible(RuntimeException exception); GemfireBeanFactoryLocator getBeanFactoryLocator(); void setCacheXml(Resource cacheXml); Resource getCacheXml(); @Override GemFireCache getObject(); @Override Class<? extends GemFireCache> getObjectType(); @SuppressWarnings("rawtypes") void setCacheFactoryInitializer(CacheFactoryInitializer cacheFactoryInitializer); @SuppressWarnings("rawtypes") CacheFactoryInitializer getCacheFactoryInitializer(); void setProperties(Properties properties); Properties getProperties(); void setClose(boolean close); boolean isClose(); PeerCacheConfigurer getCompositePeerCacheConfigurer(); void setCopyOnRead(Boolean copyOnRead); Boolean getCopyOnRead(); void setCriticalHeapPercentage(Float criticalHeapPercentage); Float getCriticalHeapPercentage(); void setCriticalOffHeapPercentage(Float criticalOffHeapPercentage); Float getCriticalOffHeapPercentage(); void setEnableAutoReconnect(Boolean enableAutoReconnect); Boolean getEnableAutoReconnect(); void setEvictionHeapPercentage(Float evictionHeapPercentage); Float getEvictionHeapPercentage(); void setEvictionOffHeapPercentage(Float evictionOffHeapPercentage); Float getEvictionOffHeapPercentage(); void setGatewayConflictResolver(GatewayConflictResolver gatewayConflictResolver); GatewayConflictResolver getGatewayConflictResolver(); void setJndiDataSources(List<JndiDataSource> jndiDataSources); List<JndiDataSource> getJndiDataSources(); void setLockLease(Integer lockLease); Integer getLockLease(); void setLockTimeout(Integer lockTimeout); Integer getLockTimeout(); void setMessageSyncInterval(Integer messageSyncInterval); Integer getMessageSyncInterval(); @Override int getPhase(); void setPdxDiskStoreName(String pdxDiskStoreName); String getPdxDiskStoreName(); void setPdxIgnoreUnreadFields(Boolean pdxIgnoreUnreadFields); Boolean getPdxIgnoreUnreadFields(); void setPdxPersistent(Boolean pdxPersistent); Boolean getPdxPersistent(); void setPdxReadSerialized(Boolean pdxReadSerialized); Boolean getPdxReadSerialized(); void setPdxSerializer(PdxSerializer serializer); PdxSerializer getPdxSerializer(); void setPeerCacheConfigurers(PeerCacheConfigurer... peerCacheConfigurers); void setPeerCacheConfigurers(List<PeerCacheConfigurer> peerCacheConfigurers); void setSearchTimeout(Integer searchTimeout); Integer getSearchTimeout(); void setSecurityManager(SecurityManager securityManager); SecurityManager getSecurityManager(); void setTransactionListeners(List<TransactionListener> transactionListeners); List<TransactionListener> getTransactionListeners(); void setTransactionWriter(TransactionWriter transactionWriter); TransactionWriter getTransactionWriter(); void setUseBeanFactoryLocator(boolean use); boolean isUseBeanFactoryLocator(); void setUseClusterConfiguration(Boolean useSharedConfiguration); Boolean getUseClusterConfiguration(); } | @Test public void resolveCacheCallsFetchCacheReturnsMock() { Cache mockCache = mock(Cache.class); CacheFactoryBean cacheFactoryBean = new CacheFactoryBean() { @Override @SuppressWarnings("unchecked ") protected <T extends GemFireCache> T fetchCache() { return (T) mockCache; } }; assertThat(cacheFactoryBean.resolveCache(), is(sameInstance(mockCache))); verifyZeroInteractions(mockCache); } |
SpringContextBootstrappingInitializer implements Declarable, ApplicationListener<ApplicationContextEvent> { public static synchronized ConfigurableApplicationContext getApplicationContext() { Assert.state(applicationContext != null, "A Spring ApplicationContext was not configured and initialized properly"); return applicationContext; } static synchronized ConfigurableApplicationContext getApplicationContext(); static void setBeanClassLoader(ClassLoader beanClassLoader); static T register(T listener); static boolean register(Class<?> annotatedClass); static T unregister(T listener); static boolean unregister(Class<?> annotatedClass); @Override @SuppressWarnings("deprecation") void init(Properties parameters); void init(Cache cache, Properties parameters); @Override void onApplicationEvent(ApplicationContextEvent event); static final String BASE_PACKAGES_PARAMETER; static final String CONTEXT_CONFIG_LOCATIONS_PARAMETER; } | @Test public void getInitializedApplicationContext() { ConfigurableApplicationContext mockApplicationContext = mock(ConfigurableApplicationContext.class, "testGetApplicationContext"); SpringContextBootstrappingInitializer.applicationContext = mockApplicationContext; assertThat(SpringContextBootstrappingInitializer.getApplicationContext(), is(sameInstance(mockApplicationContext))); }
@Test(expected = IllegalStateException.class) public void getUninitializedApplicationContext() { try { SpringContextBootstrappingInitializer.getApplicationContext(); } catch (IllegalStateException expected) { assertThat(expected.getMessage(), containsString("A Spring ApplicationContext was not configured and initialized properly")); assertThat(expected.getCause(), is(nullValue(Throwable.class))); throw expected; } } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.