auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
static public void cantSaveAttributeValueDialogBox(Attribute object) { String text = ""; String name = object.getDisplayName(); if (object.getType().equalsIgnoreCase("java.lang.String") || object.getType().equalsIgnoreCase("java.lang.LargeString")) { text = WidgetTranslation.INSTANCE.cantSaveAttributeValueDialogBoxWrongString(name); } else if (object.getType().equalsIgnoreCase("java.lang.Integer")) { text = WidgetTranslation.INSTANCE.cantSaveAttributeValueDialogBoxWrongInteger(name); } else if (object.getType().equalsIgnoreCase("java.util.ArrayList") || object.getType().equalsIgnoreCase("java.util.LargeArrayList")) { text = WidgetTranslation.INSTANCE.cantSaveAttributeValueDialogBoxWrongList(name); } else { text = WidgetTranslation.INSTANCE.cantSaveAttributeValueDialogBoxGeneral(name); } generateAlert(WidgetTranslation.INSTANCE.cantSaveAttributeValueDialogBoxHeader(), text); }

Target:
static public void cantSaveAttributeValueDialogBox(Attribute object) { String text = ""; String name = object.getDisplayName(); if (object.getType().equalsIgnoreCase("java.lang.String") || object.getType().equalsIgnoreCase(Utils.largeStringClassName)) { text = WidgetTranslation.INSTANCE.cantSaveAttributeValueDialogBoxWrongString(name); } else if (object.getType().equalsIgnoreCase("java.lang.Integer")) { text = WidgetTranslation.INSTANCE.cantSaveAttributeValueDialogBoxWrongInteger(name); } else if (object.getType().equalsIgnoreCase("java.util.ArrayList") || object.getType().equalsIgnoreCase(Utils.largeArrayListClassName)) { text = WidgetTranslation.INSTANCE.cantSaveAttributeValueDialogBoxWrongList(name); } else { text = WidgetTranslation.INSTANCE.cantSaveAttributeValueDialogBoxGeneral(name); } generateAlert(WidgetTranslation.INSTANCE.cantSaveAttributeValueDialogBoxHeader(), text); }
Source:
public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof CinderlibCommandParameters)) return false; CinderlibCommandParameters that = (CinderlibCommandParameters) o; return Objects.equals(driverInfo, that.driverInfo) && Objects.equals(extraParams, that.extraParams); }

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof CinderlibCommandParameters)) { return false; } CinderlibCommandParameters that = (CinderlibCommandParameters) o; return Objects.equals(driverInfo, that.driverInfo) && Objects.equals(extraParams, that.extraParams); }
Source:
private void setupTagSplitValues() { if (SEQUENCE_TAG_GROUP.isEmpty()) return; SPLIT_SEQUENCE_TAGS = new ArrayList<>(); SPLIT_QUALITY_TAGS = new ArrayList<>(); SPLIT_SEPARATOR_TAGS = new ArrayList<>(); for (int i = 0; i < SEQUENCE_TAG_GROUP.size(); i++) { SPLIT_SEQUENCE_TAGS.add(SEQUENCE_TAG_GROUP.get(i).trim().split(",")); SPLIT_QUALITY_TAGS.add(QUALITY_TAG_GROUP.isEmpty() ? null : QUALITY_TAG_GROUP.get(i).trim().split(",")); SPLIT_SEPARATOR_TAGS.add(TAG_GROUP_SEPERATOR.isEmpty() ? TAG_SPLIT_DEFAULT_SEP : TAG_GROUP_SEPERATOR.get(i)); } }

Target:
private void setupTagSplitValues() { SPLIT_SEQUENCE_TAGS = new ArrayList<>(); SPLIT_QUALITY_TAGS = new ArrayList<>(); SPLIT_SEPARATOR_TAGS = new ArrayList<>(); for (int i = 0; i < SEQUENCE_TAG_GROUP.size(); i++) { SPLIT_SEQUENCE_TAGS.add(SEQUENCE_TAG_GROUP.get(i).trim().split(",")); SPLIT_QUALITY_TAGS.add(QUALITY_TAG_GROUP.isEmpty() ? null : QUALITY_TAG_GROUP.get(i).trim().split(",")); SPLIT_SEPARATOR_TAGS.add(TAG_GROUP_SEPERATOR.isEmpty() ? TAG_SPLIT_DEFAULT_SEP : TAG_GROUP_SEPERATOR.get(i)); } }
Source:
public void postCollectionDefaultItemReadGroupCreateDefaultItemReadGroupUnAuthorized() throws Exception { ObjectMapper mapper = new ObjectMapper(); GroupRest groupRest = new GroupRest(); MetadataRest metadataRest = new MetadataRest(); metadataRest.put("dc.description", new MetadataValueRest("testingDescription")); metadataRest.put("dc.subject", new MetadataValueRest("testSubject")); groupRest.setMetadata(metadataRest); getClient().perform(post("/api/core/collections/" + collection.getID() + "/itemReadGroup") .content(mapper.writeValueAsBytes(groupRest)) .contentType(contentType)) .andExpect(status().isUnauthorized()); }

Target:
public void postCollectionDefaultItemReadGroupCreateDefaultItemReadGroupUnAuthorized() throws Exception { ObjectMapper mapper = new ObjectMapper(); GroupRest groupRest = new GroupRest(); MetadataRest metadataRest = new MetadataRest(); metadataRest.put("dc.description", new MetadataValueRest("testingDescription")); metadataRest.put("dc.subject", new MetadataValueRest("testSubject")); groupRest.setMetadata(metadataRest); getClient().perform(post("/api/core/collections/" + collection.getID() + "/itemReadGroup") .content(mapper.writeValueAsBytes(groupRest)) .contentType(contentType)) .andExpect(status().isUnauthorized()); String token = getAuthToken(admin.getEmail(), password); Group anon = groupService.findByName(context, Group.ANONYMOUS); getClient(token).perform(get("/api/core/collections/" + collection.getID() + "/itemReadGroup")) .andExpect(status().isOk()) .andExpect( jsonPath("$", GroupMatcher.matchGroupEntry(anon.getID(), anon.getName()))); }
Source:
private void assertColumnList(List<com.amazonaws.services.glue.model.Column> actual, List<Column> expected) { if (expected == null) { assertNull(actual); } assertEquals(actual.size(), expected.size()); for (int i = 0; i < expected.size(); i++) { assertColumn(actual.get(i), expected.get(i)); } }

