auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void checkPreviewUpdatedAfterRotateDeviceAndStopResume() { mActivityRule.getActivity().setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); pressHomeButton(); mActivityRule.getActivity().resetViewIdlingResource(); IdlingRegistry.getInstance().register(mActivityRule.getActivity().getViewIdlingResource()); mIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); mActivityRule.getActivity().startActivity(mIntent); onView(withId(R.id.textureView)).check(matches(isDisplayed())); IdlingRegistry.getInstance().unregister( mActivityRule.getActivity().getViewIdlingResource()); }

Target:
public void checkPreviewUpdatedAfterRotateDeviceAndStopResume() { mActivityRule.getActivity().setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); onView(withId(R.id.textureView)).check(matches(isDisplayed())); pressHomeButton(); mActivityRule.getActivity().resetViewIdlingResource(); IdlingRegistry.getInstance().register(mActivityRule.getActivity().getViewIdlingResource()); mIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); mActivityRule.getActivity().startActivity(mIntent); onView(withId(R.id.textureView)).check(matches(isDisplayed())); IdlingRegistry.getInstance().unregister( mActivityRule.getActivity().getViewIdlingResource()); }
Source:
public void testCountMessagesPropertyExist() throws Exception { String key = new String("key_group"); String valueGroup1 = "group_1"; String valueGroup2 = "group_2"; SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); session.createQueue(address, queue, null, false); ClientProducer producer = session.createProducer(address); for (int i = 0; i < 100; i++) { ClientMessage msg = session.createMessage(false); if(i % 3 == 0){ msg.putStringProperty(key, valueGroup1); } else { msg.putStringProperty(key, valueGroup2); } producer.send(msg); } for (int i = 0; i < 20; i++) { ClientMessage msg = session.createMessage(false); producer.send(msg); } QueueControl queueControl = createManagementControl(address, queue); Assert.assertEquals(120, getMessageCount(queueControl)); String result = queueControl.countMessagesProperty(key); JsonObject jsonObject = JsonUtil.readJsonObject(result); Assert.assertEquals(34, jsonObject.getInt(valueGroup1)); Assert.assertEquals(66, jsonObject.getInt(valueGroup2)); Assert.assertEquals(20, jsonObject.getInt("*_UNDEFINED_*")); session.deleteQueue(queue); }

Target:
public void testCountMessagesPropertyExist() throws Exception { String key = new String("key_group"); String valueGroup1 = "group_1"; String valueGroup2 = "group_2"; SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); session.createQueue(address, queue, null, false); ClientProducer producer = session.createProducer(address); for (int i = 0; i < 100; i++) { ClientMessage msg = session.createMessage(false); if (i % 3 == 0) { msg.putStringProperty(key, valueGroup1); } else { msg.putStringProperty(key, valueGroup2); } producer.send(msg); } for (int i = 0; i < 20; i++) { ClientMessage msg = session.createMessage(false); producer.send(msg); } QueueControl queueControl = createManagementControl(address, queue); Assert.assertEquals(120, getMessageCount(queueControl)); String result = queueControl.countMessages(null, key); JsonObject jsonObject = JsonUtil.readJsonObject(result); Assert.assertEquals(34, jsonObject.getInt(valueGroup1)); Assert.assertEquals(66, jsonObject.getInt(valueGroup2)); Assert.assertEquals(20, jsonObject.getInt("null")); session.deleteQueue(queue); }
Source:
public boolean isRecoveryRequiredAt( File dataDir ) throws IOException { File neoStore = new File( dataDir, MetaDataStore.DEFAULT_NAME ); boolean noStoreFound = !NeoStores.isStorePresent( pageCache, dataDir ); if ( noStoreFound ) { return false; } long logVersion = MetaDataStore.getRecord( pageCache, neoStore, MetaDataStore.Position.LOG_VERSION ); MetaDataStore.setRecord( pageCache, neoStore, MetaDataStore.Position.LOG_VERSION, logVersion ); PhysicalLogFiles logFiles = new PhysicalLogFiles( dataDir, fs ); LogEntryReader<ReadableClosablePositionAwareChannel> reader = new VersionAwareLogEntryReader<>(); LogTailScanner tailScanner = new LogTailScanner( logFiles, fs, reader ); return new PositionToRecoverFrom( tailScanner, NO_MONITOR ).get() != LogPosition.UNSPECIFIED; }

Target:
public boolean isRecoveryRequiredAt( File dataDir ) throws IOException { File neoStore = new File( dataDir, MetaDataStore.DEFAULT_NAME ); boolean noStoreFound = !NeoStores.isStorePresent( pageCache, dataDir ); if ( noStoreFound ) { return false; } PhysicalLogFiles logFiles = new PhysicalLogFiles( dataDir, fs ); LogEntryReader<ReadableClosablePositionAwareChannel> reader = new VersionAwareLogEntryReader<>(); LogTailScanner tailScanner = new LogTailScanner( logFiles, fs, reader ); return new PositionToRecoverFrom( tailScanner, NO_MONITOR ).get() != LogPosition.UNSPECIFIED; }
Source:
public boolean validate() { getLvName().validateEntity(new IValidation[] { new NotEmptyValidation(), new LengthValidation(50), new AsciiNameValidation() }); if (!getLvName().getIsValid()) { return false; } getMountPoint().validateEntity(new IValidation[] { new NotEmptyValidation(), new BrickMountPointValidation() }); if (!getMountPoint().getIsValid()) { return false; } IntegerValidation noOfPhysicalDiscsValidation = new IntegerValidation(); noOfPhysicalDiscsValidation.setMinimum(1); getNoOfPhysicalDisksInRaidVolume().validateEntity(new IValidation[] { new NotEmptyValidation(), noOfPhysicalDiscsValidation }); IntegerValidation stripSizeValidation = new IntegerValidation(); stripSizeValidation.setMinimum(1); getStripeSize().validateEntity(new IValidation[] { new NotEmptyValidation(), stripSizeValidation }); if (!getStripeSize().getIsValid()) { return false; } if (getStorageDevices().getSelectedItems() == null || getStorageDevices().getSelectedItems().isEmpty()) { setMessage(ConstantsManager.getInstance().getConstants().selectStorageDevice()); return false; } return true; }

