auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public List<Task<? extends Serializable>> handle(Context context) throws SemanticException { AlterTableMessage msg = deserializer.getAlterTableMessage(context.dmd.getPayload()); if (!context.isTableNameEmpty()) { throw new SemanticException( "RENAMES of tables are not supported for table-level replication"); } try { String oldDbName = msg.getTableObjBefore().getDbName(); String newDbName = msg.getTableObjAfter().getDbName(); if (!context.isDbNameEmpty()) { if (!oldDbName.equalsIgnoreCase(newDbName)) { throw new SemanticException("Cannot replicate an event renaming a table across" + " databases into a db level load " + oldDbName + "->" + newDbName); } else { oldDbName = context.dbName; newDbName = context.dbName; } } String oldName = oldDbName + "." + msg.getTableObjBefore().getTableName(); String newName = newDbName + "." + msg.getTableObjAfter().getTableName(); AlterTableDesc renameTableDesc = new AlterTableDesc(oldName, newName, false, eventOnlyReplicationSpec(context)); Task<DDLWork> renameTableTask = TaskFactory.get( new DDLWork(readEntitySet, writeEntitySet, renameTableDesc), context.hiveConf); context.log.debug("Added rename table task : {}:{}->{}", renameTableTask.getId(), oldName, newName); databasesUpdated.put(newDbName, context.dmd.getEventTo()); tablesUpdated.remove(oldName); tablesUpdated.put(newName, context.dmd.getEventTo()); return Collections.singletonList(renameTableTask); } catch (Exception e) { throw (e instanceof SemanticException) ? (SemanticException) e : new SemanticException("Error reading message members", e); } }

Target:
public List<Task<? extends Serializable>> handle(Context context) throws SemanticException { AlterTableMessage msg = deserializer.getAlterTableMessage(context.dmd.getPayload()); if (!context.isTableNameEmpty()) { throw new SemanticException( "RENAMES of tables are not supported for table-level replication"); } try { String oldDbName = msg.getTableObjBefore().getDbName(); String newDbName = msg.getTableObjAfter().getDbName(); if (!context.isDbNameEmpty()) { if (!oldDbName.equalsIgnoreCase(newDbName)) { throw new SemanticException("Cannot replicate an event renaming a table across" + " databases into a db level load " + oldDbName + "->" + newDbName); } else { oldDbName = context.dbName; newDbName = context.dbName; } } String oldName = oldDbName + "." + msg.getTableObjBefore().getTableName(); String newName = newDbName + "." + msg.getTableObjAfter().getTableName(); AlterTableDesc renameTableDesc = new AlterTableDesc( oldName, newName, false, context.eventOnlyReplicationSpec()); Task<DDLWork> renameTableTask = TaskFactory.get( new DDLWork(readEntitySet, writeEntitySet, renameTableDesc), context.hiveConf); context.log.debug("Added rename table task : {}:{}->{}", renameTableTask.getId(), oldName, newName); databasesUpdated.put(newDbName, context.dmd.getEventTo()); tablesUpdated.remove(oldName); tablesUpdated.put(newName, context.dmd.getEventTo()); return Collections.singletonList(renameTableTask); } catch (Exception e) { throw (e instanceof SemanticException) ? (SemanticException) e : new SemanticException("Error reading message members", e); } }
Source:
public Object getCurrentTransactionId() { if(com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionImple.getTransaction() == null) return null; return com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionImple.getTransaction().get_uid(); }

Target:
public Object getCurrentTransactionId() { com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionImple transaction = com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionImple.getTransaction(); if (transaction == null) return null; return transaction.get_uid(); }
Source:
public static String getCodeSystemUrl(@Nonnull IBaseResource theCodeSystem) { String url; switch (theCodeSystem.getStructureFhirVersionEnum()) { case DSTU2_HL7ORG: { url = ((CodeSystem) theCodeSystem).getUrl(); break; } case DSTU3: { url = ((org.hl7.fhir.dstu3.model.CodeSystem) theCodeSystem).getUrl(); break; } case R4: { url = ((org.hl7.fhir.r4.model.CodeSystem) theCodeSystem).getUrl(); break; } case R5: { url = ((org.hl7.fhir.r5.model.CodeSystem) theCodeSystem).getUrl(); break; } case DSTU2: case DSTU2_1: default: throw new IllegalArgumentException("Can not handle version: " + theCodeSystem.getStructureFhirVersionEnum()); } return url; }

Target:
public static String getCodeSystemUrl(@Nonnull IBaseResource theCodeSystem) { String url; switch (theCodeSystem.getStructureFhirVersionEnum()) { case R4: { url = ((org.hl7.fhir.r4.model.CodeSystem) theCodeSystem).getUrl(); break; } case R5: { url = ((org.hl7.fhir.r5.model.CodeSystem) theCodeSystem).getUrl(); break; } case DSTU3: default: throw new IllegalArgumentException("Can not handle version: " + theCodeSystem.getStructureFhirVersionEnum()); } return url; }
Source:
final private SecretKey getSecretKeyFromAndroidKeyStore() throws IOException, GeneralSecurityException { File keyFile = new File(mContext.getFilesDir(), "adal.secret.key"); loadKeyPair(); if (!keyFile.exists()) { Logger.v(TAG, "Key file does not exists"); final SecretKey key = generateSecretKey(); Logger.v(TAG, "Wrapping SecretKey"); final byte[] keyWrapped = wrap(key); Logger.v(TAG, "Writing SecretKey"); writeKeyData(keyFile, keyWrapped); Logger.v(TAG, "Finished writing SecretKey"); } Logger.v(TAG, "Reading SecretKey"); final byte[] encryptedKey = readKeyData(keyFile); final SecretKey key = unWrap(encryptedKey); Logger.v(TAG, "Finished reading SecretKey"); return key; }

Target:
final synchronized private SecretKey getSecretKeyFromAndroidKeyStore() throws IOException, GeneralSecurityException { if (sSecretKeyFromAndroidKeyStore != null) { return sSecretKeyFromAndroidKeyStore; } File keyFile = new File(mContext.getFilesDir(), ADALKS); loadKeyPair(); Cipher wrapCipher = Cipher.getInstance(WRAP_ALGORITHM); if (!keyFile.exists()) { Logger.v(TAG, "Key file does not exists"); final SecretKey key = generateSecretKey(); Logger.v(TAG, "Wrapping SecretKey"); final byte[] keyWrapped = wrap(wrapCipher, key); Logger.v(TAG, "Writing SecretKey"); writeKeyData(keyFile, keyWrapped); Logger.v(TAG, "Finished writing SecretKey"); } Logger.v(TAG, "Reading SecretKey"); final byte[] encryptedKey = readKeyData(keyFile); sSecretKeyFromAndroidKeyStore = unwrap(wrapCipher, encryptedKey); Logger.v(TAG, "Finished reading SecretKey"); return sSecretKeyFromAndroidKeyStore; }
Source:
Map<String, File> createOutputMap( final File outputMapFile, final File outputDir, final String defaultExtension, final List<SAMReadGroupRecord> readGroups) { final Map<String, File> outputMap; if (outputMapFile != null) { outputMap = createOutputMapFromFile(outputMapFile); } else { outputMap = createOutputMap(readGroups, outputDir, defaultExtension); } return outputMap; }