Target:
private static void assertColumnList(List<com.amazonaws.services.glue.model.Column> actual, List<Column> expected) { if (expected == null) { assertNull(actual); } assertEquals(actual.size(), expected.size()); for (int i = 0; i < expected.size(); i++) { assertColumn(actual.get(i), expected.get(i)); } }
Source:
@Override protected By buildMobileNativeBy() { AnnotatedElement annotatedElement = annotatedElementContainer.getAnnotated(); HowToUseLocators howToUseLocators = annotatedElement.getAnnotation(HowToUseLocators.class); By result = null; if (isSelendroidAutomation()) { result = buildMobileBy(howToUseLocators != null ? howToUseLocators.selendroidAutomation() : null, getBys(SelendroidFindBy.class, SelendroidFindBys.class, SelendroidFindAll.class)); } if (isAndroid() && result == null) { result = buildMobileBy(howToUseLocators != null ? howToUseLocators.androidAutomation() : null, getBys(AndroidFindBy.class, AndroidFindBys.class, AndroidFindAll.class)); } if (isIOSXcuit() && result == null) { result = buildMobileBy(howToUseLocators != null ? howToUseLocators.iOSXCUITAutomation() : null, getBys(iOSXCUITFindBy.class, iOSXCUITFindBys.class, iOSXCUITFindAll.class)); } if (isIOS() && result == null) { result = buildMobileBy(howToUseLocators != null ? howToUseLocators.iOSAutomation() : null, getBys(iOSFindBy.class, iOSFindBys.class, iOSFindAll.class)); } if (isWindows() && result == null) { result = buildMobileBy(howToUseLocators != null ? howToUseLocators.windowsAutomation() : null, getBys(WindowsFindBy.class, WindowsFindBys.class, WindowsFindAll.class)); } return ofNullable(result).orElse(null); }

Target:
protected By buildMobileNativeBy() { AnnotatedElement annotatedElement = annotatedElementContainer.getAnnotated(); HowToUseLocators howToUseLocators = annotatedElement.getAnnotation(HowToUseLocators.class); Optional<HowToUseLocators> howToUseLocatorsOptional = ofNullable(howToUseLocators); By result = null; if (isSelendroidAutomation()) { result = buildMobileBy(howToUseLocatorsOptional .map(HowToUseLocators::selendroidAutomation).orElse(null), getBys(SelendroidFindBy.class, SelendroidFindBys.class, SelendroidFindAll.class)); } if (isAndroid() && result == null) { return buildMobileBy(howToUseLocatorsOptional.map(HowToUseLocators::androidAutomation).orElse(null), getBys(AndroidFindBy.class, AndroidFindBys.class, AndroidFindAll.class)); } if (isIOSXcuit()) { result = buildMobileBy(howToUseLocatorsOptional.map(HowToUseLocators::iOSXCUITAutomation).orElse(null), getBys(iOSXCUITFindBy.class, iOSXCUITFindBys.class, iOSXCUITFindAll.class)); } if (isIOS() && result == null) { return buildMobileBy(howToUseLocatorsOptional.map(HowToUseLocators::iOSAutomation).orElse(null), getBys(iOSFindBy.class, iOSFindBys.class, iOSFindAll.class)); } if (isWindows()) { return buildMobileBy(howToUseLocatorsOptional.map(HowToUseLocators::windowsAutomation).orElse(null), getBys(WindowsFindBy.class, WindowsFindBys.class, WindowsFindAll.class)); } return ofNullable(result).orElse(null); }
Source:
public void spec302_mustAllowSynchronousRequestCallsFromOnNextAndOnSubscribe_shouldFailBy_reportingAsyncError() throws Throwable { requireTestFailure(new ThrowingRunnable() { @Override public void run() throws Throwable { onErroringPublisherVerification().spec302_mustAllowSynchronousRequestCallsFromOnNextAndOnSubscribe(); } }, "Async error during test execution: "); }

Target:
public void spec302_mustAllowSynchronousRequestCallsFromOnNextAndOnSubscribe_shouldFailBy_reportingAsyncError() throws Throwable { requireTestFailure(new ThrowingRunnable() { @Override public void run() throws Throwable { onErroringPublisherVerification().spec302_mustAllowSynchronousRequestCallsFromOnNextAndOnSubscribe(); } }, "Async error during test execution: Test Exception: Boom!"); }
Source:
private static String getOutFile() { return System.getProperty("redirect.stdout.to.file"); }

Target:
private static String getOutFile() { return System.getProperty("go.redirect.stdout.to.file"); }
Source:
public void visitToken(DetailAST ast) { if (isMultilineComment(ast) && JavadocUtil.isJavadocComment(ast)) { final String commentContent = JavadocUtil.getJavadocCommentContent(ast); final int blankLines = countBlankLines(commentContent); if (blankLines >= 0) { if (location == JavadocContentLocation.FIRST_LINE) { if (blankLines != 0) { log(ast, MSG_JAVADOC_CONTENT_FIRST_LINE); } } else if (blankLines != 1) { log(ast, MSG_JAVADOC_CONTENT_SECOND_LINE); } } } }

Target:
public void visitToken(DetailAST ast) { if (isMultilineComment(ast) && JavadocUtil.isJavadocComment(ast)) { final String commentContent = JavadocUtil.getJavadocCommentContent(ast); final int indexOfFirstNonBlankLine = findIndexOfFirstNonBlankLine(commentContent); if (indexOfFirstNonBlankLine >= 0) { if (location == JavadocContentLocationOption.FIRST_LINE) { if (indexOfFirstNonBlankLine != 0) { log(ast, MSG_JAVADOC_CONTENT_FIRST_LINE); } } else if (indexOfFirstNonBlankLine != 1) { log(ast, MSG_JAVADOC_CONTENT_SECOND_LINE); } } } }
Source:
private RelNode createUnionAll(RelOptCluster cluster, RelNode input, RexNode op1, RexNode op2) { RelBuilder builder = relBuilderFactory.create(cluster, null); builder.push(input).filter(op1); builder.push(input).filter(RexUtil.andNot(cluster.getRexBuilder(), op2, op1)); return builder.union(true).build(); }

Target:
private RelNode createUnionAll(RelOptCluster cluster, RelNode input, RexNode op1, RexNode op2) { final RelBuilder builder = relBuilderFactory.create(cluster, null); final RexBuilder rexBuilder = cluster.getRexBuilder(); builder.push(input).filter(op1); builder.push(input).filter( builder.and(op2, rexBuilder.makeCall(op1.getType(), SqlStdOperatorTable.CASE, ImmutableList.of( rexBuilder.makeCall(SqlStdOperatorTable.IS_NOT_NULL, op1), RexUtil.not(op1), rexBuilder.makeLiteral(true)) ) ) ); return builder.union(true).build(); }
Source:
public boolean performDrop(Object data) { Object target = getCurrentTarget(); if (target == null) target = filters; FilterCopy[] toDrop = (FilterCopy[]) data; if (target instanceof FilterCopy) { for (FilterCopy filterCopy : toDrop) if (filterCopy.equals(target) || ((FilterCopy) target).hasParent(filterCopy)) return false; } for (FilterCopy filterCopy : toDrop) { if (target instanceof Filters) filters.add(filterCopy); if (target instanceof String) { FilterTypeUtil.setValue(filterCopy, FilterTypeUtil.MODE, target.equals(includeOnlyGroup) ? 0 : 1); addToTopLevelFilters(filterCopy); } if (target instanceof FilterCopy) ((FilterCopy) target).addChild(filterCopy); filterView.refresh(); filterView.reveal(filterCopy); } return true; }