Target:
public boolean validate() { getLvName().validateEntity(new IValidation[] { new NotEmptyValidation(), new LengthValidation(50), new AsciiNameValidation() }); if (!getLvName().getIsValid()) { return false; } getMountPoint().validateEntity(new IValidation[] { new NotEmptyValidation(), new BrickMountPointValidation() }); if (!getMountPoint().getIsValid()) { return false; } IntegerValidation noOfPhysicalDiscsValidation = new IntegerValidation(); noOfPhysicalDiscsValidation.setMinimum(1); getNoOfPhysicalDisksInRaidVolume().validateEntity(new IValidation[] { new NotEmptyValidation(), noOfPhysicalDiscsValidation }); if (!getNoOfPhysicalDisksInRaidVolume().getIsValid()) { return false; } IntegerValidation stripSizeValidation = new IntegerValidation(); stripSizeValidation.setMinimum(1); getStripeSize().validateEntity(new IValidation[] { new NotEmptyValidation(), stripSizeValidation }); if (!getStripeSize().getIsValid()) { return false; } if (getStorageDevices().getSelectedItems() == null || getStorageDevices().getSelectedItems().isEmpty()) { setMessage(ConstantsManager.getInstance().getConstants().selectStorageDevice()); return false; } return true; }
Source:
public static String buildPayload(Map<String, String> params) { if (params == null) { return null; } StringBuilder bodyBuilder = new StringBuilder(); Iterator<Entry<String, String>> iterator = params.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, String> param = iterator.next(); bodyBuilder.append(param.getKey()).append('=').append(param.getValue()); if (iterator.hasNext()) { bodyBuilder.append('&'); } } return bodyBuilder.toString(); }

Target:
public static String buildPayload(Map<String, String> params) { StringBuilder bodyBuilder = new StringBuilder(); Iterator<Entry<String, String>> iterator = params.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, String> param = iterator.next(); bodyBuilder.append(param.getKey()).append('=').append(param.getValue()); if (iterator.hasNext()) { bodyBuilder.append('&'); } } return bodyBuilder.toString(); }
Source:
public void testPerformHandshakeWithoutOriginHeader() { EmbeddedChannel ch = new EmbeddedChannel( new HttpObjectAggregator(42), new HttpRequestDecoder(), new HttpResponseEncoder()); FullHttpRequest req = new DefaultFullHttpRequest( HTTP_1_1, HttpMethod.GET, "/chat", Unpooled.copiedBuffer("^n:ds[4U", CharsetUtil.US_ASCII)); req.headers().set(HttpHeaderNames.HOST, "server.example.com"); req.headers().set(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET); req.headers().set(HttpHeaderNames.CONNECTION, "Upgrade"); req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_KEY1, "4 @1 46546xW%0l 1 5"); req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, "chat, superchat"); WebSocketServerHandshaker00 handshaker00 = new WebSocketServerHandshaker00( "ws://example.com/chat", "chat", Integer.MAX_VALUE); try { handshaker00.handshake(ch, req); fail("Expecting WebSocketHandshakeException"); } catch (WebSocketHandshakeException e) { assertEquals("Missing origin header, got only " + "[host, upgrade, connection, sec-websocket-key1, sec-websocket-protocol]", e.getMessage()); } }

Target:
public void testPerformHandshakeWithoutOriginHeader() { EmbeddedChannel ch = new EmbeddedChannel( new HttpObjectAggregator(42), new HttpRequestDecoder(), new HttpResponseEncoder()); FullHttpRequest req = new DefaultFullHttpRequest( HTTP_1_1, HttpMethod.GET, "/chat", Unpooled.copiedBuffer("^n:ds[4U", CharsetUtil.US_ASCII)); req.headers().set(HttpHeaderNames.HOST, "server.example.com"); req.headers().set(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET); req.headers().set(HttpHeaderNames.CONNECTION, "Upgrade"); req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_KEY1, "4 @1 46546xW%0l 1 5"); req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, "chat, superchat"); WebSocketServerHandshaker00 handshaker00 = new WebSocketServerHandshaker00( "ws://example.com/chat", "chat", Integer.MAX_VALUE); try { handshaker00.handshake(ch, req); fail("Expecting WebSocketHandshakeException"); } catch (WebSocketHandshakeException e) { assertEquals("Missing origin header, got only " + "[host, upgrade, connection, sec-websocket-key1, sec-websocket-protocol]", e.getMessage()); } finally { req.release(); } }
Source:
public Map<Long, ILogData> readAll(RuntimeLayout runtimeLayout, List<Long> addresses, boolean waitForWrite) { long startAddress = Collections.min(addresses); long endAddress = Collections.max(addresses); int numUnits = runtimeLayout.getLayout().getSegmentLength(startAddress); log.trace("readAll[{}-{}]: chain {}/{}", startAddress, endAddress, numUnits, numUnits); Map<Long, LogData> logResult = CFUtils.getUninterruptibly(runtimeLayout .getLogUnitClient(startAddress, numUnits - 1) .readAll(addresses)).getAddresses(); return readOrHoleFill(runtimeLayout, logResult, startAddress, numUnits, waitForWrite); }

Target:
public Map<Long, ILogData> readAll(RuntimeLayout runtimeLayout, List<Long> addresses, boolean waitForWrite) { Map<String, List<Long>> serverAddressMap = new HashMap<>(); for (Long address : addresses) { List<String> logServers = runtimeLayout.getLayout().getStripe(address).getLogServers(); String logServer = logServers.get(logServers.size() - 1); List<Long> addressList = serverAddressMap.computeIfAbsent(logServer, s -> new ArrayList<>()); addressList.add(address); } List<CompletableFuture<ReadResponse>> futures = serverAddressMap.entrySet().stream() .map(entry -> runtimeLayout.getLogUnitClient(entry.getKey()).readAll(entry.getValue())) .collect(Collectors.toList()); Map<Long, LogData> readResult = futures.stream() .map(future -> CFUtils.getUninterruptibly(future).getAddresses()) .reduce(new HashMap<>(), (map1, map2) -> { map1.putAll(map2); return map1; }); return waitOrHoleFill(runtimeLayout, readResult, waitForWrite); }
Source:
public void onPluginLoad() { Plugin.get().screen("create-service-user", new CreateServiceUserScreen.Factory()); }

