auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static RelDataType toSql(final RelDataTypeFactory typeFactory, RelDataType type) { if (type instanceof RelRecordType) { return typeFactory.createTypeWithNullability( typeFactory.createStructType( type.getFieldList() .stream() .map(field -> toSql(typeFactory, field.getType())) .collect(Collectors.toList()), type.getFieldNames()), type.isNullable()); } else if (type instanceof JavaType) { SqlTypeName sqlTypeName = type.getSqlTypeName(); final RelDataType relDataType; if (sqlTypeName == SqlTypeName.ARRAY) { RelDataType elementType = type.getComponentType() == null <START> ? typeFactory.createSqlType(SqlTypeName.ANY) : type.getComponentType(); <END> relDataType = typeFactory.createArrayType(elementType, -1); } else { relDataType = typeFactory.createSqlType(sqlTypeName); } return typeFactory.createTypeWithNullability(relDataType, type.isNullable()); } return type; }</code><technical_language>need special consideration a nested array, i.e. element type of array is of array</technical_language>

Target:
public static RelDataType toSql(final RelDataTypeFactory typeFactory, RelDataType type) { if (type instanceof RelRecordType) { return typeFactory.createTypeWithNullability( typeFactory.createStructType( type.getFieldList() .stream() .map(field -> toSql(typeFactory, field.getType())) .collect(Collectors.toList()), type.getFieldNames()), type.isNullable()); } else if (type instanceof JavaType) { SqlTypeName sqlTypeName = type.getSqlTypeName(); final RelDataType relDataType; if (SqlTypeUtil.isArray(type)) { RelDataType elementType = type.getComponentType(); if (elementType == null) { elementType = typeFactory.createSqlType(SqlTypeName.ANY); } else { elementType = toSql(typeFactory, elementType); } relDataType = typeFactory.createArrayType(elementType, -1); } else { relDataType = typeFactory.createSqlType(sqlTypeName); } return typeFactory.createTypeWithNullability(relDataType, type.isNullable()); } return type; }
Source:
<code>private void forceRebalance(HelixManager manager, ClusterEventType eventType) { NotificationContext changeContext = new NotificationContext(manager); changeContext.setType(NotificationContext.Type.CALLBACK); String uid = UUID.randomUUID().toString().substring(0, 8); ClusterEvent event = new ClusterEvent(_clusterName, eventType, uid); <START> Optional<String> leaderSession = manager.getSessionIdIfLead(); if (!leaderSession.isPresent()) { logger.warn("Cluster manager is not leader for {}. Event is discarded.", manager.getInstanceName(), manager.getClusterName(), event); return; } event.addAttribute(AttributeName.EVENT_SESSION.name(), leaderSession.get()); <END> event.addAttribute(AttributeName.helixmanager.name(), changeContext.getManager()); event.addAttribute(AttributeName.changeContext.name(), changeContext); event.addAttribute(AttributeName.eventData.name(), new ArrayList<>()); event.addAttribute(AttributeName.AsyncFIFOWorkerPool.name(), _asyncFIFOWorkerPool); enqueueEvent(_taskEventQueue, event); enqueueEvent(_eventQueue, event.clone(uid)); logger.info(String .format("Controller rebalance pipeline triggered with event type: %s for cluster %s", eventType, _clusterName)); }</code><technical_language>In HandleEvent check if sessionId matches expected sessionId, do check here</technical_language>

Target:
private void forceRebalance(HelixManager manager, ClusterEventType eventType) { NotificationContext changeContext = new NotificationContext(manager); changeContext.setType(NotificationContext.Type.CALLBACK); String uid = UUID.randomUUID().toString().substring(0, 8); ClusterEvent event = new ClusterEvent(_clusterName, eventType, uid); event.addAttribute(AttributeName.EVENT_SESSION.name(), changeContext.getManager().getSessionIdIfLead()); event.addAttribute(AttributeName.helixmanager.name(), changeContext.getManager()); event.addAttribute(AttributeName.changeContext.name(), changeContext); event.addAttribute(AttributeName.eventData.name(), new ArrayList<>()); event.addAttribute(AttributeName.AsyncFIFOWorkerPool.name(), _asyncFIFOWorkerPool); enqueueEvent(_taskEventQueue, event); enqueueEvent(_eventQueue, event.clone(uid)); logger.info(String .format("Controller rebalance pipeline triggered with event type: %s for cluster %s", eventType, _clusterName)); }
Source:
<code>public void init(StreamGraph graph, Config config) { MessageStream<PageView> pageViews = graph.getInputStream(INPUT_TOPIC, new JsonSerdeV2<>(PageView.class)); OutputStream<KV<String, Integer>> outputStream = graph.getOutputStream(OUTPUT_TOPIC, new KVSerde<>(new StringSerde(), new IntegerSerde())); pageViews .filter(m -> !FILTER_KEY.equals(m.getUserId())) <START> .window(Windows.keyedSessionWindow(PageView::getUserId, Duration.ofSeconds(3), null, null)) <END> .map(m -> KV.of(m.getKey().getKey(), m.getMessage().size())) .sendTo(outputStream); }</code><technical_language>nice provide actual serdes params meant examples (however undiscoverable)</technical_language>

Target:
public void init(StreamGraph graph, Config config) { MessageStream<PageView> pageViews = graph.getInputStream(INPUT_TOPIC, new JsonSerdeV2<>(PageView.class)); OutputStream<KV<String, Integer>> outputStream = graph.getOutputStream(OUTPUT_TOPIC, new KVSerde<>(new StringSerde(), new IntegerSerde())); pageViews .filter(m -> !FILTER_KEY.equals(m.getUserId())) .window(Windows.keyedSessionWindow(PageView::getUserId, Duration.ofSeconds(3), new StringSerde(), new JsonSerdeV2<>(PageView.class))) .map(m -> KV.of(m.getKey().getKey(), m.getMessage().size())) .sendTo(outputStream); }
Source:
<code>public void refreshAnchorTypes() { <START> this.inputAnchor.setFreshRequiredType(this.getPane().getEnvInstance().buildType("Show a => a"), new TypeScope()); <END> }</code><technical_language>sense DisplayBlock instance of this type making fresh copies of it? This invokes ANTLR parser time</technical_language>