Target:
public boolean performDrop(Object data) { Object target = getCurrentTarget(); if (target == null) target = filters; FilterCopy[] toDrop = (FilterCopy[]) data; if (target instanceof FilterCopy) { for (FilterCopy filterToDrop : toDrop) if (filterToDrop.equals(target) || ((FilterCopy) target).hasParent(filterToDrop)) return false; } for (FilterCopy filterToDrop : toDrop) { if (target instanceof Filters) filters.add(filterToDrop); if (target instanceof String) { FilterTypeUtil.setValue(filterToDrop, FilterTypeUtil.MODE, target.equals(includeOnlyGroup) ? 0 : 1); addToTopLevelFilters(filterToDrop); } if (target instanceof FilterCopy) ((FilterCopy) target).addChild(filterToDrop); filterView.refresh(); filterView.reveal(filterToDrop); } return true; }
Source:
ActiveTaskCreator(final InternalTopologyBuilder builder, final StreamsConfig config, final StreamsMetricsImpl streamsMetrics, final StateDirectory stateDirectory, final ChangelogReader storeChangelogReader, final ThreadCache cache, final Time time, final KafkaClientSupplier clientSupplier, final String threadId, final Logger log) { this.builder = builder; this.config = config; this.streamsMetrics = streamsMetrics; this.stateDirectory = stateDirectory; this.storeChangelogReader = storeChangelogReader; this.cache = cache; this.time = time; this.clientSupplier = clientSupplier; this.threadId = threadId; this.log = log; createTaskSensor = ThreadMetrics.createTaskSensor(threadId, streamsMetrics); applicationId = config.getString(StreamsConfig.APPLICATION_ID_CONFIG); if (EXACTLY_ONCE.equals(config.getString(StreamsConfig.PROCESSING_GUARANTEE_CONFIG))) { threadProducer = null; taskProducers = new HashMap<>(); } else { log.info("Creating thread producer client"); final String threadProducerClientId = getThreadProducerClientId(threadId); final Map<String, Object> producerConfigs = config.getProducerConfigs(threadProducerClientId); final String logPrefix = String.format("stream-thread [%s] ", Thread.currentThread().getName()); final LogContext logContext = new LogContext(logPrefix); threadProducer = clientSupplier.getProducer(producerConfigs); taskProducers = Collections.emptyMap(); } }

Target:
ActiveTaskCreator(final InternalTopologyBuilder builder, final StreamsConfig config, final StreamsMetricsImpl streamsMetrics, final StateDirectory stateDirectory, final ChangelogReader storeChangelogReader, final ThreadCache cache, final Time time, final KafkaClientSupplier clientSupplier, final String threadId, final Logger log) { this.builder = builder; this.config = config; this.streamsMetrics = streamsMetrics; this.stateDirectory = stateDirectory; this.storeChangelogReader = storeChangelogReader; this.cache = cache; this.time = time; this.clientSupplier = clientSupplier; this.threadId = threadId; this.log = log; createTaskSensor = ThreadMetrics.createTaskSensor(threadId, streamsMetrics); applicationId = config.getString(StreamsConfig.APPLICATION_ID_CONFIG); if (EXACTLY_ONCE.equals(config.getString(StreamsConfig.PROCESSING_GUARANTEE_CONFIG))) { threadProducer = null; taskProducers = new HashMap<>(); } else { log.info("Creating thread producer client"); final String threadProducerClientId = getThreadProducerClientId(threadId); final Map<String, Object> producerConfigs = config.getProducerConfigs(threadProducerClientId); threadProducer = clientSupplier.getProducer(producerConfigs); taskProducers = Collections.emptyMap(); } }
Source:
public void successRationMetrics() { navigation.selectRow().invoke("View"); Application.waitUntilVisible(); MetricsAreaFragment metricsArea = tmPage.getSuccessRationMetricsArea(); double expectedCommittedPercentage = metricsArea.getPercentage(COMMITTED, NUMBER_OF_TRANSACTIONS); double expectedAbortedPercentage = metricsArea.getPercentage(ABORTED, NUMBER_OF_TRANSACTIONS); double expectedTimedOutPercentage = metricsArea.getPercentage(TIMED_OUT, NUMBER_OF_TRANSACTIONS); MetricsFragment committedMetrics = metricsArea.getMetricsFragment(COMMITTED); MetricsFragment abortedMetrics = metricsArea.getMetricsFragment(ABORTED); MetricsFragment timedOutMetrics = metricsArea.getMetricsFragment(TIMED_OUT); assertEquals(expectedCommittedPercentage, committedMetrics.getPercentage(), DELTA); assertEquals(expectedAbortedPercentage, abortedMetrics.getPercentage(), DELTA); assertEquals(expectedTimedOutPercentage, timedOutMetrics.getPercentage(), DELTA); }

Target:
public void successRationMetrics() { MetricsAreaFragment metricsArea = tmPage.getSuccessRationMetricsArea(); double expectedCommittedPercentage = metricsArea.getPercentage(COMMITTED, NUMBER_OF_TRANSACTIONS); double expectedAbortedPercentage = metricsArea.getPercentage(ABORTED, NUMBER_OF_TRANSACTIONS); double expectedTimedOutPercentage = metricsArea.getPercentage(TIMED_OUT, NUMBER_OF_TRANSACTIONS); MetricsFragment committedMetrics = metricsArea.getMetricsFragment(COMMITTED); MetricsFragment abortedMetrics = metricsArea.getMetricsFragment(ABORTED); MetricsFragment timedOutMetrics = metricsArea.getMetricsFragment(TIMED_OUT); assertEquals(expectedCommittedPercentage, committedMetrics.getPercentage(), DELTA); assertEquals(expectedAbortedPercentage, abortedMetrics.getPercentage(), DELTA); assertEquals(expectedTimedOutPercentage, timedOutMetrics.getPercentage(), DELTA); }
Source:
private <ReturnType> ReturnType uploadFile(final String fileToUpload, final String uri, final String contentType, final String createdBy, final String reason, final String comment, final Class<ReturnType> followUpClass) throws KillBillClientException { Preconditions.checkNotNull(fileToUpload, "fileToUpload cannot be null"); final File catalogFile = new File(fileToUpload); Preconditions.checkArgument(catalogFile.exists() && catalogFile.isFile() && catalogFile.canRead(), "file to upload needs to be a valid file"); try { final InputStream fileStream = Files.asByteSource(catalogFile).openStream(); return uploadFile(fileStream, uri, contentType, createdBy, reason, comment, followUpClass); } catch (IOException e) { throw new KillBillClientException(e); } }