Target:
public void onPluginLoad() { Plugin.get().screen("create", new CreateServiceUserScreen.Factory()); }
Source:
public void progressUpdatedNotification(String scriptId, int progress) { Map<Event.WorkflowProgressField, String> eventData = Maps.newHashMap(); eventData.put(Event.WorkflowProgressField.workflowProgress, Integer.toString(progress)); pushEvent(scriptId, new Event.WorkflowProgressEvent(eventData)); LOG.info("pushed event , progress={}", progress); for (DAGNode<PigJob> node : dagNodeNameMap.values()) { if (node.getJob().getId() == null) { continue; } addMapReduceJobState(node.getJob()); if (node.getJob().getMapReduceJobState() != null && !completedJobIds.contains(node.getJob().getId())) { pushEvent(scriptId, new Event.JobProgressEvent(node)); if (node.getJob().getMapReduceJobState().isComplete()) { completedJobIds.add(node.getJob().getId()); } } } }

Target:
public void progressUpdatedNotification(String scriptId, int progress) { Map<Event.WorkflowProgressField, String> eventData = Maps.newHashMap(); eventData.put(Event.WorkflowProgressField.workflowProgress, Integer.toString(progress)); pushEvent(scriptId, new Event.WorkflowProgressEvent(eventData)); for (DAGNode<PigJob> node : dagNodeNameMap.values()) { if (node.getJob().getId() == null) { continue; } addMapReduceJobState(node.getJob()); if (node.getJob().getMapReduceJobState() != null && !completedJobIds.contains(node.getJob().getId())) { pushEvent(scriptId, new Event.JobProgressEvent(node)); if (node.getJob().getMapReduceJobState().isComplete()) { completedJobIds.add(node.getJob().getId()); } } } }
Source:
public RestGatewayLink(final GatewayBean gateway) { try { this.gateway = gateway; String cfg = gateway.getConfiguration(); cfg = CurrentDataEncrypter.instance.decrypt(cfg, new DataEncryptionContext()); cfg = PROPERTY_SUBSTITUTOR.replace(cfg); setConfig((RestGatewayConfigBean) mapper.reader(RestGatewayConfigBean.class).readValue(cfg)); getConfig().setPassword( PROPERTY_SUBSTITUTOR.replace( CurrentDataEncrypter.instance.decrypt(getConfig().getPassword(), new DataEncryptionContext()))); httpClient = HttpClientBuilder.create() .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE) .setSSLSocketFactory(sslConnectionFactory) .addInterceptorFirst(new HttpRequestInterceptor() { @Override public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { configureBasicAuth(request); } }).build(); } catch (JsonProcessingException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } }

Target:
public RestGatewayLink(final GatewayBean gateway) { try { this.gateway = gateway; String cfg = gateway.getConfiguration(); cfg = CurrentDataEncrypter.instance.decrypt(cfg, new DataEncryptionContext()); cfg = PROPERTY_SUBSTITUTOR.replace(cfg); this.config = (RestGatewayConfigBean) mapper.reader(RestGatewayConfigBean.class).readValue(cfg); this.config.setPassword( PROPERTY_SUBSTITUTOR.replace( CurrentDataEncrypter.instance.decrypt(this.config.getPassword(), new DataEncryptionContext()))); httpClient = HttpClientBuilder.create() .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE) .setSSLSocketFactory(sslConnectionFactory) .addInterceptorFirst(new HttpRequestInterceptor() { @Override public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { configureBasicAuth(request); } }).build(); } catch (JsonProcessingException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } }
Source:
public void controlResized(ControlEvent e) { for (final Entry<Control, Integer> entry : controlsToAlign.entrySet()) { final int availableWidth = entry.getKey().getParent().getSize().x; if (availableWidth == 0) { continue; } final double prefWidth = entry.getValue(); int widthHint = computePreferedWidthBasedOnStep(prefWidth, step); if (widthHint > availableWidth) { widthHint = entry.getValue() > availableWidth ? entry.getValue() : availableWidth; } GridData.class.cast(entry.getKey().getLayoutData()).widthHint = widthHint; } composite.layout(true, true); }

Target:
public void controlResized(ControlEvent e) { for (final Entry<Control, Integer> entry : controlsToAlign.entrySet()) { final int availableWidth = entry.getKey().getParent().getSize().x; if (availableWidth == 0) { continue; } final int prefWidth = entry.getValue(); int widthHint = computePreferredWidthBasedOnPixelGridSize(prefWidth, pixelGridSize); if (widthHint > availableWidth) { widthHint = prefWidth > availableWidth ? prefWidth : availableWidth; } GridData.class.cast(entry.getKey().getLayoutData()).widthHint = widthHint; } composite.layout(true, true); }
Source:
public Boolean fenceOff(VirtualMachine vm, Host host) { if (host.getHypervisorType() != HypervisorType.XenServer) { s_logger.debug("Don't know how to fence non XenServer hosts " + host.getHypervisorType()); return null; } List<HostVO> hosts = _resourceMgr.listAllHostsInCluster(host.getClusterId()); FenceCommand fence = new FenceCommand(vm, host); for (HostVO h : hosts) { if (h.getHypervisorType() == HypervisorType.XenServer) { if (h.getStatus() != Status.Up) { continue; } if (h.getId() == host.getId()) { continue; } FenceAnswer answer; try { Answer ans = _agentMgr.send(h.getId(), fence); if (!(ans instanceof FenceAnswer)) { s_logger.debug("Answer is not fenceanswer. Result = " + ans.getResult() + "; Details = " + ans.getDetails()); continue; } answer = (FenceAnswer)ans; } catch (AgentUnavailableException | OperationCancelledException | OperationTimedoutException e) { if (s_logger.isDebugEnabled()) { s_logger.debug("Moving on to the next host because " + h.toString() + " is unavailable"); } continue; } if (answer != null && answer.getResult()) { return true; } } } if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to fence off " + vm.toString() + " on " + host.toString()); } return false; }

Target:
public Boolean fenceOff(VirtualMachine vm, Host host) { if (host.getHypervisorType() != HypervisorType.XenServer) { s_logger.debug("Don't know how to fence non XenServer hosts " + host.getHypervisorType()); return null; } List<HostVO> hosts = _resourceMgr.listAllHostsInCluster(host.getClusterId()); FenceCommand fence = new FenceCommand(vm, host); for (HostVO h : hosts) { if (h.getHypervisorType() == HypervisorType.XenServer) { if (h.getStatus() != Status.Up) { continue; } if (h.getId() == host.getId()) { continue; } FenceAnswer answer; try { Answer ans = _agentMgr.send(h.getId(), fence); if (!(ans instanceof FenceAnswer)) { s_logger.debug("Answer is not fenceanswer. Result = " + ans.getResult() + "; Details = " + ans.getDetails()); continue; } answer = (FenceAnswer)ans; } catch (OperationCancelledException e) { if (s_logger.isDebugEnabled()) { s_logger.debug("cancelling because " + h.toString() + " is unavailable(operation cancelled)"); } break; } catch (AgentUnavailableException | OperationTimedoutException e) { if (s_logger.isDebugEnabled()) { s_logger.debug("Moving on to the next host because " + h.toString() + " is unavailable"); } continue; } if (answer != null && answer.getResult()) { return true; } } } if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to fence off " + vm.toString() + " on " + host.toString()); } return false; }
Source:
public void testAllByConnectionId() { List<StorageDomain> domains = dao.getAllByConnectionId(Guid.createGuidFromString("0cc146e8-e5ed-482c-8814-270bc48c297f")); assertEquals("Unexpected number of storage domains by connection id", domains.size(), 1); assertEquals("Wrong storage domain id for search by connection id", domains.get(0).getId(), Guid.createGuidFromString("c2211b56-8869-41cd-84e1-78d7cb96f31d")); }

Target:
public void testAllByConnectionId() { List<StorageDomain> domains = dao.getAllByConnectionId(new Guid("0cc146e8-e5ed-482c-8814-270bc48c297f")); assertEquals("Unexpected number of storage domains by connection id", domains.size(), 1); assertEquals("Wrong storage domain id for search by connection id", domains.get(0).getId(), new Guid("c2211b56-8869-41cd-84e1-78d7cb96f31d")); }
Source:
public void testPutIfAbsentHasStoreEntryCacheAccessExceptionHasCacheWriterEntry() throws Exception { final MockStore realStore = new MockStore(Collections.singletonMap("key", "oldValue")); this.store = spy(realStore); doThrow(new CacheAccessException("")).when(this.store).computeIfAbsent(eq("key"), getAnyFunction()); final MockCacheWriter realCache = new MockCacheWriter(Collections.singletonMap("key", "oldValue")); this.cacheWriter = spy(realCache); final Ehcache<String, String> ehcache = this.getEhcache(this.cacheWriter); final InOrder ordered = inOrder(this.cacheWriter, this.spiedResilienceStrategy); assertThat(ehcache.putIfAbsent("key", "value"), is(nullValue())); verify(this.store).computeIfAbsent(eq("key"), getAnyFunction()); ordered.verify(this.cacheWriter).write(eq("key"), eq("value")); ordered.verify(this.spiedResilienceStrategy) .putIfAbsentFailure(eq("key"), eq("value"), any(CacheAccessException.class), eq(true)); assertThat(realCache.getEntries().get("key"), equalTo("value")); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.PutIfAbsentOutcome.FAILURE)); }