Target:
static Map<String, File> createOutputMap( final File outputMapFile, final File outputDir, final String defaultExtension, final List<SAMReadGroupRecord> readGroups) { final Map<String, File> outputMap; if (outputMapFile != null) { outputMap = createOutputMapFromFile(outputMapFile); } else { outputMap = createOutputMap(readGroups, outputDir, defaultExtension); } return outputMap; }
Source:
private boolean notRacyClean(final long read) { return read - lastModified > 3 * 60 * 1000L; }

Target:
private boolean notRacyClean(final long read) { return read - lastModified > 2500; }
Source:
public void testConfigOverwrittenByDynamicOpts() throws Exception { double cpuCores = 39.0; String[] commands = {RUN_BASH_JAVA_UTILS_CMD_SCRIPT, BashJavaUtils.Command.GET_TM_RESOURCE_PARAMS.toString(), "-D" + TaskManagerOptions.CPU_CORES.key() + "=" + cpuCores}; List<String> lines = Arrays.asList(executeScript(commands).split(System.lineSeparator())); assertEquals(2, lines.size()); Map<String, String> configs = ConfigurationUtils.parseTmResourceDynamicConfigs(lines.get(lines.size() - 1)); assertThat(Double.valueOf(configs.get(TaskManagerOptions.CPU_CORES.key())), is(cpuCores)); }

Target:
public void testConfigOverwrittenByDynamicOpts() throws Exception { double cpuCores = 39.0; String[] commands = {RUN_BASH_JAVA_UTILS_CMD_SCRIPT, BashJavaUtils.Command.GET_TM_RESOURCE_PARAMS.toString(), "-D" + TaskManagerOptions.CPU_CORES.key() + "=" + cpuCores}; List<String> lines = Arrays.asList(executeScript(commands).split(System.lineSeparator())); assertThat(lines.size(), is(2)); Map<String, String> configs = ConfigurationUtils.parseTmResourceDynamicConfigs(lines.get(1)); assertThat(Double.valueOf(configs.get(TaskManagerOptions.CPU_CORES.key())), is(cpuCores)); }
Source:
protected void executeCommand() { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { getCompensationContext().snapshotEntity(getVmPool()); setPoolBeingDestroyed(); setPrestartedToZero(); getCompensationContext().stateChanged(); return null; } }); setCommandShouldBeLogged(false); log(); stopVms(); if (allVmsDown) { getParameters().setTaskGroupSuccess(true); endAction(); } else { setSucceeded(true); } }

Target:
protected void executeCommand() { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { getCompensationContext().snapshotEntity(getVmPool()); setPoolBeingDestroyed(); setPrestartedToZero(); getCompensationContext().stateChanged(); return null; } }); setCommandShouldBeLogged(false); log(); stopVms(); if (allVmsDown) { getParameters().setTaskGroupSuccess(true); endSuccessfully(); } else { setSucceeded(true); } }
Source:
public Map<Long, Map<Integer, QuestionAnswerStore>> mapByQuestionIdAndIteration( List<QuestionAnswerStore> qasList) { Map<Long, Map<Integer, QuestionAnswerStore>> responseMap = new HashMap<>(); for (QuestionAnswerStore a : qasList) { Long questionId = Long.parseLong(a.getQuestionID()); Integer iteration = a.getIteration(); iteration = iteration == null ? 0 : iteration; Map<Integer, QuestionAnswerStore> iterationMap = responseMap.get(questionId); if (iterationMap == null) { iterationMap = new HashMap<>(); } iterationMap.put(iteration, a); responseMap.put(questionId, iterationMap); } return responseMap; }

Target:
public Map<Long, Map<Integer, QuestionAnswerStore>> mapByQuestionIdAndIteration( List<QuestionAnswerStore> qasList) { Map<Long, Map<Integer, QuestionAnswerStore>> responseMap = new HashMap<>(); for (QuestionAnswerStore a : qasList) { Long questionId = Long.parseLong(a.getQuestionID()); Integer iteration = a.getIteration(); iteration = iteration == null ? 0 : iteration; Map<Integer, QuestionAnswerStore> iterationMap = responseMap.get(questionId); if (iterationMap == null) { iterationMap = new HashMap<>(); responseMap.put(questionId, iterationMap); } iterationMap.put(iteration, a); } return responseMap; }
Source:
AbstractInvocationHandler(SafeCallManager manager, T target, Object identifier, long timeout, @Nullable Consumer<Throwable> exceptionHandler, @Nullable Runnable timeoutHandler) { super(); this.manager = manager; this.target = target; this.identifier = identifier; this.timeout = timeout; this.exceptionHandler = exceptionHandler; this.timeoutHandler = timeoutHandler; }

Target:
AbstractInvocationHandler(SafeCallManager manager, T target, Object identifier, long timeout, @Nullable Consumer<Throwable> exceptionHandler, @Nullable Runnable timeoutHandler) { this.manager = manager; this.target = target; this.identifier = identifier; this.timeout = timeout; this.exceptionHandler = exceptionHandler; this.timeoutHandler = timeoutHandler; }
Source:
public static StyleKeyRegistry getRegistry() { if ( registry == null ) { throw new IllegalStateException( "You have to boot LibCSS to make all style-keys known" ); } return registry; }

Target:
public static StyleKeyRegistry getRegistry() { lock.readLock().lock(); try { if ( registry == null ) { throw new IllegalStateException( "You have to boot LibCSS to make all style-keys known" ); } return registry; } finally { lock.readLock().unlock(); } }
Source:
public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp) { try { final URI requestURI = req.getRequestURI(); final String path = requestURI.getPath(); final String backendURL = getMatchedBackendURL(path); ProxyWebSocketAdapter wsAdaptor = new ProxyWebSocketAdapter (URI.create(backendURL), pool, getClientEndpointConfig(req)); wsAdaptor.setMaxBufferCount(config.getWebsocketMaxWaitBufferCount()); return wsAdaptor; } catch (final Exception e) { LOG.failedCreatingWebSocket(e); throw e; } }