Target:
public void refreshAnchorTypes() { this.inputAnchor.setFreshRequiredType(showConstraint, new TypeScope()); }
Source:
<code>private InputStream getJarFile (CustomProcessorInfo customProcessorInfo, File tarFile) { InputStream is = null; <START> byte[] jarFileBytes = this.getFileAsByteArray(tarFile, customProcessorInfo.getJarFileName()); <END> if (jarFileBytes != null && jarFileBytes.length > 0) { is = new ByteArrayInputStream(jarFileBytes); } else { LOG.warn(customProcessorInfo.getJarFileName() + " not present in tar file: " + tarFile); } return is; }</code><technical_language>remove this. for getFileAsByteArray for calls</technical_language>

Target:
private InputStream getJarFile (CustomProcessorInfo customProcessorInfo, File tarFile) { InputStream is = null; byte[] jarFileBytes = getFileAsByteArray(tarFile, customProcessorInfo.getJarFileName()); if (jarFileBytes != null && jarFileBytes.length > 0) { is = new ByteArrayInputStream(jarFileBytes); } else { LOG.warn(customProcessorInfo.getJarFileName() + " not present in tar file: " + tarFile); } return is; }
Source:
<code>public String getHostFingerprint() throws IOException { <START> return ((EngineSSHClient) _client).getHostFingerprint(); <END> }</code><technical_language>space added</technical_language>

Target:
public String getHostFingerprint() throws IOException { if (_client == null) { throw new ConnectException("SSH is not connected"); } return ((EngineSSHClient)_client).getHostFingerprint(); }
Source:
<code>public FeedsCredentials getCredentials() throws RequestException, IOException { FeedsCredentials fc = getCredentials("/config", CREDENTIALS_PATTERN); <START> if(fc != null) { <END> int presumedUsernameLength = (username != null && !username.isEmpty()) ? username.length() : httpAuthUsername != null ? httpAuthUsername.length() : 0; boolean failedToCheck = false; if(presumedUsernameLength > 0) { if(fc.userID != null && presumedUsernameLength != fc.userID.length()) { if(fc.userID.length() > presumedUsernameLength) { Log.d(TAG, "getCredentials() fc.userID is longer than presumedUsername"); fc.userID = fc.userID.substring(fc.userID.length() - presumedUsernameLength); } else { Log.i(TAG, "getCredentials() fc.userID is shorter than presumedUsername"); failedToCheck = true; } } } else { Log.i(TAG, "getCredentials() no presumedUsername, can't check fc.userID"); failedToCheck = true; } if(failedToCheck) { Log.w(TAG, "getCredentials() if you see this and can't access feeds, " + "check \"feeds user ID\""); } } return fc; }</code><technical_language>else block here, i suggest inverting condition return if fc is null. This move content of this if block some spaces left reduce nesting</technical_language>

Target:
public FeedsCredentials getCredentials() throws RequestException, IOException { FeedsCredentials fc = getCredentials("/config", CREDENTIALS_PATTERN); if(fc == null || fc.userID == null) return fc; int presumedUsernameLength = (username != null && !username.isEmpty()) ? username.length() : httpAuthUsername != null ? httpAuthUsername.length() : 0; boolean failedToCheck = false; if(presumedUsernameLength <= 0) { Log.i(TAG, "getCredentials() no presumedUsername, can't check fc.userID"); failedToCheck = true; } else if(presumedUsernameLength != fc.userID.length()) { if(fc.userID.length() > presumedUsernameLength) { Log.d(TAG, "getCredentials() fc.userID is longer than presumedUsername"); fc.userID = fc.userID.substring(fc.userID.length() - presumedUsernameLength); } else { Log.i(TAG, "getCredentials() fc.userID is shorter than presumedUsername"); failedToCheck = true; } } if(failedToCheck) { Log.w(TAG, "getCredentials() if you see this and can't access feeds, " + "check \"feeds user ID\""); } return fc; }
Source:
<code><R> R executeOnEndPoint(ServiceEndPoint endPoint, ServiceCallback<S, R> callback) throws Exception { S service = null; try { service = _serviceCache.checkOut(endPoint); TimerContext timer = _callbackExecutionTime.time(); try { return callback.call(service); } finally { timer.stop(); } } catch (NoCachedInstancesAvailableException e) { LOG.debug("Service cache exhausted. End point ID: {}", endPoint.getId(), e); throw e; } catch (Exception e) { if (_serviceFactory.isRetriableException(e)) { markEndPointAsBad(endPoint); LOG.debug("Bad end point discovered. End point ID: {}", endPoint.getId(), e); } throw e; } finally { if (service != null) { try { _serviceCache.checkIn(endPoint, service); } catch (Exception e) { <START> LOG.warn("Error returning end point to cache. End point ID: {}", endPoint.getId()); <END> LOG.debug("Exception", e); } } } }</code><technical_language>If this is happen, modify this chatty</technical_language>

Target:
<R> R executeOnEndPoint(ServiceEndPoint endPoint, ServiceCallback<S, R> callback) throws Exception { S service = null; try { service = _serviceCache.checkOut(endPoint); TimerContext timer = _callbackExecutionTime.time(); try { return callback.call(service); } finally { timer.stop(); } } catch (NoCachedInstancesAvailableException e) { LOG.debug("Service cache exhausted. End point ID: {}", endPoint.getId(), e); throw e; } catch (Exception e) { if (_serviceFactory.isRetriableException(e)) { markEndPointAsBad(endPoint); LOG.debug("Bad end point discovered. End point ID: {}", endPoint.getId(), e); } throw e; } finally { if (service != null) { try { _serviceCache.checkIn(endPoint, service); } catch (Exception e) { LOG.warn("Error returning end point to cache. End point ID: {}, {}", endPoint.getId(), e.toString()); LOG.debug("Exception", e); } } } }
Source:
<code>public void findV4() throws Exception { <START> final List<IPv4.Availability> availabilities = Lists.newArrayList(PUBLIC); <END> List<String> dto = Lists.newArrayList("PUBLIC"); context.checking(new Expectations() {{ oneOf(v4Catalog).findAll(); will(returnValue(availabilities)); }}); Reply<?> reply = service.findV4(); assertThat(reply, contains(dto)); assertThat(reply, isOk()); }</code><technical_language>path IPv4.Availability.PUBLIC</technical_language>