Target:
private <ReturnType> ReturnType uploadFile(final String fileToUpload, final String uri, final String contentType, final String createdBy, final String reason, final String comment, final Class<ReturnType> followUpClass) throws KillBillClientException { Preconditions.checkNotNull(fileToUpload, "fileToUpload cannot be null"); final File catalogFile = new File(fileToUpload); Preconditions.checkArgument(catalogFile.exists() && catalogFile.isFile() && catalogFile.canRead(), "file to upload needs to be a valid file"); try { final String body = Files.toString(catalogFile, Charset.forName("UTF-8")); return doUploadFile(body, uri, contentType, createdBy, reason, comment, followUpClass); } catch (IOException e) { throw new KillBillClientException(e); } }
Source:
public static PipelineTriggerService.EnvironmentVariable fromJSON(JsonReader jsonReader) { if (jsonReader == null) { return null; } String name = jsonReader.getString("name"); String value = jsonReader.optString("value").orElse(null); Boolean secure = jsonReader.optBoolean("secure").orElse(false); String encryptedValue = jsonReader.optString("encrypted_value").orElse(null); if (!StringUtils.isBlank(value) && !StringUtils.isBlank(encryptedValue)) throw new JsonParseException(String.format("Environment variable '%s' has both value and encryptedValue defined.", name)); return new PipelineTriggerService.EnvironmentVariable(name, value, encryptedValue, secure); }

Target:
public static EnvironmentVariableConfig fromJSON(JsonReader jsonReader) { String name = jsonReader.getString("name"); Boolean secure = jsonReader.optBoolean("secure").orElse(false); String value = secure ? jsonReader.optString("value").orElse(null) : jsonReader.getString("value"); String encryptedValue = jsonReader.optString("encrypted_value").orElse(null); try { EnvironmentVariableConfig environmentVariableConfig = new EnvironmentVariableConfig(); environmentVariableConfig.deserialize(name, value, secure, encryptedValue); return environmentVariableConfig; } catch (InvalidCipherTextException e) { throw new InvalidGoCipherTextException(e.getMessage(), e); } }
Source:
private OrcCorruptionException propagate(Throwable throwable, String message) { propagateIfPossible(throwable, InvalidFunctionArgumentException.class); propagateIfPossible(throwable, NotSupportedException.class); propagateIfPossible(throwable, GenericInternalException.class); return new OrcCorruptionException(throwable, orcDataSourceId, message); }

Target:
private OrcCorruptionException propagate(Throwable throwable, String message) { return new OrcCorruptionException(throwable, orcDataSourceId, message); }
Source:
public void testCancelFirmwareUpdateIntheMiddleOfUpdate() { final long stepsTime = 200; final int numberOfSteps = SEQUENCE.length; final AtomicBoolean isUpdateFinished = new AtomicBoolean(false); doAnswer(invocation -> { ProgressCallback progressCallback = (ProgressCallback) invocation.getArguments()[1]; progressCallback.defineSequence(SEQUENCE); for(int updateStepsCount=0; updateStepsCount < numberOfSteps; updateStepsCount++) { progressCallback.next(); Thread.sleep(stepsTime); } progressCallback.success(); isUpdateFinished.set(true); return null; }).when(handler1).updateFirmware(any(Firmware.class), any(ProgressCallback.class)); firmwareUpdateService.updateFirmware(THING1_UID, FW112_EN.getUID(), null); firmwareUpdateService.cancelFirmwareUpdate(THING1_UID); waitForAssert(() -> { verify(handler1, times(1)).cancel(); },stepsTime * numberOfSteps,50); assertThat("Cancel should stop long running updates", isUpdateFinished.get(), is(false)); }

Target:
public void testCancelFirmwareUpdateIntheMiddleOfUpdate() { final long stepsTime = 10; final int numberOfSteps = SEQUENCE.length; final AtomicBoolean isUpdateFinished = new AtomicBoolean(false); doAnswer(invocation -> { ProgressCallback progressCallback = (ProgressCallback) invocation.getArguments()[1]; progressCallback.defineSequence(SEQUENCE); for (int updateStepsCount = 0; updateStepsCount < numberOfSteps; updateStepsCount++) { progressCallback.next(); Thread.sleep(stepsTime); } progressCallback.success(); isUpdateFinished.set(true); return null; }).when(handler1).updateFirmware(any(Firmware.class), any(ProgressCallback.class)); firmwareUpdateService.updateFirmware(THING1_UID, FW112_EN.getUID(), null); firmwareUpdateService.cancelFirmwareUpdate(THING1_UID); waitForAssert(() -> { verify(handler1, times(1)).cancel(); }, stepsTime * numberOfSteps, stepsTime); assertThat(isUpdateFinished.get(), is(false)); }
Source:
private Object fetchObjects(Environment context) { if(context.data.isPresent()) { throw new BadRequestException("FETCH must not include data"); } if (context.isRoot()) { Class<?> loadClass = getRecordType(context.requestScope, context.outputType); return fetchObject(context.requestScope, loadClass, context.ids, context.sort, context.offset, context.first, context.filters); } else { return fetchObject(context.requestScope.getDictionary(), context.parentResource, context.field.getName()); } }

Target:
private Object fetchObjects(Environment context) { if(context.data.isPresent()) { throw new BadRequestException("FETCH must not include data"); } Class<?> entityClass; EntityDictionary dictionary = context.requestScope.getDictionary(); if(context.parentResource != null) { entityClass = dictionary.getLoadClass(context.parentResource.getResourceClass(), context.field.getName()); } else { entityClass = dictionary.getLoadClass(null, context.field.getName()); } if (context.isRoot()) { return fetchObject(context.requestScope, entityClass, context.ids, context.sort, context.offset, context.first, context.filters); } else { return fetchObject(context.requestScope.getDictionary(), context.ids, context.parentResource, context.field.getName()); } }
Source:
private void service() throws IOException { if (biDirectionalPipe) sendAdvertisedRefs(new PacketLineOutRefAdvertiser(pckOut)); else if (requestValidator instanceof AnyRequestValidator) advertised = Collections.emptySet(); else advertised = refIdSet(getAdvertisedOrDefaultRefs().values()); boolean sendPack; try { recvWants(); if (wantIds.isEmpty()) { preUploadHook.onBeginNegotiateRound(this, wantIds, 0); preUploadHook.onEndNegotiateRound(this, wantIds, 0, 0, false); return; } if (options.contains(OPTION_MULTI_ACK_DETAILED)) { multiAck = MultiAck.DETAILED; noDone = options.contains(OPTION_NO_DONE); } else if (options.contains(OPTION_MULTI_ACK)) multiAck = MultiAck.CONTINUE; else multiAck = MultiAck.OFF; if (depth != 0) processShallow(); else if (!clientShallowCommits.isEmpty()) walk.assumeShallow(clientShallowCommits); sendPack = negotiate(); } catch (PackProtocolException err) { reportErrorDuringNegotiate(err.getMessage()); throw err; } catch (ServiceMayNotContinueException err) { if (!err.isOutput() && err.getMessage() != null) { try { pckOut.writeString("ERR " + err.getMessage() + "\n"); err.setOutput(); } catch (Throwable err2) { } } throw err; } catch (IOException err) { reportErrorDuringNegotiate(JGitText.get().internalServerError); throw err; } catch (RuntimeException err) { reportErrorDuringNegotiate(JGitText.get().internalServerError); throw err; } catch (Error err) { reportErrorDuringNegotiate(JGitText.get().internalServerError); throw err; } if (sendPack) sendPack(); }