Target:
public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp) { try { final URI requestURI = req.getRequestURI(); final String path = requestURI.getPath(); final String backendURL = getMatchedBackendURL(path, requestURI); LOG.debugLog("Generated backend URL for websocket connection: " + backendURL); return new ProxyWebSocketAdapter (URI.create(backendURL), pool, getClientEndpointConfig(req), config); } catch (final Exception e) { LOG.failedCreatingWebSocket(e); throw e; } }
Source:
public void loadDictionaryFromFasta () throws IOException { IndexedFastaSequenceFile ff = new IndexedFastaSequenceFile(REF_FILE); DICTIONARY_BACKED_BY_REF_FILE = ff.getSequenceDictionary(); ff.close(); }

Target:
public void loadDictionaryFromFasta () throws IOException { final IndexedFastaSequenceFile ff = new IndexedFastaSequenceFile(REF_FILE); DICTIONARY_BACKED_BY_REF_FILE = ff.getSequenceDictionary(); ff.close(); }
Source:
public Standed( @NotNull(message = "work can't be NULL") final Work wrk, @NotNull(message = "name of stand can't be NULL") final String name, @NotNull(message = "key can't be NULL") final String secret, @NotNull(message = "drain can't be NULL") final Drain drain) { this.work = wrk; this.stand = name; this.key = secret; this.origin = drain; this.entry = new Standed.SQSEntry() { @Override public TestClient get() { return RestTester.start(Stand.QUEUE); } }; this.exec = new Standed.Exec() { @Override public ExecutorService get() { return Executors.newFixedThreadPool( Standed.THREADS, new VerboseThreads() ); } }; }

Target:
public Standed( @NotNull(message = "work can't be NULL") final Work wrk, @NotNull(message = "name of stand can't be NULL") final String name, @NotNull(message = "key can't be NULL") final String secret, @NotNull(message = "drain can't be NULL") final Drain drain) { this( wrk, name, secret, drain, RestTester.start(Stand.QUEUE), Executors.newFixedThreadPool(Standed.THREADS, new VerboseThreads()) ); }
Source:
public Mapper build() { JacksonEngine jacksonEngine = new JacksonEngine(createMapping()); if (queryFactory == null) { queryFactory = new BsonQueryFactory(jacksonEngine); } if (objectIdUpdater == null) { objectIdUpdater = new JacksonObjectIdUpdater(jacksonEngine.getObjectMapper()); } return new JacksonMapper(jacksonEngine, queryFactory, objectIdUpdater); }

Target:
public Mapper build() { JacksonEngine jacksonEngine = new JacksonEngine(createMapping()); if (queryFactory == null) { queryFactory = new BsonQueryFactory(jacksonEngine); } if (objectIdUpdater == null) { objectIdUpdater = new ReflectiveObjectIdUpdater(new JacksonIdFieldSelector()); } return new JacksonMapper(jacksonEngine, queryFactory, objectIdUpdater); }
Source:
private void prune(Block inactiveBlock) { if (inactiveBlock.equals(trueBlock)) { if (inactiveBlock.successors.size() != 1) { throw new IllegalStateException("True successor must be replaced by a unique successor!"); } trueBlock = inactiveBlock.successors.iterator().next(); } if (inactiveBlock.equals(falseBlock)) { if (inactiveBlock.successors.size() != 1) { throw new IllegalStateException("False successor must be replaced by a unique successor!"); } falseBlock = inactiveBlock.successors.iterator().next(); } if (inactiveBlock.equals(successorWithoutJump)) { if (inactiveBlock.successors.size() != 1) { throw new IllegalStateException("SuccessorWithoutJump successor must be replaced by a unique successor!"); } successorWithoutJump = inactiveBlock.successors.iterator().next(); } if (successors.remove(inactiveBlock)) { successors.addAll(inactiveBlock.successors); } if (exceptions.remove(inactiveBlock)) { exceptions.addAll(inactiveBlock.exceptions); exceptions.addAll(inactiveBlock.successors); } if (inactiveBlock.equals(exitBlock)) { exitBlock = inactiveBlock.successors.iterator().next(); } }

Target:
private void prune(Block inactiveBlock) { boolean hasUniqueSuccessor = inactiveBlock.successors.size() == 1; if (inactiveBlock.equals(trueBlock)) { Preconditions.checkArgument(hasUniqueSuccessor, "True successor must be replaced by a unique successor!"); trueBlock = inactiveBlock.successors.iterator().next(); } if (inactiveBlock.equals(falseBlock)) { Preconditions.checkArgument(hasUniqueSuccessor, "False successor must be replaced by a unique successor!"); falseBlock = inactiveBlock.successors.iterator().next(); } if (inactiveBlock.equals(successorWithoutJump)) { Preconditions.checkArgument(hasUniqueSuccessor, "SuccessorWithoutJump successor must be replaced by a unique successor!"); successorWithoutJump = inactiveBlock.successors.iterator().next(); } if (successors.remove(inactiveBlock)) { successors.addAll(inactiveBlock.successors); } if (exceptions.remove(inactiveBlock)) { exceptions.addAll(inactiveBlock.exceptions); exceptions.addAll(inactiveBlock.successors); } if (inactiveBlock.equals(exitBlock)) { exitBlock = inactiveBlock.successors.iterator().next(); } }
Source:
public SqlTypeName getSqlTypeName() { Class clz = clazz; if (List.class.isAssignableFrom(clazz) || java.sql.Array.class.isAssignableFrom(clazz) || java.lang.reflect.Array.class.isAssignableFrom(clazz)) { clz = List.class; } else if (Map.class.isAssignableFrom(clazz)) { clz = Map.class; } final SqlTypeName typeName = JavaToSqlTypeConversionRules.instance().lookup(clz); if (typeName == null) { return SqlTypeName.OTHER; } return typeName; }

Target:
public SqlTypeName getSqlTypeName() { final SqlTypeName typeName = JavaToSqlTypeConversionRules.instance().lookup(clazz); if (typeName == null) { return SqlTypeName.OTHER; } return typeName; }
Source:
private FunctionRegistry createFunctionRegistry(TypeRegistry typeManager) { BlockEncodingManager blockEncodingManager = new BlockEncodingManager(typeManager); FeaturesConfig featuresConfig = new FeaturesConfig(); FunctionManager functionManager = new FunctionManager(typeManager, blockEncodingManager, featuresConfig); return new FunctionRegistry(typeManager, blockEncodingManager, new FeaturesConfig(), functionManager); }