Target:
public void testPutIfAbsentHasStoreEntryCacheAccessExceptionHasCacheWriterEntry() throws Exception { final FakeStore fakeStore = new FakeStore(Collections.singletonMap("key", "oldValue")); this.store = spy(fakeStore); doThrow(new CacheAccessException("")).when(this.store).computeIfAbsent(eq("key"), getAnyFunction()); final FakeCacheWriter fakeWriter = new FakeCacheWriter(Collections.singletonMap("key", "oldValue")); this.cacheWriter = spy(fakeWriter); final Ehcache<String, String> ehcache = this.getEhcache(this.cacheWriter); final InOrder ordered = inOrder(this.cacheWriter, this.spiedResilienceStrategy); ehcache.putIfAbsent("key", "value"); verify(this.store).computeIfAbsent(eq("key"), getAnyFunction()); ordered.verify(this.cacheWriter).write(eq("key"), eq("value")); ordered.verify(this.spiedResilienceStrategy) .putIfAbsentFailure(eq("key"), eq("value"), any(CacheAccessException.class), eq(true)); assertThat(fakeWriter.getEntryMap().get("key"), equalTo("value")); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.PutIfAbsentOutcome.FAILURE)); }
Source:
private GitModelObject handleCacheTree(ObjectId repoId, ObjectId cacheId, String path) throws IOException { String pathKey = path.split("/")[0]; GitModelCacheTree cacheTree = cacheTreeMap.get(pathKey); if (cacheTree == null) { cacheTree = new GitModelCacheTree(this, baseCommit, repoId, cacheId, getLocation().append(pathKey), fileFactory); cacheTreeMap.put(pathKey, cacheTree); } cacheTree.addChild(repoId, cacheId, path.substring(path.indexOf('/') + 1)); return cacheTree; }

Target:
private GitModelObject handleCacheTree(ObjectId repoId, ObjectId cacheId, String path) throws IOException { int firstSlash = path.indexOf("/"); String pathKey = path.substring(0, firstSlash); GitModelCacheTree cacheTree = cacheTreeMap.get(pathKey); if (cacheTree == null) { cacheTree = new GitModelCacheTree(this, baseCommit, repoId, cacheId, getLocation().append(pathKey), fileFactory); cacheTreeMap.put(pathKey, cacheTree); } cacheTree.addChild(repoId, cacheId, path.substring(firstSlash + 1)); return cacheTree; }
Source:
public static DataWord of(int num) { return of(ByteBuffer.allocate(4).putInt(num).array()); }

Target:
public static DataWord of(int num) { return of(ByteBuffer.allocate(Integer.BYTES).putInt(num).array()); }
Source:
public static FixedDoubleBreakdownHistogram deserialize(SliceInput input) { int bucketCount = input.readInt(); double min = input.readDouble(); double max = input.readDouble(); verifyParameters(bucketCount, min, max); int size = input.readInt(); int[] indices = new int[size]; double[] weights = new double[size]; long[] counts = new long[size]; input.readBytes( Slices.wrappedIntArray(indices), size * SizeOf.SIZE_OF_INT); input.readBytes( Slices.wrappedDoubleArray(weights), size * SizeOf.SIZE_OF_DOUBLE); input.readBytes( Slices.wrappedLongArray(counts), size * SizeOf.SIZE_OF_LONG); return new FixedDoubleBreakdownHistogram(bucketCount, min, max, indices, weights, counts); }

