auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void killIncoming(boolean sendUpstream) { close(); left.kill(sendUpstream); right.kill(sendUpstream); }

Target:
protected void killIncoming(boolean sendUpstream) { left.kill(sendUpstream); right.kill(sendUpstream); }
Source:
public int getBufferSizeFor(int valueCount) { if (getAccessor().getValueCount() == 0) { return 0; } return offsets.getBufferSizeFor(valueCount) + vector.getBufferSizeFor(valueCount); }

Target:
public int getBufferSizeFor(int valueCount) { if (valueCount == 0) { return 0; } return offsets.getBufferSizeFor(valueCount + 1) + vector.getBufferSizeFor(valueCount); }
Source:
public void deleteOption(final String name, final OptionType type) { try { SystemOptionManager.getValidator(name); // ensure the option exists } catch (final IllegalArgumentException e) { throw UserException.validationError(e) .build(logger); } // fallback if unable to delete locally if (!deleteLocalOption(name, type)) { fallback.deleteOption(name, type); } }

Target:
public void deleteOption(final String name, final OptionType type) { SystemOptionManager.getValidator(name); // ensure the option exists // fallback if unable to delete locally if (!deleteLocalOption(name, type)) { fallback.deleteOption(name, type); } }
Source:
public void shutdownIfClient() { if (bus.isClient()) { try { Closeables.close(bus, true); } catch (Exception e) { /* do nothing */ } } }

Target:
public void shutdownIfClient() throws IOException { if (bus.isClient()) { Closeables.close(bus, true); } }
Source:
public void sort(SelectionVector4 vector4, VectorContainer container){ Stopwatch watch = Stopwatch.createStarted(); watch.start(); QuickSort qs = new QuickSort(); qs.sort(this, 0, vector4.getTotalCount()); logger.debug("Took us to sort records", watch.elapsed(TimeUnit.MICROSECONDS), vector4.getTotalCount()); }

Target:
public void sort(SelectionVector4 vector4, VectorContainer container){ Stopwatch watch = Stopwatch.createStarted(); QuickSort qs = new QuickSort(); qs.sort(this, 0, vector4.getTotalCount()); logger.debug("Took us to sort records", watch.elapsed(TimeUnit.MICROSECONDS), vector4.getTotalCount()); }
Source:
public synchronized static Set<Class<? extends StoragePluginConfig>> getSubTypes(final ScanResult classpathScan) { final Set<Class<? extends StoragePluginConfig>> packages = classpathScan.getImplementations(StoragePluginConfig.class); logger.debug("Found logical operator classes: {}.", packages.size(), packages); return packages; }

Target:
public static Set<Class<? extends StoragePluginConfig>> getSubTypes(final ScanResult classpathScan) { final Set<Class<? extends StoragePluginConfig>> packages = classpathScan.getImplementations(StoragePluginConfig.class); logger.debug("Found logical operator classes: {}.", packages.size(), packages); return packages; }
Source:
public DrillResultSetImpl newResultSet(AvaticaStatement statement, AvaticaPrepareResult prepareResult, TimeZone timeZone) { final ResultSetMetaData metaData = newResultSetMetaData(statement, prepareResult.getColumnList()); return new DrillResultSetImpl(statement, (DrillPrepareResult) prepareResult, metaData, timeZone); }

Target:
public DrillResultSetImpl newResultSet(AvaticaStatement statement, AvaticaPrepareResult prepareResult, TimeZone timeZone) { final ResultSetMetaData metaData = newResultSetMetaData(statement, prepareResult.getColumnList()); return new DrillResultSetImpl(statement, prepareResult, metaData, timeZone); }
Source:
public static SessionMap create(Config config) { Tracer tracer = new LoggingOptions(config).getTracer(); EventBus bus = new EventBusOptions(config).getEventBus(); JdbcSessionMapOptions sessionMapOptions = new JdbcSessionMapOptions(config); Connection connection; try { connection = sessionMapOptions.getJdbcConnection(); } catch (SQLException e) { throw new ConfigException(e.toString()); } return new JdbcBackedSessionMap(tracer, connection, bus); }

Target:
public static SessionMap create(Config config) { Tracer tracer = new LoggingOptions(config).getTracer(); EventBus bus = new EventBusOptions(config).getEventBus(); JdbcSessionMapOptions sessionMapOptions = new JdbcSessionMapOptions(config); Connection connection; try { connection = sessionMapOptions.getJdbcConnection(); } catch (SQLException e) { throw new ConfigException(e); } return new JdbcBackedSessionMap(tracer, connection, bus); }
Source:
public int allocate() throws IOException { synchronized (Ports.class) { int attempts = 0; int prt; do { prt = random(); ++attempts; // @checkstyle MagicNumber (1 line) if (attempts > 100) { throw new IllegalStateException( String.format( "failed to allocate TCP port after %d attempts", attempts ) ); } } while (Ports.ASSIGNED.contains(prt)); return prt; } }

Target:
public static int allocate() throws IOException { synchronized (Ports.class) { int attempts = 0; int prt; do { prt = random(); ++attempts; // @checkstyle MagicNumber (1 line) if (attempts > 100) { throw new IllegalStateException( String.format( "failed to allocate TCP port after %d attempts", attempts ) ); } } while (Ports.ASSIGNED.contains(prt)); return prt; } }
Source:
public void throwsExceptionIfUnknownAliasKicked() throws Exception { final Inbox inbox = this.rule.get().aliases() .iterate().iterator().next().inbox(); final Bout bout = inbox.bout(inbox.start()); final String friend = "jim"; bout.friends().kick(friend); }

Target:
public void throwsExceptionIfUnknownAliasKicked() throws Exception { final Inbox inbox = this.rule.get().aliases() .iterate().iterator().next().inbox(); inbox.bout(inbox.start()).friends().kick("jim"); }
Source:
/* package */ void setFillColor(String color) { // Tolerate KML with leading or trailing whitespace in colors color = color.trim(); // Add # to allow for mOutline color to be parsed correctly int polygonColorNum = (Color.parseColor("#" + convertColor(color))); setPolygonFillColor(polygonColorNum); mStylesSet.add("fillColor"); }

Target:
/* package */ void setFillColor(String color) { // Add # to allow for mOutline color to be parsed correctly int polygonColorNum = (Color.parseColor("#" + convertColor(color))); setPolygonFillColor(polygonColorNum); mStylesSet.add("fillColor"); }
Source:
private void removePlacemarks(HashMap<? extends Feature, Object> placemarks) { // Remove map object from the map super.removeFeatures((HashMap<Feature, Object>) placemarks); }

Target:
private void removePlacemarks(HashMap<? extends Feature, Object> placemarks) { // Remove map object from the map removeFeatures((HashMap<Feature, Object>) placemarks); }
Source:
public RecordReader createRecordReader( InputSplit inputSplit, TaskAttemptContext taskAttemptContext) throws IOException { Configuration conf = HadoopCompat.getConfiguration(taskAttemptContext); initInputFormat(conf); if (shouldCombine(conf)) { return new CompositeRecordReader(delegate); } else { try { return delegate.createRecordReader(inputSplit, taskAttemptContext); } catch (InterruptedException e) { LOG.error("Thread interrupted", e); Thread.currentThread().interrupt(); throw new IOException(e); } } }

Target:
public RecordReader createRecordReader( InputSplit inputSplit, TaskAttemptContext taskAttemptContext) throws IOException, InterruptedException { Configuration conf = HadoopCompat.getConfiguration(taskAttemptContext); initInputFormat(conf); if (shouldCombine(conf)) { return new CompositeRecordReader(delegate); } else { return delegate.createRecordReader(inputSplit, taskAttemptContext); } }
Source:
public static void setRequiredFieldConf(Configuration conf, RequiredFieldList requiredFieldList) { // set required fields conf for RCFile[Protobuf|Thrift] input format if (requiredFieldList != null) { List<Integer> indices = Lists.newArrayList(); for(RequiredField f : requiredFieldList.getFields()) { indices.add(f.getIndex()); } conf.set(RCFileUtil.REQUIRED_FIELD_INDICES_CONF, Joiner.on(",").join(indices)); } else { conf.set(RCFileUtil.REQUIRED_FIELD_INDICES_CONF, ""); } }

Target:
public static void setRequiredFieldConf(Configuration conf, RequiredFieldList requiredFieldList) { // set required fields conf for RCFile[Protobuf|Thrift] input format String value = ""; if (requiredFieldList != null) { List<Integer> indices = Lists.newArrayList(); for(RequiredField f : requiredFieldList.getFields()) { indices.add(f.getIndex()); } value = Joiner.on(",").join(indices); } conf.set(RCFileUtil.REQUIRED_FIELD_INDICES_CONF, value); }
Source:
protected void skipToNextSyncPoint(boolean atFirstRecord) throws IOException { // No need to skip to the sync point here; the block reader will do it for us. LOG.debug("LzoProtobufBlockRecordReader.skipToNextSyncPoint called with atFirstRecord = " + atFirstRecord); updatePosition = !atFirstRecord; LOG.debug("reset first record offset in skipToNextSyncPoint()"); }

Target:
protected void skipToNextSyncPoint(boolean atFirstRecord) throws IOException { // No need to skip to the sync point here; the block reader will do it for us. LOG.debug("LzoProtobufBlockRecordReader.skipToNextSyncPoint called with atFirstRecord = " + atFirstRecord); updatePosition = !atFirstRecord; }
Source:
private boolean matchesAnyCookieName(String cookieString, String... cookieNames) { //noinspection SimplifiableIfStatement if (StringUtils.isEmpty(cookieString) || ArrayUtils.isEmpty(cookieNames)) { return false; } return Arrays.stream(cookieNames).anyMatch(name -> matchesCookieName(cookieString, name)); }

Target:
private boolean matchesAnyCookieName(String cookieString, String... cookieNames) { boolean isEmpty = StringUtils.isEmpty(cookieString) || ArrayUtils.isEmpty(cookieNames); return isEmpty || Arrays.stream(cookieNames) .anyMatch(name -> matchesCookieName(cookieString, name)); }
Source:
protected ExpectedBehaviour getExpectedBehaviour() { return excNumberDefined ? ExpectedBehaviour.SPECIFIC_EXCEPTION : ExpectedBehaviour.ANY_EXCEPTION; }

Target:
protected ExpectedBehaviour getExpectedBehaviour() { return excNumberDefined ? SPECIFIC_EXCEPTION : ANY_EXCEPTION; }
Source:
abstract protected ResultSet getColumns() throws SQLException; public Map<String, DbParameterAccessor> getParams() throws SQLException { Map<String, DbParameterAccessor> allParams = new HashMap<String, DbParameterAccessor>(); try (ResultSet rs = getColumns()) { while (rs.next()) { DbParameterAccessor accessor = createColumnAccessor(rs); allParams.put(normaliseName(accessor.getName()), accessor); } } return allParams; }

Target:
abstract protected ResultSet getColumns() throws SQLException; public Map<String, DbParameterAccessor> getParams() throws SQLException { Map<String, DbParameterAccessor> allParams = new HashMap<>(); try (ResultSet rs = getColumns()) { while (rs.next()) { DbParameterAccessor accessor = createColumnAccessor(rs); allParams.put(normaliseName(accessor.getName()), accessor); } } return allParams; }
Source:
public void run() throws SQLException { ResultSet rs = statement.executeQuery(); try { rs.next(); returnValue = rs.getObject(1); } finally { rs.close(); } }

Target:
public void run() throws SQLException { try (ResultSet rs = statement.executeQuery()) { rs.next(); returnValue = rs.getObject(1); } }
Source:
public void afterConnectionEstablished() throws SQLException { TypeAdapter.registerParseDelegate(java.math.BigDecimal.class, new dbfit.util.BigDecimalParseDelegate()); if (currentConnection.getMetaData().supportsTransactions()) { Options.setOption(Options.OPTION_AUTO_COMMIT, "false"); currentConnection.setAutoCommit(false); } else { Options.setOption(Options.OPTION_AUTO_COMMIT, "true"); currentConnection.setAutoCommit(true); } }

Target:
public void afterConnectionEstablished() throws SQLException { if (currentConnection.getMetaData().supportsTransactions()) { Options.setOption(Options.OPTION_AUTO_COMMIT, "false"); currentConnection.setAutoCommit(false); } else { Options.setOption(Options.OPTION_AUTO_COMMIT, "true"); currentConnection.setAutoCommit(true); } }
Source:
public void setObject(int index, Object value, int sqlType) throws SQLException { if (value == null) statement.setNull(index, sqlType); else // Don't use the variant that takes sqlType. // Derby (at least) assumes no decimal places for Types.DECIMAL and truncates the source data. statement.setObject(index, value); }

Target:
public void setObject(int index, Object value, int sqlType) throws SQLException { if (value == null) { statement.setNull(index, sqlType); } else { // Don't use the variant that takes sqlType. // Derby (at least) assumes no decimal places for Types.DECIMAL and truncates the source data. statement.setObject(index, value); } }
Source:
public void doTable(Parse table) { super.doTable(table); if (counts.wrong == 0 && counts.exceptions == 0) { table.parts.last().more = getSummary(); } }

Target:
public void doTable(Parse table) { super.doTable(table); table.parts.last().more = getSummary(); }
Source:
private IProject getProject(final IJavaElementDelta delta) { final IJavaProject javaProject = delta.getElement().getJavaProject(); if (javaProject != null) { return javaProject.getProject(); } // carry on with children elements. for (IJavaElementDelta affectedChild : delta.getAffectedChildren()) { return getProject(affectedChild); } // if no child return null; }

Target:
private IProject getProject(final IJavaElementDelta delta) { final IJavaProject javaProject = delta.getElement().getJavaProject(); if (javaProject != null) { return javaProject.getProject(); } // carry on with children elements. for (IJavaElementDelta affectedChild : delta.getAffectedChildren()) { final IProject project = getProject(affectedChild); if(project != null) { return project; } } // if no child return null; }
Source:
public Map<StoreKey, MessageInfo> findKeys(List<? extends StoreKey> storeKeys) throws StoreException { Map<StoreKey, MessageInfo> messageInfoMap = new HashMap<>(); for (StoreKey storeKey : storeKeys) { // TODO: Need to look into the possibility if its more efficient to not call findKey() multiple times in a loop, // and instead search the index once for all the blobs in the list. try { messageInfoMap.put(storeKey, findKey(storeKey)); } catch (StoreException e) { logger.error("findKey failed for key with reason {}", storeKey.getID(), e.getErrorCode().toString()); } } return messageInfoMap; }

Target:
public Map<StoreKey, MessageInfo> findKeys(List<? extends StoreKey> storeKeys) throws StoreException { Map<StoreKey, MessageInfo> messageInfoMap = new HashMap<>(); for (StoreKey storeKey : storeKeys) { // TODO: Need to look into the possibility if its more efficient to not call findKey() multiple times in a loop, // and instead search the index once for all the blobs in the list. try { messageInfoMap.put(storeKey, findKey(storeKey)); } catch (StoreException e) { logger.error("findKey failed for key with reason {}", storeKey.getID(), e.getErrorCode().toString()); throw e; } } return messageInfoMap; }
Source:
public ChannelHandlerContext getCtx() { return ctx; }

Target:
ChannelHandlerContext getCtx() { return ctx; }
Source:
public PartitionLeaderInfo(StoreManager storeManager) { peerLeaderReplicasByPartition = new ConcurrentHashMap<>(); this.storeManager = storeManager; }

Target:
public PartitionLeaderInfo(StoreManager storeManager) { this.storeManager = storeManager; // We can't initialize the peerLeaderReplicasByPartition here because we don't know the leader partitions on local node (server) until it has finished participating with Helix. // peerLeaderReplicasByPartition map will be updated after server participates with Helix and state of replicas transition to LEADER (via onPartitionBecomeLeaderFromStandby()) }
Source:
void addToCache(String blobKey, short lifeVersion, BlobState blobState) { if (isVcr) { if (blobState == BlobState.TTL_UPDATED) { // In case of ttl update we update the ttl without taking into account the life version. // So make sure that we do not decrease the lifeVersion in cache due to an incoming ttl update. if (recentBlobCache.containsKey(blobKey)) { lifeVersion = (lifeVersion > recentBlobCache.get(blobKey).getLifeVersion()) ? lifeVersion : recentBlobCache.get(blobKey).getLifeVersion(); } } recentBlobCache.put(blobKey, new BlobLifeState(blobState, lifeVersion, recentBlobCache.get(blobKey))); } }

Target:
void addToCache(String blobKey, short lifeVersion, BlobState blobState) { if (isVcr) { if (blobState == BlobState.TTL_UPDATED) { // In case of ttl update we update the ttl without taking into account the life version. // So make sure that we do not decrease the lifeVersion in cache due to an incoming ttl update. if (recentBlobCache.containsKey(blobKey)) { lifeVersion = (short) Math.max(lifeVersion, recentBlobCache.get(blobKey).getLifeVersion()); } } recentBlobCache.put(blobKey, new BlobLifeState(blobState, lifeVersion, recentBlobCache.get(blobKey))); } }
Source:
public void onPartitionBecomeDroppedFromOffline(String partitionName) { // remove old replica from StorageManager and delete store directory (this also includes recover from decommission // failure and remove old replica from replication/stats manager) PartitionStateChangeListener storageManagerListener = partitionStateChangeListeners.get(StateModelListenerType.StorageManagerListener); if (storageManagerListener != null) { try { storageManagerListener.onPartitionBecomeDroppedFromOffline(partitionName); } catch (Exception e) { participantMetrics.offlineCount.addAndGet(-1); participantMetrics.errorStateCount.addAndGet(1); throw e; } } participantMetrics.offlineCount.addAndGet(-1); participantMetrics.partitionDroppedCount.inc(); }

Target:
public void onPartitionBecomeDroppedFromOffline(String partitionName) { // remove old replica from StorageManager and delete store directory (this also includes recover from decommission // failure and remove old replica from replication/stats manager) PartitionStateChangeListener storageManagerListener = partitionStateChangeListeners.get(StateModelListenerType.StorageManagerListener); try { if (storageManagerListener != null) { storageManagerListener.onPartitionBecomeDroppedFromOffline(partitionName); } } catch (Exception e) { participantMetrics.errorStateCount.addAndGet(1); throw e; } finally { participantMetrics.offlineCount.addAndGet(-1); } participantMetrics.partitionDroppedCount.inc(); }
Source:
public NettySslHttp2Factory(SSLConfig sslConfig) throws GeneralSecurityException, IOException { nettyServerSslContext = getServerSslContext(sslConfig); nettyClientSslContext = getClientSslContext(sslConfig); // Netty's OpenSsl based implementation does not use the JDK SSLContext so we have to fall back to the JDK based // factory to support this method. jdkSslContext = sslConfig.sslHttp2SelfSign ? null : new JdkSslFactory(sslConfig).getSSLContext(); this.endpointIdentification = sslConfig.sslEndpointIdentificationAlgorithm.isEmpty() ? null : sslConfig.sslEndpointIdentificationAlgorithm; }

Target:
public NettySslHttp2Factory(SSLConfig sslConfig) throws GeneralSecurityException, IOException { nettyServerSslContext = getServerSslContext(sslConfig); nettyClientSslContext = getClientSslContext(sslConfig); // Netty's OpenSsl based implementation does not use the JDK SSLContext so we have to fall back to the JDK based // factory to support this method. this.endpointIdentification = sslConfig.sslEndpointIdentificationAlgorithm.isEmpty() ? null : sslConfig.sslEndpointIdentificationAlgorithm; }
Source:
public void uploadFile(String containerName, String fileName, InputStream inputStream) throws BlobStorageException, IOException { try { BlobContainerClient containerClient = getContainer(containerName, true); BlockBlobClient blobClient = containerClient.getBlobClient(fileName).getBlockBlobClient(); blobClient.uploadWithResponse(inputStream, inputStream.available(), null, null, null, null, null, null, Context.NONE); } catch (UncheckedIOException e) { // error processing input stream throw e.getCause(); } }

Target:
public void uploadFile(String containerName, String fileName, InputStream inputStream) throws BlobStorageException, IOException { try { BlockBlobClient blobClient = getBlockBlobClient(containerName, fileName, true); blobClient.uploadWithResponse(inputStream, inputStream.available(), null, null, null, null, null, null, Context.NONE); } catch (UncheckedIOException e) { // error processing input stream throw e.getCause(); } }
Source:
String getAzureContainerName(String partitionPath) { // Include Ambry cluster name in case the same storage account is used to backup multiple clusters. // Azure requires container names to be all lower case String rawContainerName = clusterName + SEPARATOR + partitionPath; return rawContainerName.toLowerCase(); }

Target:
private String getAzureContainerName(String partitionPath) { // Include Ambry cluster name in case the same storage account is used to backup multiple clusters. // Azure requires container names to be all lower case String rawContainerName = clusterName + SEPARATOR + partitionPath; return rawContainerName.toLowerCase(); }
Source:
String getAzureBlobName(BlobId blobId) { // Use the last four chars as prefix to assist in Azure sharding, since beginning of blobId has little variation. String blobIdStr = blobId.getID(); return blobIdStr.substring(blobIdStr.length() - 4) + SEPARATOR + blobIdStr; }

Target:
private String getAzureBlobName(BlobId blobId) { // Use the last four chars as prefix to assist in Azure sharding, since beginning of blobId has little variation. String blobIdStr = blobId.getID(); return blobIdStr.substring(blobIdStr.length() - 4) + SEPARATOR + blobIdStr; }
Source:
public void testEarlyReadableStreamChannelClose() throws Exception { for (int numChunksInBlob = 0; numChunksInBlob <= 4; numChunksInBlob++) { for (int numChunksToRead = 0; numChunksToRead < numChunksInBlob; numChunksToRead++) { System.out.println("" + numChunksInBlob + " chunks but only read " + numChunksToRead); testEarlyReadableStreamChannelClose(numChunksInBlob, numChunksToRead); } } }

Target:
public void testEarlyReadableStreamChannelClose() throws Exception { for (int numChunksInBlob = 0; numChunksInBlob <= 4; numChunksInBlob++) { for (int numChunksToRead = 0; numChunksToRead < numChunksInBlob; numChunksToRead++) { testEarlyReadableStreamChannelClose(numChunksInBlob, numChunksToRead); } } }
Source:
public static List<CloudBlobMetadata> capMetadataListBySize(List<CloudBlobMetadata> originalList, long size) { long totalSize = 0; List<CloudBlobMetadata> cappedList = new ArrayList<>(); for (CloudBlobMetadata metadata : originalList) { // Cap results at max size if (totalSize + metadata.getSize() > size) { if (cappedList.size() == 0) { // We must add at least one regardless of size cappedList.add(metadata); } break; } cappedList.add(metadata); totalSize += metadata.getSize(); } return cappedList; }

Target:
public static List<CloudBlobMetadata> capMetadataListBySize(List<CloudBlobMetadata> originalList, long size) { long totalSize = 0; List<CloudBlobMetadata> cappedList = new ArrayList<>(); for (CloudBlobMetadata metadata : originalList) { // Cap results at max size if (totalSize + metadata.getSize() > size) { if (cappedList.isEmpty()) { // We must add at least one regardless of size cappedList.add(metadata); } break; } cappedList.add(metadata); totalSize += metadata.getSize(); } return cappedList; }
Source:
public void onPartitionStateChangeToStandbyFromLeader(String partitionName) { logger.debug("Partition state change notification from Leader to Standby received for partition {}", partitionName); synchronized (notificationLock) { try { removeCloudReplica(partitionName); } catch (ReplicationException rex) { // Helix will run into error state if exception throws in Helix context. logger.error("Exception on removing Partition from {}: ", partitionName, dataNodeId, rex); } } }

Target:
public void onPartitionStateChangeToStandbyFromLeader(String partitionName) { logger.info("Partition state change notification from Leader to Standby received for partition {}", partitionName); synchronized (notificationLock) { removeCloudReplica(partitionName); } }
Source:
public boolean addBlobStore(ReplicaId replica) { CloudBlobStore cloudBlobStore = partitionToStore.computeIfAbsent(replica.getPartitionId(), store -> new CloudBlobStore(properties, replica.getPartitionId(), cloudDestination, clusterMap, vcrMetrics)); partitionToStore.put(replica.getPartitionId(), cloudBlobStore); return startBlobStore(replica.getPartitionId()); }

Target:
public boolean addBlobStore(ReplicaId replica) { CloudBlobStore cloudBlobStore = partitionToStore.computeIfAbsent(replica.getPartitionId(), store -> new CloudBlobStore(properties, replica.getPartitionId(), cloudDestination, clusterMap, vcrMetrics)); return startBlobStore(replica.getPartitionId()); }
Source:
public void onResponse(ReplicaId replicaId, TrackedRequestFinalState trackedRequestFinalState) { if (respondedReplicas.contains(replicaId)) { return; } respondedReplicas.add(replicaId); inflightCount--; if (trackedRequestFinalState == TrackedRequestFinalState.SUCCESS) { succeededCount++; } else { failedCount++; // NOT_FOUND is a special error. When tracker sees more than 2 NOT_FOUND from the originating DC, we can // be sure the operation will ends up with a NOT_FOUND error. if (trackedRequestFinalState == TrackedRequestFinalState.NOT_FOUND && replicaId.getDataNodeId() .getDatacenterName() .equals(this.originatingDcName)) { originatingDcNotFoundCount++; } } }

Target:
public void onResponse(ReplicaId replicaId, TrackedRequestFinalState trackedRequestFinalState) { inflightCount--; if (trackedRequestFinalState == TrackedRequestFinalState.SUCCESS) { succeededCount++; } else { failedCount++; // NOT_FOUND is a special error. When tracker sees more than 2 NOT_FOUND from the originating DC, we can // be sure the operation will end up with a NOT_FOUND error. if (trackedRequestFinalState == TrackedRequestFinalState.NOT_FOUND && replicaId.getDataNodeId() .getDatacenterName() .equals(originatingDcName)) { originatingDcNotFoundCount++; } } }
Source:
public void testBadSegmentSubResourceNumber() throws UnsupportedEncodingException, URISyntaxException { String requestPath = "/mediaexpectedOpOrId/Segment/notAnInteger"; List<String> prefixesToRemove = new ArrayList<>(); RestRequest restRequest = RestUtilsTest.createRestRequest(RestMethod.GET, requestPath, null); try { RequestPath.parse(restRequest, prefixesToRemove, CLUSTER_NAME); } catch (RestServiceException e) { assertTrue(e.getErrorCode().equals(RestServiceErrorCode.BadRequest)); //expected return; } fail(); }

Target:
public void testBadSegmentSubResourceNumber() throws UnsupportedEncodingException, URISyntaxException { String requestPath = "/mediaexpectedOpOrId/Segment/notAnInteger"; List<String> prefixesToRemove = new ArrayList<>(); RestRequest restRequest = RestUtilsTest.createRestRequest(RestMethod.GET, requestPath, null); try { RequestPath.parse(restRequest, prefixesToRemove, CLUSTER_NAME); fail(); } catch (RestServiceException e) { assertTrue(e.getErrorCode().equals(RestServiceErrorCode.BadRequest)); } }
Source:
public String toString() { return "CloudReplica[" + dataNodeId.getHostname() + ":" + getDataNodeId().getPort() + ":" + getReplicaPath() + "]"; }

Target:
public String toString() { return "CloudReplica[" + dataNodeId.getHostname() + ":" + dataNodeId.getPort() + ":" + getReplicaPath() + "]"; }
Source:
private static void assertObjectsAreDistinct(GetBlobOptions a, GetBlobOptions b) { assertThat("GetBlobOptions should not be equal.", a, not(b)); assertThat("GetBlobOptions hashcodes should not be equal", a.hashCode(), not(b.hashCode())); assertThat("GetBlobOptions toString should not be equal", a.toString(), not(b.toString())); }

Target:
private static void assertObjectsAreDistinct(GetBlobOptions a, GetBlobOptions b) { assertThat("GetBlobOptions should not be equal.", a, not(b)); assertThat("GetBlobOptions toString should not be equal", a.toString(), not(b.toString())); // Note: don't compare hashcodes since collisions are possible. }
Source:
private void handlePutManagerClosed(BlobProperties blobProperties, boolean stitchOperation, FutureResult<String> futureResult, Callback<String> callback) { RouterException routerException = new RouterException("Cannot accept operation because Router is closed", RouterErrorCode.RouterClosed); routerMetrics.operationDequeuingRate.mark(); routerMetrics.onPutBlobError(routerException, blobProperties != null && blobProperties.isEncrypted(), stitchOperation); completeOperation(futureResult, callback, null, routerException); // Close so that any existing operations are also disposed off. close(); }

Target:
private void handlePutManagerClosed(BlobProperties blobProperties, boolean stitchOperation, FutureResult<String> futureResult, Callback<String> callback) { RouterException routerException = new RouterException("Cannot accept operation because Router is closed", RouterErrorCode.RouterClosed); routerMetrics.operationDequeuingRate.mark(); routerMetrics.onPutBlobError(routerException, blobProperties.isEncrypted(), stitchOperation); completeOperation(futureResult, callback, null, routerException); // Close so that any existing operations are also disposed off. close(); }
Source:
void readIntoDirectly(byte[] byteArray, long position, int length) throws IOException { validateReadRange(position, length); if (file.length() < position + length) { throw new IOException( "Requested range exceed file length. position = " + position + " length = " + length + "fileLength = " + file.length()); } // TODO: Try to avoid opening file on every opeartion. try (DirectRandomAccessFile directFile = new DirectRandomAccessFile(file, "r", 2 * 1024 * 1024)) { directFile.seek(position); directFile.read(byteArray, 0, length); } }

Target:
void readIntoDirectly(byte[] byteArray, long position, int length) throws IOException { validateReadRange(position, length); // TODO: Try to avoid opening file on every opeartion. try (DirectRandomAccessFile directFile = new DirectRandomAccessFile(file, "r", 2 * 1024 * 1024)) { directFile.seek(position); directFile.read(byteArray, 0, length); } }
Source:
public String getDatacenterName(byte id) { int idx = (int) id; if (idx < 0 || idx >= dataCentersInClusterMap.size()) { return null; } return dataCentersInClusterMap.get(id); }

Target:
public String getDatacenterName(byte id) { int idx = (int) id; if (idx < 0 || idx >= dataCentersInClusterMap.size()) { return null; } return dataCentersInClusterMap.get(idx); }
Source:
void shutdownBlobStore(PartitionId id) { BlobStore store = (BlobStore) getStore(id); if (store != null) { try { store.shutdown(); } catch (Exception e) { logger.error("Exception while shutting down store on disk {}", id, disk, e); } } }

Target:
boolean shutdownBlobStore(PartitionId id) { BlobStore store = (BlobStore) getStore(id); if (store == null) { return false; } try { store.shutdown(); } catch (Exception e) { logger.error("Exception while shutting down store on disk {}", id, disk, e); return false; } return true; }
Source:
boolean disableCompactionForBlobStore(BlobStore store) { if (compactionExecutor == null) { return true; } return compactionExecutor.disableCompactionForBlobStore(store); }

Target:
boolean disableCompactionForBlobStore(BlobStore store) { return compactionExecutor == null || compactionExecutor.disableCompactionForBlobStore(store); }
Source:
public static boolean validateAuthorization(short storeAccountId, short storeContainerId, short requestAccountId, short requestContainerId) { if (storeAccountId != Account.UNKNOWN_ACCOUNT_ID && storeContainerId != Container.UNKNOWN_CONTAINER_ID) { return (storeAccountId == requestAccountId) && (storeContainerId == requestContainerId); } return true; }

Target:
private boolean validateAuthorization(short storeAccountId, short storeContainerId, short requestAccountId, short requestContainerId) { if (storeAccountId != Account.UNKNOWN_ACCOUNT_ID && storeContainerId != Container.UNKNOWN_CONTAINER_ID) { return (storeAccountId == requestAccountId) && (storeContainerId == requestContainerId); } return true; }
Source:
void poll(RequestRegistrationCallback<GetOperation> requestRegistrationCallback) { //First, check if any of the existing requests have timed out. if (!maybeProcessDecryptCallbackAndComplete()) { cleanupExpiredInFlightRequests(); checkAndMaybeComplete(true); if (!isOperationComplete()) { fetchRequests(requestRegistrationCallback); } } }

Target:
void poll(RequestRegistrationCallback<GetOperation> requestRegistrationCallback) { //First, check if any of the existing requests have timed out. cleanupExpiredInFlightRequests(); checkAndMaybeComplete(); if (!isOperationComplete()) { fetchRequests(requestRegistrationCallback); } }
Source:
public void testSimpleBlobPutSuccess() throws Exception { requestAndResultsList.clear(); requestAndResultsList.add(new RequestAndResult(chunkSize)); submitPutsAndAssertSuccess(true); for (int i = 0; i < 1; i++) { // size in [1, chunkSize] requestAndResultsList.clear(); requestAndResultsList.add(new RequestAndResult(random.nextInt(chunkSize) + 1)); submitPutsAndAssertSuccess(true); } }

Target:
public void testSimpleBlobPutSuccess() throws Exception { requestAndResultsList.clear(); requestAndResultsList.add(new RequestAndResult(chunkSize)); submitPutsAndAssertSuccess(true); for (int i = 0; i < 10; i++) { // size in [1, chunkSize] requestAndResultsList.clear(); requestAndResultsList.add(new RequestAndResult(random.nextInt(chunkSize) + 1)); submitPutsAndAssertSuccess(true); } }
Source:
public Object setArg(String key, Object value) { Object oldVal = allArgs.put(key, value); return oldVal; }

Target:
public Object setArg(String key, Object value) { return allArgs.put(key, value); }
Source:
public void close() { if (isOpen) { try { isOpen = false; accountInfoMapRef.set(null); helixStore.stop(); } catch (Exception e) { logger.error("Exception occurred when closing HelixAccountService.", e); } } }

Target:
public void close() { if (isOpen) { try { isOpen = false; helixStore.stop(); } catch (Exception e) { logger.error("Exception occurred when closing HelixAccountService.", e); } } }
Source:
public static void serializeBlobPropertiesV2Record(ByteBuffer outputBuffer, BlobProperties properties) { int startOffset = outputBuffer.position(); outputBuffer.putShort(BlobProperties_Version_V1); BlobPropertiesSerDe.putBlobPropertiesToBufferV2(outputBuffer, properties); Crc32 crc = new Crc32(); crc.update(outputBuffer.array(), startOffset, getBlobPropertiesV2RecordSize(properties) - Crc_Size); outputBuffer.putLong(crc.getValue()); }

Target:
private void serializeBlobPropertiesV2Record(ByteBuffer outputBuffer, BlobProperties properties) { int startOffset = outputBuffer.position(); outputBuffer.putShort(BlobProperties_Version_V1); putBlobPropertiesToBufferV2(outputBuffer, properties); Crc32 crc = new Crc32(); crc.update(outputBuffer.array(), startOffset, getBlobPropertiesV2RecordSize(properties) - Crc_Size); outputBuffer.putLong(crc.getValue()); }
Source:
short getCurrentVersion() { return CURRENT_VERSION; }

Target:
protected short getCurrentVersion() { return CURRENT_VERSION; }
Source:
public short sizeInBytes() { short sizeForBlobIdV1 = (short) (VERSION_FIELD_LENGTH_IN_BYTES + partitionId.getBytes().length + UUID_SIZE_FIELD_LENGTH_IN_BYTES + uuid.length()); switch (version) { case BLOB_ID_V1: return sizeForBlobIdV1; case BLOB_ID_V2: return (short) (FLAG_FIELD_LENGTH_IN_BYTES + DATACENTER_ID_FIELD_LENGTH_IN_BYTES + ACCOUNT_ID_FIELD_LENGTH_IN_BYTES + CONTAINER_ID_FIELD_LENGTH_IN_BYTES + sizeForBlobIdV1); default: throw new IllegalArgumentException("blobId version=" + version + " not supported"); } }

Target:
public short sizeInBytes() { short sizeForBlobIdV1 = (short) (VERSION_FIELD_LENGTH_IN_BYTES + partitionId.getBytes().length + UUID_SIZE_FIELD_LENGTH_IN_BYTES + uuid.getBytes().length); switch (version) { case BLOB_ID_V1: return sizeForBlobIdV1; case BLOB_ID_V2: return (short) (FLAG_FIELD_LENGTH_IN_BYTES + DATACENTER_ID_FIELD_LENGTH_IN_BYTES + ACCOUNT_ID_FIELD_LENGTH_IN_BYTES + CONTAINER_ID_FIELD_LENGTH_IN_BYTES + sizeForBlobIdV1); default: throw new IllegalArgumentException("blobId version=" + version + " not supported"); } }
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Partition partition = (Partition) o; if (id == null ^ partition.id == null){ // one of them is null (XOR, so not both) return false; } return id.equals(partition.id); }

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Partition partition = (Partition) o; return id.equals(partition.id); }
Source:
CompactionDetails getCompactionDetails(BlobStore blobStore) throws StoreException { return blobStore.getCompactionDetails(compactionPolicy); }

Target:
private CompactionDetails getCompactionDetails(BlobStore blobStore) throws StoreException { return blobStore.getCompactionDetails(compactionPolicy); }
Source:
public void requestHandleWithGoodInputTest() throws Exception { doRequestHandleTest(HttpMethod.POST, "POST", false, false); doRequestHandleTest(HttpMethod.GET, "GET", false, false); doRequestHandleTest(HttpMethod.DELETE, "DELETE", false, false); // SSL enabled doRequestHandleTest(HttpMethod.GET, "GET", false, true); }

Target:
public void requestHandleWithGoodInputTest() throws Exception { doRequestHandleTest(HttpMethod.POST, "POST", false, false); doRequestHandleTest(HttpMethod.GET, "GET", false, false); doRequestHandleTest(HttpMethod.DELETE, "DELETE", false, false); // SSL enabled doRequestHandleTest(HttpMethod.POST, "POST", false, true); doRequestHandleTest(HttpMethod.GET, "GET", false, true); doRequestHandleTest(HttpMethod.DELETE, "DELETE", false, true); }
Source:
private void initializeAdminsAndAddCluster() { for (Map.Entry<String, String> entry : dataCenterToZkAddress.entrySet()) { ZKHelixAdmin admin = new ZKHelixAdmin(entry.getValue()); adminForDc.put(entry.getKey(), admin); // Add a cluster entry in every DC if (!admin.getClusters().contains(clusterName)) { admin.addCluster(clusterName); admin.addStateModelDef(clusterName, "LeaderStandby", LeaderStandbySMD.build()); } } }

Target:
private void initializeAdminsAndAddCluster() { for (Map.Entry<String, String> entry : dataCenterToZkAddress.entrySet()) { ZKHelixAdmin admin = new ZKHelixAdmin(entry.getValue()); adminForDc.put(entry.getKey(), admin); // Add a cluster entry in every DC if (!admin.getClusters().contains(clusterName)) { admin.addCluster(clusterName); admin.addStateModelDef(clusterName, LeaderStandbySMD.name, LeaderStandbySMD.build()); } } }
Source:
Store getStore(PartitionId id) { BlobStore store = stores.get(id); return store.isStarted() ? store : null; }

Target:
Store getStore(PartitionId id) { BlobStore store = stores.get(id); return (store != null && store.isStarted()) ? store : null; }
Source:
private boolean waitForThreadState(Thread thread, Thread.State state) { long MAX_WAIT_MS = 2000; long checkStartTimeMs = SystemTime.getInstance().milliseconds(); while (thread.getState() != state) { if (SystemTime.getInstance().milliseconds() - checkStartTimeMs > MAX_WAIT_MS) { return false; } else { Thread.yield(); } } return true; }

Target:
private boolean waitForThreadState(Thread thread, Thread.State state) { long checkStartTimeMs = SystemTime.getInstance().milliseconds(); while (thread.getState() != state) { if (SystemTime.getInstance().milliseconds() - checkStartTimeMs > MAX_WAIT_MS) { return false; } else { Thread.yield(); } } return true; }
Source:
void poll(RequestRegistrationCallback<DeleteOperation> requestRegistrationCallback) { try { cleanupExpiredInflightRequests(); checkAndMaybeComplete(); if (!isOperationComplete()) { fetchRequests(requestRegistrationCallback); } } catch (Exception e) { routerMetrics.unexpectedErrorCount.inc(); setOperationException(new RouterException("DeleteOperation poll encountered unexpected error", e, RouterErrorCode.UnexpectedInternalError)); } }

Target:
void poll(RequestRegistrationCallback<DeleteOperation> requestRegistrationCallback) { cleanupExpiredInflightRequests(); checkAndMaybeComplete(); if (!isOperationComplete()) { fetchRequests(requestRegistrationCallback); } }
Source:
private void maybeWriteToChannel() { // if there are chunks available to be written out, do now. if (firstChunk.isComplete() && readCalled) { while (operationException.get() == null && chunkIndexToBuffer.containsKey(indexOfNextChunkToWriteOut)) { ByteBuffer chunkBuf = chunkIndexToBuffer.remove(indexOfNextChunkToWriteOut); asyncWritableChannel.write(chunkBuf, chunkAsyncWriteCallback); indexOfNextChunkToWriteOut++; } if (operationException.get() != null || numChunksWrittenOut.get() == numChunksTotal) { completeRead(); } } }

Target:
private void maybeWriteToChannel() { // if there are chunks available to be written out, do now. if (firstChunk.isComplete() && readCalled) { while (operationException.get() == null && chunkIndexToBuffer.containsKey(indexOfNextChunkToWriteOut)) { ByteBuffer chunkBuf = chunkIndexToBuffer.remove(indexOfNextChunkToWriteOut); asyncWritableChannel.write(chunkBuf, chunkAsyncWriteCallback); indexOfNextChunkToWriteOut++; } if (operationException.get() != null || numChunksWrittenOut == numChunksTotal) { completeRead(); } } }
Source:
public void testSimpleBlobGetSuccess() throws Exception { maxChunkSize = random.nextInt(1024 * 1024) + 1; for (int i = 0; i < 10; i++) { // blobSize in the range [1, maxChunkSize] blobSize = random.nextInt(maxChunkSize) + 1; doPut(); getAndAssertSuccess(); } }

Target:
public void testSimpleBlobGetSuccess() throws Exception { for (int i = 0; i < 10; i++) { // blobSize in the range [1, maxChunkSize] blobSize = random.nextInt(maxChunkSize) + 1; doPut(); getAndAssertSuccess(); } }
Source:
protected GetRequest createGetRequest(BlobId blobId, MessageFormatFlags flag) { List<BlobId> blobIds = Collections.singletonList(blobId); List<PartitionRequestInfo> partitionRequestInfoList = new ArrayList<PartitionRequestInfo>(); PartitionRequestInfo partitionRequestInfo = new PartitionRequestInfo(blobId.getPartition(), blobIds); partitionRequestInfoList.add(partitionRequestInfo); return new GetRequest(NonBlockingRouter.correlationIdGenerator.incrementAndGet(), routerConfig.routerHostname, flag, partitionRequestInfoList, GetOptions.None); }

Target:
protected GetRequest createGetRequest(BlobId blobId, MessageFormatFlags flag) { List<BlobId> blobIds = Collections.singletonList(blobId); List<PartitionRequestInfo> partitionRequestInfoList = Collections.singletonList(new PartitionRequestInfo(blobId .getPartition(), blobIds)); return new GetRequest(NonBlockingRouter.correlationIdGenerator.incrementAndGet(), routerConfig.routerHostname, flag, partitionRequestInfoList, GetOptions.None); }
Source:
private void prepareForSending() { try { // if this is part of a retry, make sure no previously attempted partitions are retried. if (partitionId != null) { attemptedPartitionIds.add(partitionId); } partitionId = getPartitionForPut(attemptedPartitionIds); chunkBlobId = new BlobId(partitionId); operationTracker = new SimpleOperationTracker(routerConfig.routerDatacenterName, partitionId, false, routerConfig.routerPutSuccessTarget, routerConfig.routerPutRequestParallelism, false); correlationIdToChunkPutRequestInfo.clear(); state = ChunkState.Ready; } catch (RouterException e) { setOperationException(e); } }

Target:
private void prepareForSending() { try { // if this is part of a retry, make sure no previously attempted partitions are retried. if (partitionId != null) { attemptedPartitionIds.add(partitionId); } partitionId = getPartitionForPut(attemptedPartitionIds); chunkBlobId = new BlobId(partitionId); operationTracker = new SimpleOperationTracker(routerConfig.routerDatacenterName, partitionId, false, routerConfig.routerPutSuccessTarget, routerConfig.routerPutRequestParallelism); correlationIdToChunkPutRequestInfo.clear(); state = ChunkState.Ready; } catch (RouterException e) { setOperationException(e); } }
Source:
public DeleteManager(ClusterMap clusterMap, ResponseHandler responseHandler, NotificationSystem notificationSystem, RouterConfig routerConfig, NonBlockingRouterMetrics routerMetrics, Time time) { this.clusterMap = clusterMap; this.responseHandler = responseHandler; this.notificationSystem = notificationSystem; this.routerConfig = routerConfig; this.routerMetrics = routerMetrics; this.time = time; deleteOperations = Collections.newSetFromMap(new ConcurrentHashMap<DeleteOperation, Boolean>()); correlationIdToDeleteOperation = new HashMap<Integer, DeleteOperation>(); }

Target:
DeleteManager(ClusterMap clusterMap, ResponseHandler responseHandler, NotificationSystem notificationSystem, RouterConfig routerConfig, NonBlockingRouterMetrics routerMetrics, Time time) { this.clusterMap = clusterMap; this.responseHandler = responseHandler; this.notificationSystem = notificationSystem; this.routerConfig = routerConfig; this.routerMetrics = routerMetrics; this.time = time; deleteOperations = Collections.newSetFromMap(new ConcurrentHashMap<DeleteOperation, Boolean>()); correlationIdToDeleteOperation = new HashMap<Integer, DeleteOperation>(); }
Source:
MockSelector(MockServerLayout serverLayout, AtomicReference<MockSelectorState> state, Time time) throws IOException { super(new NetworkMetrics(new MetricRegistry()), time, null); // we don't need the actual selector, close it. super.close(); this.serverLayout = serverLayout; this.state = state == null ? new AtomicReference<MockSelectorState>(MockSelectorState.Good) : state; this.time = time; }

Target:
MockSelector(MockServerLayout serverLayout, AtomicReference<MockSelectorState> state, Time time) throws IOException { super(new NetworkMetrics(new MetricRegistry()), time, null); // we don't need the actual selector, close it. super.close(); this.serverLayout = serverLayout; this.state = state == null ? new AtomicReference(MockSelectorState.Good) : state; this.time = time; }
Source:
private PutChunk getChunkToFill() { if (chunkToFill != null && chunkToFill.isBuilding()) { return chunkToFill; } else { for (PutChunk chunk : putChunks) { if (chunk.isFree()) { chunkCounter++; chunk.prepareForBuilding(chunkCounter, getSizeOfChunkAt(chunkCounter)); chunkToFill = chunk; return chunk; } } } // No free or building chunks. return null; }

Target:
private PutChunk getChunkToFill() { if (chunkToFill != null && chunkToFill.isBuilding()) { return chunkToFill; } chunkToFill = null; for (PutChunk chunk : putChunks) { if (chunk.isFree()) { chunkCounter++; chunk.prepareForBuilding(chunkCounter, getSizeOfChunkAt(chunkCounter)); chunkToFill = chunk; break; } } return chunkToFill; }
Source:
public void addContent(HttpContent httpContent) throws RestServiceException { if (!isOpen()) { nettyMetrics.multipartRequestAlreadyClosedError.inc(); throw new RestServiceException("The request has been closed and is not accepting content", RestServiceErrorCode.RequestChannelClosed); } else { ReferenceCountUtil.retain(httpContent); rawRequestContents.add(httpContent); } }

Target:
public void addContent(HttpContent httpContent) throws RestServiceException { if (!isOpen()) { nettyMetrics.multipartRequestAlreadyClosedError.inc(); throw new RestServiceException("The request has been closed and is not accepting content", RestServiceErrorCode.RequestChannelClosed); } else { rawRequestContents.add(ReferenceCountUtil.retain(httpContent)); } }
Source:
private static AsyncRequestResponseHandler buildInstance(RestServerMetrics restServerMetrics) { lock.lock(); try { if (instance == null) { AsyncRequestResponseHandlerFactory.restServerMetrics = restServerMetrics; instance = new AsyncRequestResponseHandler(restServerMetrics); } // check if same instance of RestServerMetrics - otherwise it is a problem. if (AsyncRequestResponseHandlerFactory.restServerMetrics != restServerMetrics) { throw new IllegalStateException("RestServerMetrics instance provided during construction of " + "AsyncRequestResponseHandler differs from the one currently received"); } } finally { lock.unlock(); } return instance; }

Target:
private static void buildInstance(RestServerMetrics restServerMetrics) { lock.lock(); try { if (instance == null) { AsyncRequestResponseHandlerFactory.restServerMetrics = restServerMetrics; instance = new AsyncRequestResponseHandler(restServerMetrics); } // check if same instance of RestServerMetrics - otherwise it is a problem. if (AsyncRequestResponseHandlerFactory.restServerMetrics != restServerMetrics) { throw new IllegalStateException("RestServerMetrics instance provided during construction of " + "AsyncRequestResponseHandler differs from the one currently received"); } } finally { lock.unlock(); } }