Target:
private FunctionRegistry createFunctionRegistry(TypeRegistry typeManager) { BlockEncodingManager blockEncodingManager = new BlockEncodingManager(typeManager); FeaturesConfig featuresConfig = new FeaturesConfig(); FunctionManager functionManager = new FunctionManager(typeManager, blockEncodingManager, featuresConfig); return new FunctionRegistry(typeManager, blockEncodingManager, featuresConfig, functionManager); }
Source:
public void simplePhenotypeSearchExternalIdentifier() throws AvroRemoteException { SearchGenotypePhenotypeRequest request = SearchGenotypePhenotypeRequest.newBuilder().build(); ExternalIdentifier id = new ExternalIdentifier() ; id.setDatabase("<LINK_0>"); id.setIdentifier("606764"); id.setVersion("*"); List<ExternalIdentifier> ids = new ArrayList<ExternalIdentifier>() ; ids.add(id) ; ExternalIdentifierQuery phenotype = new ExternalIdentifierQuery(); phenotype.setIds(ids); request.setPhenotype(phenotype); SearchGenotypePhenotypeResponse response = client.genotypePhenotype.searchGenotypePhenotype(request); assertThat(response).isNotNull(); assertThat(response.getAssociations()).isNotNull() ; assertThat(response.getAssociations().get(0)).isNotNull() ; }

Target:
public void simplePhenotypeSearchExternalIdentifier() throws AvroRemoteException { SearchGenotypePhenotypeRequest request = SearchGenotypePhenotypeRequest.newBuilder().build(); ExternalIdentifier id = new ExternalIdentifier() ; id.setDatabase(TestData.PHENOTYPE_DB); id.setIdentifier(TestData.PHENOTYPE_DB_ID); id.setVersion(TestData.PHENOTYPE_DB_VERSION); List<ExternalIdentifier> ids = new ArrayList<>() ; ids.add(id) ; ExternalIdentifierQuery phenotype = new ExternalIdentifierQuery(); phenotype.setIds(ids); request.setPhenotype(phenotype); SearchGenotypePhenotypeResponse response = client.genotypePhenotype.searchGenotypePhenotype(request); assertThat(response.getAssociations()).isNotNull() ; assertThat(response.getAssociations()).isNotEmpty() ; }
Source:
Collection<String> getAvailableItems(Context context) throws IOException { Connection connection = context.getConnection(); return context.getConnection().getAvailableServers(connection.getActiveContainer().getName()); }

Target:
Collection<String> getAvailableItems(Context context) throws IOException { Connection connection = context.getConnection(); return connection.getAvailableServers(connection.getActiveContainer().getName()); }
Source:
public View getCustomView(int position, View convertView, ViewGroup parent) { RowViewHolder rowViewHolder; if (convertView == null) { rowViewHolder = new RowViewHolder(); convertView = mInflater.inflate(R.layout.spinner_item_layout, parent, false); rowViewHolder.rowItemText = (TextView) convertView.findViewById(R.id.spinner_item_text); if (getItem(position) == -1) { rowViewHolder.rowItemText.setText(NO_ANIMATION_TEXT); } else if (getItem(position) == 1000) { rowViewHolder.rowItemText.setText(ONE_SECOND); } else { rowViewHolder.rowItemText.setText(getItem(position).toString() + MS); } } else { rowViewHolder = (RowViewHolder) convertView.getTag(); } convertView.setTag(rowViewHolder); return convertView; }

Target:
public View getCustomView(int position, View convertView, ViewGroup parent) { RowViewHolder rowViewHolder; if (convertView == null) { rowViewHolder = new RowViewHolder(); convertView = mInflater.inflate(R.layout.spinner_item_layout, parent, false); rowViewHolder.rowItemText = (TextView) convertView.findViewById(R.id.spinner_item_text); } else { rowViewHolder = (RowViewHolder) convertView.getTag(); } if (getItem(position) == -1) { rowViewHolder.rowItemText.setText(NO_ANIMATION_TEXT); } else if (getItem(position) == 1000) { rowViewHolder.rowItemText.setText(ONE_SECOND); } else { rowViewHolder.rowItemText.setText(getItem(position).toString() + MS); } convertView.setTag(rowViewHolder); return convertView; }
Source:
public void testDeletingComponent() { CourseGroupDAO newCourseGroup = courseDao.newCourseGroup("id", "Title", "Department", "Subunit"); newCourseGroup.setSource("source"); courseDao.save(newCourseGroup); CourseComponentDAO newCourseComponent1 = courseDao.newCourseComponent("test1"); newCourseComponent1.getGroups().add(newCourseGroup); newCourseComponent1.setSource("source"); courseDao.save(newCourseComponent1); CourseComponentDAO newCourseComponent2 = courseDao.newCourseComponent("test2"); newCourseComponent2.getGroups().add(newCourseGroup); newCourseComponent2.setSource("source"); newCourseComponent2.setDeleted(true); courseDao.save(newCourseComponent2); CourseSignupDAO newSignup = courseDao.newSignup("userId", "supervisorId"); newSignup.setGroup(newCourseGroup); newSignup.getComponents().add(newCourseComponent1); courseDao.save(newSignup); courseDao.deleteSelectedCourseComponents("source"); }

Target:
public void testDeletingComponent() { CourseGroupDAO newCourseGroup = courseDao.newCourseGroup("id", "Title", "Department", "Subunit"); newCourseGroup.setSource("source"); courseDao.save(newCourseGroup); CourseComponentDAO newCourseComponent1 = courseDao.newCourseComponent("test1"); newCourseComponent1.getGroups().add(newCourseGroup); newCourseComponent1.setSource("source"); courseDao.save(newCourseComponent1); CourseComponentDAO newCourseComponent2 = courseDao.newCourseComponent("test2"); newCourseComponent2.getGroups().add(newCourseGroup); newCourseComponent2.setSource("source"); newCourseComponent2.setDeleted(true); courseDao.save(newCourseComponent2); CourseSignupDAO newSignup = courseDao.newSignup("userId", "supervisorId"); newSignup.setGroup(newCourseGroup); newSignup.getComponents().add(newCourseComponent1); courseDao.save(newSignup); try { courseDao.deleteSelectedCourseComponents("source"); } catch (RuntimeException re) { throw re; } }
Source:
public long unread() throws IOException { try { final Item item = this.region.table(DyFriends.TBL) .frame() .through( new QueryValve() .withLimit(1) .withAttributesToGet(DyFriends.ATTR_UNREAD) ) .where(DyFriends.HASH, Conditions.equalTo(this.bout)) .where(DyFriends.RANGE, Conditions.equalTo(this.self)) .iterator().next(); final long unread; if (item.has(DyFriends.ATTR_UNREAD)) { unread = Long.parseLong(item.get(DyFriends.ATTR_UNREAD).getN()); } else { unread = 0L; } return unread; } catch (final NoSuchElementException ex) { throw new RsFailure(ex); } }