Target:
private void service() throws IOException { if (biDirectionalPipe) sendAdvertisedRefs(new PacketLineOutRefAdvertiser(pckOut)); else if (requestValidator instanceof AnyRequestValidator) advertised = Collections.emptySet(); else advertised = refIdSet(getAdvertisedOrDefaultRefs().values()); boolean sendPack; try { recvWants(); if (wantIds.isEmpty()) { preUploadHook.onBeginNegotiateRound(this, wantIds, 0); preUploadHook.onEndNegotiateRound(this, wantIds, 0, 0, false); return; } if (options.contains(OPTION_MULTI_ACK_DETAILED)) { multiAck = MultiAck.DETAILED; noDone = options.contains(OPTION_NO_DONE); } else if (options.contains(OPTION_MULTI_ACK)) multiAck = MultiAck.CONTINUE; else multiAck = MultiAck.OFF; if (depth != 0) processShallow(); if (!clientShallowCommits.isEmpty()) walk.assumeShallow(clientShallowCommits); sendPack = negotiate(); } catch (PackProtocolException err) { reportErrorDuringNegotiate(err.getMessage()); throw err; } catch (ServiceMayNotContinueException err) { if (!err.isOutput() && err.getMessage() != null) { try { pckOut.writeString("ERR " + err.getMessage() + "\n"); err.setOutput(); } catch (Throwable err2) { } } throw err; } catch (IOException err) { reportErrorDuringNegotiate(JGitText.get().internalServerError); throw err; } catch (RuntimeException err) { reportErrorDuringNegotiate(JGitText.get().internalServerError); throw err; } catch (Error err) { reportErrorDuringNegotiate(JGitText.get().internalServerError); throw err; } if (sendPack) sendPack(); }
Source:
private static String printCommentTree(CommentTreeElement c, int level) { String buffer = ""; for (int i = 0; i < level; i++) { buffer += "\t"; } buffer += c.toString() + "\n"; if (c instanceof Comment) { for (CommentTreeElement child : ((Comment) c).getReplies()) { buffer += printCommentTree(child, level + 1); } } return buffer; }

Target:
private static String printCommentTree(CommentTreeElement c, int level) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < level; i++) { builder.append("\t"); } builder.append(c.toString()); builder.append("\n"); if (c instanceof Comment) { for (CommentTreeElement child : ((Comment) c).getReplies()) { builder.append(printCommentTree(child, level + 1)); } } return builder.toString(); }
Source:
private BundleStateSet getCurrentBundleStates(Set<Feature> features) { BundleStateSet bundleStateSet = new BundleStateSet(); BundleContext context = getContext(); for (Feature curFeature : features) { for (BundleInfo curBundleInfo : curFeature.getBundles()) { Bundle curBundle = context.getBundle(curBundleInfo.getLocation()); if (curBundle == null || curBundle.adapt(BundleRevision.class).getTypes() == BundleRevision.TYPE_FRAGMENT) { continue; } int bundleState = curBundle.getState(); switch (bundleState) { case Bundle.RESOLVED: case Bundle.STARTING: case Bundle.STOPPING: bundleStateSet.addInactiveBundle(curBundle); break; case Bundle.INSTALLED: case Bundle.UNINSTALLED: bundleStateSet.addFailedBundle(curBundle); break; case Bundle.ACTIVE: for (BundleStateService curStateService : bundleStateServices) { LOGGER.trace( "Checking for bundle state of {}.", curStateService.getName(), curBundle.getSymbolicName()); mapBundleState(curBundle, curStateService.getState(curBundle), bundleStateSet); } break; default: bundleStateSet.addActiveBundle(curBundle); break; } } } return bundleStateSet; }

Target:
private BundleStateSet getCurrentBundleStates(Set<Feature> features) { BundleStateSet bundleStateSet = new BundleStateSet(); BundleContext context = getContext(); for (Feature curFeature : features) { for (BundleInfo curBundleInfo : curFeature.getBundles()) { Bundle curBundle = context.getBundle(curBundleInfo.getLocation()); if (curBundle == null || isFragment(curBundle)) { continue; } int bundleState = curBundle.getState(); switch (bundleState) { case Bundle.RESOLVED: case Bundle.STARTING: case Bundle.STOPPING: bundleStateSet.addInactiveBundle(curBundle); break; case Bundle.INSTALLED: case Bundle.UNINSTALLED: bundleStateSet.addFailedBundle(curBundle); break; case Bundle.ACTIVE: for (BundleStateService curStateService : bundleStateServices) { LOGGER.trace( "Checking for bundle state of {}.", curStateService.getName(), curBundle.getSymbolicName()); mapBundleState(curBundle, curStateService.getState(curBundle), bundleStateSet); } break; default: bundleStateSet.addActiveBundle(curBundle); break; } } } return bundleStateSet; }
Source:
public boolean test() { if(this.table!=null&&this.matchers==null&&this.column==null){ return table.rowCount() > 0; }else if(this.table!=null&&this.matchers!=null&&this.column==null){ return search(0,this.table.getHeaders().size()); }else{ return search(this.column.intValue(),this.column.intValue()+1); } }