Target:
public static FixedDoubleBreakdownHistogram deserialize(SliceInput input) { int bucketCount = input.readInt(); double min = input.readDouble(); double max = input.readDouble(); validateParameters(bucketCount, min, max); int size = input.readInt(); int[] indices = new int[size]; double[] weights = new double[size]; long[] counts = new long[size]; input.readBytes(Slices.wrappedIntArray(indices), size * SizeOf.SIZE_OF_INT); input.readBytes(Slices.wrappedDoubleArray(weights), size * SizeOf.SIZE_OF_DOUBLE); input.readBytes(Slices.wrappedLongArray(counts), size * SizeOf.SIZE_OF_LONG); return new FixedDoubleBreakdownHistogram(bucketCount, min, max, indices, weights, counts); }
Source:
private static void updateTimeoutLogableObject(AuditLogableBase auditLogable, AuditLogType logType) { int duplicateEventsIntrvalValue = (auditLogable.isExternal()) ? Math.max(auditLogable.getEventFloodInSec(), 30) : logType.getDuplicateEventsIntervalValue(); if (duplicateEventsIntrvalValue > 0) { auditLogable.setEndTime(System.currentTimeMillis() + logType.getDuplicateEventsIntervalValue()); auditLogable.setTimeoutObjectId(composeObjectId(auditLogable, logType)); } }

Target:
private static void updateTimeoutLogableObject(AuditLogableBase auditLogable, AuditLogType logType) { int duplicateEventsIntrvalValue = (auditLogable.isExternal()) ? Math.max(auditLogable.getEventFloodInSec(), 30) : logType.getDuplicateEventsIntervalValue(); if (duplicateEventsIntrvalValue > 0) { auditLogable.setEndTime(System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(logType.getDuplicateEventsIntervalValue())); auditLogable.setTimeoutObjectId(composeObjectId(auditLogable, logType)); } }
Source:
private File doPostAndRetreiveFile(CloseableHttpClient httpClient, HttpRequestBase request, String bundleName) throws ClientProtocolException, IOException { request.addHeader("accept", ContentType.APPLICATION_JSON.getMimeType()); File bundle; CloseableHttpResponse response = AnalyticsServiceStreamsContext .executeAndHandleErrors(httpClient, request); HttpEntity entity = response.getEntity(); try { InputStream is = null; FileOutputStream fos = null; byte[] buffer = new byte[1024]; try{ bundle = new File(bundleName); is = entity.getContent(); fos = new FileOutputStream(bundle); for(int length; (length = is.read(buffer)) > 0;){ fos.write(buffer, 0, length); } } finally{ if(is != null) try {is.close();} catch(IOException e) { throw e; } if(fos != null) try {fos.close();} catch(IOException e) { throw e; } } } finally { response.close(); } return bundle; }

Target:
private File doPostAndRetreiveFile(CloseableHttpClient httpClient, HttpRequestBase request, String bundleName) throws ClientProtocolException, IOException { request.addHeader("accept", ContentType.APPLICATION_JSON.getMimeType()); File bundle; CloseableHttpResponse response = AnalyticsServiceStreamsContext .executeAndHandleErrors(httpClient, request); HttpEntity entity = response.getEntity(); try { InputStream is = null; FileOutputStream fos = null; byte[] buffer = new byte[1024*1024]; try{ bundle = new File(bundleName); is = entity.getContent(); fos = new FileOutputStream(bundle); for(int length; (length = is.read(buffer)) != -1;){ fos.write(buffer, 0, length); } } finally{ if(is != null) try {is.close();} catch(IOException e) { throw e; } if(fos != null) try {fos.close();} catch(IOException e) { throw e; } } } finally { response.close(); } return bundle; }
Source:
public void testValidate() throws ValidationException { Function<Element, LeaseElement> resourcesTypeSupplier = mock(Function.class); LeaseConfigValidator validator = new LeaseConfigValidator(resourcesTypeSupplier); LeaseConfigValidator spyValidator = spy(validator); Element xmlNode1 = mock(Element.class); Element xmlNode2 = mock(Element.class); LeaseElement leaseNode1 = new LeaseElement(); leaseNode1.setTimeUnit(TimeUnit.SECONDS.name()); leaseNode1.setLeaseValue("100"); LeaseElement leaseNode2 = new LeaseElement(); leaseNode2.setTimeUnit(TimeUnit.SECONDS.name()); leaseNode2.setLeaseValue("100"); doReturn(leaseNode1).when(spyValidator).createObject(xmlNode1); doReturn(leaseNode2).when(spyValidator).createObject(xmlNode2); spyValidator.validateAgainst(xmlNode1, xmlNode2); }

Target:
public void testValidate() throws ValidationException { Function<Element, LeaseElement> resourcesTypeSupplier = mock(Function.class); LeaseConfigValidator validator = new LeaseConfigValidator(resourcesTypeSupplier); LeaseConfigValidator spyValidator = spy(validator); Element xmlNode1 = mock(Element.class); Element xmlNode2 = mock(Element.class); LeaseElement leaseNode1 = new LeaseElement("100",TimeUnit.SECONDS.name()); LeaseElement leaseNode2 = new LeaseElement("100", TimeUnit.SECONDS.name()); doReturn(leaseNode1).when(spyValidator).createObject(xmlNode1); doReturn(leaseNode2).when(spyValidator).createObject(xmlNode2); spyValidator.validateAgainst(xmlNode1, xmlNode2); }
Source:
public void globalVerify() throws Exception { IList<MapOperationsCount> results = targetInstance.getList(basename + "report"); MapOperationsCount total = new MapOperationsCount(); for (MapOperationsCount i : results) { total.add(i); } log.info(basename + ": " + total + " total of " + results.size()); final IMap map = targetInstance.getMap(basename); TestUtils.assertTrueEventually(new AssertTask() { @Override public void run() throws Exception { assertEquals(basename + ": Map Size not 0, some TTL events not processed", 0, map.size()); } }, 300); }

Target:
public void globalVerify() throws Exception { IList<MapOperationsCount> results = targetInstance.getList(basename + "report"); MapOperationsCount total = new MapOperationsCount(); for (MapOperationsCount i : results) { total.add(i); } log.info(basename + ": " + total + " total of " + results.size()); final IMap map = targetInstance.getMap(basename); TestUtils.assertTrueEventually(new AssertTask() { @Override public void run() throws Exception { assertEquals(basename + ": Map Size not 0, some TTL events not processed", 0, map.size()); } }); }
Source:
public void singleDigitsAreArmstrongNumbers() { int input = 5; boolean expected = true; assertEquals(expected, armstrongNumbers.isArmstrongNumber(input)); }

Target:
public void singleDigitsAreArmstrongNumbers() { int input = 5; assertTrue(armstrongNumbers.isArmstrongNumber(input)); }
Source:
public Transaction getTransaction(Xid xid) throws XAException { Transaction transaction = com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionImple .getTransaction(new XidImple(xid).getTransactionUid()); if(transaction == null) { transaction = SubordinationManager.getTransactionImporter().getImportedTransaction(xid); } return transaction; }