Target:
public long unread() throws IOException { final Iterator<Item> iterator = this.region.table(DyFriends.TBL) .frame() .through( new QueryValve() .withLimit(1) .withAttributesToGet(DyFriends.ATTR_UNREAD) ) .where(DyFriends.HASH, Conditions.equalTo(this.bout)) .where(DyFriends.RANGE, Conditions.equalTo(this.self)) .iterator(); if (!iterator.hasNext()) { throw new HttpException( HttpURLConnection.HTTP_NOT_FOUND, new Inbox.BoutNotFoundException(this.bout) ); } final Item item = iterator.next(); final long unread; if (item.has(DyFriends.ATTR_UNREAD)) { unread = Long.parseLong(item.get(DyFriends.ATTR_UNREAD).getN()); } else { unread = 0L; } return unread; }
Source:
public LookupExtractor get() { final Map<String, String> map = Preconditions.checkNotNull(mapRef.get(), "Not started"); final long startCount = doubleEventCount.get(); return new MapLookupExtractor(map, false) { @Override public byte[] getCacheKey() { final byte[] idutf8 = StringUtils.toUtf8(factoryId); if (startCount == doubleEventCount.get()) { return ByteBuffer .allocate(idutf8.length + 1 + Longs.BYTES) .put(idutf8) .put((byte) 0xFF) .putLong(startCount) .array(); } else { final byte[] scrambler = StringUtils.toUtf8(UUID.randomUUID().toString()); return ByteBuffer .allocate(idutf8.length + 1 + scrambler.length + 1) .put(idutf8) .put((byte) 0xFF) .put(scrambler) .put((byte) 0xFF) .array(); } } }; }

Target:
public LookupExtractor get() { final Map<String, String> map = Preconditions.checkNotNull(mapRef.get(), "Not started"); final long startCount = doubleEventCount.get(); return new MapLookupExtractor(map, isOneToOne()) { @Override public byte[] getCacheKey() { final byte[] idutf8 = StringUtils.toUtf8(factoryId); if (startCount == doubleEventCount.get()) { return ByteBuffer .allocate(idutf8.length + 1 + Longs.BYTES) .put(idutf8) .put((byte) 0xFF) .putLong(startCount) .array(); } else { final byte[] scrambler = StringUtils.toUtf8(UUID.randomUUID().toString()); return ByteBuffer .allocate(idutf8.length + 1 + scrambler.length + 1) .put(idutf8) .put((byte) 0xFF) .put(scrambler) .put((byte) 0xFF) .array(); } } }; }
Source:
public CommandCallback getCallback() { return new ConcurrentChildCommandsExecutionCallback(); }

Target:
public CommandCallback getCallback() { return new SysprepVmTemplateJobCallback(); }
Source:
public static void calculateAllSpeeds() { for (Entry<InetAddress, RendererConfiguration> key : addressAssociation.entrySet()) { InetAddress sa = key.getKey(); if (sa.isLoopbackAddress() || sa.isAnyLocalAddress()) { continue; } RendererConfiguration r = key.getValue(); if (!r.isOffline()) { SpeedStats.getInstance().getSpeedInMBits(sa, r.getRendererName()); } } }

Target:
public static void calculateAllSpeeds() { for (Entry<InetAddress, RendererConfiguration> entry : addressAssociation.entrySet()) { InetAddress sa = entry.getKey(); if (sa.isLoopbackAddress() || sa.isAnyLocalAddress()) { continue; } RendererConfiguration r = entry.getValue(); if (!r.isOffline()) { SpeedStats.getInstance().getSpeedInMBits(sa, r.getRendererName()); } } }
Source:
public PeriodicQueryMetadata(String nodeId, VariableOrder varOrder, String parentNodeId, String childNodeId, long windowSize, long period, TimeUnit unit, String temporalVariable) { super(nodeId, varOrder); Preconditions.checkNotNull(parentNodeId); Preconditions.checkNotNull(childNodeId); Preconditions.checkNotNull(temporalVariable); Preconditions.checkNotNull(unit); Preconditions.checkNotNull(period > 0); Preconditions.checkArgument(windowSize >= period); this.parentNodeId = parentNodeId; this.childNodeId = childNodeId; this.temporalVariable = temporalVariable; this.windowSize = windowSize; this.period = period; this.unit = unit; }

Target:
public PeriodicQueryMetadata(String nodeId, VariableOrder varOrder, String parentNodeId, String childNodeId, long windowSize, long period, TimeUnit unit, String temporalVariable) { super(nodeId, varOrder); this.parentNodeId = Preconditions.checkNotNull(parentNodeId); this.childNodeId = Preconditions.checkNotNull(childNodeId); this.temporalVariable = Preconditions.checkNotNull(temporalVariable); this.unit = Preconditions.checkNotNull(unit); Preconditions.checkArgument(period > 0); Preconditions.checkArgument(windowSize >= period); this.windowSize = windowSize; this.period = period; }
Source:
public InMemoryMap(Map<String,Set<ByteSequence>> lggroups, boolean useNativeMap, String memDumpDir) { this.memDumpDir = memDumpDir; this.lggroups = lggroups; if (lggroups.size() == 0) { map = newMap(useNativeMap); mapType = useNativeMap ? "NativeMapWrapper" : "DefaultMap"; } else { map = new LocalityGroupMap(lggroups, useNativeMap); mapType = useNativeMap ? "LocalityGroupMap with native" : "LocalityGroupMap"; } }