Target:
public boolean test() { if (this.table != null && this.matcher == null) { return table.rowCount() > 0; } else { return !search().isEmpty(); } }
Source:
private File moveAndScaleImage(File originalImage, boolean shouldScale) { String instanceFolder = mInstancePath.substring(0, mInstancePath.lastIndexOf("/") + 1); String imageFilename = System.currentTimeMillis() + ".jpg"; String finalFilePath = instanceFolder + imageFilename; boolean savedScaledImage = false; if (shouldScale) { ImageWidget currentWidget = (ImageWidget)getPendingWidget(); int maxDimen = currentWidget.getMaxDimen(); if (maxDimen != -1) { savedScaledImage = FileUtils.scaleImage(originalImage, finalFilePath, maxDimen); } } File fileToReturn; if (!savedScaledImage) { File finalFile = new File(finalFilePath); if (!originalImage.renameTo(finalFile)) { fileToReturn = originalImage; Log.e(TAG, "Failed to rename " + originalImage.getAbsolutePath()); } else { fileToReturn = finalFile; Log.i(TAG, "renamed " + originalImage.getAbsolutePath() + " to " + finalFile.getAbsolutePath()); } } else { String rawDirPath = instanceFolder + "/raw"; File rawDir = new File(rawDirPath); if (!rawDir.exists()) { rawDir.mkdir(); } File rawImageFile = new File (rawDirPath + "/" + imageFilename); if (!originalImage.renameTo(rawImageFile)) { fileToReturn = originalImage; Log.e(TAG, "Failed to rename " + originalImage.getAbsolutePath()); } else { fileToReturn = rawImageFile; Log.i(TAG, "renamed " + originalImage.getAbsolutePath() + " to " + rawImageFile.getAbsolutePath()); } } return fileToReturn; }

Target:
private File moveAndScaleImage(File originalImage, boolean shouldScale) throws IOException { String instanceFolder = mInstancePath.substring(0, mInstancePath.lastIndexOf("/") + 1); String extension = FileUtils.getExtension(originalImage.getAbsolutePath()); String imageFilename = System.currentTimeMillis() + "." + extension; String finalFilePath = instanceFolder + imageFilename; boolean savedScaledImage = false; if (shouldScale) { ImageWidget currentWidget = (ImageWidget)getPendingWidget(); int maxDimen = currentWidget.getMaxDimen(); if (maxDimen != -1) { savedScaledImage = FileUtils.scaleImage(originalImage, finalFilePath, maxDimen); } } if (!savedScaledImage) { File finalFile = new File(finalFilePath); if (!originalImage.renameTo(finalFile)) { throw new IOException("Failed to rename " + originalImage.getAbsolutePath() + " to " + finalFile.getAbsolutePath()); } else { return finalFile; } } else { String rawDirPath = instanceFolder + "/raw"; File rawDir = new File(rawDirPath); if (!rawDir.exists()) { rawDir.mkdir(); } File rawImageFile = new File (rawDirPath + "/" + imageFilename); if (!originalImage.renameTo(rawImageFile)) { throw new IOException("Failed to rename " + originalImage.getAbsolutePath() + " to " + rawImageFile.getAbsolutePath()); } else { return rawImageFile; } } }
Source:
protected void setManagedProvider(ManagedProvider<E, K> provider) { if (managedProvider == null) { managedProvider = provider; } }

Target:
protected void setManagedProvider(ManagedProvider<E, K> provider) { managedProvider = provider; }
Source:
private int getBorderWidth(Drawable drawable) { if (drawable == lineDrawable) return lineDrawable.getIntrinsicWidth(); return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_MM, 2f, getResources().getDisplayMetrics()); }

Target:
private int getBorderWidth(Drawable drawable) { if (drawable == lineDrawable) return lineDrawable.getIntrinsicWidth(); return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 13f, getResources().getDisplayMetrics()); }
Source:
public UserInfo[] getBrokerUsers() throws OperationCanceledException, AuthenticatorException, IOException { if (Looper.myLooper() == Looper.getMainLooper()) { throw new IllegalArgumentException("Calling getBrokerUsers on main thread"); } if (isBrokerAccountServiceSupported()) { return BrokerAccountServiceHandler.getInstance().getBrokerUsers(mContext); } else { return getUserInfoFromAccountManager(); } }

Target:
public UserInfo[] getBrokerUsers() throws OperationCanceledException, AuthenticatorException, IOException { if (Looper.myLooper() == Looper.getMainLooper()) { throw new IllegalArgumentException("Calling getBrokerUsers on main thread"); } if (isBrokerAccountServiceSupported()) { return BrokerAccountServiceHandler.getInstance().getBrokerUsers(mContext); } return getUserInfoFromAccountManager(); }
Source:
public void setUp() throws InjectionException { ilpSolverOptimizer = Tang.Factory.getTang().newInjector().getInstance(ILPSolverOptimizer.class); random = new Random(System.currentTimeMillis()); }

Target:
public void setUp() throws InjectionException { ilpSolverOptimizer = Tang.Factory.getTang().newInjector().getInstance(ILPSolverOptimizer.class); random = new Random(); }
Source:
public ExpandedSwapLeg expand() { Schedule resolvedAccruals = accrualSchedule.createSchedule(); Schedule resolvedPayments = paymentSchedule.createSchedule(resolvedAccruals); ImmutableList<RateAccrualPeriod> accrualPeriods = calculation.expand(resolvedAccruals, resolvedPayments); ImmutableList<RatePaymentPeriod> payPeriods = paymentSchedule.createPaymentPeriods( resolvedPayments, accrualPeriods, notionalSchedule, payReceive); List<PaymentEvent> events = createEvents(payPeriods); return ExpandedSwapLeg.builder() .paymentPeriods(ImmutableList.copyOf(payPeriods)) .paymentEvents(events) .build(); }

Target:
public ExpandedSwapLeg expand() { Schedule resolvedAccruals = accrualSchedule.createSchedule(); Schedule resolvedPayments = paymentSchedule.createSchedule(resolvedAccruals); List<RateAccrualPeriod> accrualPeriods = calculation.expand(resolvedAccruals, resolvedPayments); List<RatePaymentPeriod> payPeriods = paymentSchedule.createPaymentPeriods( resolvedPayments, accrualPeriods, notionalSchedule, payReceive); return ExpandedSwapLeg.builder() .paymentPeriods(ImmutableList.copyOf(payPeriods)) .paymentEvents(createEvents(payPeriods)) .build(); }
Source:
private String getTextFrom(IStructuredSelection selection) { Object[] selectionEntries = selection.toArray(); if (selectionEntries.length <= 0) { return null; } else if (selectionEntries.length == 1) { return getPathFrom(selectionEntries[0]); } else { StringBuilder sb = new StringBuilder(); for (int i = 0; i < selectionEntries.length; i++) { String text = getPathFrom(selectionEntries[i]); if (text != null) { if (i < selectionEntries.length - 1) { text += System.lineSeparator(); } sb.append(text); } } return sb.toString(); } }