Target:
public void findV4() throws Exception { final List<IPv4.Availability> availabilities = Lists.newArrayList(IPv4.Availability.PUBLIC); List<String> dto = Lists.newArrayList("PUBLIC"); context.checking(new Expectations() {{ oneOf(v4Catalog).findAll(); will(returnValue(availabilities)); }}); Reply<?> reply = service.findV4(); assertThat(reply, contains(dto)); assertThat(reply, isOk()); }
Source:
<code>private void storeEnvVars(Map< ? extends Object, ? extends Object > map) { final Set< ? extends Object > keys = map.keySet(); for (Object oKey : keys) { Assert.verify(oKey instanceof String, "Key: '" + String.valueOf(oKey) + "' is not a String"); final String key = (String)oKey; if (key.startsWith(USERDEF_ENV_VAR_PREFIX)) { String value = System.getenv(key); if (value == null) { <START> value = EnvironmentUtils.getProcessOrSystemProperty(key); <END> } final String varName = key.substring(USERDEF_ENV_VAR_PREFIX.length()); store(varName, value); } } }</code><technical_language>this supposed do</technical_language>

Target:
private void storeEnvVars(Map< ? extends Object, ? extends Object > map) { final Set< ? extends Object > keys = map.keySet(); for (Object oKey : keys) { Assert.verify(oKey instanceof String, "Key: '" + String.valueOf(oKey) + "' is not a String"); final String key = (String)oKey; if (key.startsWith(USERDEF_ENV_VAR_PREFIX)) { String value = System.getenv(key); if (value == null) { value = System.getProperty(key); } final String varName = key.substring(USERDEF_ENV_VAR_PREFIX.length()); store(varName, value); } } }
Source:
<code><START> public void validateDate(Date date) throws ValidationException { <END> if (date == null) { String message = "The Date must not be null."; LOG.debug("validateDate, " + message); throw new ValidationException(message); } else { if (LOG.isDebugEnabled()) { LOG.debug("validateDate, found a valid date: " + date); } } }</code><technical_language>I cleaner for this method return true/false log error throw ValidationException. care log a valid value</technical_language>

Target:
public boolean validateDate(Date date) { boolean valid = date != null; if (valid) { LOG.debug("validateDate, found a valid date: " + date); } else { LOG.error("validateDate, found a a null date."); } return valid; }
Source:
<code>public RetryingPrestoThriftServiceProvider(@NonRetrying PrestoThriftServiceProvider original, @ForRetryDriver ListeningScheduledExecutorService retryExecutor, ThriftConnectorConfig config) { this.original = requireNonNull(original, "original is null"); requireNonNull(retryExecutor, "retryExecutor is null"); requireNonNull(config, "config is null"); <START> retryingPrestoThriftServiceStats = new RetryingPrestoThriftServiceStats(); <END> retry = RetryDriver.retry(retryExecutor) .maxAttempts(config.getMaxRetryAttempts()) .stopRetryingWhen(e -> e instanceof PrestoThriftServiceException && !((PrestoThriftServiceException) e).isRetryable()) .withClassifier(RetryingPrestoThriftServiceProvider::classifyException) .exponentialBackoff( config.getMinRetrySleepTime(), config.getMaxRetrySleepTime(), config.getMaxRetryDuration(), config.getRetryScaleFactor()); }</code><technical_language>Initialize in field declaration. Alternatively, inject this export directly, removing need for method below</technical_language>

Target:
public RetryingPrestoThriftServiceProvider(@NonRetrying PrestoThriftServiceProvider original, @ForRetryDriver ListeningScheduledExecutorService retryExecutor, ThriftConnectorConfig config) { this.original = requireNonNull(original, "original is null"); requireNonNull(retryExecutor, "retryExecutor is null"); requireNonNull(config, "config is null"); retry = RetryDriver.retry(retryExecutor) .maxAttempts(config.getMaxRetryAttempts()) .stopRetryingWhen(e -> e instanceof PrestoThriftServiceException && !((PrestoThriftServiceException) e).isRetryable()) .withClassifier(RetryingPrestoThriftServiceProvider::classifyException) .exponentialBackoff( config.getMinRetrySleepTime(), config.getMaxRetrySleepTime(), config.getMaxRetryDuration(), config.getRetryScaleFactor()); }
Source:
<code>public void whenLogin_thenUseUserCache() throws Exception { assertThat(userCache.size()).isEqualTo(0); ResponseEntity<String> response = restTemplate .withBasicAuth("user", "pass") .getForEntity(getLanguageUrl(), String.class); assertThat(response.getBody()).contains("english"); assertThat(userCache.size()).isEqualTo(1); HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.add("Cookie", response.getHeaders().getFirst(HttpHeaders.SET_COOKIE)); response = restTemplate <START> .exchange(getLanguageUrl(), HttpMethod.GET, new HttpEntity(requestHeaders), String.class); <END> assertThat(response.getBody()).contains("english"); response = restTemplate.exchange(getLogoutUrl(), HttpMethod.GET, new HttpEntity(requestHeaders), String.class); assertThat(response.getStatusCode().value()).isEqualTo(200); }</code><technical_language>new HttpEntity<String> avoid warnings</technical_language>

Target:
public void whenLogin_thenUseUserCache() { assertThat(userCache.size()).isEqualTo(0); ResponseEntity<String> response = restTemplate.withBasicAuth("user", "pass") .getForEntity(getLanguageUrl(), String.class); assertThat(response.getBody()).contains("english"); assertThat(userCache.size()).isEqualTo(1); HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.add("Cookie", response.getHeaders() .getFirst(HttpHeaders.SET_COOKIE)); response = restTemplate.exchange(getLanguageUrl(), HttpMethod.GET, new HttpEntity<String>(requestHeaders), String.class); assertThat(response.getBody()).contains("english"); response = restTemplate.exchange(getLogoutUrl(), HttpMethod.GET, new HttpEntity<String>(requestHeaders), String.class); assertThat(response.getStatusCode() .value()).isEqualTo(200); }
Source:
<code>public static MultiTokenSchemaDescriptor multiToken( int[] entityTokens, EntityType entityType, int... propertyIds ) { validatePropertyIds( propertyIds ); <START> IntConsumer validator; <END> if ( entityType == EntityType.NODE ) { validator = SchemaDescriptorFactory::validateLabelId; } else { validator = SchemaDescriptorFactory::validateRelationshipTypeLabelId; } for ( int entityToken : entityTokens ) { validator.accept( entityToken ); } return new MultiTokenSchemaDescriptor( entityTokens, entityType, propertyIds ); }</code><technical_language>I this simplified making validation methods accept varargs instead of single id. depending entity type call method</technical_language>