Target:
public InMemoryMap(Map<String,Set<ByteSequence>> lggroups, boolean useNativeMap, String memDumpDir) { this.memDumpDir = memDumpDir; this.lggroups = lggroups; if (lggroups.size() == 0) { map = newMap(useNativeMap); mapType = useNativeMap ? TYPE_NATIVE_MAP_WRAPPER : TYPE_DEFAULT_MAP; } else { map = new LocalityGroupMap(lggroups, useNativeMap); mapType = useNativeMap ? TYPE_LOCALITY_GROUP_MAP : TYPE_LOCALITY_GROUP_MAP_NATIVE; } }
Source:
public CqlQueryResponse executeCqlQuery(CqlRequest cqlRequest) throws UnsupportedQueryException, SourceUnavailableException, FederationException { QueryRequest request = cqlRequest.createQueryRequest( catalogFramework.getId(), filterBuilder, cqlRequest.getFacets()); Stopwatch stopwatch = Stopwatch.createStarted(); List<QueryResponse> responses = Collections.synchronizedList(new ArrayList<>()); List<Result> results; if (cqlRequest.getCount() == 0) { results = retrieveHitCount(request, responses); } else { results = retrieveResults(cqlRequest, request, responses); } QueryResponse response = new QueryResponseImpl( request, results, true, responses .stream() .filter(Objects::nonNull) .map(QueryResponse::getHits) .findFirst() .orElse(-1L), responses .stream() .filter(Objects::nonNull) .map(QueryResponse::getProperties) .findFirst() .orElse(Collections.emptyMap())); stopwatch.stop(); return new CqlQueryResponse( cqlRequest.getId(), request, response, cqlRequest.getSource(), stopwatch.elapsed(TimeUnit.MILLISECONDS), cqlRequest.isNormalize(), filterAdapter, actionRegistry); }

Target:
public CqlQueryResponse executeCqlQuery(CqlRequest cqlRequest) throws UnsupportedQueryException, SourceUnavailableException, FederationException { QueryRequest request = cqlRequest.createQueryRequest(catalogFramework.getId(), filterBuilder); Stopwatch stopwatch = Stopwatch.createStarted(); List<QueryResponse> responses = Collections.synchronizedList(new ArrayList<>()); List<Result> results; if (cqlRequest.getCount() == 0) { results = retrieveHitCount(request, responses); } else { results = retrieveResults(cqlRequest, request, responses); } QueryResponse response = new QueryResponseImpl( request, results, true, responses .stream() .filter(Objects::nonNull) .map(QueryResponse::getHits) .findFirst() .orElse(-1L), responses .stream() .filter(Objects::nonNull) .map(QueryResponse::getProperties) .findFirst() .orElse(Collections.emptyMap())); stopwatch.stop(); return new CqlQueryResponse( cqlRequest.getId(), request, response, cqlRequest.getSourceResponseString(), stopwatch.elapsed(TimeUnit.MILLISECONDS), cqlRequest.isNormalize(), filterAdapter, actionRegistry); }
Source:
public void awaitPopulation() throws IOException { applier.writeBarrier().await(); }

Target:
public void awaitPopulation() throws IOException { applier.writeBarrier().awaitCompletion(); }
Source:
private RevCommit parse(final String msg) { final StringBuilder buf = new StringBuilder(); buf.append("tree " + ObjectId.zeroId().name() + "\n"); buf.append("author A. U. Thor <a@example.com> 1 +0000\n"); buf.append("committer A. U. Thor <a@example.com> 1 +0000\n"); buf.append("\n"); buf.append(msg); final RevWalk walk = new RevWalk(db); walk.setRetainBody(true); final RevCommit c = new RevCommit(ObjectId.zeroId()); try { c.parseCanonical(walk, Constants.encode(buf.toString())); } catch (IOException ex) { fail(); } return c; }

Target:
private RevCommit parse(final String msg) throws IOException { final StringBuilder buf = new StringBuilder(); buf.append("tree " + ObjectId.zeroId().name() + "\n"); buf.append("author A. U. Thor <a@example.com> 1 +0000\n"); buf.append("committer A. U. Thor <a@example.com> 1 +0000\n"); buf.append("\n"); buf.append(msg); final RevWalk walk = new RevWalk(db); walk.setRetainBody(true); final RevCommit c = new RevCommit(ObjectId.zeroId()); c.parseCanonical(walk, Constants.encode(buf.toString())); return c; }
Source:
private static void addClassesForPackage(String packageName, ArrayList<Class<?>> classes, File directory) { assert directory != null; File[] files = directory.listFiles(); if ( files == null ) { return; } for ( File file : files ) { if ( file.getAbsolutePath().endsWith( ".class" ) ) { String className = file.getPath().substring( 0, file.getPath().length() - 6 ); className = className.substring( className.lastIndexOf(File.separator) ); try { Class<?> clazz = Class.forName( className ); classes.add( clazz ); } catch( ClassNotFoundException e ) { } } else if ( file.isDirectory() ) { addClassesForPackage( packageName, classes, file ); } } }

Target:
private static void addClassesForPackage(String packageName, ArrayList<Class<?>> classes, File directory) { assert directory != null; File[] files = directory.listFiles(); if ( files == null ) { return; } for ( File file : files ) { if ( file.getAbsolutePath().endsWith( ".class" ) ) { String className = file.getPath().substring( 0, file.getPath().length() - 6 ); className = className.replace( File.separator, "." ); className = className.substring( className.lastIndexOf(File.separator) ); try { Class<?> clazz = Class.forName( className ); classes.add( clazz ); } catch( ClassNotFoundException e ) { } } else if ( file.isDirectory() ) { addClassesForPackage( packageName, classes, file ); } } }
Source:
private void testIssueCreation(InputFile.Type onType, int expectedIssues) throws IOException { MapSettings settings = new MapSettings(); NoSonarFilter noSonarFilter = mock(NoSonarFilter.class); SensorContextTester context = createContext(onType).setRuntime(SonarRuntimeImpl.forSonarLint(Version.create(6, 7))); DefaultFileSystem fs = context.fileSystem(); SonarComponents sonarComponents = createSonarComponentsMock(context); DefaultJavaResourceLocator javaResourceLocator = new DefaultJavaResourceLocator(fs, newJavaClasspath(settings.asConfig(), fs)); PostAnalysisIssueFilter postAnalysisIssueFilter = new PostAnalysisIssueFilter(fs); JavaSquidSensor jss = new JavaSquidSensor(sonarComponents, fs, javaResourceLocator, settings.asConfig(), noSonarFilter, postAnalysisIssueFilter); jss.execute(context); verify(noSonarFilter, times(1)).noSonarInFile(fs.inputFiles().iterator().next(), Sets.newHashSet(97)); verify(sonarComponents, times(expectedIssues)).reportIssue(any(AnalyzerMessage.class)); settings.setProperty(Java.SOURCE_VERSION, "wrongFormat"); jss.execute(context); settings.setProperty(Java.SOURCE_VERSION, "1.7"); jss.execute(context); }