Target:
public Transaction getTransaction(Xid xid) throws XAException { Transaction transaction = TransactionImple.getTransaction(new XidImple(xid).getTransactionUid()); if(transaction == null) { transaction = SubordinationManager.getTransactionImporter().getImportedTransaction(xid); } return transaction; }
Source:
protected String getBaseParameters(Item item) throws UnsupportedEncodingException { String clientIP = request.getRemoteAddr(); if (configurationService.getBooleanProperty("useProxies", false) && request .getHeader("X-Forwarded-For") != null) { for (String xfip : request.getHeader("X-Forwarded-For").split(",")) { if (!request.getHeader("X-Forwarded-For").contains(clientIP)) { clientIP = xfip.trim(); } } } String clientUA = StringUtils.defaultIfBlank(request.getHeader("USER-AGENT"), ""); String referer = StringUtils.defaultIfBlank(request.getHeader("referer"), ""); StringBuilder data = new StringBuilder(); data.append(URLEncoder.encode("url_ver", UTF_8) + "=" + URLEncoder.encode(trackerUrlVersion, UTF_8)); data.append("&").append(URLEncoder.encode("req_id", UTF_8)).append("=") .append(URLEncoder.encode(clientIP, UTF_8)); data.append("&").append(URLEncoder.encode("req_dat", UTF_8)).append("=") .append(URLEncoder.encode(clientUA, UTF_8)); data.append("&").append(URLEncoder.encode("rft.artnum", UTF_8)).append("="). append(URLEncoder.encode("oai:" + configurationService.getProperty("dspace.hostname") + ":" + item .getHandle(), UTF_8)); data.append("&").append(URLEncoder.encode("rfr_dat", UTF_8)).append("=") .append(URLEncoder.encode(referer, UTF_8)); data.append("&").append(URLEncoder.encode("rfr_id", UTF_8)).append("=") .append(URLEncoder.encode(configurationService.getProperty("dspace.hostname"), UTF_8)); data.append("&").append(URLEncoder.encode("url_tim", UTF_8)).append("=") .append(URLEncoder.encode(getCurrentDateString(), UTF_8)); return data.toString(); }

Target:
protected String getBaseParameters(Item item) throws UnsupportedEncodingException { String clientIP = request.getRemoteAddr(); if (configurationService.getBooleanProperty("useProxies", false) && request .getHeader("X-Forwarded-For") != null) { for (String xfip : request.getHeader("X-Forwarded-For").split(",")) { if (!request.getHeader("X-Forwarded-For").contains(clientIP)) { clientIP = xfip.trim(); } } } String clientUA = StringUtils.defaultIfBlank(request.getHeader("USER-AGENT"), ""); String referer = StringUtils.defaultIfBlank(request.getHeader("referer"), ""); StringBuilder data = new StringBuilder(); data.append(URLEncoder.encode("url_ver", UTF_8) + "=" + URLEncoder.encode(trackerUrlVersion, UTF_8)); data.append("&").append(URLEncoder.encode("req_id", UTF_8)).append("=") .append(URLEncoder.encode(clientIP, UTF_8)); data.append("&").append(URLEncoder.encode("req_dat", UTF_8)).append("=") .append(URLEncoder.encode(clientUA, UTF_8)); String hostName = Utils.getHostName(configurationService.getProperty("dspace.ui.url")); data.append("&").append(URLEncoder.encode("rft.artnum", UTF_8)).append("="). append(URLEncoder.encode("oai:" + hostName + ":" + item .getHandle(), UTF_8)); data.append("&").append(URLEncoder.encode("rfr_dat", UTF_8)).append("=") .append(URLEncoder.encode(referer, UTF_8)); data.append("&").append(URLEncoder.encode("rfr_id", UTF_8)).append("=") .append(URLEncoder.encode(hostName, UTF_8)); data.append("&").append(URLEncoder.encode("url_tim", UTF_8)).append("=") .append(URLEncoder.encode(getCurrentDateString(), UTF_8)); return data.toString(); }
Source:
public void writeUserPrefs(CommandWithArg<Boolean> onCompleted) { UpdatePrefs(session_.getSessionInfo().getPrefs()); server_.setUserPrefs( session_.getSessionInfo().getUserPrefs(), new ServerRequestCallback<Void>() { @Override public void onResponseReceived(Void v) { UserPrefsChangedEvent event = new UserPrefsChangedEvent( session_.getSessionInfo().getUserPrefLayer()); if (Satellite.isCurrentWindowSatellite()) { RStudioGinjector.INSTANCE.getEventBus() .fireEventToMainWindow(event); } else { satelliteManager_.dispatchCrossWindowEvent(event); } if (onCompleted != null) { onCompleted.execute(true); } } @Override public void onError(ServerError error) { if (onCompleted != null) { onCompleted.execute(false); } Debug.logError(error); } }); }

Target:
public void writeUserPrefs(CommandWithArg<Boolean> onCompleted) { updatePrefs(session_.getSessionInfo().getPrefs()); server_.setUserPrefs( session_.getSessionInfo().getUserPrefs(), new ServerRequestCallback<Void>() { @Override public void onResponseReceived(Void v) { UserPrefsChangedEvent event = new UserPrefsChangedEvent( session_.getSessionInfo().getUserPrefLayer()); if (Satellite.isCurrentWindowSatellite()) { RStudioGinjector.INSTANCE.getEventBus() .fireEventToMainWindow(event); } else { satelliteManager_.dispatchCrossWindowEvent(event); } if (onCompleted != null) { onCompleted.execute(true); } } @Override public void onError(ServerError error) { if (onCompleted != null) { onCompleted.execute(false); } Debug.logError(error); } }); }
Source:
private void zipFileSystem(FileSystem fs, ZipOutputStream zos) { Path root = fs.getRootDirectories().iterator().next(); Files.walkFileTree(root, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException { try { String location = fs.getName() + path.toString(); zipFile(path.toFile(), location, zos); return FileVisitResult.CONTINUE; } catch (Exception e) { e.printStackTrace(); return FileVisitResult.TERMINATE; } } }); }

Target:
private void zipFileSystem(FileSystem fs, ZipOutputStream zos) { Path root = fs.getRootDirectories().iterator().next(); Files.walkFileTree(root, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) { try { String location = fs.getName() + path.toString(); zipFile(path.toFile(), location, zos); return FileVisitResult.CONTINUE; } catch (Exception e) { LOGGER.error(e.getMessage(), e); return FileVisitResult.TERMINATE; } } }); }
Source:
public void teardown() { closeQuietly(handle); mySqlServer.close(); }

