method2testcases
stringlengths
118
6.63k
### Question: LobbyActivity extends AppCompatActivity implements LobbyView { @Override protected void onDestroy() { presenter.onViewDestroyed(); super.onDestroy(); } @OnClick(R.id.generate_report) void onGenerateReportButtonClicked(); @Override void displayReportData(CharSequence report); @Override void hideReportData(); @Override void displayReportError(); @Override void displayLoadingIndicator(); @Override void hideLoadingIndicator(); }### Answer: @Test public void onDestroy_callsOnViewDestroyedOnPresenter() throws Exception { testSubject.onDestroy(); verify(presenter).onViewDestroyed(); }
### Question: LobbyActivity extends AppCompatActivity implements LobbyView { @OnClick(R.id.generate_report) public void onGenerateReportButtonClicked() { presenter.generateReport(); } @OnClick(R.id.generate_report) void onGenerateReportButtonClicked(); @Override void displayReportData(CharSequence report); @Override void hideReportData(); @Override void displayReportError(); @Override void displayLoadingIndicator(); @Override void hideLoadingIndicator(); }### Answer: @Test public void onGenerateReportButtonClicked_callsGenerateReportOnPresenter() throws Exception { testSubject.onGenerateReportButtonClicked(); verify(presenter).generateReport(); }
### Question: Validators { public static void checkTopic(String topic) throws MQClientException { if (UtilAll.isBlank(topic)) { throw new MQClientException("the specified topic is blank", null); } if (!regularExpressionMatcher(topic, PATTERN)) { throw new MQClientException(String.format( "the specified topic[%s] contains illegal characters, allowing only %s", topic, VALID_PATTERN_STR), null); } if (topic.length() > CHARACTER_MAX_LENGTH) { throw new MQClientException("the specified topic is longer than topic max length 255.", null); } if (topic.equals(MixAll.DEFAULT_TOPIC)) { throw new MQClientException( String.format("the topic[%s] is conflict with default topic.", topic), null); } } static String getGroupWithRegularExpression(String origin, String patternStr); static void checkGroup(String group); static boolean regularExpressionMatcher(String origin, Pattern pattern); static void checkMessage(Message msg, DefaultMQProducer defaultMQProducer); static void checkTopic(String topic); static final String VALID_PATTERN_STR; static final Pattern PATTERN; static final int CHARACTER_MAX_LENGTH; }### Answer: @Test public void topicValidatorTest() { try { Validators.checkTopic("Hello"); Validators.checkTopic("%RETRY%Hello"); Validators.checkTopic("_%RETRY%Hello"); Validators.checkTopic("-%RETRY%Hello"); Validators.checkTopic("223-%RETRY%Hello"); } catch (Exception e) { e.printStackTrace(); Assert.assertTrue(false); } }
### Question: ConsumerOffsetManager extends ConfigManager { public void commitOffset(final String clientHost, final String group, final String topic, final int queueId, final long offset) { String key = topic + TOPIC_GROUP_SEPARATOR + group; this.commitOffset(clientHost, key, queueId, offset); } ConsumerOffsetManager(); ConsumerOffsetManager(BrokerController brokerController); void scanUnsubscribedTopic(); Set<String> whichTopicByConsumer(final String group); Set<String> whichGroupByTopic(final String topic); void commitOffset(final String clientHost, final String group, final String topic, final int queueId, final long offset); long queryOffset(final String group, final String topic, final int queueId); String encode(); @Override String configFilePath(); @Override void decode(String jsonString); String encode(final boolean prettyFormat); ConcurrentHashMap<String, ConcurrentHashMap<Integer, Long>> getOffsetTable(); void setOffsetTable(ConcurrentHashMap<String, ConcurrentHashMap<Integer, Long>> offsetTable); Map<Integer, Long> queryMinOffsetInAllGroup(final String topic, final String filterGroups); Map<Integer, Long> queryOffset(final String group, final String topic); void cloneOffset(final String srcGroup, final String destGroup, final String topic); }### Answer: @Test public void test_flushConsumerOffset() throws Exception { BrokerController brokerController = new BrokerController( new BrokerConfig(), new NettyServerConfig(), new NettyClientConfig(), new MessageStoreConfig()); boolean initResult = brokerController.initialize(); System.out.println("initialize " + initResult); brokerController.start(); ConsumerOffsetManager consumerOffsetManager = new ConsumerOffsetManager(brokerController); Random random = new Random(); for (int i = 0; i < 100; i++) { String group = "DIANPU_GROUP_" + i; for (int id = 0; id < 16; id++) { consumerOffsetManager.commitOffset(null, group, "TOPIC_A", id, random.nextLong() % 1024 * 1024 * 1024); consumerOffsetManager.commitOffset(null, group, "TOPIC_B", id, random.nextLong() % 1024 * 1024 * 1024); consumerOffsetManager.commitOffset(null, group, "TOPIC_C", id, random.nextLong() % 1024 * 1024 * 1024); } } consumerOffsetManager.persist(); brokerController.shutdown(); }
### Question: FilterAPI { public static SubscriptionData buildSubscriptionData(final String consumerGroup, String topic, String subString) throws Exception { SubscriptionData subscriptionData = new SubscriptionData(); subscriptionData.setTopic(topic); subscriptionData.setSubString(subString); if (null == subString || subString.equals(SubscriptionData.SUB_ALL) || subString.length() == 0) { subscriptionData.setSubString(SubscriptionData.SUB_ALL); } else { String[] tags = subString.split("\\|\\|"); if (tags != null && tags.length > 0) { for (String tag : tags) { if (tag.length() > 0) { String trimString = tag.trim(); if (trimString.length() > 0) { subscriptionData.getTagsSet().add(trimString); subscriptionData.getCodeSet().add(trimString.hashCode()); } } } } else { throw new Exception("subString split error"); } } return subscriptionData; } static URL classFile(final String className); static String simpleClassName(final String className); static SubscriptionData buildSubscriptionData(final String consumerGroup, String topic, String subString); }### Answer: @Test public void testBuildSubscriptionData() throws Exception { SubscriptionData subscriptionData = FilterAPI.buildSubscriptionData("ConsumerGroup1", "TestTopic", "TAG1 || Tag2 || tag3"); System.out.println(subscriptionData); } @Test public void testSubscriptionData() throws Exception { SubscriptionData subscriptionData = FilterAPI.buildSubscriptionData("ConsumerGroup1", "TestTopic", "TAG1 || Tag2 || tag3"); subscriptionData.setFilterClassSource("java hello"); String json = RemotingSerializable.toJson(subscriptionData, true); System.out.println(json); }
### Question: UtilAll { public static String currentStackTrace() { StringBuilder sb = new StringBuilder(); StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); for (StackTraceElement ste : stackTrace) { sb.append("\n\t"); sb.append(ste.toString()); } return sb.toString(); } static int getPid(); static String currentStackTrace(); static String offset2FileName(final long offset); static long computeEclipseTimeMilliseconds(final long beginTime); static boolean isItTimeToDo(final String when); static String timeMillisToHumanString(); static String timeMillisToHumanString(final long t); static long computNextMorningTimeMillis(); static long computNextMinutesTimeMillis(); static long computNextHourTimeMillis(); static long computNextHalfHourTimeMillis(); static String timeMillisToHumanString2(final long t); static String timeMillisToHumanString3(final long t); static double getDiskPartitionSpaceUsedPercent(final String path); static final int crc32(byte[] array); static final int crc32(byte[] array, int offset, int length); static String bytes2string(byte[] src); static byte[] string2bytes(String hexString); static byte[] uncompress(final byte[] src); static byte[] compress(final byte[] src, final int level); static int asInt(String str, int defaultValue); static long asLong(String str, long defaultValue); static String formatDate(Date date, String pattern); static Date parseDate(String date, String pattern); static String responseCode2String(final int code); static String frontStringAtLeast(final String str, final int size); static boolean isBlank(String str); static String jstack(); static String jstack(Map<Thread, StackTraceElement[]> map); static boolean isInternalIP(byte[] ip); static String ipToIPv4Str(byte[] ip); static byte[] getIP(); static final String yyyy_MM_dd_HH_mm_ss; static final String yyyy_MM_dd_HH_mm_ss_SSS; static final String yyyyMMddHHmmss; }### Answer: @Test public void test_currentStackTrace() { System.out.println(UtilAll.currentStackTrace()); }
### Question: UtilAll { public static String timeMillisToHumanString() { return timeMillisToHumanString(System.currentTimeMillis()); } static int getPid(); static String currentStackTrace(); static String offset2FileName(final long offset); static long computeEclipseTimeMilliseconds(final long beginTime); static boolean isItTimeToDo(final String when); static String timeMillisToHumanString(); static String timeMillisToHumanString(final long t); static long computNextMorningTimeMillis(); static long computNextMinutesTimeMillis(); static long computNextHourTimeMillis(); static long computNextHalfHourTimeMillis(); static String timeMillisToHumanString2(final long t); static String timeMillisToHumanString3(final long t); static double getDiskPartitionSpaceUsedPercent(final String path); static final int crc32(byte[] array); static final int crc32(byte[] array, int offset, int length); static String bytes2string(byte[] src); static byte[] string2bytes(String hexString); static byte[] uncompress(final byte[] src); static byte[] compress(final byte[] src, final int level); static int asInt(String str, int defaultValue); static long asLong(String str, long defaultValue); static String formatDate(Date date, String pattern); static Date parseDate(String date, String pattern); static String responseCode2String(final int code); static String frontStringAtLeast(final String str, final int size); static boolean isBlank(String str); static String jstack(); static String jstack(Map<Thread, StackTraceElement[]> map); static boolean isInternalIP(byte[] ip); static String ipToIPv4Str(byte[] ip); static byte[] getIP(); static final String yyyy_MM_dd_HH_mm_ss; static final String yyyy_MM_dd_HH_mm_ss_SSS; static final String yyyyMMddHHmmss; }### Answer: @Test public void test_timeMillisToHumanString() { System.out.println(UtilAll.timeMillisToHumanString()); }
### Question: UtilAll { public static int getPid() { RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); String name = runtime.getName(); try { return Integer.parseInt(name.substring(0, name.indexOf('@'))); } catch (Exception e) { return -1; } } static int getPid(); static String currentStackTrace(); static String offset2FileName(final long offset); static long computeEclipseTimeMilliseconds(final long beginTime); static boolean isItTimeToDo(final String when); static String timeMillisToHumanString(); static String timeMillisToHumanString(final long t); static long computNextMorningTimeMillis(); static long computNextMinutesTimeMillis(); static long computNextHourTimeMillis(); static long computNextHalfHourTimeMillis(); static String timeMillisToHumanString2(final long t); static String timeMillisToHumanString3(final long t); static double getDiskPartitionSpaceUsedPercent(final String path); static final int crc32(byte[] array); static final int crc32(byte[] array, int offset, int length); static String bytes2string(byte[] src); static byte[] string2bytes(String hexString); static byte[] uncompress(final byte[] src); static byte[] compress(final byte[] src, final int level); static int asInt(String str, int defaultValue); static long asLong(String str, long defaultValue); static String formatDate(Date date, String pattern); static Date parseDate(String date, String pattern); static String responseCode2String(final int code); static String frontStringAtLeast(final String str, final int size); static boolean isBlank(String str); static String jstack(); static String jstack(Map<Thread, StackTraceElement[]> map); static boolean isInternalIP(byte[] ip); static String ipToIPv4Str(byte[] ip); static byte[] getIP(); static final String yyyy_MM_dd_HH_mm_ss; static final String yyyy_MM_dd_HH_mm_ss_SSS; static final String yyyyMMddHHmmss; }### Answer: @Test public void test_getpid() { int pid = UtilAll.getPid(); System.out.println("PID = " + pid); assertTrue(pid > 0); }
### Question: UtilAll { public static boolean isBlank(String str) { int strLen; if (str == null || (strLen = str.length()) == 0) { return true; } for (int i = 0; i < strLen; i++) { if ((Character.isWhitespace(str.charAt(i)) == false)) { return false; } } return true; } static int getPid(); static String currentStackTrace(); static String offset2FileName(final long offset); static long computeEclipseTimeMilliseconds(final long beginTime); static boolean isItTimeToDo(final String when); static String timeMillisToHumanString(); static String timeMillisToHumanString(final long t); static long computNextMorningTimeMillis(); static long computNextMinutesTimeMillis(); static long computNextHourTimeMillis(); static long computNextHalfHourTimeMillis(); static String timeMillisToHumanString2(final long t); static String timeMillisToHumanString3(final long t); static double getDiskPartitionSpaceUsedPercent(final String path); static final int crc32(byte[] array); static final int crc32(byte[] array, int offset, int length); static String bytes2string(byte[] src); static byte[] string2bytes(String hexString); static byte[] uncompress(final byte[] src); static byte[] compress(final byte[] src, final int level); static int asInt(String str, int defaultValue); static long asLong(String str, long defaultValue); static String formatDate(Date date, String pattern); static Date parseDate(String date, String pattern); static String responseCode2String(final int code); static String frontStringAtLeast(final String str, final int size); static boolean isBlank(String str); static String jstack(); static String jstack(Map<Thread, StackTraceElement[]> map); static boolean isInternalIP(byte[] ip); static String ipToIPv4Str(byte[] ip); static byte[] getIP(); static final String yyyy_MM_dd_HH_mm_ss; static final String yyyy_MM_dd_HH_mm_ss_SSS; static final String yyyyMMddHHmmss; }### Answer: @Test public void test_isBlank() { { boolean result = UtilAll.isBlank("Hello "); assertTrue(!result); } { boolean result = UtilAll.isBlank(" Hello"); assertTrue(!result); } { boolean result = UtilAll.isBlank("He llo"); assertTrue(!result); } { boolean result = UtilAll.isBlank(" "); assertTrue(result); } { boolean result = UtilAll.isBlank("Hello"); assertTrue(!result); } }
### Question: MixAll { public static List<String> getLocalInetAddress() { List<String> inetAddressList = new ArrayList<String>(); try { Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces(); while (enumeration.hasMoreElements()) { NetworkInterface networkInterface = enumeration.nextElement(); Enumeration<InetAddress> addrs = networkInterface.getInetAddresses(); while (addrs.hasMoreElements()) { inetAddressList.add(addrs.nextElement().getHostAddress()); } } } catch (SocketException e) { throw new RuntimeException("get local inet address fail", e); } return inetAddressList; } static String getRetryTopic(final String consumerGroup); static boolean isSysConsumerGroup(final String consumerGroup); static boolean isSystemTopic(final String topic); static String getDLQTopic(final String consumerGroup); static String brokerVIPChannel(final boolean isChange, final String brokerAddr); static long getPID(); static long createBrokerId(final String ip, final int port); static final void string2File(final String str, final String fileName); static final void string2FileNotSafe(final String str, final String fileName); static final String file2String(final String fileName); static final String file2String(final File file); static final String file2String(final URL url); static String findClassPath(Class<?> c); static void printObjectProperties(final Logger log, final Object object); static void printObjectProperties(final Logger log, final Object object, final boolean onlyImportantField); static String properties2String(final Properties properties); static Properties string2Properties(final String str); static Properties object2Properties(final Object object); static void properties2Object(final Properties p, final Object object); static boolean isPropertiesEqual(final Properties p1, final Properties p2); static List<String> getLocalInetAddress(); static boolean isLocalAddr(String address); static boolean compareAndIncreaseOnly(final AtomicLong target, final long value); static String localhostName(); Set<String> list2Set(List<String> values); List<String> set2List(Set<String> values); static final String ROCKETMQ_HOME_ENV; static final String ROCKETMQ_HOME_PROPERTY; static final String NAMESRV_ADDR_ENV; static final String NAMESRV_ADDR_PROPERTY; static final String MESSAGE_COMPRESS_LEVEL; static final String WS_DOMAIN_NAME; static final String WS_DOMAIN_SUBGROUP; static final String WS_ADDR; static final String DEFAULT_TOPIC; static final String BENCHMARK_TOPIC; static final String DEFAULT_PRODUCER_GROUP; static final String DEFAULT_CONSUMER_GROUP; static final String TOOLS_CONSUMER_GROUP; static final String FILTERSRV_CONSUMER_GROUP; static final String MONITOR_CONSUMER_GROUP; static final String CLIENT_INNER_PRODUCER_GROUP; static final String SELF_TEST_PRODUCER_GROUP; static final String SELF_TEST_CONSUMER_GROUP; static final String SELF_TEST_TOPIC; static final String OFFSET_MOVED_EVENT; static final String ONS_HTTP_PROXY_GROUP; static final String CID_ONSAPI_PERMISSION_GROUP; static final String CID_ONSAPI_OWNER_GROUP; static final String CID_ONSAPI_PULL_GROUP; static final String CID_RMQ_SYS_PREFIX; static final List<String> LocalInetAddrs; static final String Localhost; static final String DEFAULT_CHARSET; static final long MASTER_ID; static final long CURRENT_JVM_PID; static final String RETRY_GROUP_TOPIC_PREFIX; static final String DLQ_GROUP_TOPIC_PREFIX; static final String SYSTEM_TOPIC_PREFIX; static final String UNIQUE_MSG_QUERY_FLAG; }### Answer: @Test public void test() throws Exception { List<String> localInetAddress = MixAll.getLocalInetAddress(); String local = InetAddress.getLocalHost().getHostAddress(); Assert.assertTrue(localInetAddress.contains("127.0.0.1")); Assert.assertTrue(localInetAddress.contains(local)); }
### Question: ModelUtils { @NonNull static <T extends ModelObject> T deserializeModel(@NonNull JSONObject jsonObject, @NonNull Class<T> modelClass) { final ModelObject.Serializer<T> serializer = (ModelObject.Serializer<T>) ModelUtils.readModelSerializer(modelClass); return serializer.deserialize(jsonObject); } private ModelUtils(); @Nullable static T deserializeOpt(@Nullable JSONObject jsonObject, @NonNull ModelObject.Serializer<T> serializer); @Nullable static List<T> deserializeOptList(@Nullable JSONArray jsonArray, @NonNull ModelObject.Serializer<T> serializer); @Nullable static JSONObject serializeOpt(@Nullable T modelObject, @NonNull ModelObject.Serializer<T> serializer); @Nullable static JSONArray serializeOptList(@Nullable List<T> modelList, @NonNull ModelObject.Serializer<T> serializer); static final String SERIALIZER_FIELD_NAME; }### Answer: @Test public void parseModel_Pass_ParseMockedModelByClass() { JSONObject jsonObject = new JSONObject(); MockModelObject parsedResult = ModelUtils.deserializeModel(jsonObject, MockModelObject.class); assertNotNull(parsedResult); }
### Question: JsonUtils { @Nullable public static List<String> parseOptStringList(@Nullable JSONArray jsonArray) { if (jsonArray == null) { return null; } final List<String> list = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { final String item = jsonArray.optString(i, null); if (item != null) { list.add(item); } } return Collections.unmodifiableList(list); } private JsonUtils(); @NonNull static String indent(@Nullable JSONObject jsonObject); static void writeToParcel(@NonNull Parcel parcel, @Nullable JSONObject jsonObject); @Nullable static JSONObject readFromParcel(@NonNull Parcel parcel); @Nullable static List<String> parseOptStringList(@Nullable JSONArray jsonArray); @Nullable static JSONArray serializeOptStringList(@Nullable List<String> stringList); static final int INDENTATION_SPACES; }### Answer: @Test public void parseOptStringList_Pass_ParseEmptyArray() { JSONArray jsonArray = new JSONArray(); List<String> stringList = JsonUtils.parseOptStringList(jsonArray); Assert.assertNotNull(stringList); Assert.assertTrue(stringList.isEmpty()); } @SuppressWarnings("ConstantConditions") @Test public void parseOptStringList_Pass_ParseNull() { List<String> stringList = JsonUtils.parseOptStringList(null); Assert.assertNull(stringList); } @Test public void parseOptStringList_Pass_ParseStringArray() { JSONArray jsonArray = new JSONArray(); String testString = "Test"; jsonArray.put(testString); List<String> stringList = JsonUtils.parseOptStringList(jsonArray); Assert.assertNotNull(stringList); String first = stringList.get(0); Assert.assertEquals(testString, first); }
### Question: BaseHttpUrlConnectionFactory { @NonNull HttpURLConnection createHttpUrlConnection(@NonNull String url) throws IOException { final HttpURLConnection urlConnection = (HttpURLConnection) new URL(url).openConnection(); if (urlConnection instanceof HttpsURLConnection) { ((HttpsURLConnection) urlConnection).setSSLSocketFactory(TLS_SOCKET_FACTORY); return urlConnection; } else { return handleInsecureConnection(urlConnection); } } }### Answer: @Test public void initBaseHttpUrl_Pass_HTTPS_ExpectSecureConnection() throws IOException { String url = "https: HttpURLConnection urlConnection = new BaseHttpUrlConnectionFactory() { @NonNull @Override HttpURLConnection handleInsecureConnection(@NonNull HttpURLConnection httpUrlConnection) { assertEquals(1, 2); return httpUrlConnection; } }.createHttpUrlConnection(url); assertEquals(urlConnection.getURL().toString(), url); } @Test public void initBaseHttpUrl_Pass_HTTPS_ExpectInsecureConnection() throws IOException { final String url = "http: HttpURLConnection urlConnection = new BaseHttpUrlConnectionFactory() { @NonNull @Override HttpURLConnection handleInsecureConnection(@NonNull HttpURLConnection httpUrlConnection) { assertEquals(httpUrlConnection.getURL().toString(), url); return httpUrlConnection; } }.createHttpUrlConnection(url); }
### Question: ModelUtils { @Nullable public static <T extends ModelObject> T deserializeOpt(@Nullable JSONObject jsonObject, @NonNull ModelObject.Serializer<T> serializer) { return jsonObject == null ? null : serializer.deserialize(jsonObject); } private ModelUtils(); @Nullable static T deserializeOpt(@Nullable JSONObject jsonObject, @NonNull ModelObject.Serializer<T> serializer); @Nullable static List<T> deserializeOptList(@Nullable JSONArray jsonArray, @NonNull ModelObject.Serializer<T> serializer); @Nullable static JSONObject serializeOpt(@Nullable T modelObject, @NonNull ModelObject.Serializer<T> serializer); @Nullable static JSONArray serializeOptList(@Nullable List<T> modelList, @NonNull ModelObject.Serializer<T> serializer); static final String SERIALIZER_FIELD_NAME; }### Answer: @Test public void parseOpt_Pass_ParseMockedModel() { JSONObject jsonObject = new JSONObject(); MockModelObject parsedResult = ModelUtils.deserializeOpt(jsonObject, MockModelObject.SERIALIZER); Assert.assertNotNull(parsedResult); } @SuppressWarnings("ConstantConditions") @Test public void parseOpt_Pass_ParseNull() { MockModelObject parsedResult = ModelUtils.deserializeOpt(null, MockModelObject.SERIALIZER); Assert.assertNull(parsedResult); }
### Question: ModelUtils { @Nullable public static <T extends ModelObject> List<T> deserializeOptList(@Nullable JSONArray jsonArray, @NonNull ModelObject.Serializer<T> serializer) { if (jsonArray == null) { return null; } final List<T> list = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { final JSONObject itemJson = jsonArray.optJSONObject(i); if (itemJson != null) { final T item = serializer.deserialize(itemJson); list.add(item); } } return Collections.unmodifiableList(list); } private ModelUtils(); @Nullable static T deserializeOpt(@Nullable JSONObject jsonObject, @NonNull ModelObject.Serializer<T> serializer); @Nullable static List<T> deserializeOptList(@Nullable JSONArray jsonArray, @NonNull ModelObject.Serializer<T> serializer); @Nullable static JSONObject serializeOpt(@Nullable T modelObject, @NonNull ModelObject.Serializer<T> serializer); @Nullable static JSONArray serializeOptList(@Nullable List<T> modelList, @NonNull ModelObject.Serializer<T> serializer); static final String SERIALIZER_FIELD_NAME; }### Answer: @Test public void parseOptList_Pass_ParseMockedModel() { JSONArray jsonArray = new JSONArray(); List<MockModelObject> modelList = ModelUtils.deserializeOptList(jsonArray, MockModelObject.SERIALIZER); Assert.assertNotNull(modelList); } @SuppressWarnings("ConstantConditions") @Test public void parseOptList_Pass_ParseNull() { List<MockModelObject> modelList = ModelUtils.deserializeOptList(null, MockModelObject.SERIALIZER); Assert.assertNull(modelList); }
### Question: ModelUtils { @Nullable public static <T extends ModelObject> JSONObject serializeOpt(@Nullable T modelObject, @NonNull ModelObject.Serializer<T> serializer) { return modelObject == null ? null : serializer.serialize(modelObject); } private ModelUtils(); @Nullable static T deserializeOpt(@Nullable JSONObject jsonObject, @NonNull ModelObject.Serializer<T> serializer); @Nullable static List<T> deserializeOptList(@Nullable JSONArray jsonArray, @NonNull ModelObject.Serializer<T> serializer); @Nullable static JSONObject serializeOpt(@Nullable T modelObject, @NonNull ModelObject.Serializer<T> serializer); @Nullable static JSONArray serializeOptList(@Nullable List<T> modelList, @NonNull ModelObject.Serializer<T> serializer); static final String SERIALIZER_FIELD_NAME; }### Answer: @Test public void serializeOpt_Pass_SerializeMockedModel() { MockModelObject mockModelObject = new MockModelObject(); JSONObject jsonObject = ModelUtils.serializeOpt(mockModelObject, MockModelObject.SERIALIZER); Assert.assertNotNull(jsonObject); } @SuppressWarnings("ConstantConditions") @Test public void serializeOpt_Pass_SerializeNull() { JSONObject jsonObject = ModelUtils.serializeOpt(null, MockModelObject.SERIALIZER); Assert.assertNull(jsonObject); }
### Question: ModelUtils { @Nullable public static <T extends ModelObject> JSONArray serializeOptList(@Nullable List<T> modelList, @NonNull ModelObject.Serializer<T> serializer) { if (modelList == null || modelList.isEmpty()) { return null; } final JSONArray jsonArray = new JSONArray(); for (T model : modelList) { jsonArray.put(serializer.serialize(model)); } return jsonArray; } private ModelUtils(); @Nullable static T deserializeOpt(@Nullable JSONObject jsonObject, @NonNull ModelObject.Serializer<T> serializer); @Nullable static List<T> deserializeOptList(@Nullable JSONArray jsonArray, @NonNull ModelObject.Serializer<T> serializer); @Nullable static JSONObject serializeOpt(@Nullable T modelObject, @NonNull ModelObject.Serializer<T> serializer); @Nullable static JSONArray serializeOptList(@Nullable List<T> modelList, @NonNull ModelObject.Serializer<T> serializer); static final String SERIALIZER_FIELD_NAME; }### Answer: @Test public void serializeOptList_Pass_SerializeMockedModelList() { List<MockModelObject> modelObjectList = new ArrayList<>(); modelObjectList.add(new MockModelObject()); JSONArray jsonArray = ModelUtils.serializeOptList(modelObjectList, MockModelObject.SERIALIZER); Assert.assertNotNull(jsonArray); Assert.assertTrue(!jsonArray.isNull(0)); } @SuppressWarnings("ConstantConditions") @Test public void serializeOptList_Pass_SerializeNull() { JSONArray jsonArray = ModelUtils.serializeOptList(null, MockModelObject.SERIALIZER); Assert.assertNull(jsonArray); }
### Question: XmlUtils { public static List<String> determineArrays(InputStream in) throws XMLStreamException { Set<String> arrayKeys = new HashSet<>(); XMLStreamReader sr = null; try { XMLInputFactory f = XMLInputFactory.newFactory(); sr = f.createXMLStreamReader(in); getObjectElements(null, sr, new LongAdder(), arrayKeys); if (LOGGER.isDebugEnabled()) { StringBuilder sb = new StringBuilder(); arrayKeys.forEach(key -> sb.append(sb.length() > 0 ? "\n" : "").append(key)); LOGGER.trace("Found arrays:\n{}", sb.toString()); } } finally { if (null != sr) { sr.close(); } } return new ArrayList<>(arrayKeys); } private XmlUtils(); static List<String> determineArrays(InputStream in); }### Answer: @Test public void testParseXml() throws FileNotFoundException, XMLStreamException { XMLInputFactory f = XMLInputFactory.newFactory(); File inputFile = new File(getClass().getResource("/SampleXml.xml").getFile()); XMLStreamReader sr = f.createXMLStreamReader(new FileInputStream(inputFile)); InputStream in = new FileInputStream(inputFile); List<String> arrays = XmlUtils.determineArrays(in); Assert.assertFalse(arrays.isEmpty()); Assert.assertEquals(2, arrays.size()); Assert.assertEquals("/root/channel", arrays.get(0)); Assert.assertEquals("/root/channel/formats/format", arrays.get(1)); sr.close(); }
### Question: CustomPatternFileFilter implements FileFilter { @Override public boolean accept(File file) { String fileNameInLowerCase = file.getName().toLowerCase(); FileTypeEnum fileType = FileTypeEnum.parseByFileName(fileNameInLowerCase); return (null != fileType) && fileNameInLowerCase.matches(pattern); } CustomPatternFileFilter(String pattern); @Override boolean accept(File file); }### Answer: @Test public void testFilteringXmlByPartialFileNamePatternFalse() { String pattern = "*Fle*.xml"; File file = new File("SomeFileWithXml.xml"); CustomPatternFileFilter filter = new CustomPatternFileFilter(pattern); Assert.assertFalse(filter.accept(file)); } @Test public void testFilteringXmlByPartialFileNamePatternCaseInsensitive() { String pattern = "*File*.xml"; File file = new File("Some FileWithXml.XML"); CustomPatternFileFilter filter = new CustomPatternFileFilter(pattern); Assert.assertTrue(filter.accept(file)); } @Test public void testFilteringJsonByPattern() { String pattern = "*.json"; File file = new File("SomeFileWithJson.json"); CustomPatternFileFilter filter = new CustomPatternFileFilter(pattern); Assert.assertTrue(filter.accept(file)); } @Test public void testFilteringUnsupportedExtension() { String pattern = "*.txt"; File file = new File("SomeFileWithJson.txt"); CustomPatternFileFilter filter = new CustomPatternFileFilter(pattern); Assert.assertFalse(filter.accept(file)); } @Test public void testFilteringXmlByPattern() { String pattern = "*.xml"; File file = new File("SomeFileWithXml.xml"); CustomPatternFileFilter filter = new CustomPatternFileFilter(pattern); Assert.assertTrue(filter.accept(file)); } @Test public void testFilteringXmlByPatternFalse() { String pattern = "*.xml"; File file = new File("SomeFileWithXml.json"); CustomPatternFileFilter filter = new CustomPatternFileFilter(pattern); Assert.assertFalse(filter.accept(file)); } @Test public void testFilteringXmlByPartialFileNamePattern() { String pattern = "*File*.xml"; File file = new File("SomeFileWithXml.xml"); CustomPatternFileFilter filter = new CustomPatternFileFilter(pattern); Assert.assertTrue(filter.accept(file)); }
### Question: ApplicationUtils { public static final String getVersion() { String version = getVersionFromManifest(); if (null == version || version.isEmpty()) { version = UNNOWN_VERSION; } return version; } private ApplicationUtils(); static final String getVersion(); static final String UNNOWN_VERSION; }### Answer: @Test public void testApplicationVersion() { Assert.assertEquals(ApplicationUtils.UNNOWN_VERSION, ApplicationUtils.getVersion()); } @Test public void getImplementationVersion() throws Exception { PowerMockito.spy(ApplicationUtils.class); PowerMockito.doReturn("1.0.0").when(ApplicationUtils.class, "getVersionFromManifest"); String s = ApplicationUtils.getVersion(); PowerMockito.verifyStatic(Package.class); Assert.assertEquals("1.0.0", s); } @Test public void getImplementationVersionEmptyValue() throws Exception { PowerMockito.spy(ApplicationUtils.class); PowerMockito.doReturn("").when(ApplicationUtils.class, "getVersionFromManifest"); String s = ApplicationUtils.getVersion(); PowerMockito.verifyStatic(Package.class); Assert.assertEquals(ApplicationUtils.UNNOWN_VERSION, s); }
### Question: HostServicesProvider { public HostServices getHostServices() { if (hostServices == null) { throw new IllegalStateException("Host services not initialized"); } return hostServices; } void init(HostServices hostServices); HostServices getHostServices(); static final HostServicesProvider INSTANCE; }### Answer: @Test(expected = IllegalStateException.class) public void testNotInitializedInstance() { HostServicesProvider.INSTANCE.getHostServices(); }
### Question: PropertiesLoader { public Properties load() throws IOException { Properties properties = new Properties(); LOGGER.debug("Loading properties from {}", propertiesFile.getAbsolutePath()); if (propertiesFile.exists()) { try (InputStream in = new FileInputStream(propertiesFile)) { properties.load(in); LOGGER.debug("Loaded {} properties", properties.size()); } } else { throw new FileNotFoundException("File '" + propertiesFile.getAbsolutePath() + "' is not exist"); } return properties; } PropertiesLoader(File propertiesFile); Properties load(); void saveProperties(Properties properties); }### Answer: @Test(expected = FileNotFoundException.class) public void testLoadFromNonExistingFile() throws IOException { PropertiesLoader loader = new PropertiesLoader(new File("someProperties.txt")); loader.load(); } @Test public void testLoad() throws IOException { PropertiesLoader loader = new PropertiesLoader(getPropertiesFile()); Properties props = loader.load(); Assert.assertEquals(4, props.size()); } @Test(expected = FileNotFoundException.class) public void testLoadFileNotExists() throws IOException { File propsFile = new File(getDestinationDirectory(), "someFolder" + TEST_FILE); PropertiesLoader loader = new PropertiesLoader(propsFile); loader.load(); }
### Question: ApplicationProperties { public void setPropertiesLoader(PropertiesLoader loader) { if (loader == null) { throw new IllegalArgumentException("Properties loader cannot be null"); } this.loader = loader; } ApplicationProperties(PropertiesLoader loader); String getLastOpenedPath(); void saveLastOpenedPath(File path); void setPropertiesLoader(PropertiesLoader loader); }### Answer: @Test(expected = IllegalArgumentException.class) public void testApplicationPropertiesSetNullLoader() { File propsFile = new File(getDestinationDirectory(), TEST_FILE); ApplicationProperties props = new ApplicationProperties(new PropertiesLoader(propsFile)); Assert.assertNotNull(props); props.setPropertiesLoader(null); } @Test public void testApplicationPropertiesSetNotNullLoader() { File propsFile = new File(getDestinationDirectory(), TEST_FILE); PropertiesLoader loader = new PropertiesLoader(propsFile); ApplicationProperties props = new ApplicationProperties(new PropertiesLoader(propsFile)); Assert.assertNotNull(props); props.setPropertiesLoader(loader); }
### Question: ApplicationProperties { public String getLastOpenedPath() { if (!isInitialized) { loadProperties(); } String path = properties.getProperty(Config.LAST_DIRECTORY); if (null == path || path.trim().isEmpty()) { return null; } else { File f = new File(path); if (!f.exists()) { return null; } } return path; } ApplicationProperties(PropertiesLoader loader); String getLastOpenedPath(); void saveLastOpenedPath(File path); void setPropertiesLoader(PropertiesLoader loader); }### Answer: @Test public void testGetPropertiesAndPathNotExists() { File propsFile = new File(getDestinationDirectory(), TEST_FILE); ApplicationProperties props = new ApplicationProperties(new PropertiesLoader(propsFile)); Assert.assertNotNull(props); String path = props.getLastOpenedPath(); Assert.assertNull(path); path = props.getLastOpenedPath(); Assert.assertNull(path); } @Test public void testGetPropertiesAndPathIsEmpty() throws IOException { File propsFile = new File(getDestinationDirectory(), TEST_FILE); PropertiesLoader loader = new PropertiesLoader(propsFile); ApplicationProperties appProps = new ApplicationProperties(loader); Properties props = loader.load(); props.put(Config.LAST_DIRECTORY, ""); loader.saveProperties(props); String path = appProps.getLastOpenedPath(); Assert.assertNull(path); } @Test public void testGetPropertiesAndPathWithOnlySpaces() throws IOException { File propsFile = new File(getDestinationDirectory(), TEST_FILE); PropertiesLoader loader = new PropertiesLoader(propsFile); ApplicationProperties appProps = new ApplicationProperties(loader); Properties props = loader.load(); props.put(Config.LAST_DIRECTORY, " "); loader.saveProperties(props); String path = appProps.getLastOpenedPath(); Assert.assertNull(path); } @Test public void testGetPropertiesAndPathIsNotExist() throws IOException { File propsFile = new File(getDestinationDirectory(), TEST_FILE); PropertiesLoader loader = new PropertiesLoader(propsFile); ApplicationProperties appProps = new ApplicationProperties(loader); Properties props = loader.load(); props.put(Config.LAST_DIRECTORY, new File(propsFile.getParentFile(), "someNameFolder/file.txt").getAbsolutePath()); loader.saveProperties(props); String path = appProps.getLastOpenedPath(); Assert.assertNull(path); } @Test public void testLoadWithException() throws IOException { PropertiesLoader loader = Mockito.mock(PropertiesLoader.class); BDDMockito.when(loader.load()).thenThrow(new IOException()); ApplicationProperties appProps = Mockito.spy(new ApplicationProperties(loader)); String path = appProps.getLastOpenedPath(); Assert.assertNull(path); }
### Question: ApplicationCommandLine { public static ApplicationCommandLine parse(String[] args) throws java.text.ParseException, FileNotFoundException { CommandLineParser parser = new DefaultParser(); ApplicationCommandLine cmd = null; try { cmd = new ApplicationCommandLine(parser.parse(OPTIONS, args, true)); cmd.checkInputParameters(); } catch (ParseException ex) { throw new java.text.ParseException(ex.getMessage(), 0); } return cmd; } private ApplicationCommandLine(CommandLine cmd); static ApplicationCommandLine parse(String[] args); static void printHelp(); boolean isNoGuiEnabled(); File getSourceFolder(); File getDestinationFolder(); String getPattern(); boolean isForceOverwrite(); }### Answer: @Test(expected = ParseException.class) public void testParseNoGuiAndSourceFolderWithoutValue() throws ParseException, FileNotFoundException { String[] args = new String[]{"--noGui", "--sourceFolder", "--destinationFolder", DESTINATION_FOLDER_PATH, "--pattern", "*.json"}; ApplicationCommandLine.parse(args); }
### Question: ApplicationCommandLine { public static void printHelp() { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(HELP_WINDOW_SIZE, "\n java -jar xml2json.jar " + PARAM_SIGN + Config.PAR_NO_GUI + " " + PARAM_SIGN + Config.PAR_SOURCE_FOLDER + "=[path_to_source_folder] " + PARAM_SIGN + Config.PAR_DESTINATION_FOLDER + "=[path_to_destination_folder] " + PARAM_SIGN + Config.PAR_SOURCE_FILE_PATTERN + "=[*.json|*.xml]", ", where:", OPTIONS, "example:\n java -jar xml2json.jar " + PARAM_SIGN + Config.PAR_NO_GUI + " " + PARAM_SIGN + Config.PAR_SOURCE_FOLDER + "=C:\\temp\\input " + PARAM_SIGN + Config.PAR_DESTINATION_FOLDER + "=C:\\temp\\output " + PARAM_SIGN + Config.PAR_SOURCE_FILE_PATTERN + "=*.json\n\n"); } private ApplicationCommandLine(CommandLine cmd); static ApplicationCommandLine parse(String[] args); static void printHelp(); boolean isNoGuiEnabled(); File getSourceFolder(); File getDestinationFolder(); String getPattern(); boolean isForceOverwrite(); }### Answer: @Test public void testPrintHelp() { ApplicationCommandLine.printHelp(); }
### Question: JsonXMLArrayProvider extends AbstractJsonXMLProvider { @Override protected boolean isReadWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { if (!isSupported(mediaType)) { return false; } Class<?> componentType = getComponentType(type, genericType); return componentType != null && getJsonXML(componentType, annotations) != null && isBindable(componentType); } JsonXMLArrayProvider(@Context Providers providers); @Override Object read( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, Reader stream); @Override void write( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, Writer stream, Object entry); }### Answer: @Test public void testIsReadWriteable() throws NoSuchFieldException { JsonXMLArrayProvider provider = new JsonXMLArrayProvider(null); Annotation[] annotations = new Annotation[]{JsonXMLDefault.class.getAnnotation(JsonXML.class)}; Type type = getClass().getDeclaredField("sampleRootElementList").getGenericType(); Assert.assertTrue(provider.isReadWriteable(List.class, type, annotations, MediaType.APPLICATION_JSON_TYPE)); type = getClass().getDeclaredField("sampleTypeList").getGenericType(); Assert.assertTrue(provider.isReadWriteable(List.class, type, annotations, MediaType.APPLICATION_JSON_TYPE)); type = getClass().getDeclaredField("objectList").getGenericType(); Assert.assertFalse(provider.isReadWriteable(List.class, type, annotations, MediaType.APPLICATION_JSON_TYPE)); type = getClass().getDeclaredField("sampleTypeIterable").getGenericType(); Assert.assertFalse(provider.isReadWriteable(Iterable.class, type, annotations, MediaType.APPLICATION_JSON_TYPE)); type = getClass().getDeclaredField("sampleTypeList").getGenericType(); Assert.assertFalse(provider.isReadWriteable(List.class, type, new Annotation[0], MediaType.APPLICATION_JSON_TYPE)); Assert.assertFalse(provider.isReadWriteable(List.class, type, annotations, MediaType.APPLICATION_XML_TYPE)); }
### Question: JsonXMLArrayProvider extends AbstractJsonXMLProvider { @Override public void write( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, Writer stream, Object entry) throws IOException, WebApplicationException { Class<?> componentType = getComponentType(type, genericType); JsonXML config = getJsonXML(componentType, annotations); Collection<?> collection; if (entry == null) { collection = null; } else if (type.isArray()) { collection = Arrays.asList((Object[]) entry); } else { collection = (Collection<?>) entry; } try { writeArray(componentType, config, getContext(componentType, mediaType), stream, collection); } catch (XMLStreamException e) { throw new WebApplicationException(e, Status.INTERNAL_SERVER_ERROR); } catch (JAXBException e) { throw new WebApplicationException(e, Status.INTERNAL_SERVER_ERROR); } } JsonXMLArrayProvider(@Context Providers providers); @Override Object read( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, Reader stream); @Override void write( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, Writer stream, Object entry); }### Answer: @Test public void testWriteSampleRootElementList() throws Exception { JsonXMLArrayProvider provider = new JsonXMLArrayProvider(null); Annotation[] annotations = new Annotation[0]; Type type = getClass().getDeclaredField("sampleRootElementList").getGenericType(); List<SampleRootElement> list = new ArrayList<SampleRootElement>(); list.add(new SampleRootElement()); list.get(0).attribute = "hello"; list.add(new SampleRootElement()); list.get(1).attribute = "world"; StringWriter writer = new StringWriter(); provider.write(List.class, type, annotations, MediaType.APPLICATION_JSON_TYPE, null, writer, list); String json = "[{\"sampleRootElement\":{\"@attribute\":\"hello\"}},{\"sampleRootElement\":{\"@attribute\":\"world\"}}]"; Assert.assertEquals(json, writer.toString()); } @Test public void testWriteSampleTypeList() throws Exception { JsonXMLArrayProvider provider = new JsonXMLArrayProvider(null); Annotation[] annotations = new Annotation[]{JsonXMLDefault.class.getAnnotation(JsonXML.class)}; Type type = getClass().getDeclaredField("sampleTypeList").getGenericType(); List<SampleType> list = new ArrayList<SampleType>(); list.add(new SampleType()); list.get(0).element = "hello"; list.add(new SampleType()); list.get(1).element = "world"; StringWriter writer = new StringWriter(); provider.write(List.class, type, annotations, MediaType.APPLICATION_JSON_TYPE, null, writer, list); String json = "[{\"sampleType\":{\"element\":\"hello\"}},{\"sampleType\":{\"element\":\"world\"}}]"; Assert.assertEquals(json, writer.toString()); } @Test public void testWriteEmptyList() throws Exception { JsonXMLArrayProvider provider = new JsonXMLArrayProvider(null); Annotation[] annotations = new Annotation[0]; Type type = getClass().getDeclaredField("sampleRootElementList").getGenericType(); List<SampleRootElement> list = new ArrayList<SampleRootElement>(); StringWriter writer = new StringWriter(); provider.write(List.class, type, annotations, MediaType.APPLICATION_JSON_TYPE, null, writer, list); String json = "[]"; Assert.assertEquals(json, writer.toString()); } @Test public void testWriteEmptyListWithVirtualRoot() throws Exception { JsonXMLArrayProvider provider = new JsonXMLArrayProvider(null); Annotation[] annotations = new Annotation[]{JsonXMLVirtualSampleRootElement.class.getAnnotation(JsonXML.class)}; Type type = getClass().getDeclaredField("sampleRootElementList").getGenericType(); List<SampleRootElement> list = new ArrayList<SampleRootElement>(); StringWriter writer = new StringWriter(); provider.write(List.class, type, annotations, MediaType.APPLICATION_JSON_TYPE, null, writer, list); String json = "[]"; Assert.assertEquals(json, writer.toString()); }
### Question: AbstractJsonXMLProvider extends JsonXMLBinder implements MessageBodyReader<Object>, MessageBodyWriter<Object> { protected static <A extends Annotation> A getAnnotation(Annotation[] annotations, Class<A> annotationType) { for (Annotation annotation : annotations) { if (annotation.annotationType() == annotationType) { return annotationType.cast(annotation); } } return null; } AbstractJsonXMLProvider(Providers providers); @Override boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override long getSize(Object t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); abstract Object read( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, Reader entityStream); @Override final Object readFrom( Class<Object> type, // <-- how sad... Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream); abstract void write( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, Writer entityStream, Object entry); @Override final void writeTo( Object entry, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream); }### Answer: @Test public void testGetAnnotation() { Annotation[] annotations = new Annotation[2]; annotations[0] = SampleType.class.getAnnotation(XmlType.class); annotations[1] = JsonXMLDefault.class.getAnnotation(JsonXML.class); Assert.assertEquals(XmlType.class, AbstractJsonXMLProvider.getAnnotation(annotations, XmlType.class).annotationType()); Assert.assertEquals(JsonXML.class, AbstractJsonXMLProvider.getAnnotation(annotations, JsonXML.class).annotationType()); Assert.assertNull(AbstractJsonXMLProvider.getAnnotation(annotations, XmlRootElement.class)); }
### Question: AbstractJsonXMLProvider extends JsonXMLBinder implements MessageBodyReader<Object>, MessageBodyWriter<Object> { protected String getCharset(MediaType mediaType) { Map<String, String> parameters = mediaType.getParameters(); return parameters.containsKey("charset") ? parameters.get("charset") : "UTF-8"; } AbstractJsonXMLProvider(Providers providers); @Override boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override long getSize(Object t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); abstract Object read( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, Reader entityStream); @Override final Object readFrom( Class<Object> type, // <-- how sad... Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream); abstract void write( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, Writer entityStream, Object entry); @Override final void writeTo( Object entry, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream); }### Answer: @Test public void testGetCharset() { Assert.assertEquals("UTF-8", new TestProvider().getCharset(MediaType.APPLICATION_JSON_TYPE)); Map<String, String> parameters = new HashMap<String, String>(); parameters.put("charset", "ASCII"); MediaType customMediaType = new MediaType("application", "json", parameters); Assert.assertEquals("ASCII", new TestProvider().getCharset(customMediaType)); }
### Question: ConverterUtils { public static File getConvertedFile(File sourceFile, File destinationFolder) { FileTypeEnum fileType = FileTypeEnum.parseByFileName(sourceFile.getName()); String convertedFileName = ""; String fileNameWithoutExtension = sourceFile.getName().substring(0, sourceFile.getName().lastIndexOf('.')); switch (fileType) { case JSON: convertedFileName = fileNameWithoutExtension + FileTypeEnum.XML.getExtension(); break; case XML: convertedFileName = fileNameWithoutExtension + FileTypeEnum.JSON.getExtension(); break; default: throw new UnsupportedFileType("Unsupported file's extension"); } return new File(destinationFolder, convertedFileName); } private ConverterUtils(); static File getConvertedFile(File sourceFile, File destinationFolder); }### Answer: @Test public void testGetConvertedFileForJson() { File sourceFile = new File("someJsonFile.json"); File outputDirectory = new File("."); File outFile = ConverterUtils.getConvertedFile(sourceFile, outputDirectory); Assert.assertEquals("someJsonFile.xml", outFile.getName()); } @Test public void testGetConvertedFileForXml() { File sourceFile = new File("someFile.xml"); File outputDirectory = new File("."); File outFile = ConverterUtils.getConvertedFile(sourceFile, outputDirectory); Assert.assertEquals("someFile.json", outFile.getName()); } @Test(expected = NullPointerException.class) public void testGetConvertedFileWithUnsupportedFile() { File sourceFile = new File("someIncorrectFile.txt"); File outputDirectory = new File("."); ConverterUtils.getConvertedFile(sourceFile, outputDirectory); }
### Question: AbstractJsonXMLProvider extends JsonXMLBinder implements MessageBodyReader<Object>, MessageBodyWriter<Object> { protected JsonXML getJsonXML(Class<?> type, Annotation[] resourceAnnotations) { JsonXML result = getAnnotation(resourceAnnotations, JsonXML.class); if (result == null) { result = type.getAnnotation(JsonXML.class); } return result; } AbstractJsonXMLProvider(Providers providers); @Override boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override long getSize(Object t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); abstract Object read( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, Reader entityStream); @Override final Object readFrom( Class<Object> type, // <-- how sad... Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream); abstract void write( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, Writer entityStream, Object entry); @Override final void writeTo( Object entry, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream); }### Answer: @Test public void testGetJsonXML() { JsonXML typeAnnotation = SampleRootElement.class.getAnnotation(JsonXML.class); Assert.assertEquals(typeAnnotation, new TestProvider().getJsonXML(SampleRootElement.class, new Annotation[0])); Annotation[] resourceAnnotations = new Annotation[]{JsonXMLDefault.class.getAnnotation(JsonXML.class)}; Assert.assertEquals(resourceAnnotations[0], new TestProvider().getJsonXML(SampleType.class, resourceAnnotations)); Assert.assertNull(new TestProvider().getJsonXML(SampleType.class, new Annotation[0])); }
### Question: AbstractJsonXMLProvider extends JsonXMLBinder implements MessageBodyReader<Object>, MessageBodyWriter<Object> { @Override public long getSize(Object t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } AbstractJsonXMLProvider(Providers providers); @Override boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override long getSize(Object t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); abstract Object read( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, Reader entityStream); @Override final Object readFrom( Class<Object> type, // <-- how sad... Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream); abstract void write( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, Writer entityStream, Object entry); @Override final void writeTo( Object entry, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream); }### Answer: @Test public void testGetSize() { Assert.assertEquals(-1, new TestProvider().getSize(null, null, null, null, null)); }
### Question: AbstractJsonXMLProvider extends JsonXMLBinder implements MessageBodyReader<Object>, MessageBodyWriter<Object> { protected boolean isSupported(MediaType mediaType) { return "json".equalsIgnoreCase(mediaType.getSubtype()) || mediaType.getSubtype().endsWith("+json"); } AbstractJsonXMLProvider(Providers providers); @Override boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); @Override long getSize(Object t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType); abstract Object read( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, Reader entityStream); @Override final Object readFrom( Class<Object> type, // <-- how sad... Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream); abstract void write( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, Writer entityStream, Object entry); @Override final void writeTo( Object entry, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream); }### Answer: @Test public void testIsSupported() { Assert.assertTrue(new TestProvider().isSupported(MediaType.APPLICATION_JSON_TYPE)); Assert.assertTrue(new TestProvider().isSupported(new MediaType("text", "json"))); Assert.assertTrue(new TestProvider().isSupported(new MediaType("text", "JSON"))); Assert.assertTrue(new TestProvider().isSupported(new MediaType("text", "special+json"))); Assert.assertFalse(new TestProvider().isSupported(MediaType.APPLICATION_XML_TYPE)); }
### Question: JsonXMLObjectProvider extends AbstractJsonXMLProvider { @Override protected boolean isReadWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return isSupported(mediaType) && getJsonXML(type, annotations) != null && isBindable(type); } JsonXMLObjectProvider(@Context Providers providers); @Override Object read( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, Reader stream); @Override void write( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, Writer stream, Object value); }### Answer: @Test public void testIsReadWriteable() { JsonXMLObjectProvider provider = new JsonXMLObjectProvider(null); Annotation[] jsonXMLAnnotations = new Annotation[]{JsonXMLDefault.class.getAnnotation(JsonXML.class)}; Assert.assertTrue(provider.isReadWriteable(SampleRootElement.class, null, jsonXMLAnnotations, MediaType.APPLICATION_JSON_TYPE)); Assert.assertTrue(provider.isReadWriteable(SampleType.class, null, jsonXMLAnnotations, MediaType.APPLICATION_JSON_TYPE)); Assert.assertFalse(provider.isReadWriteable(Object.class, null, jsonXMLAnnotations, MediaType.APPLICATION_JSON_TYPE)); Assert.assertFalse(provider.isReadWriteable(SampleType.class, null, new Annotation[0], MediaType.APPLICATION_JSON_TYPE)); Assert.assertFalse(provider.isReadWriteable(SampleRootElement.class, null, jsonXMLAnnotations, MediaType.APPLICATION_XML_TYPE)); }
### Question: JsonXMLObjectProvider extends AbstractJsonXMLProvider { @Override public Object read( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, Reader stream) throws IOException, WebApplicationException { JsonXML config = getJsonXML(type, annotations); try { return readObject(type, config, getContext(type, mediaType), stream); } catch (XMLStreamException | JAXBException e) { throw new WebApplicationException(e, Status.INTERNAL_SERVER_ERROR); } } JsonXMLObjectProvider(@Context Providers providers); @Override Object read( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, Reader stream); @Override void write( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, Writer stream, Object value); }### Answer: @Test public void testReadSampleRootElement() throws Exception { JsonXMLObjectProvider provider = new JsonXMLObjectProvider(null); Annotation[] annotations = new Annotation[0]; String json = "{\"sampleRootElement\":{\"@attribute\":\"hello\",\"elements\":[\"world\"]}}"; SampleRootElement sampleRootElement = (SampleRootElement)provider.read(SampleRootElement.class, null, annotations, MediaType.APPLICATION_JSON_TYPE, null, new StringReader(json)); Assert.assertEquals("hello", sampleRootElement.attribute); Assert.assertEquals("world", sampleRootElement.elements.get(0)); } @Test public void testReadSampleType() throws Exception { JsonXMLObjectProvider provider = new JsonXMLObjectProvider(null); Annotation[] annotations = new Annotation[]{JsonXMLDefault.class.getAnnotation(JsonXML.class)}; String json = "{\"sampleType\":{\"element\":\"hi!\"}}"; SampleType sampleType = (SampleType)provider.read(SampleType.class, null, annotations, MediaType.APPLICATION_JSON_TYPE, null, new StringReader(json)); Assert.assertEquals("hi!", sampleType.element); } @Test public void testReadNull() throws Exception { JsonXMLObjectProvider provider = new JsonXMLObjectProvider(null); Annotation[] annotations = new Annotation[0]; String json = "null"; SampleRootElement sampleRootElement = (SampleRootElement)provider.read(SampleRootElement.class, null, annotations, MediaType.APPLICATION_JSON_TYPE, null, new StringReader(json)); Assert.assertNull(sampleRootElement); } @Test public void testReadNullWithVirtualRoot() throws Exception { JsonXMLObjectProvider provider = new JsonXMLObjectProvider(null); Annotation[] annotations = new Annotation[]{JsonXMLVirtualSampleRootElement.class.getAnnotation(JsonXML.class)}; String json = "null"; SampleRootElement sampleRootElement = (SampleRootElement)provider.read(SampleRootElement.class, null, annotations, MediaType.APPLICATION_JSON_TYPE, null, new StringReader(json)); Assert.assertNotNull(sampleRootElement); }
### Question: JsonXMLObjectProvider extends AbstractJsonXMLProvider { @Override public void write( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, Writer stream, Object value) throws IOException, WebApplicationException { JsonXML config = getJsonXML(type, annotations); try { writeObject(type, config, getContext(type, mediaType), stream, value); } catch (XMLStreamException | JAXBException e) { throw new WebApplicationException(e, Status.INTERNAL_SERVER_ERROR); } } JsonXMLObjectProvider(@Context Providers providers); @Override Object read( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, Reader stream); @Override void write( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, Writer stream, Object value); }### Answer: @Test public void testWriteSampleRootElement() throws Exception { JsonXMLObjectProvider provider = new JsonXMLObjectProvider(null); Annotation[] annotations = new Annotation[0]; SampleRootElement sampleRootElement = new SampleRootElement(); sampleRootElement.attribute = "hello"; sampleRootElement.elements = Arrays.asList("world"); StringWriter writer = new StringWriter(); provider.write(SampleRootElement.class, null, annotations, MediaType.APPLICATION_JSON_TYPE, null, writer, sampleRootElement); String json = "{\"sampleRootElement\":{\"@attribute\":\"hello\",\"elements\":[\"world\"]}}"; Assert.assertEquals(json, writer.toString()); } @Test public void testWriteSampleType() throws Exception { JsonXMLObjectProvider provider = new JsonXMLObjectProvider(null); Annotation[] annotations = new Annotation[]{JsonXMLDefault.class.getAnnotation(JsonXML.class)}; SampleType sampleType = new SampleType(); sampleType.element = "hi!"; StringWriter writer = new StringWriter(); provider.write(SampleType.class, null, annotations, MediaType.APPLICATION_JSON_TYPE, null, writer, sampleType); String json = "{\"sampleType\":{\"element\":\"hi!\"}}"; Assert.assertEquals(json, writer.toString()); } @Test public void testWriteNull() throws Exception { JsonXMLObjectProvider provider = new JsonXMLObjectProvider(null); Annotation[] annotations = new Annotation[0]; StringWriter writer = new StringWriter(); provider.write(SampleRootElement.class, null, annotations, MediaType.APPLICATION_JSON_TYPE, null, writer, null); String json = "null"; Assert.assertEquals(json, writer.toString()); } @Test public void testWriteNullWithVirtualRoot() throws Exception { JsonXMLObjectProvider provider = new JsonXMLObjectProvider(null); Annotation[] annotations = new Annotation[]{JsonXMLVirtualSampleRootElement.class.getAnnotation(JsonXML.class)}; StringWriter writer = new StringWriter(); provider.write(SampleRootElement.class, null, annotations, MediaType.APPLICATION_JSON_TYPE, null, writer, null); String json = "null"; Assert.assertEquals(json, writer.toString()); }
### Question: WebhookAPI { @GET @Produces(MediaType.APPLICATION_JSON) public static Response get() { return Responses.ok(Webhooks.instance().hooks()); } @GET @Produces(MediaType.APPLICATION_JSON) static Response get(); @GET @Path("/{id}") @Produces(MediaType.APPLICATION_JSON) static Response get(@PathParam("id") long id); @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) static Response create( @Context UriInfo uriInfo, InputStream reqBody); @PATCH @Path("/{id}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) static Response update( @PathParam("id") long id, InputStream reqBody); @DELETE @Path("/{id}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) static Response delete(@PathParam("id") long id); @POST @Path("/{id}/pings") @Consumes(MediaType.APPLICATION_JSON) static Response ping(@PathParam("id") long id); }### Answer: @Test public void _3_get1() throws Exception { Response res = target("").path("1").request() .get(); assertEquals(200, res.getStatus()); assertEquals( "{\"active\":false,\"callback_url\":\"" + CALLBACK_URL + "\",\"failed\":false,\"filter\":{\"exists\":[],\"for_all\":[]},\"id\":1,\"message\":null}", res.readEntity(String.class)); } @Test public void _8_get_not_found() throws Exception { Response res = target("").path("1").request() .get(); assertEquals(404, res.getStatus()); } @Test public void _9_getAll() throws Exception { String body2 = "{\"callback_url\": \"" + CALLBACK_URL + "/2\"}"; String body3 = "{\"callback_url\": \"" + CALLBACK_URL + "/3\"}"; String body4 = "{\"callback_url\": \"" + CALLBACK_URL + "/4\"}"; target("").request().post(Entity.entity(body2, MediaType.APPLICATION_JSON_TYPE)); target("").request().post(Entity.entity(body3, MediaType.APPLICATION_JSON_TYPE)); target("").request().post(Entity.entity(body4, MediaType.APPLICATION_JSON_TYPE)); Response res = target("").request().get(); assertEquals(200, res.getStatus()); assertEquals("[" + "{\"active\":true,\"callback_url\":\"" + CALLBACK_URL + "/2\",\"failed\":false,\"filter\":{\"exists\":[],\"for_all\":[]},\"id\":2,\"message\":null}," + "{\"active\":true,\"callback_url\":\"" + CALLBACK_URL + "/3\",\"failed\":false,\"filter\":{\"exists\":[],\"for_all\":[]},\"id\":3,\"message\":null}," + "{\"active\":true,\"callback_url\":\"" + CALLBACK_URL + "/4\",\"failed\":false,\"filter\":{\"exists\":[],\"for_all\":[]},\"id\":4,\"message\":null}" + "]", res.readEntity(String.class)); }
### Question: WebhookAPI { @DELETE @Path("/{id}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public static Response delete(@PathParam("id") long id) throws NotFound { boolean removed = Webhooks.instance().remove(id); if (removed) { return Responses.noContent(); } else { return Responses.badRequest(); } } @GET @Produces(MediaType.APPLICATION_JSON) static Response get(); @GET @Path("/{id}") @Produces(MediaType.APPLICATION_JSON) static Response get(@PathParam("id") long id); @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) static Response create( @Context UriInfo uriInfo, InputStream reqBody); @PATCH @Path("/{id}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) static Response update( @PathParam("id") long id, InputStream reqBody); @DELETE @Path("/{id}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) static Response delete(@PathParam("id") long id); @POST @Path("/{id}/pings") @Consumes(MediaType.APPLICATION_JSON) static Response ping(@PathParam("id") long id); }### Answer: @Test public void _7_delete() throws Exception { Response res = target("").path("1").request() .delete(); assertEquals(204, res.getStatus()); }
### Question: Notifier implements ServletContextListener { public static URL getDtoChangesUri(TransactionId.W tx, DateTime time) throws IOException { NotifierConfig conf = NotifierConfig.instance(); String urlStr = new Formatter().format( "http: conf.naefAddr(), conf.naefRestApiPort(), conf.naefRestApiVersion()) .toString(); StringJoiner queries = new StringJoiner("&"); if (tx != null) { queries.add("version=" + tx.toString()); } if (time != null) { queries.add("time=" + time.getValue()); } if (queries.length() > 0) { urlStr += "?" + queries.toString(); } return new URL(urlStr); } Notifier(); static synchronized void start(); static void main(String[] args); @Override void contextInitialized(ServletContextEvent sce); @Override void contextDestroyed(ServletContextEvent sce); static URL getDtoChangesUri(TransactionId.W tx, DateTime time); static Map<String, Object> getDtoChangesJson(TransactionId.W tx, DateTime time); static final String KEY_ROOT_DIR; static final String DEFAULT_ROOT_DIR_NAME; static final String BASE_DIR; }### Answer: @Test public void DtoChangesURLを生成() throws Exception { URL url = Notifier.getDtoChangesUri(tx, time); assertEquals( "http: url.toString()); }
### Question: NameUtilities { public static String getFullName(Class c) { if (c == null) { throw new IllegalArgumentException("class cannot be null"); } StringBuilder name = new StringBuilder(); name.append(c.getPackage().getName()).append("."); Class klaus = c; List<Class> enclosingClasses = new ArrayList<Class>(); while ((klaus = klaus.getEnclosingClass()) != null) { enclosingClasses.add(klaus); } for (int i = enclosingClasses.size() - 1; i >= 0; i--) { name.append(enclosingClasses.get(i).getSimpleName()).append("."); } name.append(c.getSimpleName()); return name.toString(); } static String getFullName(Class c); }### Answer: @Test public void testInnerClassNaming() { String expected = NameUtilitiesTest.class.getPackage().getName()+"." + NameUtilitiesTest.class.getSimpleName()+"." + "Inner" ; String name = NameUtilities.getFullName(Inner.class); Assert.assertEquals(expected, name); }
### Question: SparqlQcReader { public static List<Resource> loadTasks(String baseFile) throws IOException { List<Resource> testSuites = loadTestSuites(baseFile); List<Resource> testCases = extractTasks(testSuites); return testCases; } static List<Resource> loadTestSuitesSqcf(String baseFile); static List<Resource> extractTasks(Collection<Resource> testSuites); static List<Resource> loadTasksSqcf(String baseFile); static void renameProperty(Model model, Property p, String uri); static void normalizeSqcfModel(Model testSuitesModel); static List<Resource> loadTestSuites(String baseFile); static List<Resource> loadTestSuites(Model testSuitesModel, String baseFile); static List<Resource> loadTasks(String baseFile); static void enrichTestCasesWithLabels(Model model); static RDFNode resolveIoResourceRef(Resource testCase, Property property, // String basePath, Map<String, RDFNode> cache, BiFunction<String, Model, RDFNode> rdfizer); static void loadTestSuite(Resource testSuite, String basePath); static Resource processQueryRecordUnchecked( org.springframework.core.io.Resource resource, Model inout); static Long parseSchemaId(String ref); static Resource parseQueryId(String ref); static String createQueryResourceIri(String baseIri, Resource qr); static Resource createSchemaResource(Long id); static Resource processSchemaUnchecked( org.springframework.core.io.Resource resource, Model inout); static Resource processSchema(org.springframework.core.io.Resource resource, Model inout); static Resource processQueryRecord(org.springframework.core.io.Resource resource, Model inout); @Deprecated static Model readQueryFolder(String path); static final Property LSQtext; static final Pattern queryNamePattern; static final Pattern schemaNamePattern; }### Answer: @Test public void testReadSchema() throws IOException { List<Resource> tasks = SparqlQcReader.loadTasks("sparqlqc/1.4/benchmark/ucqrdfs.rdf"); for(Resource task : tasks) { RDFDataMgr.write(System.out, task.getModel(), RDFFormat.TURTLE); } }
### Question: SparqlStmtUtils { public static SparqlStmt optimizePrefixes(SparqlStmt stmt) { optimizePrefixes(stmt, null); return stmt; } static Map<String, Boolean> mentionedEnvVars(SparqlStmt stmt); static List<Var> getUnionProjectVars(Collection<? extends SparqlStmt> stmts); static SparqlStmt optimizePrefixes(SparqlStmt stmt); static SparqlStmt optimizePrefixes(SparqlStmt stmt, PrefixMapping globalPm); static SparqlStmt applyOpTransform(SparqlStmt stmt, Function<? super Op, ? extends Op> transform); static SparqlStmt applyNodeTransform(SparqlStmt stmt, NodeTransform xform); static SparqlStmtIterator processFile(PrefixMapping pm, String filenameOrURI); static URI extractBaseIri(String filenameOrURI); static String loadString(String filenameOrURI); static TypedInputStream openInputStream(String filenameOrURI); static SparqlStmtIterator processFile(PrefixMapping pm, String filenameOrURI, String baseIri); static SparqlStmtIterator processInputStream(PrefixMapping pm, String baseIri, InputStream in); static SparqlStmtIterator parse(InputStream in, Function<String, SparqlStmt> parser); static SPARQLResultEx execAny(RDFConnection conn, SparqlStmt stmt); static Sink<Quad> createSinkQuads(RDFFormat format, OutputStream out, PrefixMapping pm, Supplier<Dataset> datasetSupp); static void output( SPARQLResultEx rr, SPARQLResultVisitor sink); static void output( SPARQLResultEx rr, Consumer<Quad> sink ); static void output(SPARQLResultEx r); static void process(RDFConnection conn, SparqlStmt stmt, SPARQLResultVisitor sink); static void processOld(RDFConnection conn, SparqlStmt stmt); static Op toAlgebra(SparqlStmt stmt); static final Symbol symConnection; }### Answer: @Test public void testUsedPrefixes1() { PrefixMapping pm = RDFDataMgr.loadModel("rdf-prefixes/wikidata.jsonld"); String queryStr = "SELECT ?s ?desc WHERE {\n" + " ?s wdt:P279 wd:Q7725634 .\n" + " OPTIONAL {\n" + " ?s rdfs:label ?desc \n" + " FILTER (LANG(?desc) = \"en\").\n" + " }\n" + "}"; SparqlStmt stmt = SparqlStmtParserImpl.create(pm).apply(queryStr); SparqlStmtUtils.optimizePrefixes(stmt); Query query = stmt.getQuery(); Set<String> actual = query.getPrefixMapping().getNsPrefixMap().keySet(); Assert.assertEquals(Sets.newHashSet("rdfs", "wd", "wdt"), actual); } @Test public void testUsedPrefixes2() { PrefixMapping pm = RDFDataMgr.loadModel("rdf-prefixes/wikidata.jsonld"); String queryStr = "INSERT {" + " ?s wdt:P279 wd:Q7725634 .\n" + "}\n" + " WHERE {\n" + " ?s rdfs:label ?desc \n" + " FILTER (LANG(?desc) = \"en\").\n" + " }\n"; SparqlStmt stmt = SparqlStmtParserImpl.create(pm).apply(queryStr); SparqlStmtUtils.optimizePrefixes(stmt); UpdateRequest updateRequest = stmt.getUpdateRequest(); Set<String> actual = updateRequest.getPrefixMapping().getNsPrefixMap().keySet(); Assert.assertEquals(Sets.newHashSet("rdfs", "wd", "wdt"), actual); }
### Question: UriUtils { public static String replaceNamespace(String base, String replacement) { Matcher m = replaceNamespacePattern.matcher(base); String result = m.replaceAll(replacement); return result; } static Map<String, String> createMapFromUriQueryString(URI uri); static String getNameSpace(String s); static String getLocalName(String s); static String replaceNamespace(String base, String replacement); static Multimap<String, String> parseQueryString(String queryString); static Multimap<String, String> parseQueryStringEx(String queryString); static final Pattern replaceNamespacePattern; }### Answer: @Test public void test() { String r = UriUtils.replaceNamespace("http: Assert.assertEquals("http: }
### Question: QueryUtils { public static PrefixMapping usedPrefixes(Query query, PrefixMapping global) { PrefixMapping local = query.getPrefixMapping(); PrefixMapping pm = global == null ? local : new PrefixMapping2(global, local); PrefixMapping result = usedReferencePrefixes(query, pm); return result; } static Query applyOpTransform(Query beforeQuery, Function<? super Op, ? extends Op> transform); static Query restoreQueryForm(Query query, Query proto); static Query selectToConstruct(Query query, Template template); static Query rewrite(Query beforeQuery, Function<? super Op, ? extends Op> xform); static Element asPatternForConstruct(Query q); static boolean canActAsConstruct(Query q); static Set<Var> mentionedVars(Query query); static Set<Node> mentionedNodes(Query query); static Var freshVar(Query query); static Var freshVar(Query query, String baseVarName); static Map<String, Node> applyNodeTransform(Map<String, Node> jsonMapping, NodeTransform nodeTransform); static Query applyNodeTransform(Query query, NodeTransform nodeTransform); static PrefixMapping usedPrefixes(Query query, PrefixMapping global); static PrefixMapping usedPrefixes(Query query); static PrefixMapping usedReferencePrefixes(Query query, PrefixMapping pm); static Query optimizePrefixes(Query query, PrefixMapping globalPm); static Query optimizePrefixes(Query query); static Query randomizeVars(Query query); static Map<Var, Var> createRandomVarMap(Query query, String base); static void injectFilter(Query query, String exprStr); static void injectFilter(Query query, Expr expr); static void injectElement(Query query, Element element); static Range<Long> toRange(OpSlice op); static Op applyRange(Op op, Range<Long> range); static Query applySlice(Query query, Long offset, Long limit, boolean cloneOnChange); static void applyRange(Query query, Range<Long> range); static Range<Long> createRange(Long limit, Long offset); static long rangeToOffset(Range<Long> range); static long rangeToLimit(Range<Long> range); static Range<Long> toRange(Query query); static Range<Long> toRange(Long offset, Long limit); static Range<Long> subRange(Range<Long> parent, Range<Long> child); static void applyDatasetDescription(Query query, DatasetDescription dd); static Query fixVarNames(Query query); static Query elementToQuery(Element pattern, String resultVar); static Query elementToQuery(Element pattern); static Set<Quad> instanciate(Iterable<Quad> quads, Binding binding); }### Answer: @Test public void testReducedPrefixes() { Query query = QueryFactory.create(String.join("\n", "PREFIX rdf: <http: "PREFIX foo: <http: "PREFIX bar: <http: "PREFIX baz: <http: "SELECT * {", " { SELECT * {", " ?s a foo:Foo.", " } }", " ?s rdf:type foo:Bar", "}")); PrefixMapping pm = org.aksw.jena_sparql_api.utils.QueryUtils.usedPrefixes(query); Assert.assertEquals(pm.getNsPrefixMap().keySet(), new HashSet<>(Arrays.asList("rdf", "foo"))); }
### Question: JSONReader { public Attributes readDataset(Attributes attrs) { boolean wrappedInArray = next() == Event.START_ARRAY; if (wrappedInArray) next(); expect(Event.START_OBJECT); if (attrs == null) { attrs = new Attributes(); } fmi = null; next(); doReadDataset(attrs); if (wrappedInArray) next(); return attrs; } JSONReader(JsonParser parser); boolean isSkipBulkDataURI(); void setSkipBulkDataURI(boolean skipBulkDataURI); Attributes getFileMetaInformation(); Attributes readDataset(Attributes attrs); void readDatasets(Callback callback); }### Answer: @Test public void test() { StringReader reader = new StringReader(JSON); JsonParser parser = Json.createParser(reader); Attributes dataset = new JSONReader(parser).readDataset(null); assertArrayEquals(IS, dataset.getStrings(Tag.SelectorISValue)); assertArrayEquals(DS, dataset.getStrings(Tag.SelectorDSValue)); assertInfinityAndNaN(dataset.getDoubles(Tag.SelectorFDValue)); assertInfinityAndNaN(dataset.getFloats(Tag.SelectorFLValue)); }
### Question: ByteUtils { public static byte[] floatToBytesBE(float f, byte[] bytes, int off) { return intToBytesBE(Float.floatToIntBits(f), bytes, off); } static int bytesToVR(byte[] bytes, int off); static int bytesToUShort(byte[] bytes, int off, boolean bigEndian); static int bytesToUShortBE(byte[] bytes, int off); static int bytesToUShortLE(byte[] bytes, int off); static int bytesToShort(byte[] bytes, int off, boolean bigEndian); static int bytesToShortBE(byte[] bytes, int off); static int bytesToShortLE(byte[] bytes, int off); static void bytesToShorts(byte[] b, short[] s, int off, int len, boolean bigEndian); static void bytesToShortsLE(byte[] b, short[] s, int off, int len); static void bytesToShortsBE(byte[] b, short[] s, int off, int len); static int bytesToInt(byte[] bytes, int off, boolean bigEndian); static int bytesToIntBE(byte[] bytes, int off); static int bytesToIntLE(byte[] bytes, int off); static int bytesToTag(byte[] bytes, int off, boolean bigEndian); static int bytesToTagBE(byte[] bytes, int off); static int bytesToTagLE(byte[] bytes, int off); static float bytesToFloat(byte[] bytes, int off, boolean bigEndian); static float bytesToFloatBE(byte[] bytes, int off); static float bytesToFloatLE(byte[] bytes, int off); static long bytesToLong(byte[] bytes, int off, boolean bigEndian); static long bytesToLongBE(byte[] bytes, int off); static long bytesToLongLE(byte[] bytes, int off); static double bytesToDouble(byte[] bytes, int off, boolean bigEndian); static double bytesToDoubleBE(byte[] bytes, int off); static double bytesToDoubleLE(byte[] bytes, int off); static byte[] shortToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] shortToBytesBE(int i, byte[] bytes, int off); static byte[] shortToBytesLE(int i, byte[] bytes, int off); static byte[] intToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] intToBytesBE(int i, byte[] bytes, int off); static byte[] intToBytesLE(int i, byte[] bytes, int off); static byte[] tagToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] tagToBytesBE(int i, byte[] bytes, int off); static byte[] tagToBytesLE(int i, byte[] bytes, int off); static byte[] floatToBytes(float f, byte[] bytes, int off, boolean bigEndian); static byte[] floatToBytesBE(float f, byte[] bytes, int off); static byte[] floatToBytesLE(float f, byte[] bytes, int off); static byte[] doubleToBytes(double d, byte[] bytes, int off, boolean bigEndian); static byte[] doubleToBytesBE(double d, byte[] bytes, int off); static byte[] doubleToBytesLE(double d, byte[] bytes, int off); static byte[] longToBytes(long l, byte[] bytes, int off, boolean bigEndian); static byte[] longToBytesBE(long l, byte[] bytes, int off); static byte[] longToBytesLE(long l, byte[] bytes, int off); static byte[][] swapShorts(byte bs[][]); static byte[] swapShorts(byte b[], int off, int len); static byte[] swapInts(byte b[], int off, int len); static byte[] swapLongs(byte b[], int off, int len); static byte[] intsToBytesLE(int... values); static final byte[] EMPTY_BYTES; static final int[] EMPTY_INTS; static final float[] EMPTY_FLOATS; static final double[] EMPTY_DOUBLES; }### Answer: @Test public void testFloatToBytesBE() { assertArrayEquals(FLOAT_PI_BE , ByteUtils.floatToBytesBE((float) Math.PI, new byte[4], 0)); }
### Question: ByteUtils { public static byte[] floatToBytesLE(float f, byte[] bytes, int off) { return intToBytesLE(Float.floatToIntBits(f), bytes, off); } static int bytesToVR(byte[] bytes, int off); static int bytesToUShort(byte[] bytes, int off, boolean bigEndian); static int bytesToUShortBE(byte[] bytes, int off); static int bytesToUShortLE(byte[] bytes, int off); static int bytesToShort(byte[] bytes, int off, boolean bigEndian); static int bytesToShortBE(byte[] bytes, int off); static int bytesToShortLE(byte[] bytes, int off); static void bytesToShorts(byte[] b, short[] s, int off, int len, boolean bigEndian); static void bytesToShortsLE(byte[] b, short[] s, int off, int len); static void bytesToShortsBE(byte[] b, short[] s, int off, int len); static int bytesToInt(byte[] bytes, int off, boolean bigEndian); static int bytesToIntBE(byte[] bytes, int off); static int bytesToIntLE(byte[] bytes, int off); static int bytesToTag(byte[] bytes, int off, boolean bigEndian); static int bytesToTagBE(byte[] bytes, int off); static int bytesToTagLE(byte[] bytes, int off); static float bytesToFloat(byte[] bytes, int off, boolean bigEndian); static float bytesToFloatBE(byte[] bytes, int off); static float bytesToFloatLE(byte[] bytes, int off); static long bytesToLong(byte[] bytes, int off, boolean bigEndian); static long bytesToLongBE(byte[] bytes, int off); static long bytesToLongLE(byte[] bytes, int off); static double bytesToDouble(byte[] bytes, int off, boolean bigEndian); static double bytesToDoubleBE(byte[] bytes, int off); static double bytesToDoubleLE(byte[] bytes, int off); static byte[] shortToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] shortToBytesBE(int i, byte[] bytes, int off); static byte[] shortToBytesLE(int i, byte[] bytes, int off); static byte[] intToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] intToBytesBE(int i, byte[] bytes, int off); static byte[] intToBytesLE(int i, byte[] bytes, int off); static byte[] tagToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] tagToBytesBE(int i, byte[] bytes, int off); static byte[] tagToBytesLE(int i, byte[] bytes, int off); static byte[] floatToBytes(float f, byte[] bytes, int off, boolean bigEndian); static byte[] floatToBytesBE(float f, byte[] bytes, int off); static byte[] floatToBytesLE(float f, byte[] bytes, int off); static byte[] doubleToBytes(double d, byte[] bytes, int off, boolean bigEndian); static byte[] doubleToBytesBE(double d, byte[] bytes, int off); static byte[] doubleToBytesLE(double d, byte[] bytes, int off); static byte[] longToBytes(long l, byte[] bytes, int off, boolean bigEndian); static byte[] longToBytesBE(long l, byte[] bytes, int off); static byte[] longToBytesLE(long l, byte[] bytes, int off); static byte[][] swapShorts(byte bs[][]); static byte[] swapShorts(byte b[], int off, int len); static byte[] swapInts(byte b[], int off, int len); static byte[] swapLongs(byte b[], int off, int len); static byte[] intsToBytesLE(int... values); static final byte[] EMPTY_BYTES; static final int[] EMPTY_INTS; static final float[] EMPTY_FLOATS; static final double[] EMPTY_DOUBLES; }### Answer: @Test public void testFloatToBytesLE() { assertArrayEquals(FLOAT_PI_LE , ByteUtils.floatToBytesLE((float) Math.PI, new byte[4], 0)); }
### Question: ByteUtils { public static byte[] doubleToBytesBE(double d, byte[] bytes, int off) { return longToBytesBE(Double.doubleToLongBits(d), bytes, off); } static int bytesToVR(byte[] bytes, int off); static int bytesToUShort(byte[] bytes, int off, boolean bigEndian); static int bytesToUShortBE(byte[] bytes, int off); static int bytesToUShortLE(byte[] bytes, int off); static int bytesToShort(byte[] bytes, int off, boolean bigEndian); static int bytesToShortBE(byte[] bytes, int off); static int bytesToShortLE(byte[] bytes, int off); static void bytesToShorts(byte[] b, short[] s, int off, int len, boolean bigEndian); static void bytesToShortsLE(byte[] b, short[] s, int off, int len); static void bytesToShortsBE(byte[] b, short[] s, int off, int len); static int bytesToInt(byte[] bytes, int off, boolean bigEndian); static int bytesToIntBE(byte[] bytes, int off); static int bytesToIntLE(byte[] bytes, int off); static int bytesToTag(byte[] bytes, int off, boolean bigEndian); static int bytesToTagBE(byte[] bytes, int off); static int bytesToTagLE(byte[] bytes, int off); static float bytesToFloat(byte[] bytes, int off, boolean bigEndian); static float bytesToFloatBE(byte[] bytes, int off); static float bytesToFloatLE(byte[] bytes, int off); static long bytesToLong(byte[] bytes, int off, boolean bigEndian); static long bytesToLongBE(byte[] bytes, int off); static long bytesToLongLE(byte[] bytes, int off); static double bytesToDouble(byte[] bytes, int off, boolean bigEndian); static double bytesToDoubleBE(byte[] bytes, int off); static double bytesToDoubleLE(byte[] bytes, int off); static byte[] shortToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] shortToBytesBE(int i, byte[] bytes, int off); static byte[] shortToBytesLE(int i, byte[] bytes, int off); static byte[] intToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] intToBytesBE(int i, byte[] bytes, int off); static byte[] intToBytesLE(int i, byte[] bytes, int off); static byte[] tagToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] tagToBytesBE(int i, byte[] bytes, int off); static byte[] tagToBytesLE(int i, byte[] bytes, int off); static byte[] floatToBytes(float f, byte[] bytes, int off, boolean bigEndian); static byte[] floatToBytesBE(float f, byte[] bytes, int off); static byte[] floatToBytesLE(float f, byte[] bytes, int off); static byte[] doubleToBytes(double d, byte[] bytes, int off, boolean bigEndian); static byte[] doubleToBytesBE(double d, byte[] bytes, int off); static byte[] doubleToBytesLE(double d, byte[] bytes, int off); static byte[] longToBytes(long l, byte[] bytes, int off, boolean bigEndian); static byte[] longToBytesBE(long l, byte[] bytes, int off); static byte[] longToBytesLE(long l, byte[] bytes, int off); static byte[][] swapShorts(byte bs[][]); static byte[] swapShorts(byte b[], int off, int len); static byte[] swapInts(byte b[], int off, int len); static byte[] swapLongs(byte b[], int off, int len); static byte[] intsToBytesLE(int... values); static final byte[] EMPTY_BYTES; static final int[] EMPTY_INTS; static final float[] EMPTY_FLOATS; static final double[] EMPTY_DOUBLES; }### Answer: @Test public void testDoubleToBytesBE() { assertArrayEquals(DOUBLE_PI_BE , ByteUtils.doubleToBytesBE(Math.PI, new byte[8], 0)); }
### Question: ByteUtils { public static byte[] doubleToBytesLE(double d, byte[] bytes, int off) { return longToBytesLE(Double.doubleToLongBits(d), bytes, off); } static int bytesToVR(byte[] bytes, int off); static int bytesToUShort(byte[] bytes, int off, boolean bigEndian); static int bytesToUShortBE(byte[] bytes, int off); static int bytesToUShortLE(byte[] bytes, int off); static int bytesToShort(byte[] bytes, int off, boolean bigEndian); static int bytesToShortBE(byte[] bytes, int off); static int bytesToShortLE(byte[] bytes, int off); static void bytesToShorts(byte[] b, short[] s, int off, int len, boolean bigEndian); static void bytesToShortsLE(byte[] b, short[] s, int off, int len); static void bytesToShortsBE(byte[] b, short[] s, int off, int len); static int bytesToInt(byte[] bytes, int off, boolean bigEndian); static int bytesToIntBE(byte[] bytes, int off); static int bytesToIntLE(byte[] bytes, int off); static int bytesToTag(byte[] bytes, int off, boolean bigEndian); static int bytesToTagBE(byte[] bytes, int off); static int bytesToTagLE(byte[] bytes, int off); static float bytesToFloat(byte[] bytes, int off, boolean bigEndian); static float bytesToFloatBE(byte[] bytes, int off); static float bytesToFloatLE(byte[] bytes, int off); static long bytesToLong(byte[] bytes, int off, boolean bigEndian); static long bytesToLongBE(byte[] bytes, int off); static long bytesToLongLE(byte[] bytes, int off); static double bytesToDouble(byte[] bytes, int off, boolean bigEndian); static double bytesToDoubleBE(byte[] bytes, int off); static double bytesToDoubleLE(byte[] bytes, int off); static byte[] shortToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] shortToBytesBE(int i, byte[] bytes, int off); static byte[] shortToBytesLE(int i, byte[] bytes, int off); static byte[] intToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] intToBytesBE(int i, byte[] bytes, int off); static byte[] intToBytesLE(int i, byte[] bytes, int off); static byte[] tagToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] tagToBytesBE(int i, byte[] bytes, int off); static byte[] tagToBytesLE(int i, byte[] bytes, int off); static byte[] floatToBytes(float f, byte[] bytes, int off, boolean bigEndian); static byte[] floatToBytesBE(float f, byte[] bytes, int off); static byte[] floatToBytesLE(float f, byte[] bytes, int off); static byte[] doubleToBytes(double d, byte[] bytes, int off, boolean bigEndian); static byte[] doubleToBytesBE(double d, byte[] bytes, int off); static byte[] doubleToBytesLE(double d, byte[] bytes, int off); static byte[] longToBytes(long l, byte[] bytes, int off, boolean bigEndian); static byte[] longToBytesBE(long l, byte[] bytes, int off); static byte[] longToBytesLE(long l, byte[] bytes, int off); static byte[][] swapShorts(byte bs[][]); static byte[] swapShorts(byte b[], int off, int len); static byte[] swapInts(byte b[], int off, int len); static byte[] swapLongs(byte b[], int off, int len); static byte[] intsToBytesLE(int... values); static final byte[] EMPTY_BYTES; static final int[] EMPTY_INTS; static final float[] EMPTY_FLOATS; static final double[] EMPTY_DOUBLES; }### Answer: @Test public void testDoubleToBytesLE() { assertArrayEquals(DOUBLE_PI_LE , ByteUtils.doubleToBytesLE(Math.PI, new byte[8], 0)); }
### Question: DicomInputStream extends FilterInputStream implements DicomInputHandler, BulkDataCreator { public Attributes readDataset(int len, int stopTag) throws IOException { handler.startDataset(this); readFileMetaInformation(); Attributes attrs = new Attributes(bigEndian, 64); readAttributes(attrs, len, stopTag); attrs.trimToSize(); handler.endDataset(this); return attrs; } DicomInputStream(InputStream in, String tsuid); DicomInputStream(InputStream in); DicomInputStream(File file); final String getTransferSyntax(); final int getAllocateLimit(); final void setAllocateLimit(int allocateLimit); final String getURI(); final void setURI(String uri); final IncludeBulkData getIncludeBulkData(); final void setIncludeBulkData(IncludeBulkData includeBulkData); final BulkDataDescriptor getBulkDataDescriptor(); final void setBulkDataDescriptor(BulkDataDescriptor bulkDataDescriptor); final String getBulkDataFilePrefix(); final void setBulkDataFilePrefix(String blkFilePrefix); final String getBulkDataFileSuffix(); final void setBulkDataFileSuffix(String blkFileSuffix); final File getBulkDataDirectory(); final void setBulkDataDirectory(File blkDirectory); final boolean isConcatenateBulkDataFiles(); final void setConcatenateBulkDataFiles(boolean catBlkFiles); final List<File> getBulkDataFiles(); final void setDicomInputHandler(DicomInputHandler handler); void setBulkDataCreator(BulkDataCreator bulkDataCreator); final void setFileMetaInformationGroupLength(byte[] val); final byte[] getPreamble(); Attributes getFileMetaInformation(); final int level(); final int tag(); final VR vr(); final int length(); final long getPosition(); void setPosition(long pos); long getTagPosition(); final boolean bigEndian(); final boolean explicitVR(); boolean isExcludeBulkData(); boolean isIncludeBulkDataURI(); static String toAttributePath(List<ItemPointer> itemPointers, int tag); String getAttributePath(); @Override void close(); @Override synchronized void mark(int readlimit); @Override synchronized void reset(); @Override final int read(); @Override final int read(byte[] b, int off, int len); @Override final int read(byte[] b); @Override final long skip(long n); void skipFully(long n); void readFully(byte b[]); void readFully(byte b[], int off, int len); void readFully(short[] s, int off, int len); void readHeader(); boolean readItemHeader(); Attributes readCommand(); Attributes readDataset(int len, int stopTag); Attributes readFileMetaInformation(); void readAttributes(Attributes attrs, int len, int stopTag); @Override void readValue(DicomInputStream dis, Attributes attrs); @Override BulkData createBulkData(DicomInputStream dis); @Override void readValue(DicomInputStream dis, Sequence seq); @Override void readValue(DicomInputStream dis, Fragments frags); @Override void startDataset(DicomInputStream dis); @Override void endDataset(DicomInputStream dis); Attributes readItem(); byte[] readValue(); }### Answer: @Test(expected = EOFException.class) public void testNoOutOfMemoryErrorOnInvalidLength() throws IOException { byte[] b = { 8, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 'e', 'v', 'i', 'l', 'l', 'e', 'n', 'g', 'h' }; try ( DicomInputStream in = new DicomInputStream(new ByteArrayInputStream(b))) { in.readDataset(-1, -1); } }
### Question: DicomOutputStream extends FilterOutputStream { public void writeCommand(Attributes cmd) throws IOException { if (explicitVR || bigEndian) throw new IllegalStateException("explicitVR=" + explicitVR + ", bigEndian=" + bigEndian); cmd.writeGroupTo(this, Tag.CommandGroupLength); } DicomOutputStream(OutputStream out, String tsuid); DicomOutputStream(File file); final void setPreamble(byte[] preamble); final boolean isExplicitVR(); final boolean isBigEndian(); final DicomEncodingOptions getEncodingOptions(); final void setEncodingOptions(DicomEncodingOptions encOpts); @Override void write(byte[] b, int off, int len); void writeCommand(Attributes cmd); void writeFileMetaInformation(Attributes fmi); void writeDataset(Attributes fmi, Attributes dataset); void switchTransferSyntax(String tsuid); void writeHeader(int tag, VR vr, int len); void writeAttribute(int tag, VR vr, Object value, SpecificCharacterSet cs); void writeAttribute(int tag, VR vr, byte[] val); void writeAttribute(int tag, VR vr, Value val); void writeGroupLength(int tag, int len); void finish(); void close(); }### Answer: @Test public void testWriteCommand() throws IOException { DicomOutputStream out = new DicomOutputStream( new FileOutputStream(file), UID.ImplicitVRLittleEndian); try { out.writeCommand(cechorq()); } finally { out.close(); } assertEquals(4, readAttributes().size()); }
### Question: AttributeSelector implements Serializable { public boolean matches(List<ItemPointer> itemPointers, String privateCreator, int tag) { int level; if (tag != this.tag || !Objects.equals(privateCreator, this.privateCreator) || (itemPointers.size() != (level = level()))) { return false; } for (int i = 0; i < level; i++) { ItemPointer itemPointer = itemPointers.get(i); ItemPointer other = itemPointer(i); if (!(itemPointer.itemIndex < 0 || other.itemIndex < 0 ? itemPointer.equalsIgnoreItemIndex(other) : itemPointer.equals(other))) { return false; } } return true; } AttributeSelector(int tag); AttributeSelector(int tag, String privateCreator); AttributeSelector(int tag, String privateCreator, ItemPointer... itemPointers); AttributeSelector(int tag, String privateCreator, List<ItemPointer> itemPointers); int tag(); String privateCreator(); int level(); ItemPointer itemPointer(int index); String selectStringValue(Attributes attrs, int valueIndex, String defVal); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); static AttributeSelector valueOf(String s); boolean matches(List<ItemPointer> itemPointers, String privateCreator, int tag); }### Answer: @Test public void testMatches() { ItemPointer ip = new ItemPointer(Tag.RequestAttributesSequence); AttributeSelector selector = new AttributeSelector(Tag.StudyInstanceUID, null, ip); assertTrue(selector.matches(Collections.singletonList(ip), null, Tag.StudyInstanceUID)); }
### Question: DicomOutputStream extends FilterOutputStream { public void writeDataset(Attributes fmi, Attributes dataset) throws IOException { if (fmi != null) { writeFileMetaInformation(fmi); switchTransferSyntax(fmi.getString(Tag.TransferSyntaxUID, null)); } if (dataset.bigEndian() != bigEndian || encOpts.groupLength || !encOpts.undefSequenceLength || !encOpts.undefItemLength) dataset = new Attributes(dataset, bigEndian); if (encOpts.groupLength) dataset.calcLength(encOpts, explicitVR); dataset.writeTo(this); } DicomOutputStream(OutputStream out, String tsuid); DicomOutputStream(File file); final void setPreamble(byte[] preamble); final boolean isExplicitVR(); final boolean isBigEndian(); final DicomEncodingOptions getEncodingOptions(); final void setEncodingOptions(DicomEncodingOptions encOpts); @Override void write(byte[] b, int off, int len); void writeCommand(Attributes cmd); void writeFileMetaInformation(Attributes fmi); void writeDataset(Attributes fmi, Attributes dataset); void switchTransferSyntax(String tsuid); void writeHeader(int tag, VR vr, int len); void writeAttribute(int tag, VR vr, Object value, SpecificCharacterSet cs); void writeAttribute(int tag, VR vr, byte[] val); void writeAttribute(int tag, VR vr, Value val); void writeGroupLength(int tag, int len); void finish(); void close(); }### Answer: @Test public void testWriteDataset() throws IOException { DicomOutputStream out = new DicomOutputStream(file); } @Test public void testWriteDeflatedEvenLength() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); try (DicomOutputStream dos = new DicomOutputStream( out, UID.DeflatedExplicitVRLittleEndian)) { Attributes attrs = new Attributes(); attrs.setString(Tag.SOPClassUID, VR.UI, UID.CTImageStorage); dos.writeDataset(null, attrs); } assertEquals("odd number of bytes", 0, out.size() & 1); }
### Question: DicomOutputStream extends FilterOutputStream { public final void setEncodingOptions(DicomEncodingOptions encOpts) { if (encOpts == null) throw new NullPointerException(); this.encOpts = encOpts; } DicomOutputStream(OutputStream out, String tsuid); DicomOutputStream(File file); final void setPreamble(byte[] preamble); final boolean isExplicitVR(); final boolean isBigEndian(); final DicomEncodingOptions getEncodingOptions(); final void setEncodingOptions(DicomEncodingOptions encOpts); @Override void write(byte[] b, int off, int len); void writeCommand(Attributes cmd); void writeFileMetaInformation(Attributes fmi); void writeDataset(Attributes fmi, Attributes dataset); void switchTransferSyntax(String tsuid); void writeHeader(int tag, VR vr, int len); void writeAttribute(int tag, VR vr, Object value, SpecificCharacterSet cs); void writeAttribute(int tag, VR vr, byte[] val); void writeAttribute(int tag, VR vr, Value val); void writeGroupLength(int tag, int len); void finish(); void close(); }### Answer: @Test public void testWriteDatasetWithGroupLength() throws IOException { DicomOutputStream out = new DicomOutputStream(file); out.setEncodingOptions( new DicomEncodingOptions(true, true, false, true, false)); testWriteDataset(out, UID.ExplicitVRLittleEndian); } @Test public void testWriteDatasetWithoutUndefLength() throws IOException { DicomOutputStream out = new DicomOutputStream(file); out.setEncodingOptions( new DicomEncodingOptions(false, false, false, false, false)); testWriteDataset(out, UID.ExplicitVRLittleEndian); } @Test public void testWriteDatasetWithUndefEmptyLength() throws IOException { DicomOutputStream out = new DicomOutputStream(file); out.setEncodingOptions( new DicomEncodingOptions(false, true, true, true, true)); testWriteDataset(out, UID.ExplicitVRLittleEndian); }
### Question: DicomOutputStream extends FilterOutputStream { public void close() throws IOException { try { finish(); } catch (IOException ignored) { } super.close(); } DicomOutputStream(OutputStream out, String tsuid); DicomOutputStream(File file); final void setPreamble(byte[] preamble); final boolean isExplicitVR(); final boolean isBigEndian(); final DicomEncodingOptions getEncodingOptions(); final void setEncodingOptions(DicomEncodingOptions encOpts); @Override void write(byte[] b, int off, int len); void writeCommand(Attributes cmd); void writeFileMetaInformation(Attributes fmi); void writeDataset(Attributes fmi, Attributes dataset); void switchTransferSyntax(String tsuid); void writeHeader(int tag, VR vr, int len); void writeAttribute(int tag, VR vr, Object value, SpecificCharacterSet cs); void writeAttribute(int tag, VR vr, byte[] val); void writeAttribute(int tag, VR vr, Value val); void writeGroupLength(int tag, int len); void finish(); void close(); }### Answer: @Test public void testSerializeDataset() throws Exception { ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream(file)); try { out.writeObject(dataset()); out.writeUTF("END"); } finally { out.close(); } deserializeAttributes(); }
### Question: DicomOutputStream extends FilterOutputStream { public void writeFileMetaInformation(Attributes fmi) throws IOException { if (!explicitVR || bigEndian || countingOutputStream != null) throw new IllegalStateException("explicitVR=" + explicitVR + ", bigEndian=" + bigEndian + ", deflated=" + (countingOutputStream != null)); write(preamble); write(DICM); fmi.writeGroupTo(this, Tag.FileMetaInformationGroupLength); } DicomOutputStream(OutputStream out, String tsuid); DicomOutputStream(File file); final void setPreamble(byte[] preamble); final boolean isExplicitVR(); final boolean isBigEndian(); final DicomEncodingOptions getEncodingOptions(); final void setEncodingOptions(DicomEncodingOptions encOpts); @Override void write(byte[] b, int off, int len); void writeCommand(Attributes cmd); void writeFileMetaInformation(Attributes fmi); void writeDataset(Attributes fmi, Attributes dataset); void switchTransferSyntax(String tsuid); void writeHeader(int tag, VR vr, int len); void writeAttribute(int tag, VR vr, Object value, SpecificCharacterSet cs); void writeAttribute(int tag, VR vr, byte[] val); void writeAttribute(int tag, VR vr, Value val); void writeGroupLength(int tag, int len); void finish(); void close(); }### Answer: @Test(expected = IllegalStateException.class) public void testWriteFMIDeflated() throws IOException { try (DicomOutputStream out = new DicomOutputStream( new ByteArrayOutputStream(), UID.DeflatedExplicitVRLittleEndian)) { out.writeFileMetaInformation( Attributes.createFileMetaInformation(UIDUtils.createUID(), UID.CTImageStorage, UID.DeflatedExplicitVRLittleEndian)); } }
### Question: RecordFactory { public RecordType getRecordType(String cuid) { if (cuid == null) throw new NullPointerException(); lazyLoadDefaultConfiguration(); RecordType recordType = recordTypes.get(cuid); return recordType != null ? recordType : RecordType.PRIVATE; } void loadDefaultConfiguration(); void loadConfiguration(String uri); RecordType getRecordType(String cuid); RecordType setRecordType(String cuid, RecordType type); void setRecordKeys(RecordType type, int[] keys); int[] getRecordKeys(RecordType type); String getPrivateRecordUID(String cuid); String setPrivateRecordUID(String cuid, String uid); int[] setPrivateRecordKeys(String uid, int[] keys); Attributes createRecord(Attributes dataset, Attributes fmi, String[] fileIDs); Attributes createRecord(RecordType type, String privRecUID, Attributes dataset, Attributes fmi, String[] fileIDs); }### Answer: @Test public void testGetRecordType() { RecordFactory f = new RecordFactory(); assertEquals(RecordType.IMAGE, f.getRecordType(UID.SecondaryCaptureImageStorage)); }
### Question: FindSCU { static void mergeKeys(Attributes attrs, Attributes keys) { try { attrs.accept(new MergeNested(keys), false); } catch (Exception e) { throw new RuntimeException(e); } attrs.addAll(keys); } FindSCU(); final void setPriority(int priority); final void setInformationModel(InformationModel model, String[] tss, EnumSet<QueryOption> queryOptions); void addLevel(String s); final void setCancelAfter(int cancelAfter); final void setOutputDirectory(File outDir); final void setOutputFileFormat(String outFileFormat); final void setXSLT(File xsltFile); final void setXML(boolean xml); final void setXMLIndent(boolean indent); final void setXMLIncludeKeyword(boolean includeKeyword); final void setXMLIncludeNamespaceDeclaration( boolean includeNamespaceDeclaration); final void setConcatenateOutputFiles(boolean catOut); final void setInputFilter(int[] inFilter); ApplicationEntity getApplicationEntity(); Connection getRemoteConnection(); AAssociateRQ getAAssociateRQ(); Association getAssociation(); Device getDevice(); Attributes getKeys(); @SuppressWarnings("unchecked") static void main(String[] args); void open(); void close(); void query(File f); void query(); void query( DimseRSPHandler rspHandler); }### Answer: @Test public void mergeNestedKeys() throws Exception { Attributes attrs = withSSA(returnKeys()); FindSCU.mergeKeys(attrs, withSSA(matchingKeys())); assertEquals(mergedKeys(), attrs.getNestedDataset(Tag.ScheduledStepAttributesSequence)); }
### Question: JSONWriter implements DicomInputHandler { public void write(Attributes attrs) { final SpecificCharacterSet cs = attrs.getSpecificCharacterSet(); gen.writeStartObject(); try { attrs.accept(new Attributes.Visitor(){ @Override public boolean visit(Attributes attrs, int tag, VR vr, Object value) throws Exception { writeAttribute(tag, vr, value, cs, attrs); return true; }}, false); } catch (Exception e) { throw new RuntimeException(e); } gen.writeEnd(); } JSONWriter(JsonGenerator gen); String getReplaceBulkDataURI(); void setReplaceBulkDataURI(String replaceBulkDataURI); void write(Attributes attrs); @Override void readValue(DicomInputStream dis, Attributes attrs); @Override void readValue(DicomInputStream dis, Sequence seq); @Override void readValue(DicomInputStream dis, Fragments frags); @Override void startDataset(DicomInputStream dis); @Override void endDataset(DicomInputStream dis); }### Answer: @Test public void test() { Attributes dataset = new Attributes(); dataset.setString(Tag.SpecificCharacterSet, VR.CS, null, "ISO 2022 IR 87"); dataset.setString(Tag.ImageType, VR.CS, "DERIVED", "PRIMARY"); Attributes item = new Attributes(2); dataset.newSequence(Tag.SourceImageSequence, 1).add(item); item.setString(Tag.ReferencedSOPClassUID, VR.UI, UID.CTImageStorage); item.setString(Tag.ReferencedSOPInstanceUID, VR.UI, "1.2.3.4"); dataset.setString(Tag.PatientName, VR.PN, "af^ag=if^ig=pf^pg"); dataset.setBytes("PRIVATE", 0x00090002, VR.OB, BYTE01); dataset.setDouble(Tag.FrameTime, VR.DS, 33.0); dataset.setInt(Tag.SamplesPerPixel, VR.US, 1); dataset.setInt(Tag.NumberOfFrames, VR.IS, 1); dataset.setInt(Tag.FrameIncrementPointer, VR.AT, Tag.FrameTime); dataset.setValue(Tag.OverlayData, VR.OW, new BulkData(null, "file:/OverlayData", false)); Fragments frags = dataset.newFragments(Tag.PixelData, VR.OB, 2); frags.add(null); frags.add(new BulkData(null, "file:/PixelData", false)); StringWriter writer = new StringWriter(); JsonGenerator gen = Json.createGenerator(writer); new JSONWriter(gen).write(dataset); gen.flush(); assertEquals(RESULT, writer.toString()); } @Test public void testInfinityAndNaN() { Attributes dataset = new Attributes(); dataset.setDouble(Tag.SelectorFDValue, VR.FD, Double.NEGATIVE_INFINITY, Double.NaN, Double.POSITIVE_INFINITY); dataset.setFloat(Tag.SelectorFLValue, VR.FL, Float.NEGATIVE_INFINITY, Float.NaN, Float.POSITIVE_INFINITY); StringWriter writer = new StringWriter(); JsonGenerator gen = Json.createGenerator(writer); new JSONWriter(gen).write(dataset); gen.flush(); assertEquals(INFINITY_AND_NAN, writer.toString()); }
### Question: LdapHL7Configuration extends LdapDicomConfigurationExtension implements HL7Configuration { @Override public HL7Application findHL7Application(String name) throws ConfigurationException { Device device = config.findDevice( "(&(objectclass=hl7Application)(hl7ApplicationName=" + name + "))", name); HL7DeviceExtension hl7Ext = device.getDeviceExtension(HL7DeviceExtension.class); return hl7Ext.getHL7Application(name); } void addHL7ConfigurationExtension(LdapHL7ConfigurationExtension ext); boolean removeHL7ConfigurationExtension( LdapHL7ConfigurationExtension ext); @Override boolean registerHL7Application(String name); @Override void unregisterHL7Application(String name); @Override String[] listRegisteredHL7ApplicationNames(); @Override HL7Application findHL7Application(String name); @Override synchronized HL7ApplicationInfo[] listHL7AppInfos(HL7ApplicationInfo keys); }### Answer: @Test public void testPersist() throws Exception { try { config.removeDevice("Test-Device-1", null); } catch (ConfigurationNotFoundException e) {} Device device = createDevice("Test-Device-1", "TEST1^DCM4CHE"); config.persist(device, null); HL7Application app = hl7Ext.findHL7Application("TEST1^DCM4CHE"); assertEquals(2575, app.getConnections().get(0).getPort()); assertEquals("TEST2^DCM4CHE", app.getAcceptedSendingApplications()[0]); assertEquals(7, app.getAcceptedMessageTypes().length); config.removeDevice("Test-Device-1", null); }
### Question: IDWithIssuer { public static Set<IDWithIssuer> pidsOf(Attributes attrs) { IDWithIssuer pid = IDWithIssuer.pidOf(attrs); Sequence opidseq = attrs.getSequence(Tag.OtherPatientIDsSequence); if (opidseq == null) if (pid == null) return Collections.emptySet(); else return Collections.singleton(pid); Set<IDWithIssuer> pids = new HashSet<IDWithIssuer>((1 + opidseq.size()) << 1); if (pid != null) pids.add(pid); for (Attributes item : opidseq) addTo(IDWithIssuer.pidOf(item), pids); return pids; } IDWithIssuer(String id, Issuer issuer); IDWithIssuer(String id, String issuer); IDWithIssuer(String cx); IDWithIssuer withoutIssuer(); final String getID(); String getTypeOfPatientID(); void setTypeOfPatientID(String typeOfPatientID); final String getIdentifierTypeCode(); final void setIdentifierTypeCode(String identifierTypeCode); final Issuer getIssuer(); final void setIssuer(Issuer issuer); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); boolean matches(IDWithIssuer other); Attributes exportPatientIDWithIssuer(Attributes attrs); static IDWithIssuer valueOf(Attributes attrs, int idTag, int issuerSeqTag); static IDWithIssuer pidOf(Attributes attrs); static Set<IDWithIssuer> pidsOf(Attributes attrs); static final IDWithIssuer[] EMPTY; }### Answer: @Test public void pidsOfTest_faking_duplicate_by_using_same_PID_but_different_issuer() { Attributes rootWithMainId = createIdWithNS(NS); rootWithMainId.newSequence(OtherPatientIDsSequence, 0); Sequence other = rootWithMainId.getSequence(OtherPatientIDsSequence); Attributes otherPatientId = otherPatientIds("other_ns"); other.add(otherPatientId); Set<IDWithIssuer> all = IDWithIssuer.pidsOf(rootWithMainId); assertEquals("Same pid but for different issuer should not be removed!", all.size(), 2); } @Test public void no_main_id_returns_all() { Attributes rootWithMainId = createIdWithNS(NS); rootWithMainId.newSequence(OtherPatientIDsSequence, 0); Sequence other = rootWithMainId.getSequence(OtherPatientIDsSequence); Attributes otherPatientId = otherPatientIds("other_ns"); other.add(otherPatientId); Set<IDWithIssuer> all = IDWithIssuer.pidsOf(rootWithMainId); assertEquals("Same pid but for different issuer should not be removed!", all.size(), 2); }
### Question: IOD extends ArrayList<IOD.DataElement> { public static IOD load(String uri) throws IOException { if (uri.startsWith("resource:")) { try { uri = ResourceLocator.getResource(uri.substring(9), IOD.class); } catch (NullPointerException npe) { throw new FileNotFoundException(uri); } } else if (uri.indexOf(':') < 2) { uri = new File(uri).toURI().toString(); } IOD iod = new IOD(); iod.parse(uri); iod.trimToSize(); return iod; } void setType(DataElementType type); DataElementType getType(); void setCondition(Condition condition); Condition getCondition(); int getLineNumber(); void setLineNumber(int lineNumber); void parse(String uri); static IOD load(String uri); static IOD valueOf(Code code); }### Answer: @Test public void testValidateDICOMDIR() throws Exception { IOD iod = IOD.load("resource:dicomdir-iod.xml"); Attributes attrs = readDataset("DICOMDIR"); ValidationResult result = attrs.validate(iod); assertTrue(result.isValid()); } @Test public void testValidateCode() throws Exception { IOD iod = IOD.load("resource:code-iod.xml"); Attributes attrs = new Attributes(2); attrs.newSequence(Tag.ConceptNameCodeSequence, 1).add( new Code("CV-9991", "99DCM4CHE", null, "CM-9991").toItem()); Attributes contentNode = new Attributes(2); contentNode.newSequence(Tag.ConceptNameCodeSequence, 1).add( new Code("CV-9992", "99DCM4CHE", null, "CM-9992").toItem()); contentNode.newSequence(Tag.ConceptCodeSequence, 1).add( new Code("CV-9993", "99DCM4CHE", null, "CM-9993").toItem()); attrs.newSequence(Tag.ContentSequence, 1).add(contentNode); ValidationResult result = attrs.validate(iod); assertTrue(result.isValid()); }
### Question: PersonName { public String get(Component c) { return get(Group.Alphabetic, c); } PersonName(); PersonName(String s); PersonName(String s, boolean lenient); String toString(); String toString(Group g, boolean trim); String get(Component c); String get(Group g, Component c); void set(Component c, String s); void set(Group g, Component c, String s); boolean isEmpty(); boolean contains(Group g); boolean contains(Group g, Component c); boolean contains(Component c); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testValueOf() { PersonName pn = new PersonName( "Adams^John Robert Quincy^^Rev.^B.A. M.Div."); assertEquals("Adams", pn.get(PersonName.Component.FamilyName)); assertEquals("John Robert Quincy", pn.get(PersonName.Component.GivenName)); assertEquals("Rev.", pn.get(PersonName.Component.NamePrefix)); assertEquals("B.A. M.Div.", pn.get(PersonName.Component.NameSuffix)); } @Test public void testValueOf2() { PersonName pn = new PersonName("Hong^Gildong=洪^吉洞=홍^길동"); assertEquals("Hong", pn.get(PersonName.Group.Alphabetic, PersonName.Component.FamilyName)); assertEquals("Gildong", pn.get(PersonName.Group.Alphabetic, PersonName.Component.GivenName)); assertEquals("洪", pn.get(PersonName.Group.Ideographic, PersonName.Component.FamilyName)); assertEquals("吉洞", pn.get(PersonName.Group.Ideographic, PersonName.Component.GivenName)); assertEquals("홍", pn.get(PersonName.Group.Phonetic, PersonName.Component.FamilyName)); assertEquals("길동", pn.get(PersonName.Group.Phonetic, PersonName.Component.GivenName)); }
### Question: PersonName { public String toString() { int totLen = 0; Group lastGroup = Group.Alphabetic; for (Group g : Group.values()) { Component lastCompOfGroup = Component.FamilyName; for (Component c : Component.values()) { String s = get(g, c); if (s != null) { totLen += s.length(); lastGroup = g; lastCompOfGroup = c; } } totLen += lastCompOfGroup.ordinal(); } totLen += lastGroup.ordinal(); char[] ch = new char[totLen]; int wpos = 0; for (Group g : Group.values()) { Component lastCompOfGroup = Component.FamilyName; for (Component c : Component.values()) { String s = get(g, c); if (s != null) { int d = c.ordinal() - lastCompOfGroup.ordinal(); while (d-- > 0) ch[wpos++] = '^'; d = s.length(); s.getChars(0, d, ch, wpos); wpos += d; lastCompOfGroup = c; } } if (g == lastGroup) break; ch[wpos++] = '='; } return new String(ch); } PersonName(); PersonName(String s); PersonName(String s, boolean lenient); String toString(); String toString(Group g, boolean trim); String get(Component c); String get(Group g, Component c); void set(Component c, String s); void set(Group g, Component c, String s); boolean isEmpty(); boolean contains(Group g); boolean contains(Group g, Component c); boolean contains(Component c); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testToString() { PersonName pn = new PersonName(); pn.set(PersonName.Component.FamilyName, "Morrison-Jones"); pn.set(PersonName.Component.GivenName, "Susan"); pn.set(PersonName.Component.NameSuffix, "Ph.D., Chief Executive Officer"); assertEquals("Morrison-Jones^Susan^^^Ph.D., Chief Executive Officer", pn.toString()); }
### Question: ValueSelector implements Serializable { @Override public String toString() { if (str == null) str = attributeSelector.toStringBuilder() .append("/Value[@number=\"") .append(valueIndex + 1) .append("\"]") .toString(); return str; } ValueSelector(int tag, String privateCreator, int index, ItemPointer... itemPointers); ValueSelector(AttributeSelector attributeSelector, int index); int tag(); String privateCreator(); int level(); ItemPointer itemPointer(int index); int valueIndex(); String selectStringValue(Attributes attrs, String defVal); @Override String toString(); static ValueSelector valueOf(String s); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testToString() { ItemPointer ip = new ItemPointer(Tag.RequestAttributesSequence, 0); ValueSelector vs = new ValueSelector(Tag.StudyInstanceUID, null, 0, ip); assertEquals(XPATH, vs.toString()); }
### Question: ValueSelector implements Serializable { public static ValueSelector valueOf(String s) { int fromIndex = s.lastIndexOf("DicomAttribute"); try { return new ValueSelector(AttributeSelector.valueOf(s), AttributeSelector.selectNumber(s, fromIndex) - 1); } catch (Exception e) { throw new IllegalArgumentException(s); } } ValueSelector(int tag, String privateCreator, int index, ItemPointer... itemPointers); ValueSelector(AttributeSelector attributeSelector, int index); int tag(); String privateCreator(); int level(); ItemPointer itemPointer(int index); int valueIndex(); String selectStringValue(Attributes attrs, String defVal); @Override String toString(); static ValueSelector valueOf(String s); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testValueOf() { ValueSelector vs = ValueSelector.valueOf(XPATH); assertEquals(Tag.StudyInstanceUID, vs.tag()); assertNull(vs.privateCreator()); assertEquals(0, vs.valueIndex()); assertEquals(1, vs.level()); ItemPointer ip = vs.itemPointer(0); assertEquals(Tag.RequestAttributesSequence, ip.sequenceTag); assertNull(ip.privateCreator); assertEquals(0, ip.itemIndex); }
### Question: ElementDictionary { public static VR vrOf(int tag, String privateCreator) { return getElementDictionary(privateCreator).vrOf(tag); } protected ElementDictionary(String privateCreator, Class<?> tagClass); static ElementDictionary getStandardElementDictionary(); static ElementDictionary getElementDictionary(String privateCreator); static void reload(); static VR vrOf(int tag, String privateCreator); static String keywordOf(int tag, String privateCreator); static int tagForKeyword(String keyword, String privateCreatorID); final String getPrivateCreator(); abstract VR vrOf(int tag); abstract String keywordOf(int tag); int tmTagOf(int daTag); int daTagOf(int tmTag); int tagForKeyword(String keyword); }### Answer: @Test public void testVrOf() { for (int i = 0; i < TAGS.length; i++) assertEquals(VRS[i], ElementDictionary.vrOf(TAGS[i], null)); } @Test public void testPrivateVrOf() { for (int i = 0; i < SIEMENS_CSA_HEADER_TAGS.length; i++) assertEquals(SIEMENS_CSA_HEADER_VRS[i], ElementDictionary.vrOf(SIEMENS_CSA_HEADER_TAGS[i], SIEMENS_CSA_HEADER)); for (int i = 0; i < SIEMENS_CSA_NON_IMAGE_TAGS.length; i++) assertEquals(SIEMENS_CSA_NON_IMAGE_VRS[i], ElementDictionary.vrOf(SIEMENS_CSA_NON_IMAGE_TAGS[i], SIEMENS_CSA_NON_IMAGE)); }
### Question: ElementDictionary { public static String keywordOf(int tag, String privateCreator) { return getElementDictionary(privateCreator).keywordOf(tag); } protected ElementDictionary(String privateCreator, Class<?> tagClass); static ElementDictionary getStandardElementDictionary(); static ElementDictionary getElementDictionary(String privateCreator); static void reload(); static VR vrOf(int tag, String privateCreator); static String keywordOf(int tag, String privateCreator); static int tagForKeyword(String keyword, String privateCreatorID); final String getPrivateCreator(); abstract VR vrOf(int tag); abstract String keywordOf(int tag); int tmTagOf(int daTag); int daTagOf(int tmTag); int tagForKeyword(String keyword); }### Answer: @Test public void testKeywordOf() { for (int i = 0; i < TAGS.length; i++) assertEquals(KEYWORDS[i], ElementDictionary.keywordOf(TAGS[i], null)); } @Test public void testPrivateKeywordOf() { for (int i = 0; i < SIEMENS_CSA_HEADER_TAGS.length; i++) assertEquals(SIEMENS_CSA_HEADER_KEYWORDS[i], ElementDictionary.keywordOf( SIEMENS_CSA_HEADER_TAGS[i], SIEMENS_CSA_HEADER)); for (int i = 0; i < SIEMENS_CSA_NON_IMAGE_TAGS.length; i++) assertEquals(SIEMENS_CSA_NON_IMAGE_KEYWORDS[i], ElementDictionary.keywordOf( SIEMENS_CSA_NON_IMAGE_TAGS[i], SIEMENS_CSA_NON_IMAGE)); }
### Question: ElementDictionary { public static int tagForKeyword(String keyword, String privateCreatorID) { return getElementDictionary(privateCreatorID).tagForKeyword(keyword); } protected ElementDictionary(String privateCreator, Class<?> tagClass); static ElementDictionary getStandardElementDictionary(); static ElementDictionary getElementDictionary(String privateCreator); static void reload(); static VR vrOf(int tag, String privateCreator); static String keywordOf(int tag, String privateCreator); static int tagForKeyword(String keyword, String privateCreatorID); final String getPrivateCreator(); abstract VR vrOf(int tag); abstract String keywordOf(int tag); int tmTagOf(int daTag); int daTagOf(int tmTag); int tagForKeyword(String keyword); }### Answer: @Test public void tagForKeyword() { for (int i = 0; i < KEYWORDS.length-1; i++) assertEquals(TAGS[i], ElementDictionary.tagForKeyword(KEYWORDS[i], null)); } @Test public void tagPrivateForKeyword() { for (int i = 0; i < SIEMENS_CSA_HEADER_KEYWORDS.length; i++) assertEquals(SIEMENS_CSA_HEADER_TAGS[i], ElementDictionary.tagForKeyword( SIEMENS_CSA_HEADER_KEYWORDS[i], SIEMENS_CSA_HEADER)); for (int i = 0; i < SIEMENS_CSA_NON_IMAGE_KEYWORDS.length; i++) assertEquals(SIEMENS_CSA_NON_IMAGE_TAGS[i], ElementDictionary.tagForKeyword( SIEMENS_CSA_NON_IMAGE_KEYWORDS[i], SIEMENS_CSA_NON_IMAGE)); }
### Question: StringUtils { public static boolean matches(String s, String key, boolean matchNullOrEmpty, boolean ignoreCase) { if (key == null || key.isEmpty()) return true; if (s == null || s.isEmpty()) return matchNullOrEmpty; return containsWildCard(key) ? compilePattern(key, ignoreCase).matcher(s).matches() : ignoreCase ? key.equalsIgnoreCase(s) : key.equals(s); } static StringBuilder appendLine(StringBuilder sb, Object... ss); static String concat(String[] ss, char delim); static String concat(Collection<String> ss, char delim); static Object splitAndTrim(String s, char delim); static String[] split(String s, char delim); static String cut(String s, int index, char delim); static String trimTrailing(String s); static int parseIS(String s); static double parseDS(String s); static String formatDS(float f); static String formatDS(double d); static boolean matches(String s, String key, boolean matchNullOrEmpty, boolean ignoreCase); static Pattern compilePattern(String key, boolean ignoreCase); static boolean containsWildCard(String s); static String[] maskNull(String[] ss); static T maskNull(T o, T mask); static T nullify(T o, T val); static String maskEmpty(String s, String mask); static String truncate(String s, int maxlen); static boolean equals(T o1, T o2); static String replaceSystemProperties(String s); @Deprecated static String resourceURL(String name); static boolean isUpperCase(String s); static boolean isIPAddr(String s); static boolean contains(T[] a, T o); static T[] requireNotEmpty(T[] a, String message); static String requireNotEmpty(String s, String message); static String[] requireContainsNoEmpty(String[] ss, String message); static String LINE_SEPARATOR; static String[] EMPTY_STRING; }### Answer: @Test public void testMatches() { assertTrue(StringUtils.matches("aBcD", "aBcD", false, false)); assertFalse(StringUtils.matches("aBcD", "abCd", false, false)); assertTrue(StringUtils.matches("aBcD", "abCd", false, true)); assertFalse(StringUtils.matches("aBcD", "ab*", false, false)); assertTrue(StringUtils.matches("aBcD", "ab*", false, true)); assertTrue(StringUtils.matches("aBcD", "a?c?", false, false)); assertTrue(StringUtils.matches("aBcD", "a*D*", false, false)); assertFalse(StringUtils.matches("aBcD", "a*d?", false, true)); }
### Question: AttributesFormat extends Format { @Override public StringBuffer format(Object obj, StringBuffer result, FieldPosition pos) { return format.format(toArgs((Attributes) obj), result, pos); } AttributesFormat(String pattern); static AttributesFormat valueOf(String s); @Override StringBuffer format(Object obj, StringBuffer result, FieldPosition pos); @Override Object parseObject(String source, ParsePosition pos); @Override String toString(); }### Answer: @Test public void testFormat() { Attributes attrs = new Attributes(); attrs.setString(Tag.ImageType, VR.CS, "ORIGINAL", "PRIMARY", "AXIAL"); attrs.setString(Tag.StudyDate, VR.DA, "20111012"); attrs.setString(Tag.StudyTime, VR.TM, "0930"); attrs.setString(Tag.StudyInstanceUID, VR.UI, "1.2.3"); attrs.setString(Tag.SeriesInstanceUID, VR.UI, "1.2.3.4"); attrs.setString(Tag.SOPInstanceUID, VR.UI, "1.2.3.4.5"); assertEquals("2011/10/12/09/02C82A3A/71668980/PRIMARY/1.2.3.4.5.dcm", new AttributesFormat(TEST_PATTERN).format(attrs)); } @Test public void testFormatMD5() { Attributes attrs = new Attributes(); attrs.setString(Tag.StudyDate, VR.DA, "20111012"); attrs.setString(Tag.StudyTime, VR.TM, "0930"); attrs.setString(Tag.StudyInstanceUID, VR.UI, "1.2.3"); attrs.setString(Tag.SeriesInstanceUID, VR.UI, "1.2.3.4"); attrs.setString(Tag.SOPInstanceUID, VR.UI, "1.2.3.4.5"); assertEquals("2011/10/12/09/02C82A3A/71668980/08vpsu2l2shpb0kc3orpgfnhv0.dcm", new AttributesFormat(TEST_PATTERN_MD5).format(attrs)); } @Test public void testFormatRND() { assertTrue(ASSERT_PATTERN_RND.matcher( new AttributesFormat(TEST_PATTERN_RND).format(new Attributes())).matches()); } @Test public void testOffset() { Attributes attrs = new Attributes(); attrs.setString(Tag.SeriesNumber, VR.IS, "1"); attrs.setString(Tag.InstanceNumber, VR.IS, "2"); assertEquals("101/1", new AttributesFormat(TEST_PATTERN_OFFSET).format(attrs)); }
### Question: DateUtils { public static String formatDA(TimeZone tz, Date date) { return formatDA(tz, date, new StringBuilder(8)).toString(); } static String formatDA(TimeZone tz, Date date); static StringBuilder formatDA(TimeZone tz, Date date, StringBuilder toAppendTo); static String formatTM(TimeZone tz, Date date); static String formatTM(TimeZone tz, Date date, DatePrecision precision); static String formatDT(TimeZone tz, Date date); static String formatDT(TimeZone tz, Date date, DatePrecision precision); static StringBuilder formatDT(TimeZone tz, Date date, StringBuilder toAppendTo, DatePrecision precision); static String formatTimezoneOffsetFromUTC(TimeZone tz); static String formatTimezoneOffsetFromUTC(TimeZone tz, Date date); static Date parseDA(TimeZone tz, String s); static Date parseDA(TimeZone tz, String s, boolean ceil); static Date parseTM(TimeZone tz, String s, DatePrecision precision); static Date parseTM(TimeZone tz, String s, boolean ceil, DatePrecision precision); static Date parseDT(TimeZone tz, String s, DatePrecision precision); static TimeZone timeZone(String s); static Date parseDT(TimeZone tz, String s, boolean ceil, DatePrecision precision); static final Date[] EMPTY_DATES; }### Answer: @Test public void testFormatDA() { assertEquals("19700101", DateUtils.formatDA(tz, new Date(0))); }
### Question: DateUtils { public static String formatTM(TimeZone tz, Date date) { return formatTM(tz, date, new DatePrecision()); } static String formatDA(TimeZone tz, Date date); static StringBuilder formatDA(TimeZone tz, Date date, StringBuilder toAppendTo); static String formatTM(TimeZone tz, Date date); static String formatTM(TimeZone tz, Date date, DatePrecision precision); static String formatDT(TimeZone tz, Date date); static String formatDT(TimeZone tz, Date date, DatePrecision precision); static StringBuilder formatDT(TimeZone tz, Date date, StringBuilder toAppendTo, DatePrecision precision); static String formatTimezoneOffsetFromUTC(TimeZone tz); static String formatTimezoneOffsetFromUTC(TimeZone tz, Date date); static Date parseDA(TimeZone tz, String s); static Date parseDA(TimeZone tz, String s, boolean ceil); static Date parseTM(TimeZone tz, String s, DatePrecision precision); static Date parseTM(TimeZone tz, String s, boolean ceil, DatePrecision precision); static Date parseDT(TimeZone tz, String s, DatePrecision precision); static TimeZone timeZone(String s); static Date parseDT(TimeZone tz, String s, boolean ceil, DatePrecision precision); static final Date[] EMPTY_DATES; }### Answer: @Test public void testFormatTM() { assertEquals("020000.000", DateUtils.formatTM(tz, new Date(0))); }
### Question: DateUtils { public static String formatDT(TimeZone tz, Date date) { return formatDT(tz, date, new DatePrecision()); } static String formatDA(TimeZone tz, Date date); static StringBuilder formatDA(TimeZone tz, Date date, StringBuilder toAppendTo); static String formatTM(TimeZone tz, Date date); static String formatTM(TimeZone tz, Date date, DatePrecision precision); static String formatDT(TimeZone tz, Date date); static String formatDT(TimeZone tz, Date date, DatePrecision precision); static StringBuilder formatDT(TimeZone tz, Date date, StringBuilder toAppendTo, DatePrecision precision); static String formatTimezoneOffsetFromUTC(TimeZone tz); static String formatTimezoneOffsetFromUTC(TimeZone tz, Date date); static Date parseDA(TimeZone tz, String s); static Date parseDA(TimeZone tz, String s, boolean ceil); static Date parseTM(TimeZone tz, String s, DatePrecision precision); static Date parseTM(TimeZone tz, String s, boolean ceil, DatePrecision precision); static Date parseDT(TimeZone tz, String s, DatePrecision precision); static TimeZone timeZone(String s); static Date parseDT(TimeZone tz, String s, boolean ceil, DatePrecision precision); static final Date[] EMPTY_DATES; }### Answer: @Test public void testFormatDT() { assertEquals("19700101020000.000", DateUtils.formatDT(tz, new Date(0))); } @Test public void testFormatDTwithTZ() { assertEquals("19700101020000.000+0200", DateUtils.formatDT(tz, new Date(0), new DatePrecision(Calendar.MILLISECOND, true))); }
### Question: DateUtils { public static Date parseDA(TimeZone tz, String s) { return parseDA(tz, s, false); } static String formatDA(TimeZone tz, Date date); static StringBuilder formatDA(TimeZone tz, Date date, StringBuilder toAppendTo); static String formatTM(TimeZone tz, Date date); static String formatTM(TimeZone tz, Date date, DatePrecision precision); static String formatDT(TimeZone tz, Date date); static String formatDT(TimeZone tz, Date date, DatePrecision precision); static StringBuilder formatDT(TimeZone tz, Date date, StringBuilder toAppendTo, DatePrecision precision); static String formatTimezoneOffsetFromUTC(TimeZone tz); static String formatTimezoneOffsetFromUTC(TimeZone tz, Date date); static Date parseDA(TimeZone tz, String s); static Date parseDA(TimeZone tz, String s, boolean ceil); static Date parseTM(TimeZone tz, String s, DatePrecision precision); static Date parseTM(TimeZone tz, String s, boolean ceil, DatePrecision precision); static Date parseDT(TimeZone tz, String s, DatePrecision precision); static TimeZone timeZone(String s); static Date parseDT(TimeZone tz, String s, boolean ceil, DatePrecision precision); static final Date[] EMPTY_DATES; }### Answer: @Test public void testParseDA() { assertEquals(-2 * HOUR, DateUtils.parseDA(tz, "19700101").getTime()); } @Test public void testParseDAacrnema() { assertEquals(-2 * HOUR, DateUtils.parseDA(tz, "1970.01.01").getTime()); } @Test public void testParseDAceil() { assertEquals(DAY - 2 * HOUR - 1, DateUtils.parseDA(tz, "19700101", true).getTime()); }
### Question: DateUtils { public static Date parseTM(TimeZone tz, String s, DatePrecision precision) { return parseTM(tz, s, false, precision); } static String formatDA(TimeZone tz, Date date); static StringBuilder formatDA(TimeZone tz, Date date, StringBuilder toAppendTo); static String formatTM(TimeZone tz, Date date); static String formatTM(TimeZone tz, Date date, DatePrecision precision); static String formatDT(TimeZone tz, Date date); static String formatDT(TimeZone tz, Date date, DatePrecision precision); static StringBuilder formatDT(TimeZone tz, Date date, StringBuilder toAppendTo, DatePrecision precision); static String formatTimezoneOffsetFromUTC(TimeZone tz); static String formatTimezoneOffsetFromUTC(TimeZone tz, Date date); static Date parseDA(TimeZone tz, String s); static Date parseDA(TimeZone tz, String s, boolean ceil); static Date parseTM(TimeZone tz, String s, DatePrecision precision); static Date parseTM(TimeZone tz, String s, boolean ceil, DatePrecision precision); static Date parseDT(TimeZone tz, String s, DatePrecision precision); static TimeZone timeZone(String s); static Date parseDT(TimeZone tz, String s, boolean ceil, DatePrecision precision); static final Date[] EMPTY_DATES; }### Answer: @Test public void testParseTM() { DatePrecision precision = new DatePrecision(); assertEquals(0, DateUtils.parseTM(tz, "020000.000", precision).getTime()); assertEquals(Calendar.MILLISECOND, precision.lastField); } @Test public void testParseTMacrnema() { DatePrecision precision = new DatePrecision(); assertEquals(0, DateUtils.parseTM(tz, "02:00:00", precision).getTime()); assertEquals(Calendar.SECOND, precision.lastField); } @Test public void testParseTMceil() { DatePrecision precision = new DatePrecision(); assertEquals(MINUTE - 1, DateUtils.parseTM(tz, "0200", true, precision).getTime()); assertEquals(Calendar.MINUTE, precision.lastField); }
### Question: DateUtils { public static Date parseDT(TimeZone tz, String s, DatePrecision precision) { return parseDT(tz, s, false, precision); } static String formatDA(TimeZone tz, Date date); static StringBuilder formatDA(TimeZone tz, Date date, StringBuilder toAppendTo); static String formatTM(TimeZone tz, Date date); static String formatTM(TimeZone tz, Date date, DatePrecision precision); static String formatDT(TimeZone tz, Date date); static String formatDT(TimeZone tz, Date date, DatePrecision precision); static StringBuilder formatDT(TimeZone tz, Date date, StringBuilder toAppendTo, DatePrecision precision); static String formatTimezoneOffsetFromUTC(TimeZone tz); static String formatTimezoneOffsetFromUTC(TimeZone tz, Date date); static Date parseDA(TimeZone tz, String s); static Date parseDA(TimeZone tz, String s, boolean ceil); static Date parseTM(TimeZone tz, String s, DatePrecision precision); static Date parseTM(TimeZone tz, String s, boolean ceil, DatePrecision precision); static Date parseDT(TimeZone tz, String s, DatePrecision precision); static TimeZone timeZone(String s); static Date parseDT(TimeZone tz, String s, boolean ceil, DatePrecision precision); static final Date[] EMPTY_DATES; }### Answer: @Test public void testParseDT() { DatePrecision precision = new DatePrecision(); assertEquals(0, DateUtils.parseDT(tz, "19700101020000.000", precision).getTime()); assertEquals(Calendar.MILLISECOND, precision.lastField); assertFalse(precision.includeTimezone); } @Test public void testParseWithTZ() { DatePrecision precision = new DatePrecision(); assertEquals(2 * HOUR, DateUtils.parseDT(tz, "19700101020000.000+0000", precision).getTime()); assertEquals(Calendar.MILLISECOND, precision.lastField); assertTrue(precision.includeTimezone); } @Test public void testParseDTceil() { DatePrecision precision = new DatePrecision(); assertEquals(YEAR - 2 * HOUR - 1, DateUtils.parseDT(tz, "1970", true, precision).getTime()); assertEquals(Calendar.YEAR, precision.lastField); assertFalse(precision.includeTimezone); }
### Question: IntHashMap implements Cloneable, java.io.Serializable { public int size() { return size; } IntHashMap(); IntHashMap(int expectedMaxSize); int size(); boolean isEmpty(); @SuppressWarnings("unchecked") V get(int key); boolean containsKey(int key); @SuppressWarnings("unchecked") V put(int key, V value); void trimToSize(); void rehash(); @SuppressWarnings("unchecked") V remove(int key); void clear(); @SuppressWarnings("unchecked") Object clone(); @SuppressWarnings("unchecked") boolean accept(Visitor<V> visitor); }### Answer: @Test public void testSize() { assertEquals(15, map.size()); removeOdd(); assertEquals(7, map.size()); }
### Question: IntHashMap implements Cloneable, java.io.Serializable { @SuppressWarnings("unchecked") public V get(int key) { byte[] states = this.states; int[] keys = this.keys; int mask = keys.length - 1; int i = key & mask; while (states[i] != FREE) { if (keys[i] == key) return (V) values[i]; i = (i + 1) & mask; } return null; } IntHashMap(); IntHashMap(int expectedMaxSize); int size(); boolean isEmpty(); @SuppressWarnings("unchecked") V get(int key); boolean containsKey(int key); @SuppressWarnings("unchecked") V put(int key, V value); void trimToSize(); void rehash(); @SuppressWarnings("unchecked") V remove(int key); void clear(); @SuppressWarnings("unchecked") Object clone(); @SuppressWarnings("unchecked") boolean accept(Visitor<V> visitor); }### Answer: @Test public void testGet() { removeOdd(); testGet(map); }
### Question: IntHashMap implements Cloneable, java.io.Serializable { @SuppressWarnings("unchecked") public V put(int key, V value) { byte[] states = this.states; int[] keys = this.keys; int mask = keys.length - 1; int i = key & mask; while (states[i] > FREE) { if (keys[i] == key) { V oldValue = (V) values[i]; values[i] = value; return oldValue; } i = (i + 1) & mask; } byte oldState = states[i]; states[i] = FULL; keys[i] = key; values[i] = value; ++size; if (oldState == FREE && --free < 0) resize(Math.max(capacity(size), keys.length)); return null; } IntHashMap(); IntHashMap(int expectedMaxSize); int size(); boolean isEmpty(); @SuppressWarnings("unchecked") V get(int key); boolean containsKey(int key); @SuppressWarnings("unchecked") V put(int key, V value); void trimToSize(); void rehash(); @SuppressWarnings("unchecked") V remove(int key); void clear(); @SuppressWarnings("unchecked") Object clone(); @SuppressWarnings("unchecked") boolean accept(Visitor<V> visitor); }### Answer: @Test public void testPut() { removeOdd(); for (int i = 0; i < 45; i++) map.put(i, Integer.valueOf(i)); assertEquals(45, map.size()); for (int i = 0; i < 45; i++) assertEquals(Integer.valueOf(i), map.get(i)); }
### Question: IntHashMap implements Cloneable, java.io.Serializable { public boolean containsKey(int key) { byte[] states = this.states; int[] keys = this.keys; int mask = keys.length - 1; int i = key & mask; while (states[i] != FREE) { if (keys[i] == key) return states[i] > FREE; i = (i + 1) & mask; } return false; } IntHashMap(); IntHashMap(int expectedMaxSize); int size(); boolean isEmpty(); @SuppressWarnings("unchecked") V get(int key); boolean containsKey(int key); @SuppressWarnings("unchecked") V put(int key, V value); void trimToSize(); void rehash(); @SuppressWarnings("unchecked") V remove(int key); void clear(); @SuppressWarnings("unchecked") Object clone(); @SuppressWarnings("unchecked") boolean accept(Visitor<V> visitor); }### Answer: @Test public void testContainsKey() { removeOdd(); for (int i = 1; i < 45; i++) assertEquals((i & 1) == 0 && (i % 3) == 1, map.containsKey(i)); }
### Question: IntHashMap implements Cloneable, java.io.Serializable { public void rehash() { resize(keys.length); } IntHashMap(); IntHashMap(int expectedMaxSize); int size(); boolean isEmpty(); @SuppressWarnings("unchecked") V get(int key); boolean containsKey(int key); @SuppressWarnings("unchecked") V put(int key, V value); void trimToSize(); void rehash(); @SuppressWarnings("unchecked") V remove(int key); void clear(); @SuppressWarnings("unchecked") Object clone(); @SuppressWarnings("unchecked") boolean accept(Visitor<V> visitor); }### Answer: @Test public void testRehash() { removeOdd(); map.trimToSize(); testGet(map); }
### Question: JsonConfiguration { public void writeTo(DeviceInfo deviceInfo, JsonGenerator gen) { JsonWriter writer = new JsonWriter(gen); gen.writeStartObject(); gen.write("dicomDeviceName", deviceInfo.getDeviceName()); writer.writeNotNullOrDef("dicomDescription", deviceInfo.getDescription(), null); writer.writeNotNullOrDef("dicomManufacturer", deviceInfo.getManufacturer(), null); writer.writeNotNullOrDef("dicomManufacturerModelName", deviceInfo.getManufacturerModelName(), null); writer.writeNotEmpty("dicomSoftwareVersion", deviceInfo.getSoftwareVersions()); writer.writeNotNullOrDef("dicomStationName", deviceInfo.getStationName(), null); writer.writeNotEmpty("dicomInstitutionName", deviceInfo.getInstitutionNames()); writer.writeNotEmpty("dicomInstitutionDepartmentName", deviceInfo.getInstitutionalDepartmentNames()); writer.writeNotEmpty("dicomPrimaryDeviceType", deviceInfo.getPrimaryDeviceTypes()); gen.write("dicomInstalled", deviceInfo.getInstalled()); gen.write("hasArcDevExt", deviceInfo.getArcDevExt()); gen.writeEnd(); } void addJsonConfigurationExtension(JsonConfigurationExtension ext); boolean removeJsonConfigurationExtension(JsonConfigurationExtension ext); T getJsonConfigurationExtension(Class<T> clazz); void writeTo(DeviceInfo deviceInfo, JsonGenerator gen); void writeTo(ApplicationEntityInfo aetInfo, JsonGenerator gen); void writeTo(WebApplicationInfo webappInfo, JsonGenerator gen); void writeTo(WebApplicationInfo webappInfo, JsonGenerator gen, String keycloakClientID); void writeTo(HL7ApplicationInfo hl7AppInfo, JsonGenerator gen); void writeTo(Device device, JsonGenerator gen, boolean extended); Device loadDeviceFrom(JsonParser parser, ConfigurationDelegate config); void writeBulkdataDescriptors(Map<String, BasicBulkDataDescriptor> descriptors, JsonWriter writer); void loadBulkdataDescriptors(Map<String, BasicBulkDataDescriptor> descriptors, JsonReader reader); }### Answer: @Test public void testWriteTo() throws Exception { StringWriter writer = new StringWriter(); try ( JsonGenerator gen = Json.createGenerator(writer)) { JsonConfiguration config = new JsonConfiguration(); config.addJsonConfigurationExtension(new JsonAuditLoggerConfiguration()); config.addJsonConfigurationExtension(new JsonAuditRecordRepositoryConfiguration()); config.addJsonConfigurationExtension(new JsonImageReaderConfiguration()); config.addJsonConfigurationExtension(new JsonImageWriterConfiguration()); config.addJsonConfigurationExtension(new JsonHL7Configuration()); config.writeTo(createDevice("Test-Device-1", "TEST-AET1"), gen, true); } Path path = Paths.get("src/test/data/device.json"); try (BufferedReader reader = Files.newBufferedReader(path, Charset.forName("UTF-8"))) { assertEquals(reader.readLine(), writer.toString()); } }
### Question: IntHashMap implements Cloneable, java.io.Serializable { @SuppressWarnings("unchecked") public V remove(int key) { byte[] states = this.states; int[] keys = this.keys; int mask = keys.length - 1; int i = key & mask; while (states[i] != FREE) { if (keys[i] == key) { if (states[i] < FREE) return null; states[i] = REMOVED; V oldValue = (V) values[i]; values[i] = null; size--; return oldValue; } i = (i + 1) & mask; } return null; } IntHashMap(); IntHashMap(int expectedMaxSize); int size(); boolean isEmpty(); @SuppressWarnings("unchecked") V get(int key); boolean containsKey(int key); @SuppressWarnings("unchecked") V put(int key, V value); void trimToSize(); void rehash(); @SuppressWarnings("unchecked") V remove(int key); void clear(); @SuppressWarnings("unchecked") Object clone(); @SuppressWarnings("unchecked") boolean accept(Visitor<V> visitor); }### Answer: @Test public void testRemove() { for (int i = 1; i < 45; i += 2) if ((i % 3) == 1) assertEquals(Integer.valueOf(i), map.remove(i)); else assertNull(map.remove(i)); }
### Question: IntHashMap implements Cloneable, java.io.Serializable { public void clear() { Arrays.fill(values, null); Arrays.fill(states, FREE); size = 0; free = keys.length >>> 1; } IntHashMap(); IntHashMap(int expectedMaxSize); int size(); boolean isEmpty(); @SuppressWarnings("unchecked") V get(int key); boolean containsKey(int key); @SuppressWarnings("unchecked") V put(int key, V value); void trimToSize(); void rehash(); @SuppressWarnings("unchecked") V remove(int key); void clear(); @SuppressWarnings("unchecked") Object clone(); @SuppressWarnings("unchecked") boolean accept(Visitor<V> visitor); }### Answer: @Test public void testClear() { assertFalse(map.isEmpty()); map.clear(); assertTrue(map.isEmpty()); }
### Question: IntHashMap implements Cloneable, java.io.Serializable { @SuppressWarnings("unchecked") public Object clone() { try { IntHashMap<V> m = (IntHashMap<V>) super.clone(); m.states = states.clone(); m.keys = keys.clone(); m.values = values.clone(); return m; } catch (CloneNotSupportedException e) { throw new InternalError(); } } IntHashMap(); IntHashMap(int expectedMaxSize); int size(); boolean isEmpty(); @SuppressWarnings("unchecked") V get(int key); boolean containsKey(int key); @SuppressWarnings("unchecked") V put(int key, V value); void trimToSize(); void rehash(); @SuppressWarnings("unchecked") V remove(int key); void clear(); @SuppressWarnings("unchecked") Object clone(); @SuppressWarnings("unchecked") boolean accept(Visitor<V> visitor); }### Answer: @SuppressWarnings("unchecked") @Test public void testClone() { removeOdd(); IntHashMap<Integer> clone = (IntHashMap<Integer>) map.clone(); map.clear(); testGet(clone); }
### Question: ByteUtils { public static int bytesToUShortBE(byte[] bytes, int off) { return ((bytes[off] & 255) << 8) + (bytes[off + 1] & 255); } static int bytesToVR(byte[] bytes, int off); static int bytesToUShort(byte[] bytes, int off, boolean bigEndian); static int bytesToUShortBE(byte[] bytes, int off); static int bytesToUShortLE(byte[] bytes, int off); static int bytesToShort(byte[] bytes, int off, boolean bigEndian); static int bytesToShortBE(byte[] bytes, int off); static int bytesToShortLE(byte[] bytes, int off); static void bytesToShorts(byte[] b, short[] s, int off, int len, boolean bigEndian); static void bytesToShortsLE(byte[] b, short[] s, int off, int len); static void bytesToShortsBE(byte[] b, short[] s, int off, int len); static int bytesToInt(byte[] bytes, int off, boolean bigEndian); static int bytesToIntBE(byte[] bytes, int off); static int bytesToIntLE(byte[] bytes, int off); static int bytesToTag(byte[] bytes, int off, boolean bigEndian); static int bytesToTagBE(byte[] bytes, int off); static int bytesToTagLE(byte[] bytes, int off); static float bytesToFloat(byte[] bytes, int off, boolean bigEndian); static float bytesToFloatBE(byte[] bytes, int off); static float bytesToFloatLE(byte[] bytes, int off); static long bytesToLong(byte[] bytes, int off, boolean bigEndian); static long bytesToLongBE(byte[] bytes, int off); static long bytesToLongLE(byte[] bytes, int off); static double bytesToDouble(byte[] bytes, int off, boolean bigEndian); static double bytesToDoubleBE(byte[] bytes, int off); static double bytesToDoubleLE(byte[] bytes, int off); static byte[] shortToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] shortToBytesBE(int i, byte[] bytes, int off); static byte[] shortToBytesLE(int i, byte[] bytes, int off); static byte[] intToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] intToBytesBE(int i, byte[] bytes, int off); static byte[] intToBytesLE(int i, byte[] bytes, int off); static byte[] tagToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] tagToBytesBE(int i, byte[] bytes, int off); static byte[] tagToBytesLE(int i, byte[] bytes, int off); static byte[] floatToBytes(float f, byte[] bytes, int off, boolean bigEndian); static byte[] floatToBytesBE(float f, byte[] bytes, int off); static byte[] floatToBytesLE(float f, byte[] bytes, int off); static byte[] doubleToBytes(double d, byte[] bytes, int off, boolean bigEndian); static byte[] doubleToBytesBE(double d, byte[] bytes, int off); static byte[] doubleToBytesLE(double d, byte[] bytes, int off); static byte[] longToBytes(long l, byte[] bytes, int off, boolean bigEndian); static byte[] longToBytesBE(long l, byte[] bytes, int off); static byte[] longToBytesLE(long l, byte[] bytes, int off); static byte[][] swapShorts(byte bs[][]); static byte[] swapShorts(byte b[], int off, int len); static byte[] swapInts(byte b[], int off, int len); static byte[] swapLongs(byte b[], int off, int len); static byte[] intsToBytesLE(int... values); static final byte[] EMPTY_BYTES; static final int[] EMPTY_INTS; static final float[] EMPTY_FLOATS; static final double[] EMPTY_DOUBLES; }### Answer: @Test public void testBytesToUShortBE() { assertEquals(-12345 & 0xffff, ByteUtils.bytesToUShortBE(SHORT_12345_BE, 0)); }
### Question: ByteUtils { public static int bytesToUShortLE(byte[] bytes, int off) { return ((bytes[off + 1] & 255) << 8) + (bytes[off] & 255); } static int bytesToVR(byte[] bytes, int off); static int bytesToUShort(byte[] bytes, int off, boolean bigEndian); static int bytesToUShortBE(byte[] bytes, int off); static int bytesToUShortLE(byte[] bytes, int off); static int bytesToShort(byte[] bytes, int off, boolean bigEndian); static int bytesToShortBE(byte[] bytes, int off); static int bytesToShortLE(byte[] bytes, int off); static void bytesToShorts(byte[] b, short[] s, int off, int len, boolean bigEndian); static void bytesToShortsLE(byte[] b, short[] s, int off, int len); static void bytesToShortsBE(byte[] b, short[] s, int off, int len); static int bytesToInt(byte[] bytes, int off, boolean bigEndian); static int bytesToIntBE(byte[] bytes, int off); static int bytesToIntLE(byte[] bytes, int off); static int bytesToTag(byte[] bytes, int off, boolean bigEndian); static int bytesToTagBE(byte[] bytes, int off); static int bytesToTagLE(byte[] bytes, int off); static float bytesToFloat(byte[] bytes, int off, boolean bigEndian); static float bytesToFloatBE(byte[] bytes, int off); static float bytesToFloatLE(byte[] bytes, int off); static long bytesToLong(byte[] bytes, int off, boolean bigEndian); static long bytesToLongBE(byte[] bytes, int off); static long bytesToLongLE(byte[] bytes, int off); static double bytesToDouble(byte[] bytes, int off, boolean bigEndian); static double bytesToDoubleBE(byte[] bytes, int off); static double bytesToDoubleLE(byte[] bytes, int off); static byte[] shortToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] shortToBytesBE(int i, byte[] bytes, int off); static byte[] shortToBytesLE(int i, byte[] bytes, int off); static byte[] intToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] intToBytesBE(int i, byte[] bytes, int off); static byte[] intToBytesLE(int i, byte[] bytes, int off); static byte[] tagToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] tagToBytesBE(int i, byte[] bytes, int off); static byte[] tagToBytesLE(int i, byte[] bytes, int off); static byte[] floatToBytes(float f, byte[] bytes, int off, boolean bigEndian); static byte[] floatToBytesBE(float f, byte[] bytes, int off); static byte[] floatToBytesLE(float f, byte[] bytes, int off); static byte[] doubleToBytes(double d, byte[] bytes, int off, boolean bigEndian); static byte[] doubleToBytesBE(double d, byte[] bytes, int off); static byte[] doubleToBytesLE(double d, byte[] bytes, int off); static byte[] longToBytes(long l, byte[] bytes, int off, boolean bigEndian); static byte[] longToBytesBE(long l, byte[] bytes, int off); static byte[] longToBytesLE(long l, byte[] bytes, int off); static byte[][] swapShorts(byte bs[][]); static byte[] swapShorts(byte b[], int off, int len); static byte[] swapInts(byte b[], int off, int len); static byte[] swapLongs(byte b[], int off, int len); static byte[] intsToBytesLE(int... values); static final byte[] EMPTY_BYTES; static final int[] EMPTY_INTS; static final float[] EMPTY_FLOATS; static final double[] EMPTY_DOUBLES; }### Answer: @Test public void testBytesToUShortLE() { assertEquals(-12345 & 0xffff, ByteUtils.bytesToUShortLE(SHORT_12345_LE, 0)); }
### Question: ByteUtils { public static int bytesToShortBE(byte[] bytes, int off) { return (bytes[off] << 8) + (bytes[off + 1] & 255); } static int bytesToVR(byte[] bytes, int off); static int bytesToUShort(byte[] bytes, int off, boolean bigEndian); static int bytesToUShortBE(byte[] bytes, int off); static int bytesToUShortLE(byte[] bytes, int off); static int bytesToShort(byte[] bytes, int off, boolean bigEndian); static int bytesToShortBE(byte[] bytes, int off); static int bytesToShortLE(byte[] bytes, int off); static void bytesToShorts(byte[] b, short[] s, int off, int len, boolean bigEndian); static void bytesToShortsLE(byte[] b, short[] s, int off, int len); static void bytesToShortsBE(byte[] b, short[] s, int off, int len); static int bytesToInt(byte[] bytes, int off, boolean bigEndian); static int bytesToIntBE(byte[] bytes, int off); static int bytesToIntLE(byte[] bytes, int off); static int bytesToTag(byte[] bytes, int off, boolean bigEndian); static int bytesToTagBE(byte[] bytes, int off); static int bytesToTagLE(byte[] bytes, int off); static float bytesToFloat(byte[] bytes, int off, boolean bigEndian); static float bytesToFloatBE(byte[] bytes, int off); static float bytesToFloatLE(byte[] bytes, int off); static long bytesToLong(byte[] bytes, int off, boolean bigEndian); static long bytesToLongBE(byte[] bytes, int off); static long bytesToLongLE(byte[] bytes, int off); static double bytesToDouble(byte[] bytes, int off, boolean bigEndian); static double bytesToDoubleBE(byte[] bytes, int off); static double bytesToDoubleLE(byte[] bytes, int off); static byte[] shortToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] shortToBytesBE(int i, byte[] bytes, int off); static byte[] shortToBytesLE(int i, byte[] bytes, int off); static byte[] intToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] intToBytesBE(int i, byte[] bytes, int off); static byte[] intToBytesLE(int i, byte[] bytes, int off); static byte[] tagToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] tagToBytesBE(int i, byte[] bytes, int off); static byte[] tagToBytesLE(int i, byte[] bytes, int off); static byte[] floatToBytes(float f, byte[] bytes, int off, boolean bigEndian); static byte[] floatToBytesBE(float f, byte[] bytes, int off); static byte[] floatToBytesLE(float f, byte[] bytes, int off); static byte[] doubleToBytes(double d, byte[] bytes, int off, boolean bigEndian); static byte[] doubleToBytesBE(double d, byte[] bytes, int off); static byte[] doubleToBytesLE(double d, byte[] bytes, int off); static byte[] longToBytes(long l, byte[] bytes, int off, boolean bigEndian); static byte[] longToBytesBE(long l, byte[] bytes, int off); static byte[] longToBytesLE(long l, byte[] bytes, int off); static byte[][] swapShorts(byte bs[][]); static byte[] swapShorts(byte b[], int off, int len); static byte[] swapInts(byte b[], int off, int len); static byte[] swapLongs(byte b[], int off, int len); static byte[] intsToBytesLE(int... values); static final byte[] EMPTY_BYTES; static final int[] EMPTY_INTS; static final float[] EMPTY_FLOATS; static final double[] EMPTY_DOUBLES; }### Answer: @Test public void testBytesToShortBE() { assertEquals(-12345, ByteUtils.bytesToShortBE(SHORT_12345_BE, 0)); }
### Question: ByteUtils { public static int bytesToShortLE(byte[] bytes, int off) { return (bytes[off + 1] << 8) + (bytes[off] & 255); } static int bytesToVR(byte[] bytes, int off); static int bytesToUShort(byte[] bytes, int off, boolean bigEndian); static int bytesToUShortBE(byte[] bytes, int off); static int bytesToUShortLE(byte[] bytes, int off); static int bytesToShort(byte[] bytes, int off, boolean bigEndian); static int bytesToShortBE(byte[] bytes, int off); static int bytesToShortLE(byte[] bytes, int off); static void bytesToShorts(byte[] b, short[] s, int off, int len, boolean bigEndian); static void bytesToShortsLE(byte[] b, short[] s, int off, int len); static void bytesToShortsBE(byte[] b, short[] s, int off, int len); static int bytesToInt(byte[] bytes, int off, boolean bigEndian); static int bytesToIntBE(byte[] bytes, int off); static int bytesToIntLE(byte[] bytes, int off); static int bytesToTag(byte[] bytes, int off, boolean bigEndian); static int bytesToTagBE(byte[] bytes, int off); static int bytesToTagLE(byte[] bytes, int off); static float bytesToFloat(byte[] bytes, int off, boolean bigEndian); static float bytesToFloatBE(byte[] bytes, int off); static float bytesToFloatLE(byte[] bytes, int off); static long bytesToLong(byte[] bytes, int off, boolean bigEndian); static long bytesToLongBE(byte[] bytes, int off); static long bytesToLongLE(byte[] bytes, int off); static double bytesToDouble(byte[] bytes, int off, boolean bigEndian); static double bytesToDoubleBE(byte[] bytes, int off); static double bytesToDoubleLE(byte[] bytes, int off); static byte[] shortToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] shortToBytesBE(int i, byte[] bytes, int off); static byte[] shortToBytesLE(int i, byte[] bytes, int off); static byte[] intToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] intToBytesBE(int i, byte[] bytes, int off); static byte[] intToBytesLE(int i, byte[] bytes, int off); static byte[] tagToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] tagToBytesBE(int i, byte[] bytes, int off); static byte[] tagToBytesLE(int i, byte[] bytes, int off); static byte[] floatToBytes(float f, byte[] bytes, int off, boolean bigEndian); static byte[] floatToBytesBE(float f, byte[] bytes, int off); static byte[] floatToBytesLE(float f, byte[] bytes, int off); static byte[] doubleToBytes(double d, byte[] bytes, int off, boolean bigEndian); static byte[] doubleToBytesBE(double d, byte[] bytes, int off); static byte[] doubleToBytesLE(double d, byte[] bytes, int off); static byte[] longToBytes(long l, byte[] bytes, int off, boolean bigEndian); static byte[] longToBytesBE(long l, byte[] bytes, int off); static byte[] longToBytesLE(long l, byte[] bytes, int off); static byte[][] swapShorts(byte bs[][]); static byte[] swapShorts(byte b[], int off, int len); static byte[] swapInts(byte b[], int off, int len); static byte[] swapLongs(byte b[], int off, int len); static byte[] intsToBytesLE(int... values); static final byte[] EMPTY_BYTES; static final int[] EMPTY_INTS; static final float[] EMPTY_FLOATS; static final double[] EMPTY_DOUBLES; }### Answer: @Test public void testBytesToShortLE() { assertEquals(-12345, ByteUtils.bytesToShortLE(SHORT_12345_LE, 0)); }
### Question: ByteUtils { public static int bytesToIntBE(byte[] bytes, int off) { return (bytes[off] << 24) + ((bytes[off + 1] & 255) << 16) + ((bytes[off + 2] & 255) << 8) + (bytes[off + 3] & 255); } static int bytesToVR(byte[] bytes, int off); static int bytesToUShort(byte[] bytes, int off, boolean bigEndian); static int bytesToUShortBE(byte[] bytes, int off); static int bytesToUShortLE(byte[] bytes, int off); static int bytesToShort(byte[] bytes, int off, boolean bigEndian); static int bytesToShortBE(byte[] bytes, int off); static int bytesToShortLE(byte[] bytes, int off); static void bytesToShorts(byte[] b, short[] s, int off, int len, boolean bigEndian); static void bytesToShortsLE(byte[] b, short[] s, int off, int len); static void bytesToShortsBE(byte[] b, short[] s, int off, int len); static int bytesToInt(byte[] bytes, int off, boolean bigEndian); static int bytesToIntBE(byte[] bytes, int off); static int bytesToIntLE(byte[] bytes, int off); static int bytesToTag(byte[] bytes, int off, boolean bigEndian); static int bytesToTagBE(byte[] bytes, int off); static int bytesToTagLE(byte[] bytes, int off); static float bytesToFloat(byte[] bytes, int off, boolean bigEndian); static float bytesToFloatBE(byte[] bytes, int off); static float bytesToFloatLE(byte[] bytes, int off); static long bytesToLong(byte[] bytes, int off, boolean bigEndian); static long bytesToLongBE(byte[] bytes, int off); static long bytesToLongLE(byte[] bytes, int off); static double bytesToDouble(byte[] bytes, int off, boolean bigEndian); static double bytesToDoubleBE(byte[] bytes, int off); static double bytesToDoubleLE(byte[] bytes, int off); static byte[] shortToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] shortToBytesBE(int i, byte[] bytes, int off); static byte[] shortToBytesLE(int i, byte[] bytes, int off); static byte[] intToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] intToBytesBE(int i, byte[] bytes, int off); static byte[] intToBytesLE(int i, byte[] bytes, int off); static byte[] tagToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] tagToBytesBE(int i, byte[] bytes, int off); static byte[] tagToBytesLE(int i, byte[] bytes, int off); static byte[] floatToBytes(float f, byte[] bytes, int off, boolean bigEndian); static byte[] floatToBytesBE(float f, byte[] bytes, int off); static byte[] floatToBytesLE(float f, byte[] bytes, int off); static byte[] doubleToBytes(double d, byte[] bytes, int off, boolean bigEndian); static byte[] doubleToBytesBE(double d, byte[] bytes, int off); static byte[] doubleToBytesLE(double d, byte[] bytes, int off); static byte[] longToBytes(long l, byte[] bytes, int off, boolean bigEndian); static byte[] longToBytesBE(long l, byte[] bytes, int off); static byte[] longToBytesLE(long l, byte[] bytes, int off); static byte[][] swapShorts(byte bs[][]); static byte[] swapShorts(byte b[], int off, int len); static byte[] swapInts(byte b[], int off, int len); static byte[] swapLongs(byte b[], int off, int len); static byte[] intsToBytesLE(int... values); static final byte[] EMPTY_BYTES; static final int[] EMPTY_INTS; static final float[] EMPTY_FLOATS; static final double[] EMPTY_DOUBLES; }### Answer: @Test public void testBytesToIntBE() { assertEquals(-12345, ByteUtils.bytesToIntBE(INT_12345_BE, 0)); }
### Question: ByteUtils { public static int bytesToIntLE(byte[] bytes, int off) { return (bytes[off + 3] << 24) + ((bytes[off + 2] & 255) << 16) + ((bytes[off + 1] & 255) << 8) + (bytes[off] & 255); } static int bytesToVR(byte[] bytes, int off); static int bytesToUShort(byte[] bytes, int off, boolean bigEndian); static int bytesToUShortBE(byte[] bytes, int off); static int bytesToUShortLE(byte[] bytes, int off); static int bytesToShort(byte[] bytes, int off, boolean bigEndian); static int bytesToShortBE(byte[] bytes, int off); static int bytesToShortLE(byte[] bytes, int off); static void bytesToShorts(byte[] b, short[] s, int off, int len, boolean bigEndian); static void bytesToShortsLE(byte[] b, short[] s, int off, int len); static void bytesToShortsBE(byte[] b, short[] s, int off, int len); static int bytesToInt(byte[] bytes, int off, boolean bigEndian); static int bytesToIntBE(byte[] bytes, int off); static int bytesToIntLE(byte[] bytes, int off); static int bytesToTag(byte[] bytes, int off, boolean bigEndian); static int bytesToTagBE(byte[] bytes, int off); static int bytesToTagLE(byte[] bytes, int off); static float bytesToFloat(byte[] bytes, int off, boolean bigEndian); static float bytesToFloatBE(byte[] bytes, int off); static float bytesToFloatLE(byte[] bytes, int off); static long bytesToLong(byte[] bytes, int off, boolean bigEndian); static long bytesToLongBE(byte[] bytes, int off); static long bytesToLongLE(byte[] bytes, int off); static double bytesToDouble(byte[] bytes, int off, boolean bigEndian); static double bytesToDoubleBE(byte[] bytes, int off); static double bytesToDoubleLE(byte[] bytes, int off); static byte[] shortToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] shortToBytesBE(int i, byte[] bytes, int off); static byte[] shortToBytesLE(int i, byte[] bytes, int off); static byte[] intToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] intToBytesBE(int i, byte[] bytes, int off); static byte[] intToBytesLE(int i, byte[] bytes, int off); static byte[] tagToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] tagToBytesBE(int i, byte[] bytes, int off); static byte[] tagToBytesLE(int i, byte[] bytes, int off); static byte[] floatToBytes(float f, byte[] bytes, int off, boolean bigEndian); static byte[] floatToBytesBE(float f, byte[] bytes, int off); static byte[] floatToBytesLE(float f, byte[] bytes, int off); static byte[] doubleToBytes(double d, byte[] bytes, int off, boolean bigEndian); static byte[] doubleToBytesBE(double d, byte[] bytes, int off); static byte[] doubleToBytesLE(double d, byte[] bytes, int off); static byte[] longToBytes(long l, byte[] bytes, int off, boolean bigEndian); static byte[] longToBytesBE(long l, byte[] bytes, int off); static byte[] longToBytesLE(long l, byte[] bytes, int off); static byte[][] swapShorts(byte bs[][]); static byte[] swapShorts(byte b[], int off, int len); static byte[] swapInts(byte b[], int off, int len); static byte[] swapLongs(byte b[], int off, int len); static byte[] intsToBytesLE(int... values); static final byte[] EMPTY_BYTES; static final int[] EMPTY_INTS; static final float[] EMPTY_FLOATS; static final double[] EMPTY_DOUBLES; }### Answer: @Test public void testBytesToIntLE() { assertEquals(-12345, ByteUtils.bytesToIntLE(INT_12345_LE, 0)); }
### Question: ByteUtils { public static int bytesToTagBE(byte[] bytes, int off) { return bytesToIntBE(bytes, off); } static int bytesToVR(byte[] bytes, int off); static int bytesToUShort(byte[] bytes, int off, boolean bigEndian); static int bytesToUShortBE(byte[] bytes, int off); static int bytesToUShortLE(byte[] bytes, int off); static int bytesToShort(byte[] bytes, int off, boolean bigEndian); static int bytesToShortBE(byte[] bytes, int off); static int bytesToShortLE(byte[] bytes, int off); static void bytesToShorts(byte[] b, short[] s, int off, int len, boolean bigEndian); static void bytesToShortsLE(byte[] b, short[] s, int off, int len); static void bytesToShortsBE(byte[] b, short[] s, int off, int len); static int bytesToInt(byte[] bytes, int off, boolean bigEndian); static int bytesToIntBE(byte[] bytes, int off); static int bytesToIntLE(byte[] bytes, int off); static int bytesToTag(byte[] bytes, int off, boolean bigEndian); static int bytesToTagBE(byte[] bytes, int off); static int bytesToTagLE(byte[] bytes, int off); static float bytesToFloat(byte[] bytes, int off, boolean bigEndian); static float bytesToFloatBE(byte[] bytes, int off); static float bytesToFloatLE(byte[] bytes, int off); static long bytesToLong(byte[] bytes, int off, boolean bigEndian); static long bytesToLongBE(byte[] bytes, int off); static long bytesToLongLE(byte[] bytes, int off); static double bytesToDouble(byte[] bytes, int off, boolean bigEndian); static double bytesToDoubleBE(byte[] bytes, int off); static double bytesToDoubleLE(byte[] bytes, int off); static byte[] shortToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] shortToBytesBE(int i, byte[] bytes, int off); static byte[] shortToBytesLE(int i, byte[] bytes, int off); static byte[] intToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] intToBytesBE(int i, byte[] bytes, int off); static byte[] intToBytesLE(int i, byte[] bytes, int off); static byte[] tagToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] tagToBytesBE(int i, byte[] bytes, int off); static byte[] tagToBytesLE(int i, byte[] bytes, int off); static byte[] floatToBytes(float f, byte[] bytes, int off, boolean bigEndian); static byte[] floatToBytesBE(float f, byte[] bytes, int off); static byte[] floatToBytesLE(float f, byte[] bytes, int off); static byte[] doubleToBytes(double d, byte[] bytes, int off, boolean bigEndian); static byte[] doubleToBytesBE(double d, byte[] bytes, int off); static byte[] doubleToBytesLE(double d, byte[] bytes, int off); static byte[] longToBytes(long l, byte[] bytes, int off, boolean bigEndian); static byte[] longToBytesBE(long l, byte[] bytes, int off); static byte[] longToBytesLE(long l, byte[] bytes, int off); static byte[][] swapShorts(byte bs[][]); static byte[] swapShorts(byte b[], int off, int len); static byte[] swapInts(byte b[], int off, int len); static byte[] swapLongs(byte b[], int off, int len); static byte[] intsToBytesLE(int... values); static final byte[] EMPTY_BYTES; static final int[] EMPTY_INTS; static final float[] EMPTY_FLOATS; static final double[] EMPTY_DOUBLES; }### Answer: @Test public void testBytesToTagBE() { assertEquals(Tag.PixelData, ByteUtils.bytesToTagBE(TAG_PIXEL_DATA_BE, 0)); }
### Question: AttributeSelector implements Serializable { @Override public String toString() { if (str == null) str = toStringBuilder().toString(); return str; } AttributeSelector(int tag); AttributeSelector(int tag, String privateCreator); AttributeSelector(int tag, String privateCreator, ItemPointer... itemPointers); AttributeSelector(int tag, String privateCreator, List<ItemPointer> itemPointers); int tag(); String privateCreator(); int level(); ItemPointer itemPointer(int index); String selectStringValue(Attributes attrs, int valueIndex, String defVal); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); static AttributeSelector valueOf(String s); boolean matches(List<ItemPointer> itemPointers, String privateCreator, int tag); }### Answer: @Test public void testToString() { ItemPointer ip = new ItemPointer(Tag.RequestAttributesSequence); AttributeSelector selector = new AttributeSelector(Tag.StudyInstanceUID, null, ip); assertEquals(XPATH, selector.toString()); }
### Question: ByteUtils { public static int bytesToTagLE(byte[] bytes, int off) { return (bytes[off + 1] << 24) + ((bytes[off] & 255) << 16) + ((bytes[off + 3] & 255) << 8) + (bytes[off + 2] & 255); } static int bytesToVR(byte[] bytes, int off); static int bytesToUShort(byte[] bytes, int off, boolean bigEndian); static int bytesToUShortBE(byte[] bytes, int off); static int bytesToUShortLE(byte[] bytes, int off); static int bytesToShort(byte[] bytes, int off, boolean bigEndian); static int bytesToShortBE(byte[] bytes, int off); static int bytesToShortLE(byte[] bytes, int off); static void bytesToShorts(byte[] b, short[] s, int off, int len, boolean bigEndian); static void bytesToShortsLE(byte[] b, short[] s, int off, int len); static void bytesToShortsBE(byte[] b, short[] s, int off, int len); static int bytesToInt(byte[] bytes, int off, boolean bigEndian); static int bytesToIntBE(byte[] bytes, int off); static int bytesToIntLE(byte[] bytes, int off); static int bytesToTag(byte[] bytes, int off, boolean bigEndian); static int bytesToTagBE(byte[] bytes, int off); static int bytesToTagLE(byte[] bytes, int off); static float bytesToFloat(byte[] bytes, int off, boolean bigEndian); static float bytesToFloatBE(byte[] bytes, int off); static float bytesToFloatLE(byte[] bytes, int off); static long bytesToLong(byte[] bytes, int off, boolean bigEndian); static long bytesToLongBE(byte[] bytes, int off); static long bytesToLongLE(byte[] bytes, int off); static double bytesToDouble(byte[] bytes, int off, boolean bigEndian); static double bytesToDoubleBE(byte[] bytes, int off); static double bytesToDoubleLE(byte[] bytes, int off); static byte[] shortToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] shortToBytesBE(int i, byte[] bytes, int off); static byte[] shortToBytesLE(int i, byte[] bytes, int off); static byte[] intToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] intToBytesBE(int i, byte[] bytes, int off); static byte[] intToBytesLE(int i, byte[] bytes, int off); static byte[] tagToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] tagToBytesBE(int i, byte[] bytes, int off); static byte[] tagToBytesLE(int i, byte[] bytes, int off); static byte[] floatToBytes(float f, byte[] bytes, int off, boolean bigEndian); static byte[] floatToBytesBE(float f, byte[] bytes, int off); static byte[] floatToBytesLE(float f, byte[] bytes, int off); static byte[] doubleToBytes(double d, byte[] bytes, int off, boolean bigEndian); static byte[] doubleToBytesBE(double d, byte[] bytes, int off); static byte[] doubleToBytesLE(double d, byte[] bytes, int off); static byte[] longToBytes(long l, byte[] bytes, int off, boolean bigEndian); static byte[] longToBytesBE(long l, byte[] bytes, int off); static byte[] longToBytesLE(long l, byte[] bytes, int off); static byte[][] swapShorts(byte bs[][]); static byte[] swapShorts(byte b[], int off, int len); static byte[] swapInts(byte b[], int off, int len); static byte[] swapLongs(byte b[], int off, int len); static byte[] intsToBytesLE(int... values); static final byte[] EMPTY_BYTES; static final int[] EMPTY_INTS; static final float[] EMPTY_FLOATS; static final double[] EMPTY_DOUBLES; }### Answer: @Test public void testBytesToTagLE() { assertEquals(Tag.PixelData, ByteUtils.bytesToTagLE(TAG_PIXEL_DATA_LE, 0)); }
### Question: ByteUtils { public static float bytesToFloatBE(byte[] bytes, int off) { return Float.intBitsToFloat(bytesToIntBE(bytes, off)); } static int bytesToVR(byte[] bytes, int off); static int bytesToUShort(byte[] bytes, int off, boolean bigEndian); static int bytesToUShortBE(byte[] bytes, int off); static int bytesToUShortLE(byte[] bytes, int off); static int bytesToShort(byte[] bytes, int off, boolean bigEndian); static int bytesToShortBE(byte[] bytes, int off); static int bytesToShortLE(byte[] bytes, int off); static void bytesToShorts(byte[] b, short[] s, int off, int len, boolean bigEndian); static void bytesToShortsLE(byte[] b, short[] s, int off, int len); static void bytesToShortsBE(byte[] b, short[] s, int off, int len); static int bytesToInt(byte[] bytes, int off, boolean bigEndian); static int bytesToIntBE(byte[] bytes, int off); static int bytesToIntLE(byte[] bytes, int off); static int bytesToTag(byte[] bytes, int off, boolean bigEndian); static int bytesToTagBE(byte[] bytes, int off); static int bytesToTagLE(byte[] bytes, int off); static float bytesToFloat(byte[] bytes, int off, boolean bigEndian); static float bytesToFloatBE(byte[] bytes, int off); static float bytesToFloatLE(byte[] bytes, int off); static long bytesToLong(byte[] bytes, int off, boolean bigEndian); static long bytesToLongBE(byte[] bytes, int off); static long bytesToLongLE(byte[] bytes, int off); static double bytesToDouble(byte[] bytes, int off, boolean bigEndian); static double bytesToDoubleBE(byte[] bytes, int off); static double bytesToDoubleLE(byte[] bytes, int off); static byte[] shortToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] shortToBytesBE(int i, byte[] bytes, int off); static byte[] shortToBytesLE(int i, byte[] bytes, int off); static byte[] intToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] intToBytesBE(int i, byte[] bytes, int off); static byte[] intToBytesLE(int i, byte[] bytes, int off); static byte[] tagToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] tagToBytesBE(int i, byte[] bytes, int off); static byte[] tagToBytesLE(int i, byte[] bytes, int off); static byte[] floatToBytes(float f, byte[] bytes, int off, boolean bigEndian); static byte[] floatToBytesBE(float f, byte[] bytes, int off); static byte[] floatToBytesLE(float f, byte[] bytes, int off); static byte[] doubleToBytes(double d, byte[] bytes, int off, boolean bigEndian); static byte[] doubleToBytesBE(double d, byte[] bytes, int off); static byte[] doubleToBytesLE(double d, byte[] bytes, int off); static byte[] longToBytes(long l, byte[] bytes, int off, boolean bigEndian); static byte[] longToBytesBE(long l, byte[] bytes, int off); static byte[] longToBytesLE(long l, byte[] bytes, int off); static byte[][] swapShorts(byte bs[][]); static byte[] swapShorts(byte b[], int off, int len); static byte[] swapInts(byte b[], int off, int len); static byte[] swapLongs(byte b[], int off, int len); static byte[] intsToBytesLE(int... values); static final byte[] EMPTY_BYTES; static final int[] EMPTY_INTS; static final float[] EMPTY_FLOATS; static final double[] EMPTY_DOUBLES; }### Answer: @Test public void testBytesToFloatBE() { assertEquals((float) Math.PI, ByteUtils.bytesToFloatBE(FLOAT_PI_BE, 0), 0); }
### Question: ByteUtils { public static float bytesToFloatLE(byte[] bytes, int off) { return Float.intBitsToFloat(bytesToIntLE(bytes, off)); } static int bytesToVR(byte[] bytes, int off); static int bytesToUShort(byte[] bytes, int off, boolean bigEndian); static int bytesToUShortBE(byte[] bytes, int off); static int bytesToUShortLE(byte[] bytes, int off); static int bytesToShort(byte[] bytes, int off, boolean bigEndian); static int bytesToShortBE(byte[] bytes, int off); static int bytesToShortLE(byte[] bytes, int off); static void bytesToShorts(byte[] b, short[] s, int off, int len, boolean bigEndian); static void bytesToShortsLE(byte[] b, short[] s, int off, int len); static void bytesToShortsBE(byte[] b, short[] s, int off, int len); static int bytesToInt(byte[] bytes, int off, boolean bigEndian); static int bytesToIntBE(byte[] bytes, int off); static int bytesToIntLE(byte[] bytes, int off); static int bytesToTag(byte[] bytes, int off, boolean bigEndian); static int bytesToTagBE(byte[] bytes, int off); static int bytesToTagLE(byte[] bytes, int off); static float bytesToFloat(byte[] bytes, int off, boolean bigEndian); static float bytesToFloatBE(byte[] bytes, int off); static float bytesToFloatLE(byte[] bytes, int off); static long bytesToLong(byte[] bytes, int off, boolean bigEndian); static long bytesToLongBE(byte[] bytes, int off); static long bytesToLongLE(byte[] bytes, int off); static double bytesToDouble(byte[] bytes, int off, boolean bigEndian); static double bytesToDoubleBE(byte[] bytes, int off); static double bytesToDoubleLE(byte[] bytes, int off); static byte[] shortToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] shortToBytesBE(int i, byte[] bytes, int off); static byte[] shortToBytesLE(int i, byte[] bytes, int off); static byte[] intToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] intToBytesBE(int i, byte[] bytes, int off); static byte[] intToBytesLE(int i, byte[] bytes, int off); static byte[] tagToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] tagToBytesBE(int i, byte[] bytes, int off); static byte[] tagToBytesLE(int i, byte[] bytes, int off); static byte[] floatToBytes(float f, byte[] bytes, int off, boolean bigEndian); static byte[] floatToBytesBE(float f, byte[] bytes, int off); static byte[] floatToBytesLE(float f, byte[] bytes, int off); static byte[] doubleToBytes(double d, byte[] bytes, int off, boolean bigEndian); static byte[] doubleToBytesBE(double d, byte[] bytes, int off); static byte[] doubleToBytesLE(double d, byte[] bytes, int off); static byte[] longToBytes(long l, byte[] bytes, int off, boolean bigEndian); static byte[] longToBytesBE(long l, byte[] bytes, int off); static byte[] longToBytesLE(long l, byte[] bytes, int off); static byte[][] swapShorts(byte bs[][]); static byte[] swapShorts(byte b[], int off, int len); static byte[] swapInts(byte b[], int off, int len); static byte[] swapLongs(byte b[], int off, int len); static byte[] intsToBytesLE(int... values); static final byte[] EMPTY_BYTES; static final int[] EMPTY_INTS; static final float[] EMPTY_FLOATS; static final double[] EMPTY_DOUBLES; }### Answer: @Test public void testBytesToFloatLE() { assertEquals((float) Math.PI, ByteUtils.bytesToFloatLE(FLOAT_PI_LE, 0), 0); }
### Question: ByteUtils { public static double bytesToDoubleBE(byte[] bytes, int off) { return Double.longBitsToDouble(bytesToLongBE(bytes, off)); } static int bytesToVR(byte[] bytes, int off); static int bytesToUShort(byte[] bytes, int off, boolean bigEndian); static int bytesToUShortBE(byte[] bytes, int off); static int bytesToUShortLE(byte[] bytes, int off); static int bytesToShort(byte[] bytes, int off, boolean bigEndian); static int bytesToShortBE(byte[] bytes, int off); static int bytesToShortLE(byte[] bytes, int off); static void bytesToShorts(byte[] b, short[] s, int off, int len, boolean bigEndian); static void bytesToShortsLE(byte[] b, short[] s, int off, int len); static void bytesToShortsBE(byte[] b, short[] s, int off, int len); static int bytesToInt(byte[] bytes, int off, boolean bigEndian); static int bytesToIntBE(byte[] bytes, int off); static int bytesToIntLE(byte[] bytes, int off); static int bytesToTag(byte[] bytes, int off, boolean bigEndian); static int bytesToTagBE(byte[] bytes, int off); static int bytesToTagLE(byte[] bytes, int off); static float bytesToFloat(byte[] bytes, int off, boolean bigEndian); static float bytesToFloatBE(byte[] bytes, int off); static float bytesToFloatLE(byte[] bytes, int off); static long bytesToLong(byte[] bytes, int off, boolean bigEndian); static long bytesToLongBE(byte[] bytes, int off); static long bytesToLongLE(byte[] bytes, int off); static double bytesToDouble(byte[] bytes, int off, boolean bigEndian); static double bytesToDoubleBE(byte[] bytes, int off); static double bytesToDoubleLE(byte[] bytes, int off); static byte[] shortToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] shortToBytesBE(int i, byte[] bytes, int off); static byte[] shortToBytesLE(int i, byte[] bytes, int off); static byte[] intToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] intToBytesBE(int i, byte[] bytes, int off); static byte[] intToBytesLE(int i, byte[] bytes, int off); static byte[] tagToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] tagToBytesBE(int i, byte[] bytes, int off); static byte[] tagToBytesLE(int i, byte[] bytes, int off); static byte[] floatToBytes(float f, byte[] bytes, int off, boolean bigEndian); static byte[] floatToBytesBE(float f, byte[] bytes, int off); static byte[] floatToBytesLE(float f, byte[] bytes, int off); static byte[] doubleToBytes(double d, byte[] bytes, int off, boolean bigEndian); static byte[] doubleToBytesBE(double d, byte[] bytes, int off); static byte[] doubleToBytesLE(double d, byte[] bytes, int off); static byte[] longToBytes(long l, byte[] bytes, int off, boolean bigEndian); static byte[] longToBytesBE(long l, byte[] bytes, int off); static byte[] longToBytesLE(long l, byte[] bytes, int off); static byte[][] swapShorts(byte bs[][]); static byte[] swapShorts(byte b[], int off, int len); static byte[] swapInts(byte b[], int off, int len); static byte[] swapLongs(byte b[], int off, int len); static byte[] intsToBytesLE(int... values); static final byte[] EMPTY_BYTES; static final int[] EMPTY_INTS; static final float[] EMPTY_FLOATS; static final double[] EMPTY_DOUBLES; }### Answer: @Test public void testBytesToDoubleBE() { assertEquals(Math.PI, ByteUtils.bytesToDoubleBE(DOUBLE_PI_BE, 0), 0); }
### Question: ByteUtils { public static double bytesToDoubleLE(byte[] bytes, int off) { return Double.longBitsToDouble(bytesToLongLE(bytes, off)); } static int bytesToVR(byte[] bytes, int off); static int bytesToUShort(byte[] bytes, int off, boolean bigEndian); static int bytesToUShortBE(byte[] bytes, int off); static int bytesToUShortLE(byte[] bytes, int off); static int bytesToShort(byte[] bytes, int off, boolean bigEndian); static int bytesToShortBE(byte[] bytes, int off); static int bytesToShortLE(byte[] bytes, int off); static void bytesToShorts(byte[] b, short[] s, int off, int len, boolean bigEndian); static void bytesToShortsLE(byte[] b, short[] s, int off, int len); static void bytesToShortsBE(byte[] b, short[] s, int off, int len); static int bytesToInt(byte[] bytes, int off, boolean bigEndian); static int bytesToIntBE(byte[] bytes, int off); static int bytesToIntLE(byte[] bytes, int off); static int bytesToTag(byte[] bytes, int off, boolean bigEndian); static int bytesToTagBE(byte[] bytes, int off); static int bytesToTagLE(byte[] bytes, int off); static float bytesToFloat(byte[] bytes, int off, boolean bigEndian); static float bytesToFloatBE(byte[] bytes, int off); static float bytesToFloatLE(byte[] bytes, int off); static long bytesToLong(byte[] bytes, int off, boolean bigEndian); static long bytesToLongBE(byte[] bytes, int off); static long bytesToLongLE(byte[] bytes, int off); static double bytesToDouble(byte[] bytes, int off, boolean bigEndian); static double bytesToDoubleBE(byte[] bytes, int off); static double bytesToDoubleLE(byte[] bytes, int off); static byte[] shortToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] shortToBytesBE(int i, byte[] bytes, int off); static byte[] shortToBytesLE(int i, byte[] bytes, int off); static byte[] intToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] intToBytesBE(int i, byte[] bytes, int off); static byte[] intToBytesLE(int i, byte[] bytes, int off); static byte[] tagToBytes(int i, byte[] bytes, int off, boolean bigEndian); static byte[] tagToBytesBE(int i, byte[] bytes, int off); static byte[] tagToBytesLE(int i, byte[] bytes, int off); static byte[] floatToBytes(float f, byte[] bytes, int off, boolean bigEndian); static byte[] floatToBytesBE(float f, byte[] bytes, int off); static byte[] floatToBytesLE(float f, byte[] bytes, int off); static byte[] doubleToBytes(double d, byte[] bytes, int off, boolean bigEndian); static byte[] doubleToBytesBE(double d, byte[] bytes, int off); static byte[] doubleToBytesLE(double d, byte[] bytes, int off); static byte[] longToBytes(long l, byte[] bytes, int off, boolean bigEndian); static byte[] longToBytesBE(long l, byte[] bytes, int off); static byte[] longToBytesLE(long l, byte[] bytes, int off); static byte[][] swapShorts(byte bs[][]); static byte[] swapShorts(byte b[], int off, int len); static byte[] swapInts(byte b[], int off, int len); static byte[] swapLongs(byte b[], int off, int len); static byte[] intsToBytesLE(int... values); static final byte[] EMPTY_BYTES; static final int[] EMPTY_INTS; static final float[] EMPTY_FLOATS; static final double[] EMPTY_DOUBLES; }### Answer: @Test public void testBytesToDoubleLE() { assertEquals(Math.PI, ByteUtils.bytesToDoubleLE(DOUBLE_PI_LE, 0), 0); }