Target:
private void testIssueCreation(InputFile.Type onType, int expectedIssues) throws IOException { MapSettings settings = new MapSettings(); NoSonarFilter noSonarFilter = mock(NoSonarFilter.class); SensorContextTester context = createContext(onType).setRuntime(SonarRuntimeImpl.forSonarLint(Version.create(6, 7))); DefaultFileSystem fs = context.fileSystem(); SonarComponents sonarComponents = createSonarComponentsMock(context); DefaultJavaResourceLocator javaResourceLocator = new DefaultJavaResourceLocator(fs, new JavaClasspath(settings.asConfig(), fs)); PostAnalysisIssueFilter postAnalysisIssueFilter = new PostAnalysisIssueFilter(fs); JavaSquidSensor jss = new JavaSquidSensor(sonarComponents, fs, javaResourceLocator, settings.asConfig(), noSonarFilter, postAnalysisIssueFilter); jss.execute(context); verify(noSonarFilter, times(1)).noSonarInFile(fs.inputFiles().iterator().next(), Sets.newHashSet(96)); verify(sonarComponents, times(expectedIssues)).reportIssue(any(AnalyzerMessage.class)); settings.setProperty(Java.SOURCE_VERSION, "wrongFormat"); jss.execute(context); settings.setProperty(Java.SOURCE_VERSION, "1.7"); jss.execute(context); }
Source:
public void transform(StructuredRecord input, Emitter<KeyValue<Text, NullWritable>> emitter) throws Exception { List<String> dataArray = new ArrayList<>(); for (Schema.Field field : input.getSchema().getFields()) { String data = (input.get(field.getName()) != null) ? input.get(field.getName()).toString() : ""; dataArray.add(data); } emitter.emit(new KeyValue<>(new Text(Joiner.on(",").join(dataArray)), NullWritable.get())); }

Target:
public void transform(StructuredRecord input, Emitter<KeyValue<Text, NullWritable>> emitter) throws Exception { List<String> dataArray = new ArrayList<>(); for (Schema.Field field : input.getSchema().getFields()) { Object fieldValue = input.get(field.getName()); String data = (fieldValue != null) ? fieldValue.toString() : NULL_STRING; dataArray.add(data); } emitter.emit(new KeyValue<>(new Text(Joiner.on(",").join(dataArray)), NullWritable.get())); }
Source:
public void testScreenConfiguration() { WindowManager windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE); Display display = windowManager.getDefaultDisplay(); DisplayMetrics metrics = new DisplayMetrics(); display.getMetrics(metrics); double xInches = (double) metrics.widthPixels / metrics.xdpi; double yInches = (double) metrics.heightPixels / metrics.ydpi; double diagonalInches = Math.sqrt(Math.pow(xInches, 2) + Math.pow(yInches, 2)); assertTrue("Screen diagonal must be at least 2.5 inches: " + diagonalInches, diagonalInches >= 2.5d); double density = 160.0d * metrics.density; assertTrue("Screen density must be at least 100 dpi: " + density, density >= 100.0d); double aspectRatio = (double) Math.max(metrics.widthPixels, metrics.heightPixels) / (double) Math.min(metrics.widthPixels, metrics.heightPixels); assertTrue("Aspect ratio should be between 1.333 (4:3) and 1.779 (16:9): " + aspectRatio, aspectRatio >= 1.333d && aspectRatio <= 1.779d); }

Target:
public void testScreenConfiguration() { WindowManager windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE); Display display = windowManager.getDefaultDisplay(); DisplayMetrics metrics = new DisplayMetrics(); display.getMetrics(metrics); double xInches = (double) metrics.widthPixels / metrics.xdpi; double yInches = (double) metrics.heightPixels / metrics.ydpi; double diagonalInches = Math.sqrt(Math.pow(xInches, 2) + Math.pow(yInches, 2)); assertTrue("Screen diagonal must be at least 2.5 inches: " + diagonalInches, diagonalInches >= 2.5d); double density = 160.0d * metrics.density; assertTrue("Screen density must be at least 100 dpi: " + density, density >= 100.0d); double aspectRatio = (double) Math.max(metrics.widthPixels, metrics.heightPixels) / (double) Math.min(metrics.widthPixels, metrics.heightPixels); assertTrue("Aspect ratio must be between 1.333 (4:3) and 1.779 (16:9): " + aspectRatio, aspectRatio >= 1.333d && aspectRatio <= 1.779d); }
Source:
protected Text createFilterText(Composite parent) { filterText = new Text(parent, SWT.NONE); Dialog.applyDialogFont(filterText); GridData data = new GridData(GridData.FILL_HORIZONTAL); data.horizontalAlignment = GridData.FILL; data.verticalAlignment = GridData.CENTER; filterText.setLayoutData(data); filterText.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.keyCode == SWT.CR) { gotoSelectedElement(); dispose(); } else if (e.keyCode == SWT.ARROW_DOWN) { delegate.getTreeViewer().getTree().setFocus(); } else if (e.character == SWT.ESC) { dispose(); } } }); filterText.setText(""); filterText.addModifyListener(e -> { AtomicBoolean firstMatchFound = new AtomicBoolean(false); TreeViewer viewer = delegate.getTreeViewer(); try { viewer.getControl().setRedraw(false); String text = filterText.getText(); Pattern pattern = Pattern.compile( ".*" + text.replace('?', '.').replaceAll("\\*", "\\.\\*") + ".*", Pattern.CASE_INSENSITIVE); viewer.setFilters(new ViewerFilter() { @Override public boolean select(Viewer v, Object parentElement, Object element) { boolean result = isMatch(text, pattern, element); if (result && element instanceof FileDiffRegion && !firstMatchFound.getAndSet(true)) { viewer.setSelection( new StructuredSelection(element)); } return result; } }); viewer.expandAll(); } finally { viewer.getControl().setRedraw(true); } }); return filterText; }

Target:
protected Text createFilterText(Composite parent) { filterText = new Text(parent, SWT.NONE); Dialog.applyDialogFont(filterText); GridData data = new GridData(GridData.FILL_HORIZONTAL); data.horizontalAlignment = GridData.FILL; data.verticalAlignment = GridData.CENTER; filterText.setLayoutData(data); filterText.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.keyCode == SWT.CR) { gotoSelectedElement(); dispose(); } else if (e.keyCode == SWT.ARROW_DOWN) { delegate.getTreeViewer().getTree().setFocus(); } else if (e.character == SWT.ESC) { dispose(); } } }); filterText.setText(""); filterText.addModifyListener(e -> { AtomicBoolean firstMatchFound = new AtomicBoolean(false); TreeViewer viewer = delegate.getTreeViewer(); try { viewer.getControl().setRedraw(false); String text = filterText.getText(); if (StringUtils.isEmptyOrNull(text)) { viewer.setFilters(); } else { final SearchPattern pattern = new SearchPattern(); pattern.setPattern(text); viewer.setFilters(new ViewerFilter() { @Override public boolean select(Viewer v, Object parentElement, Object element) { boolean result = isMatch(pattern, element); if (result && element instanceof FileDiffRegion && !firstMatchFound.getAndSet(true)) { viewer.setSelection( new StructuredSelection(element)); } return result; } }); } viewer.expandAll(); } finally { viewer.getControl().setRedraw(true); } }); return filterText; }
Source:
public Obs getRevisionObs(Obs initialObs) { return (Obs) sessionFactory.getCurrentSession() .createQuery("from Obs o where o.previousVersion = :id") .setString("id",initialObs.getId().toString()) .uniqueResult(); }