Target:
private String getTextFrom(IStructuredSelection selection) { Object[] selectionEntries = selection.toArray(); if (selectionEntries.length <= 0) { return null; } else if (selectionEntries.length == 1) { return getPathFrom(selectionEntries[0]); } else { StringBuilder sb = new StringBuilder(); for (int i = 0; i < selectionEntries.length; i++) { String text = getPathFrom(selectionEntries[i]); if (text != null) { if (i < selectionEntries.length - 1) { sb.append(text).append(System.lineSeparator()); } else { sb.append(text); } } } return sb.toString(); } }
Source:
protected void executeCommand() { ManagedBlockStorage managedBlockStorage = cinderStorageDao.get(getParameters().getStorageDomainId()); Guid volumeId = Guid.newGuid(); List<String> extraParams = new ArrayList<>(); extraParams.add(volumeId.toString()); Number sizeInGiB = SizeConverter.convert(getParameters().getDiskInfo().getSize(), SizeConverter.SizeUnit.BYTES, SizeConverter.SizeUnit.GiB); extraParams.add(Long.toString(sizeInGiB.longValue())); CinderlibReturnValue returnValue; try { Map<String, Object> driverOptions = new HashMap<>(managedBlockStorage.getDriverOptions()); if (managedBlockStorage.getDriverSensitiveOptions() != null) { driverOptions.putAll(managedBlockStorage.getDriverSensitiveOptions()); } CinderlibCommandParameters params = new CinderlibCommandParameters(JsonHelper.mapToJson(driverOptions, false), extraParams); returnValue = cinderlibExecutor.runCommand(CinderlibCommand.CREATE_VOLUME, params); } catch (Exception e) { log.error("Failed executing volume creation", e); return; } if (!returnValue.getSucceed()) { return; } saveDisk(volumeId); getReturnValue().setActionReturnValue(volumeId); setSucceeded(true); }

Target:
protected void executeCommand() { ManagedBlockStorage managedBlockStorage = cinderStorageDao.get(getParameters().getStorageDomainId()); Guid volumeId = Guid.newGuid(); List<String> extraParams = new ArrayList<>(); extraParams.add(volumeId.toString()); Number sizeInGiB = SizeConverter.convert(getParameters().getDiskInfo().getSize(), SizeConverter.SizeUnit.BYTES, SizeConverter.SizeUnit.GiB); extraParams.add(Long.toString(sizeInGiB.longValue())); CinderlibReturnValue returnValue; Map<String, Object> driverOptions = new HashMap<>(managedBlockStorage.getDriverOptions()); if (managedBlockStorage.getDriverSensitiveOptions() != null) { driverOptions.putAll(managedBlockStorage.getDriverSensitiveOptions()); } try { CinderlibCommandParameters params = new CinderlibCommandParameters(JsonHelper.mapToJson(driverOptions, false), extraParams); returnValue = cinderlibExecutor.runCommand(CinderlibCommand.CREATE_VOLUME, params); } catch (Exception e) { log.error("Failed executing volume creation", e); return; } if (!returnValue.getSucceed()) { return; } saveDisk(volumeId); getReturnValue().setActionReturnValue(volumeId); setSucceeded(true); }
Source:
public boolean validate() { getName().validateEntity(new IValidation[] { new NotEmptyValidation(), new AsciiNameValidation() }); return getName().getIsValid(); }

Target:
public boolean validate() { getName().validateEntity(new IValidation[] { new NotEmptyValidation(), new SpecialAsciiI18NOrNoneValidation() }); return getName().getIsValid(); }
Source:
public void testExplicitPropertyMappings() { Map<String, String> properties = new ImmutableMap.Builder<String, String>() .put("druid.broker-url", "<LINK_0>") .put("druid.coordinator-url", "http://druid.coordinator:4321") .put("druid.schema-name", "test") .put("druid.pushdown", "true") .build(); DruidConfig expected = new DruidConfig() .setDruidBrokerUrl("<LINK_0>") .setDruidCoordinatorUrl("http://druid.coordinator:4321") .setDruidSchema("test") .setPushdown(true); ConfigAssertions.assertFullMapping(properties, expected); }

Target:
public void testExplicitPropertyMappings() { Map<String, String> properties = new ImmutableMap.Builder<String, String>() .put("druid.broker-url", "<LINK_0>") .put("druid.coordinator-url", "http://druid.coordinator:4321") .put("druid.schema-name", "test") .put("druid.compute-pushdown-enabled", "true") .build(); DruidConfig expected = new DruidConfig() .setDruidBrokerUrl("<LINK_0>") .setDruidCoordinatorUrl("http://druid.coordinator:4321") .setDruidSchema("test") .setComputePushdownEnabled(true); ConfigAssertions.assertFullMapping(properties, expected); }
Source:
protected GroovyCodeSource getScriptSource(boolean isScriptFile, String script) throws IOException, URISyntaxException { if (isScriptFile) { File scriptFile = huntForTheScriptFile(script); if (!scriptFile.exists() && uriPattern.matcher(script).matches()) { return new GroovyCodeSource(new URI(script)); } return new GroovyCodeSource(huntForTheScriptFile(script)); } return new GroovyCodeSource(script, "script_from_command_line", GroovyShell.DEFAULT_CODE_BASE); }

Target:
protected GroovyCodeSource getScriptSource(boolean isScriptFile, String script) throws IOException, URISyntaxException { if (isScriptFile) { File scriptFile = huntForTheScriptFile(script); if (!scriptFile.exists() && uriPattern.matcher(script).matches()) { return new GroovyCodeSource(new URI(script)); } return new GroovyCodeSource( scriptFile ); } return new GroovyCodeSource(script, "script_from_command_line", GroovyShell.DEFAULT_CODE_BASE); }
Source:
public T read(Kryo kryo, Input input, Class<T> type) { int length = input.readInt(true); if (length == NULL) { return null; } byte[] bytes = input.readBytes(length - 1); try { Method method = type.getMethod("parseFrom", byte[].class); return (T) method.invoke(type, bytes); } catch (NoSuchMethodException e) { throw new RuntimeException("Unable to deserialize protobuf "+e.getMessage()); } catch (InvocationTargetException e) { throw new RuntimeException("Unable to deserialize protobuf "+e.getMessage()); } catch (IllegalAccessException e) { throw new RuntimeException("Unable to deserialize protobuf "+e.getMessage()); } }