Target:
public static MultiTokenSchemaDescriptor multiToken( int[] entityTokens, EntityType entityType, int... propertyIds ) { validatePropertyIds( propertyIds ); switch ( entityType ) { case NODE: validateLabelIds( entityTokens ); break; case RELATIONSHIP: validateRelationshipTypeIds( entityTokens ); break; default: throw new IllegalArgumentException( "Cannot create schemadescriptor of type :" + entityType ); } return new MultiTokenSchemaDescriptor( entityTokens, entityType, propertyIds ); }
Source:
<code>public boolean isThisType(String name, boolean open) { String id = new Location(name).getAbsolutePath(); <START> File f = new File(id); <END> boolean dirCheck = f.isDirectory(); if (dirCheck) return false; if (name.endsWith(EXPERIMENT_FILE)) return true; if (!open) return false; try { id = locateExperimentFile(id); } catch (FormatException f) { return false; } catch (IOException f) { return false; } catch (NullPointerException e) { return false; } if (id.endsWith(EXPERIMENT_FILE)) { return true; } return super.isThisType(name, open); }</code><technical_language><LINK_0> [ERROR] /home/travis/build/openmicroscopy/bioformats/components/formats-gpl/src/loci/formats/in/BDReader.java:[127,28] variable f is defined in method isThisType(java.lang.String,boolean) [ERROR] /home/travis/build/openmicroscopy/bioformats/components/formats-gpl/src/loci/formats/in/BDReader.java:[130,24] variable f is defined in method isThisType(java.lang.String,boolean)</technical_language>

Target:
public boolean isThisType(String name, boolean open) { Location location = new Location(name); String id = location.getAbsolutePath(); boolean dirCheck = location.isDirectory(); if (dirCheck) return false; if (name.endsWith(EXPERIMENT_FILE)) return true; if (!open) return false; try { id = locateExperimentFile(id); } catch (FormatException f) { return false; } catch (IOException f) { return false; } catch (NullPointerException e) { return false; } if (id.endsWith(EXPERIMENT_FILE)) { return true; } return super.isThisType(name, open); }
Source:
<code>boolean reachedEnd() throws IOException; RowData nextRecord(RowData reuse) throws IOException; default void seekToRow(long rowCount, RowData reuse) throws IOException { for (int i = 0; i < rowCount; i++) { boolean end = reachedEnd(); if (end) { <START> throw new RuntimeException("Seek to many rows."); <END> } nextRecord(reuse); } }</code><technical_language>"Seek rows."</technical_language>

Target:
boolean reachedEnd() throws IOException; RowData nextRecord(RowData reuse) throws IOException; default void seekToRow(long rowCount, RowData reuse) throws IOException { for (int i = 0; i < rowCount; i++) { boolean end = reachedEnd(); if (end) { throw new RuntimeException("Seek too many rows."); } nextRecord(reuse); } }
Source:
<code>private ExecutionResult parseValidateAndExecute(ExecutionInput executionInput) { <START> PreparsedDocumentEntry preparsedDoc = preparsedDocumentProvider.get(executionInput.getQuery(), query -> { <END> ParseResult parseResult = parse(executionInput); if (parseResult.isFailure()) { return new PreparsedDocumentEntry(toInvalidSyntaxError(parseResult.getException())); } else { final Document document = parseResult.getDocument(); final List<ValidationError> errors = validate(executionInput, document); if (!errors.isEmpty()) { return new PreparsedDocumentEntry(errors); } return new PreparsedDocumentEntry(document); } }); if (preparsedDoc.hasErrors()) { return new ExecutionResultImpl(preparsedDoc.getErrors()); } return execute(executionInput, preparsedDoc.getDocument()); }</code><technical_language>write tests for lamba expression</technical_language>

Target:
private ExecutionResult parseValidateAndExecute(ExecutionInput executionInput) { PreparsedDocumentEntry preparsedDoc = preparsedDocumentProvider.get(executionInput.getQuery(), query -> parseAndValidate(executionInput)); if (preparsedDoc.hasErrors()) { return new ExecutionResultImpl(preparsedDoc.getErrors()); } return execute(executionInput, preparsedDoc.getDocument()); }
Source:
<code>public void test(TestHarness th) { this.th = th; Configuration config = Configuration.getConfiguration(); try { TonePlayer tonePlayer = config.getTonePlayer(); tonePlayer.playTone(ToneControl.C4, 500, 100); Thread.sleep(1000); tonePlayer.playTone(ToneControl.C4, 500, 100); Thread.sleep(400); tonePlayer.playTone(ToneControl.C4 + 2, 500, 100); Thread.sleep(400); tonePlayer.stopTone(); <START> } catch (Exception e) { <END> e.printStackTrace(); th.fail("Unexpected exception: " + e); } }</code><technical_language>add a th.check(true) right this line</technical_language>

Target:
public void test(TestHarness th) { Configuration config = Configuration.getConfiguration(); try { TonePlayer tonePlayer = config.getTonePlayer(); tonePlayer.playTone(ToneControl.C4, 500, 100); Thread.sleep(1000); tonePlayer.playTone(ToneControl.C4, 500, 100); Thread.sleep(400); tonePlayer.playTone(ToneControl.C4 + 2, 500, 100); Thread.sleep(400); tonePlayer.stopTone(); th.check(true); } catch (Exception e) { e.printStackTrace(); th.fail("Unexpected exception: " + e); } }
Source:
<code>protected static AggregateLifecycle getInstance() { AggregateLifecycle instance = Scope.getCurrentScope(); <START> if (CurrentUnitOfWork.isStarted()) { <END> UnitOfWork<?> unitOfWork = CurrentUnitOfWork.get(); Set<AggregateLifecycle> managedAggregates = unitOfWork.getResource("ManagedAggregates"); if (managedAggregates != null && managedAggregates.size() == 1) { instance = managedAggregates.iterator().next(); } } return instance; }</code><technical_language>this is semantically correct anymore. lookup of AggregateInstance in UnitOfWork done if a Current Scope defined. If Current Scope is aggregate, precedence</technical_language>