Target:
public void teardown() { closeQuietly(mySqlServer, handle); }
Source:
private void parseMakeRequest() throws CommCareSessionException { String command = sessionWrapper.getCommand(); Entry commandEntry = sessionWrapper.getPlatform().getEntry(command); if (commandEntry instanceof RemoteRequestEntry) { PostRequest syncPost = ((RemoteRequestEntry)commandEntry).getPostRequest(); Response response = makeSyncRequest(syncPost); if (response == null || !response.isSuccessful()) { printStream.println(String.format("Sync failed with response %s", response)); printStream.println("Press 'enter' to retry."); return; } syncSuccessful = true; ApplicationHost.restoreUserToSandbox(sessionWrapper.getSandbox(), sessionWrapper, sessionWrapper.getPlatform(), username, password); printStream.println(String.format("Sync successful with response %s", response)); printStream.println("Press 'enter' to continue."); } else { throw new CommCareSessionException("Initialized sync request while not on sync screen"); } }

Target:
private void parseMakeRequest() throws CommCareSessionException { String command = sessionWrapper.getCommand(); Entry commandEntry = sessionWrapper.getPlatform().getEntry(command); if (!(commandEntry instanceof RemoteRequestEntry)) { throw new CommCareSessionException("Initialized sync request while not on sync screen"); } PostRequest syncPost = ((RemoteRequestEntry)commandEntry).getPostRequest(); try { Response response = makeSyncRequest(syncPost); if (!response.isSuccessful()) { printStream.println(String.format("Sync request failed with response code %s and message %s", response.code(), response.body())); printStream.println("Press 'enter' to retry."); return; } syncSuccessful = true; SessionUtils.restoreUserToSandbox(sessionWrapper.getSandbox(), sessionWrapper, sessionWrapper.getPlatform(), username, password, printStream); printStream.println(String.format("Sync successful with response %s", response)); printStream.println("Press 'enter' to continue."); } catch (IOException e) { e.printStackTrace(); printStream.println(String.format("Sync failed with exception %s", e.getMessage())); printStream.println("Press 'enter' to retry."); } }
Source:
private boolean isMetacardTagsSet(Metacard metacard) { Attribute attribute = metacard.getAttribute(Core.METACARD_TAGS); if (attribute == null) { return false; } return CollectionUtils.isNotEmpty(attribute.getValues()); }

Target:
private boolean isMetacardTagsSet(Metacard metacard) { return !metacard.getTags().isEmpty(); }
Source:
@After public void tearDown() throws Exception { if (socksProxy != null) { socksProxy.shutdown(); } if (cache != null) { cache.delete(); } client.connectionPool().evictAll(); if (client.connectionPool().connectionCount() > 0) { System.out.println("Delaying to avoid flakes"); Thread.sleep(500L); System.out.println("After delay: " + client.connectionPool().connectionCount()); } }

Target:
@After public void tearDown() throws Exception { if (socksProxy != null) { socksProxy.shutdown(); } if (cache != null) { cache.delete(); } }
Source:
public static X509Certificate publicKeyFromPem(byte[] pem) { Pattern pattern = Pattern.compile("(?s)-----BEGIN CERTIFICATE-----.*-----END CERTIFICATE-----"); Matcher matcher = pattern.matcher(new String(pem, StandardCharsets.UTF_8)); if (!matcher.find()) { throw LOGGER.logErrorAndThrow(new IllegalArgumentException("PEM certificate provided does not contain -----BEGIN CERTIFICATE-----END CERTIFICATE----- block")); } try { CertificateFactory factory = CertificateFactory.getInstance("X.509"); InputStream stream = new ByteArrayInputStream(matcher.group().getBytes(StandardCharsets.UTF_8)); return (X509Certificate) factory.generateCertificate(stream); } catch (CertificateException e) { throw LOGGER.logErrorAndThrow(new IllegalStateException(e)); } }

Target:
public static X509Certificate publicKeyFromPem(byte[] pem) { Pattern pattern = Pattern.compile("(?s)-----BEGIN CERTIFICATE-----.*-----END CERTIFICATE-----"); Matcher matcher = pattern.matcher(new String(pem, StandardCharsets.UTF_8)); if (!matcher.find()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("PEM certificate provided does not contain -----BEGIN CERTIFICATE-----END CERTIFICATE----- block")); } try { CertificateFactory factory = CertificateFactory.getInstance("X.509"); InputStream stream = new ByteArrayInputStream(matcher.group().getBytes(StandardCharsets.UTF_8)); return (X509Certificate) factory.generateCertificate(stream); } catch (CertificateException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } }
Source:
public void testListSnapshotsWithNullAndEmptyString() { Exception actualError = null; try { listSnapshotsSize((String) null); } catch (Exception ex) { actualError = ex; } assertNotNull(actualError); assertTrue(actualError instanceof NullPointerException); actualError = null; try { assertEquals(0, listSnapshotsSize((Pattern) null)); } catch (Exception ex) { actualError = ex; } assertNull(actualError); actualError = null; try { assertEquals(0, listSnapshotsSize("")); } catch (Exception ex) { actualError = ex; } assertNull(actualError); }

Target:
public void testListSnapshotsWithNullAndEmptyString() throws IOException { Exception actualError = null; try { listSnapshotsSize((String) null); } catch (Exception ex) { actualError = ex; } assertNotNull(actualError); assertTrue(actualError instanceof NullPointerException); assertEquals(0, listSnapshotsSize((Pattern) null)); assertEquals(0, listSnapshotsSize("")); }
Source:
private AlleleFractionState.MinorFractions estimateMinorFractions(final AlleleFractionData data) { AlleleFractionState.MinorFractions result = new AlleleFractionState.MinorFractions(); for (int segment = 0; segment < data.numSegments(); segment++) { result.add(estimateMinorFraction(segment, data)); } return result; }

Target:
private AlleleFractionState.MinorFractions estimateMinorFractions(final AlleleFractionData data) { return new AlleleFractionState.MinorFractions( IntStream.range(0, data.numSegments()) .mapToDouble(segment -> estimateMinorFraction(segment, data)) .boxed().collect(Collectors.toList())); }
Source:
private void invokeExceptionCaughtFromOutbound(Throwable t) { if ((executionMask & MASK_EXCEPTION_CAUGHT) != 0) { invokeExceptionCaught(t); } else { findContextInbound(MASK_EXCEPTION_CAUGHT).invokeExceptionCaught(t); } }