Target:
public Obs getRevisionObs(Obs initialObs) { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Obs.class, "obs"); criteria.add(Restrictions.eq("previousVersion", initialObs)); return (Obs) criteria.uniqueResult(); }
Source:
private RequiresHttpAction handleInvalidCredentials(final WebContext context, final String username, String message, String errorMessage, int errorCode) throws RequiresHttpAction { if (getAjaxRequestResolver().isAjax(context)) { logger.info("AJAX request detected -> returning " + errorCode); return RequiresHttpAction.configurable("AJAX request -> " + errorCode, errorCode, context); } else { String redirectionUrl = CommonHelper.addParameter(this.loginUrl, this.usernameParameter, username); redirectionUrl = CommonHelper.addParameter(redirectionUrl, ERROR_PARAMETER, errorMessage); logger.debug("redirectionUrl: {}", redirectionUrl); logger.debug(message); return RequiresHttpAction.redirect(message, context, redirectionUrl); } }

Target:
private RequiresHttpAction handleInvalidCredentials(final WebContext context, final String username, String message, String errorMessage, int errorCode) throws RequiresHttpAction { if (getAjaxRequestResolver().isAjax(context)) { logger.info("AJAX request detected -> returning " + errorCode); return RequiresHttpAction.status("AJAX request -> " + errorCode, errorCode, context); } else { String redirectionUrl = CommonHelper.addParameter(this.loginUrl, this.usernameParameter, username); redirectionUrl = CommonHelper.addParameter(redirectionUrl, ERROR_PARAMETER, errorMessage); logger.debug("redirectionUrl: {}", redirectionUrl); logger.debug(message); return RequiresHttpAction.redirect(message, context, redirectionUrl); } }
Source:
public AsyncFileAlterationObserver(File fileToObserve, ObjectPersistentStore serializer) { if (fileToObserve == null || serializer == null) { throw new IllegalArgumentException(); } this.serializer = serializer; rootFile = new AsyncFileEntry(fileToObserve); }

Target:
public AsyncFileAlterationObserver(File fileToObserve, ObjectPersistentStore serializer) { if (fileToObserve == null || serializer == null) { throw new IllegalArgumentException("Arguments can not be null"); } this.serializer = serializer; rootFile = new AsyncFileEntry(fileToObserve); }
Source:
public void register(ExtensionBuilder builder) { if (Validate.classExists("javax.ejb.EJB")) { builder.service(TestEnricher.class, EJBInjectionEnricher.class); } }

Target:
public void register(ExtensionBuilder builder) { if (Validate.classExists("jakarta.ejb.EJB")) { builder.service(TestEnricher.class, EJBInjectionEnricher.class); } }
Source:
public PythonEggParser(IFile file) throws IOException, CoreException { setupOptions = new HashMap<String, String>(); variables = new HashMap<String, String>(); if (file.getContents().available() <= 0) return; this.file = file; parse(); }

Target:
public PythonEggParser(IFile file) throws IOException, CoreException { setupOptions = new HashMap<String, String>(); variables = new HashMap<String, String>(); if (file.getContents().available() <= 0) { return; } this.file = file; parse(); }
Source:
public synchronized boolean setRoutingData(Map<String, List<String>> routingData) { if (_leaderElection.isLeader()) { if (_zkClient.isClosed()) { throw new IllegalStateException("ZkClient is closed!"); } if (routingData == null) { throw new IllegalArgumentException("routingData given is null!"); } for (String zkRealm : _zkClient .getChildren(MetadataStoreRoutingConstants.ROUTING_DATA_PATH)) { if (!_zkClient.delete(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + zkRealm)) { LOG.error( "Failed to delete existing routing data in setRoutingData()! Namespace: {}, Realm: {}", _namespace, zkRealm); return false; } } for (Map.Entry<String, List<String>> routingDataEntry : routingData.entrySet()) { String zkRealm = routingDataEntry.getKey(); List<String> shardingKeyList = routingDataEntry.getValue(); ZNRecord znRecord = new ZNRecord(zkRealm); znRecord .setListField(MetadataStoreRoutingConstants.ZNRECORD_LIST_FIELD_KEY, shardingKeyList); try { if (!_zkClient.exists(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + zkRealm)) { _zkClient .createPersistent(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + zkRealm); } _zkClient .writeData(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + zkRealm, znRecord); } catch (Exception e) { LOG.error("Failed to write data in setRoutingData()! Namespace: {}, Realm: {}", _namespace, zkRealm, e); return false; } } return true; } return true; }

Target:
public synchronized boolean setRoutingData(Map<String, List<String>> routingData) { if (_leaderElection.isLeader()) { if (_zkClient.isClosed()) { throw new IllegalStateException("ZkClient is closed!"); } if (routingData == null) { throw new IllegalArgumentException("routingData given is null!"); } for (String zkRealm : _zkClient .getChildren(MetadataStoreRoutingConstants.ROUTING_DATA_PATH)) { if (!_zkClient.delete(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + zkRealm)) { LOG.error( "Failed to delete existing routing data in setRoutingData()! Namespace: {}, Realm: {}", _namespace, zkRealm); return false; } } for (Map.Entry<String, List<String>> routingDataEntry : routingData.entrySet()) { String zkRealm = routingDataEntry.getKey(); List<String> shardingKeyList = routingDataEntry.getValue(); ZNRecord znRecord = new ZNRecord(zkRealm); znRecord .setListField(MetadataStoreRoutingConstants.ZNRECORD_LIST_FIELD_KEY, shardingKeyList); String realmPath = MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + zkRealm; try { if (!_zkClient.exists(realmPath)) { _zkClient.createPersistent(realmPath); } _zkClient.writeData(realmPath, znRecord); } catch (Exception e) { LOG.error("Failed to write data in setRoutingData()! Namespace: {}, Realm: {}", _namespace, zkRealm, e); return false; } } return true; } return true; }