Target:
protected static AggregateLifecycle getInstance() { return Scope.getCurrentScope(); }
Source:
<code>public Collection<RegistryObject<T>> getEntries() { if(entriesView.isEmpty()) { <START> return lazyEntriesView.stream().map(LazyRegistryObject::getRegistryObject).collect(Collectors.toSet()); <END> } return entriesView; }</code><technical_language>is caching lazyEntriesView is exposed externally more sense remove lazyEntriesView do lazyEntries.keySet() (with remainder of line currently is)</technical_language>

Target:
public Collection<RegistryObject<T>> getEntries() { if(entriesView.isEmpty()) { return Collections.unmodifiableSet(lazyEntries.keySet().stream().map(LazyRegistryObject::getRegistryObject).collect(Collectors.toSet())); } return entriesView; }
Source:
<code>@Test public void deleteCollection() { final List<User> allUsers = putUsers(10); final List<User> usersToDelete = new ArrayList<>(); for (int i = 0; i < allUsers.size(); i += 2) { usersToDelete.add(allUsers.get(i)); } final DeleteCollectionOfObjectsResult<User> deleteResult = storIODb .delete() .objects(usersToDelete) .withMapFunc(User.MAP_TO_DELETE_QUERY) .prepare() .executeAsBlocking(); final List<User> existUsers = storIODb .get() .listOfObjects(User.class) .withMapFunc(User.MAP_FROM_CURSOR) .withQuery(new Query.Builder() .table(User.TABLE) .build()) .prepare() .executeAsBlocking(); for (User user : allUsers) { <START> final boolean deleted = usersToDelete.contains(user); <END> assertEquals(deleteResult.results().containsKey(user), deleted); assertEquals(existUsers.contains(user), !deleted); } }</code><technical_language>rename deleted shouldBeDeleted for understanding</technical_language>

Target:
@Test public void deleteCollection() { final List<User> allUsers = putUsers(10); final List<User> usersToDelete = new ArrayList<>(); for (int i = 0; i < allUsers.size(); i += 2) { usersToDelete.add(allUsers.get(i)); } final DeleteCollectionOfObjectsResult<User> deleteResult = storIODb .delete() .objects(usersToDelete) .withMapFunc(User.MAP_TO_DELETE_QUERY) .prepare() .executeAsBlocking(); final List<User> existUsers = getAllUsers(); for (User user : allUsers) { final boolean shouldBeDeleted = usersToDelete.contains(user); assertEquals(shouldBeDeleted, deleteResult.wasDeleted(user)); assertEquals(!shouldBeDeleted, existUsers.contains(user)); } }
Source:
<code>protected TemplateInput extractTemplateInputFromXMLNode(Element node) throws DocumentException { String paramName = getNameFromXMLNode(node); InputType paramType = getTypeFromXMLNode(node); String paramDesc = node.getText(); Boolean isReadonly = getIsReadonlyFromXMLNode(node); Boolean isAutoloop = getIsAutoloopFromXMLNode(node); Object paramValue = node.attributeValue("value"); switch (paramType) { case StringValue: case BooleanValue: break; case DateValue: try { SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT); paramValue = dateFormat.parse((String) paramValue); } catch (ParseException e) { throw new DocumentException(e); } break; case MapValue: case ListValue: LinkedHashMap<String, TemplateInput> listValue = new LinkedHashMap<>(); for (Element childNode : node.elements()) { <START> TemplateInput childParam = extractTemplateInputFromXMLNode(childNode); <END> if (childNode != null) { listValue.put(childParam.getName(), childParam); } } paramValue = listValue; break; default: paramValue = node.attributeValue("source"); } return TemplateInput.factory(paramName, paramType, paramValue, paramDesc, isReadonly, isAutoloop); }</code><technical_language>Map<String, TemplateInput> listValue = new LinkedHashMap<>()</technical_language>

Target:
protected TemplateInput extractTemplateInputFromXMLNode(Element node) throws DocumentException { String paramName = getNameFromXMLNode(node); InputType paramType = getTypeFromXMLNode(node); String paramDesc = node.getText(); Boolean isReadonly = getIsReadonlyFromXMLNode(node); Boolean isAutoloop = getIsAutoloopFromXMLNode(node); Object paramValue = node.attributeValue("value"); switch (paramType) { case StringValue: case BooleanValue: break; case DateValue: try { SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT); paramValue = dateFormat.parse((String) paramValue); } catch (ParseException e) { throw new DocumentException(e); } break; case MapValue: case ListValue: Map<String, TemplateInput> listValue = new LinkedHashMap<>(); for (Element childNode : node.elements()) { TemplateInput childParam = extractTemplateInputFromXMLNode(childNode); if (childNode != null) { listValue.put(childParam.getName(), childParam); } } paramValue = listValue; break; default: paramValue = node.attributeValue("source"); } return TemplateInput.factory(paramName, paramType, paramValue, paramDesc, isReadonly, isAutoloop); }
Source:
<code>IndexMapping(IndexSchemaElement root) { supportedFieldModels = mapSupportedFields( root, "", ignored -> { } ); supportedFieldWithProjectionConverterModels = mapSupportedFields( root, "converted_", c -> c.projectionConverter( ValueWrapper.fromIndexFieldConverter() ) ); string1Field = FieldModel.mapper( String.class, "ccc", "mmm", "xxx" ) .map( root, "string1" ); string2Field = FieldModel.mapper( String.class, "ddd", "nnn", "yyy" ) .map( root, "string2" ); scoreField = FieldModel.mapper( String.class, "scorepattern scorepattern", "scorepattern", "xxx" ) <START> .map( root, "score", c -> ( (StringIndexSchemaFieldTypedContext<?>) c ) <END> .analyzer( DefaultAnalysisDefinitions.ANALYZER_STANDARD.name ) ); flattenedObject = new ObjectMapping( root, "flattenedObject", ObjectFieldStorage.FLATTENED ); nestedObject = new ObjectMapping( root, "nestedObject", ObjectFieldStorage.NESTED ); }</code><technical_language>Instead of casting here, do similar I in org.hibernate.search.integrationtest.backend.tck.search.sort.SearchSortByFieldIT.ByTypeFieldModel pass a lambda .mapper method (when necessary). Note cast in org.hibernate.search.integrationtest.backend.tck.search.sort.SearchSortByFieldIT.ByTypeFieldModel is due a limitation of compiler, cast in practice</technical_language>