Target:
private void invokeExceptionCaughtFromOutbound(Throwable t) { if ((executionMask & MASK_EXCEPTION_CAUGHT) != 0) { notifyHandlerException(t); } else { findContextInbound(MASK_EXCEPTION_CAUGHT).notifyHandlerException(t); } }
Source:
private CacheEntryEvent<? extends K, ? extends V> launderEvent( CacheEntryEvent<? extends K, ? extends V> e, CacheEntryListenerConfiguration<K, V> cfg) { switch (e.getEventType()) { case UPDATED: case REMOVED: case EXPIRED: if (cfg.isOldValueRequired()) return new RICacheEntryEvent<>(e.getSource(), e.getKey(), e.getValue(), e.getOldValue(), e.getEventType()); if (e.getEventType() == EventType.REMOVED || e.getEventType() == EventType.EXPIRED) return new RICacheEntryEvent<>(e.getSource(), e.getKey(), null, null, e.getEventType(), false); return new RICacheEntryEvent(e.getSource(), e.getKey(), e.getValue(), null, e.getEventType(), false); default: return e; } }

Target:
private CacheEntryEvent<? extends K, ? extends V> launderEvent( CacheEntryEvent<? extends K, ? extends V> e, CacheEntryListenerConfiguration<K, V> cfg) { switch (e.getEventType()) { case UPDATED: case REMOVED: case EXPIRED: if (cfg.isOldValueRequired()) return e; if (e.getEventType() == EventType.REMOVED || e.getEventType() == EventType.EXPIRED) return new RICacheEntryEvent<>(e.getSource(), e.getKey(), null, null, e.getEventType(), false); return new RICacheEntryEvent(e.getSource(), e.getKey(), e.getValue(), e.getEventType()); default: return e; } }
Source:
IndexValue(String logSegmentName, ByteBuffer value, short version) { this.version = version; switch (version) { case PersistentIndex.VERSION_0: if (value.capacity() != INDEX_VALUE_SIZE_IN_BYTES_V0) { throw new IllegalArgumentException("Invalid buffer size for version 0"); } size = value.getLong(); offset = new Offset(logSegmentName, value.getLong()); flags = value.get(); expiresAtMs = value.getLong(); originalMessageOffset = value.getLong(); operationTimeInMs = (int) Utils.Infinite_Time; serviceId = SERVICE_CONTAINER_ID_DEFAULT_VALUE; containerId = SERVICE_CONTAINER_ID_DEFAULT_VALUE; break; case PersistentIndex.VERSION_1: if (value.capacity() != INDEX_VALUE_SIZE_IN_BYTES_V1) { throw new IllegalArgumentException("Invalid buffer size for version 1"); } size = value.getLong(); offset = new Offset(logSegmentName, value.getLong()); flags = value.get(); int expiresAt = value.getInt(); expiresAtMs = expiresAt != Utils.Infinite_Time ? ((long) expiresAt * Time.MsPerSec) : Utils.Infinite_Time; originalMessageOffset = value.getLong(); int operationTimeInSecs = value.getInt(); operationTimeInMs = operationTimeInSecs != Utils.Infinite_Time ? ((long) operationTimeInSecs * Time.MsPerSec) : Utils.Infinite_Time; serviceId = value.getShort(); containerId = value.getShort(); break; default: throw new IllegalArgumentException("Unsupported version " + version + " passed in for IndexValue "); } }

Target:
IndexValue(String logSegmentName, ByteBuffer value, short version) { this.version = version; switch (version) { case PersistentIndex.VERSION_0: if (value.capacity() != INDEX_VALUE_SIZE_IN_BYTES_V0) { throw new IllegalArgumentException("Invalid buffer size for version 0"); } size = value.getLong(); offset = new Offset(logSegmentName, value.getLong()); flags = value.get(); expiresAtMs = value.getLong(); originalMessageOffset = value.getLong(); operationTimeInMs = (int) Utils.Infinite_Time; serviceId = SERVICE_CONTAINER_ID_DEFAULT_VALUE; containerId = SERVICE_CONTAINER_ID_DEFAULT_VALUE; break; case PersistentIndex.VERSION_1: if (value.capacity() != INDEX_VALUE_SIZE_IN_BYTES_V1) { throw new IllegalArgumentException("Invalid buffer size for version 1"); } size = value.getLong(); offset = new Offset(logSegmentName, value.getLong()); flags = value.get(); long expiresAt = value.getInt(); expiresAtMs = expiresAt != Utils.Infinite_Time ? (expiresAt * Time.MsPerSec) : Utils.Infinite_Time; originalMessageOffset = value.getLong(); long operationTimeInSecs = value.getInt(); operationTimeInMs = operationTimeInSecs != Utils.Infinite_Time ? (operationTimeInSecs * Time.MsPerSec) : Utils.Infinite_Time; serviceId = value.getShort(); containerId = value.getShort(); break; default: throw new IllegalArgumentException("Unsupported version " + version + " passed in for IndexValue "); } }
Source:
public void stop() { if (Objects.nonNull(metadataStore)) { metadataStore.flush(); metadataStore.close(); metadataStore = null; LOG.info("StartpointManager has stopped and this instance can no longer be used."); } else { LOG.warn("StartpointManager has already stopped"); } }

Target:
public void stop() { if (started) { metadataStore.close(); started = false; } else { LOG.warn("StartpointManager already stopped."); } }
Source:
protected File atomicFileCreate(String filename) throws FileNotFoundException, IOException { File file = new File(ROOT_DIR, filename + ".tmp"); File fileFinal = new File(ROOT_DIR, "test.txt"); file.delete(); file.deleteOnExit(); fileFinal.delete(); fileFinal.deleteOnExit(); FileOutputStream fos = new FileOutputStream(file); fos.write("this is a test\nline2\n".getBytes()); fos.close(); assertTrue(file.renameTo(fileFinal)); return fileFinal; }

Target:
protected File atomicFileCreate(String filename) throws FileNotFoundException, IOException { File file = new File(ROOT_DIR, filename + ".tmp"); File fileFinal = new File(ROOT_DIR, filename); file.delete(); file.deleteOnExit(); fileFinal.delete(); fileFinal.deleteOnExit(); FileOutputStream fos = new FileOutputStream(file); fos.write("this is a test\nline2\n".getBytes()); fos.close(); assertTrue(file.renameTo(fileFinal)); return fileFinal; }