Target:
public T read(Kryo kryo, Input input, Class<T> type) { int length = input.readInt(true); if (length == NULL) { return null; } byte[] bytes = input.readBytes(length - 1); try { return (T) (getParseFromMethod(type).invoke(type, bytes)); } catch (NoSuchMethodException e) { throw new RuntimeException("Unable to deserialize protobuf "+e.getMessage(), e); } catch (InvocationTargetException e) { throw new RuntimeException("Unable to deserialize protobuf "+e.getMessage(), e); } catch (IllegalAccessException e) { throw new RuntimeException("Unable to deserialize protobuf "+e.getMessage(), e); } }
Source:
CompletableFuture<ClientResponse> processExplainPlannedStmtBatch(AdHocPlannedStmtBatch planBatch) { Database db = VoltDB.instance().getCatalogContext().database; int size = planBatch.getPlannedStatementCount(); VoltTable[] vt = new VoltTable[ size ]; for (int i = 0; i < size; ++i) { vt[i] = new VoltTable(new VoltTable.ColumnInfo("EXECUTION_PLAN", VoltType.STRING)); String str = planBatch.explainStatement(i, db); vt[i].addRow(str); } ClientResponseImpl response = new ClientResponseImpl( ClientResponseImpl.SUCCESS, ClientResponse.UNINITIALIZED_APP_STATUS_CODE, null, vt, null); CompletableFuture<ClientResponse> fut = new CompletableFuture<>(); fut.complete(response); return fut; }

Target:
static CompletableFuture<ClientResponse> processExplainPlannedStmtBatch(AdHocPlannedStmtBatch planBatch) { Database db = VoltDB.instance().getCatalogContext().database; int size = planBatch.getPlannedStatementCount(); VoltTable[] vt = new VoltTable[ size ]; for (int i = 0; i < size; ++i) { vt[i] = new VoltTable(new VoltTable.ColumnInfo("EXECUTION_PLAN", VoltType.STRING)); String str = planBatch.explainStatement(i, db); vt[i].addRow(str); } ClientResponseImpl response = new ClientResponseImpl( ClientResponseImpl.SUCCESS, ClientResponse.UNINITIALIZED_APP_STATUS_CODE, null, vt, null); CompletableFuture<ClientResponse> fut = new CompletableFuture<>(); fut.complete(response); return fut; }
Source:
public void shouldCreateUniqueFileIndex() throws Exception { String databaseName = mongoRule.getRandomTemporaryDatabaseName(); MongoOperations mongoOperations = mongoConfiguration.getDefaultMongoOperations(databaseName); DBCollection fileCollection = mongoRule.getCollection(databaseName, jobOptions.getDbCollectionsFilesName()); VariantSourceEntityMongoWriter filesWriter = new VariantSourceEntityMongoWriter( mongoOperations, jobOptions.getDbCollectionsFilesName()); VariantSourceEntity variantSourceEntity = getVariantSourceEntity(); filesWriter.write(Collections.singletonList(variantSourceEntity)); List<DBObject> indexInfo = fileCollection.getIndexInfo(); Set<String> createdIndexes = indexInfo.stream().map(index -> index.get("name").toString()) .collect(Collectors.toSet()); Set<String> expectedIndexes = new HashSet<>(); expectedIndexes.addAll(Arrays.asList("unique_file", "_id_")); assertEquals(expectedIndexes, createdIndexes); DBObject uniqueIndex = indexInfo.stream().filter( index -> ("unique_file".equals(index.get("name").toString()))).findFirst().get(); assertNotNull(uniqueIndex); assertEquals("true", uniqueIndex.get("unique").toString()); assertEquals("true", uniqueIndex.get("background").toString()); }

Target:
public void shouldCreateUniqueFileIndex() throws Exception { String databaseName = mongoRule.getRandomTemporaryDatabaseName(); MongoOperations mongoOperations = mongoConfiguration.getDefaultMongoOperations(databaseName); DBCollection fileCollection = mongoRule.getCollection(databaseName, jobOptions.getDbCollectionsFilesName()); VariantSourceEntityMongoWriter filesWriter = new VariantSourceEntityMongoWriter( mongoOperations, jobOptions.getDbCollectionsFilesName()); VariantSourceEntity variantSourceEntity = getVariantSourceEntity(); filesWriter.write(Collections.singletonList(variantSourceEntity)); List<DBObject> indexInfo = fileCollection.getIndexInfo(); Set<String> createdIndexes = indexInfo.stream().map(index -> index.get("name").toString()) .collect(Collectors.toSet()); Set<String> expectedIndexes = new HashSet<>(); expectedIndexes.addAll(Arrays.asList(VariantSourceEntityMongoWriter.UNIQUE_FILE_INDEX_NAME, "_id_")); assertEquals(expectedIndexes, createdIndexes); DBObject uniqueIndex = indexInfo.stream().filter( index -> (VariantSourceEntityMongoWriter.UNIQUE_FILE_INDEX_NAME.equals(index.get("name").toString()))) .findFirst().get(); assertNotNull(uniqueIndex); assertEquals("true", uniqueIndex.get(MongoDBHelper.UNIQUE_INDEX).toString()); assertEquals("true", uniqueIndex.get(MongoDBHelper.BACKGROUND_INDEX).toString()); }
Source:
private void assertHasNoTags(ProjectResource rsrc) throws CannotDeleteProjectException { try { Repository repo = repoManager.openRepository(rsrc.getNameKey()); try { RevWalk rw = new RevWalk(repo); try { if (!repo.getRefDatabase().getRefs(Constants.R_TAGS).isEmpty()) { throw new CannotDeleteProjectException( String.format("Project %s has tags", rsrc.getName())); } } finally { rw.release(); } } finally { repo.close(); } } catch (IOException e) { throw new CannotDeleteProjectException(e); } }

Target:
private void assertHasNoTags(ProjectResource rsrc) throws CannotDeleteProjectException { try { Repository repo = repoManager.openRepository(rsrc.getNameKey()); try { if (!repo.getRefDatabase().getRefs(Constants.R_TAGS).isEmpty()) { throw new CannotDeleteProjectException( String.format("Project %s has tags", rsrc.getName())); } } finally { repo.close(); } } catch (IOException e) { throw new CannotDeleteProjectException(e); } }
Source:
protected void processIterableBatch(InvocationContext ctx, PutMapCommand cmd, PersistenceManager.AccessMode mode, Predicate<Object> filter) { Iterable<MarshalledEntry> iterable = () -> StreamSupport.stream(Spliterators.spliterator(cmd.getMap().keySet(), Spliterator.NONNULL), false) .filter(filter) .peek(Void -> { if (getStatisticsEnabled()) cacheStores.incrementAndGet(); }) .map(key -> createMarshalledEntry(ctx, key)) .iterator(); persistenceManager.writeBatchToAllNonTxStores(iterable, mode, cmd.getFlagsBitSet()); }

Target:
protected void processIterableBatch(InvocationContext ctx, PutMapCommand cmd, PersistenceManager.AccessMode mode, Predicate<Object> filter) { if (getStatisticsEnabled()) cacheStores.addAndGet(cmd.getMap().size()); Iterable<MarshalledEntry> iterable = () -> cmd.getMap().keySet().stream() .filter(filter) .map(key -> createMarshalledEntry(ctx, key)) .iterator(); persistenceManager.writeBatchToAllNonTxStores(iterable, mode, cmd.getFlagsBitSet()); }