Target:
IndexMapping(IndexSchemaElement root) { supportedFieldModels = mapSupportedFields( root, "", ignored -> { } ); supportedFieldWithProjectionConverterModels = mapSupportedFields( root, "converted_", c -> c.projectionConverter( ValueWrapper.fromIndexFieldConverter() ) ); string1Field = FieldModel.mapper( String.class, "ccc", "mmm", "xxx" ) .map( root, "string1" ); string2Field = FieldModel.mapper( String.class, "ddd", "nnn", "yyy" ) .map( root, "string2" ); scoreField = FieldModel.mapper( String.class, c -> c.asString().analyzer( DefaultAnalysisDefinitions.ANALYZER_STANDARD.name ), "scorepattern scorepattern", "scorepattern", "xxx" ) .map( root, "score" ); flattenedObject = new ObjectMapping( root, "flattenedObject", ObjectFieldStorage.FLATTENED ); nestedObject = new ObjectMapping( root, "nestedObject", ObjectFieldStorage.NESTED ); }
Source:
<code>public void removeParticipantInformation(final ParticipantInformation participantInformation) { if (LOG.isTraceEnabled()) { LOG.trace("RecoveryManager.removeParticipantInformation: participantInformation=" + participantInformation); } final RecoveryStore recoveryStore = StoreManager.getRecoveryStore(); String participantId = participantInformation.getId(); if(committedParticipants.get(participantId) != null) { try { recoveryStore.remove_committed(new Uid(participantId), PARTICIPANT_INFORMATION_RECORD_TYPE); committedParticipants.remove(participantId); } catch (ObjectStoreException e) { <START> LOG.warn("Failure while removing participant information from the object store.", e); <END> } } }</code><technical_language>If remove_committed call throws exception participantId is in map code if executed recovery pass exception in log pass. code instead: java if (committedParticipants.remove(participantId) != null) { // key in map removed try { recoveryStore.remove_committed</technical_language>

Target:
public void removeParticipantInformation(final ParticipantInformation participantInformation) { if (LOG.isTraceEnabled()) { LOG.trace("RecoveryManager.removeParticipantInformation: participantInformation=" + participantInformation); } final RecoveryStore recoveryStore = StoreManager.getRecoveryStore(); String participantId = participantInformation.getId(); if(persistedParticipants.get(participantId) != null) { try { recoveryStore.remove_committed(new Uid(participantId), PARTICIPANT_INFORMATION_RECORD_TYPE); persistedParticipants.remove(participantId); } catch (ObjectStoreException ose) { LOG.warn("Failure while removing participant information from the object store.", ose); } } }
Source:
<code>private void assertCanReleaseTask(String taskId) { Task task; try { task = task(taskId); } catch (IllegalStateException ex) { <START> throw new IllegalStateException("The authenticated user cannot release task" + taskId + " due it is not a candidate for it"); <END> } if (task.getAssignee() == null || task.getAssignee().isEmpty()) { throw new IllegalStateException("You cannot release a task that is not claimed"); } String authenticatedUserId = securityManager.getAuthenticatedUserId(); if (!task.getAssignee().equals(authenticatedUserId)) { throw new IllegalStateException("You cannot release a task where you are not the assignee"); } }</code><technical_language>IMO, is need catch this exception rethrow a message. do think</technical_language>

Target:
private void assertCanReleaseTask(String taskId) { Task task = task(taskId); if (task.getAssignee() == null || task.getAssignee().isEmpty()) { throw new IllegalStateException("You cannot release a task that is not claimed"); } String authenticatedUserId = securityManager.getAuthenticatedUserId(); if (!task.getAssignee().equals(authenticatedUserId)) { throw new IllegalStateException("You cannot release a task where you are not the assignee"); } }
Source:
<code>public Collection<DataSegment> getSegments() { <START> return idToSegmentMap.values(); <END> }</code><technical_language>unmodifiableCollection()</technical_language>

Target:
public Collection<DataSegment> getSegments() { return Collections.unmodifiableCollection(idToSegmentMap.values()); }
Source:
<code>private void updateDetails() { issueDetails.getChildren().clear(); TurboIssue issue = guiElement.getIssue(); if (issue.isPullRequest()) { Label icon = new Label(OCTICON_PULL_REQUEST); icon.getStyleClass().addAll("octicon", "issue-pull-request-icon"); issueDetails.getChildren().add(icon); } if (issue.getCommentCount() > 0){ Label commentIcon = new Label(OCTICON_COMMENT); commentIcon.getStyleClass().addAll("octicon", "comments-label-button"); Label commentCount = new Label(Integer.toString(issue.getCommentCount())); issueDetails.getChildren().add(commentIcon); issueDetails.getChildren().add(commentCount); } for (TurboLabel label : guiElement.getLabels()) { issueDetails.getChildren().add(label.getNode()); } if (issue.getMilestone().isPresent() && guiElement.getMilestone().isPresent()) { TurboMilestone milestone = guiElement.getMilestone().get(); issueDetails.getChildren().add(new Label(milestone.getTitle())); } if (issue.isPullRequest()) { HBox authorBox = createDisplayUserBox(guiElement.getAuthor(), issue.getCreator()); authorAssigneeBox.getChildren().add(authorBox); if (issue.getAssignee().isPresent()) { Label rightArrow = new Label(OCTICON_ARROW_RIGHT); rightArrow.getStyleClass().addAll("octicon", "pull-request-assign-icon"); authorAssigneeBox.getChildren().add(rightArrow); } } if (issue.getAssignee().isPresent()) { HBox assigneeBox = createDisplayUserBox(guiElement.getAssignee(), issue.getAssignee().get()); authorAssigneeBox.getChildren().add(assigneeBox); } <START> } <END></code><technical_language>Method long. extract smaller update... methods</technical_language>

Target:
private void updateDetails() { issueDetails.getChildren().clear(); TurboIssue issue = guiElement.getIssue(); addPullRequestIcon(issue); addCommentIcon(issue); addLabels(); addMilestoneIcon(issue); createAuthorBox(issue); createAssigneeBox(issue); }
Source:
<code>public String escapeHeader(final String text) { <START> return text.replace("\r", "\\\r").replace("\n", "\\\n").replace("\\", "\\\\").replace("\"", "\\\""); <END> }</code><technical_language>discussed, existing JavaMail mime utility for unfoldung additionally escaping quote. MimeUtility.quote(...) optionally surrounds result quotations, need remove quotation escapeHeader above. return MimeUtility.quote(MimeUtility.unfold(text), javax.mail.internet.HeaderTokenizer.RFC822);</technical_language>

Target:
private String escapeHeader(final String text) { return MimeUtility.unfold(text).replace("\\", "\\\\").replace("\"", "\\\""); }
Source:
<code>public synchronized @Nullable PcapNgPacket parseNextPacket() throws IOException, BadPcapFileException, BadPacketException { ByteBuffer pcapPacketHeader; ByteBuffer pcapPacketData; pcapPacketHeader = parsePacketHeader(); int blockType = 0; int blockLength = 0; if (pcapPacketHeader != null) { blockType = pcapPacketHeader.getInt(); blockLength = pcapPacketHeader.getInt(); } else { return null; } switch (blockType) { case PcapFileValues.PCAPNG_IDB: pcapPacketData = parsePacketIDBAndNRB(blockLength); break; case PcapFileValues.PCAPNG_SPB: pcapPacketData = parsePacketSPB(pcapPacketHeader, blockLength); break; case PcapFileValues.PCAPNG_NRB: <START> return null; <END> case PcapFileValues.PCAPNG_ISB: parsePacketISB(pcapPacketHeader, blockLength); return null; case PcapFileValues.PCAPNG_PB: case PcapFileValues.PCAPNG_EPB: pcapPacketData = parsePayLoad(pcapPacketHeader, blockLength); break; default:// Invalid block type found throw new BadPcapFileException(String.format("%04x", blockType) + " is an invalid pcapNg block type."); } ++currentRank; TreeMap<Long, Long> fFileIndex = getFileIndex(); SeekableByteChannel fFileChannel = getFileChannel(); fFileIndex.put(currentRank, fFileChannel.position()); setCurrentRank(currentRank); return new PcapNgPacket(this, null, pcapPacketHeader, pcapPacketData, currentRank - 1); }</code><technical_language>I unhandled block skipped instead of returning null this end parsing</technical_language>

Target:
public synchronized @Nullable PcapNgPacket parseNextPacket() throws IOException, BadPcapFileException, BadPacketException { ByteBuffer pcapPacketHeader; ByteBuffer pcapPacketData; pcapPacketHeader = parsePacketHeader(); int blockType = 0; int blockLength = 0; if (pcapPacketHeader != null) { blockType = pcapPacketHeader.getInt(); blockLength = pcapPacketHeader.getInt(); } else { return null; } switch (blockType) { case PcapFileValues.PCAPNG_IDB: pcapPacketData = parsePacketIDBAndNRB(blockLength); break; case PcapFileValues.PCAPNG_SPB: pcapPacketData = parsePacketSPB(pcapPacketHeader, blockLength); break; case PcapFileValues.PCAPNG_NRB: pcapPacketData = parsePacketIDBAndNRB(blockLength); return new PcapNgPacket(this, null, pcapPacketHeader, pcapPacketData, getCurrentRank() - 1); case PcapFileValues.PCAPNG_ISB: pcapPacketData = parsePacketISB(pcapPacketHeader, blockLength); return new PcapNgPacket(this, null, pcapPacketHeader, pcapPacketData, getCurrentRank() - 1); case PcapFileValues.PCAPNG_PB: case PcapFileValues.PCAPNG_EPB: pcapPacketData = parsePayLoad(pcapPacketHeader, blockLength); break; default:// Invalid block type found throw new BadPcapFileException(String.format("%04x", blockType) + " is an invalid pcapNg block type."); } setCurrentRank(getCurrentRank()+1); TreeMap<Long, Long> fileIndex = getFileIndex(); SeekableByteChannel fFileChannel = getFileChannel(); fileIndex.put(getCurrentRank(), fFileChannel.position()); setCurrentRank(getCurrentRank()); return new PcapNgPacket(this, null, pcapPacketHeader, pcapPacketData, getCurrentRank() - 1); }
Source:
<code>private boolean executeWithoutTransaction() { boolean functionReturnValue = false; boolean exceptionOccurred = true; try { logRunningCommand(); if (hasTaskHandlers()) { getCurrentTaskHandler().execute(); } else { executeCommand(); } functionReturnValue = getSucceeded(); exceptionOccurred = false; } catch (VdcBLLException e) { <START> log.error("Command '{}' throw Vdc Bll exception. With error message: {}", <END> getClass().getName(), e.getMessage()); log.debug("Exception", e); processExceptionToClient(new VdcFault(e, e.getVdsError().getCode())); } catch (RuntimeException e) { processExceptionToClient(new VdcFault(e, VdcBllErrors.ENGINE)); log.error("Command '{}' throw exception: {}", getClass().getName(), e.getMessage()); log.error("Exception", e); } finally { if (!exceptionOccurred) { setCommandExecuted(); } if (exceptionOccurred || !getSucceeded()) { clearChildAsyncTasksWithOutVdsmId(); setCommandStatus(CommandStatus.FAILED); setSucceeded(false); compensate(); } else { if (getTaskType() == AsyncTaskType.notSupported && getReturnValue().getVdsmTaskIdList().isEmpty() && getCallBack() == null && commandStatus == CommandStatus.ACTIVE) { setCommandStatus(CommandStatus.SUCCEEDED); } cleanUpCompensationData(); } } return functionReturnValue; }</code><technical_language>Command '{}' failed: {}</technical_language>

Target:
private boolean executeWithoutTransaction() { boolean functionReturnValue = false; boolean exceptionOccurred = true; try { logRunningCommand(); if (hasTaskHandlers()) { getCurrentTaskHandler().execute(); } else { executeCommand(); } functionReturnValue = getSucceeded(); exceptionOccurred = false; } catch (VdcBLLException e) { log.error("Command '{}' failed: {}", getClass().getName(), e.getMessage()); log.debug("Exception", e); processExceptionToClient(new VdcFault(e, e.getVdsError().getCode())); } catch (RuntimeException e) { processExceptionToClient(new VdcFault(e, VdcBllErrors.ENGINE)); log.error("Command '{}' failed: {}", getClass().getName(), e.getMessage()); log.error("Exception", e); } finally { if (!exceptionOccurred) { setCommandExecuted(); } if (exceptionOccurred || !getSucceeded()) { clearChildAsyncTasksWithOutVdsmId(); setCommandStatus(CommandStatus.FAILED); setSucceeded(false); compensate(); } else { if (getTaskType() == AsyncTaskType.notSupported && getReturnValue().getVdsmTaskIdList().isEmpty() && getCallBack() == null && commandStatus == CommandStatus.ACTIVE) { setCommandStatus(CommandStatus.SUCCEEDED); } cleanUpCompensationData(); } } return functionReturnValue; }
Source:
<code>private static boolean isOptionalProperty(Class beanClass, PropertyDescriptor beanProp) { Field field = getField(beanClass, beanProp.getName()); return field != null ? field.getAnnotationsByType(Optional.class).length > 0 <START> || beanProp.getReadMethod().getAnnotationsByType(Optional.class).length > 0 <END> : beanProp.getReadMethod().getAnnotationsByType(Optional.class).length > 0; }</code><technical_language>beanProp.getReadMethod().getAnnotationsByType(Optional.class).length > 0 checked calling getField ? Method getField modifies field reflection optionally recursively calls itself, costly</technical_language>

Target:
private static boolean isOptionalProperty(Class beanClass, PropertyDescriptor beanProp) { if (beanProp.getReadMethod().getAnnotationsByType(Optional.class).length > 0) { return true; } Field field = getField(beanClass, beanProp.getName()); return field != null && field.getAnnotationsByType(Optional.class).length > 0; }
Source:
<code>private void runAutodefineForOneProvider(Guid providerId, int index) { Network externalNetwork = createExternalNetwork(getNetworkName(index), providerId); AddNetworkStoragePoolParameters storagePoolParameters = new AddNetworkStoragePoolParameters(getNetwork().getStoragePoolId(), externalNetwork); storagePoolParameters.setVnicProfileRequired(false); ActionReturnValue returnValue = runInternalAction(ActionType.AddNetworkOnProvider, storagePoolParameters); if (returnValue.getSucceeded()) { <START> Guid networkId = returnValue.getActionReturnValue(); <END> networkHelper.attachNetworkToClusters(networkId, clustersByProvider.get(providerId)); externalNetwork.setId(networkId); networkHelper.addVnicProfileWithoutFilter(externalNetwork, true); } }</code><technical_language>s/networkId/externalNetworkId</technical_language>

Target:
private void runAutodefineForOneProvider(Guid providerId, int index) { try (EngineLock lock = acquireLockForProvider(providerId)) { Network externalNetwork = createExternalNetwork(calcExternalNetworkName(index), providerId); AddNetworkStoragePoolParameters storagePoolParameters = new AddNetworkStoragePoolParameters(getNetwork().getStoragePoolId(), externalNetwork); storagePoolParameters.setVnicProfileRequired(false); ActionReturnValue returnValue = runInternalAction(ActionType.AddNetworkOnProvider, storagePoolParameters); if (returnValue.getSucceeded()) { Guid externalNetworkId = returnValue.getActionReturnValue(); networkHelper.attachNetworkToClusters(externalNetworkId, clustersByProvider.get(providerId)); externalNetwork.setId(externalNetworkId); networkHelper.addVnicProfileWithoutFilter(externalNetwork, true); } } catch (Exception e) { log.error("Exception occurred while acquiring lock for provider: {}", providerId.toString()); log.debug("Exception", e); } }
Source:
<code>Set<T> doGetNextGroup(Set<T> idle, Set<T> active) { <START> if (active.isEmpty()) { <END> return idle; } else { return ImmutableSet.of(); } }</code><technical_language>I copy current BatchStrategy impl of this is same: return active.isEmpty() ? idle : ImmutableSet.of();</technical_language>

Target:
Set<T> doGetNextGroup(Set<T> idle, Set<T> active) { return active.isEmpty() ? idle : ImmutableSet.of(); }
Source:
<code>private double calcTimeoutToFence(int vmCount, VdsSpmStatus spmStatus) { int spmIndicator = 0; if (spmStatus == VdsSpmStatus.SPM) { spmIndicator = 1; } return TimeUnit.SECONDS.toMillis( Config.<Integer> GetValue(ConfigValues.TimeoutToResetVdsInSeconds) + (Config.<Integer> GetValue(ConfigValues.DelayResetForSpmInSeconds) * spmIndicator) + <START> (Config.<Integer> GetValue(ConfigValues.DelayResetPerVmInSeconds) * vmCount)); <END> }</code><technical_language>Integer this field is configured double</technical_language>

Target:
private double calcTimeoutToFence(int vmCount, VdsSpmStatus spmStatus) { int spmIndicator = 0; if (spmStatus == VdsSpmStatus.SPM) { spmIndicator = 1; } return TimeUnit.SECONDS.toMillis((int)( Config.<Integer> GetValue(ConfigValues.TimeoutToResetVdsInSeconds) + (Config.<Double> GetValue(ConfigValues.DelayResetForSpmInSeconds) * spmIndicator) + (Config.<Double> GetValue(ConfigValues.DelayResetPerVmInSeconds) * vmCount))); }
Source:
<code>private Object convertAssociation(Object source, MongoPersistentProperty property) { <START> if (property == null || !property.isAssociation() || source == null || source instanceof DBRef) { <END> return source; } if (source instanceof Iterable) { BasicDBList result = new BasicDBList(); for (Object element : (Iterable<?>) source) { result.add(element instanceof DBRef ? element : converter.toDBRef(element, property)); } return result; } if (property.isMap()) { BasicDBObject result = new BasicDBObject(); DBObject dbObject = (DBObject) source; for (String key : dbObject.keySet()) { Object o = dbObject.get(key); result.put(key, o instanceof DBRef ? o : converter.toDBRef(o, property)); } return result; } return property.isEntity() ? converter.toDBRef(source, property) : source; }</code><technical_language>I simply add a !property.isEntity() here. This catch simply types prevent DBRef creation. creation is necessary if find a complex object</technical_language>

Target:
private Object convertAssociation(Object source, MongoPersistentProperty property) { if (property == null || !property.isAssociation() || source == null || source instanceof DBRef || !property.isEntity()) { return source; } if (source instanceof Iterable) { BasicDBList result = new BasicDBList(); for (Object element : (Iterable<?>) source) { result.add(element instanceof DBRef ? element : converter.toDBRef(element, property)); } return result; } if (property.isMap()) { BasicDBObject result = new BasicDBObject(); DBObject dbObject = (DBObject) source; for (String key : dbObject.keySet()) { Object o = dbObject.get(key); result.put(key, o instanceof DBRef ? o : converter.toDBRef(o, property)); } return result; } return converter.toDBRef(source, property); }