auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { List<ForgeTimings<T>> timingsList = getSortedTimings(); if (timingsList.isEmpty()) { sender.sendMessage(TextComponentHelper.createComponentTranslation(sender, "commands.forge.tracking.noData")); } else { List<ForgeTimings<T>> subList = new ArrayList<>(); int count = 0; for (ForgeTimings<T> e : timingsList) { T te = e.getObject().get(); if (te == null) continue; subList.add(e); if (++count >= 10) break; } for (ForgeTimings<T> e : subList) { T te = e.getObject().get(); if (te == null) continue; sender.sendMessage(buildTrackString(sender, e)); } } }

Target:
public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { List<ForgeTimings<T>> timingsList = getSortedTimings(); if (timingsList.isEmpty()) { sender.sendMessage(TextComponentHelper.createComponentTranslation(sender, "commands.forge.tracking.noData")); } else { timingsList.stream() .filter(timings -> timings.getObject().get() != null) .limit(10) .forEach(timings -> sender.sendMessage(buildTrackString(sender, timings)) ); } }
Source:
public void testSelectStarOnForbiddenTable() throws Exception { assertQueryIsForbidden( "SELECT * FROM druid.forbiddenDatasource", CalciteTests.REGULAR_USER_AUTH_RESULT ); testQuery( "SELECT * FROM druid.forbiddenDatasource", CalciteTests.SUPER_USER_AUTH_RESULT, ImmutableList.<Query>of( newScanQueryBuilder() .dataSource(CalciteTests.FORBIDDEN_DATASOURCE) .intervals(QSS(Filtration.eternity())) .columns("__time", "cnt", "dim1", "dim2", "m1", "m2", "unique_dim1") .resultFormat(ScanQuery.RESULT_FORMAT_COMPACTED_LIST) .context(QUERY_CONTEXT_DEFAULT) .build() ), ImmutableList.of( new Object[]{T("2000-01-01"), 1L, "forbidden", "abcd", 9999.0f, 0.0, HLLCV1.class.getName()} ) ); }

Target:
public void testSelectStarOnForbiddenTable() throws Exception { assertQueryIsForbidden( "SELECT * FROM druid.forbiddenDatasource", CalciteTests.REGULAR_USER_AUTH_RESULT ); testQuery( PLANNER_CONFIG_DEFAULT, "SELECT * FROM druid.forbiddenDatasource", CalciteTests.SUPER_USER_AUTH_RESULT, ImmutableList.<Query>of( newScanQueryBuilder() .dataSource(CalciteTests.FORBIDDEN_DATASOURCE) .intervals(QSS(Filtration.eternity())) .columns("__time", "cnt", "dim1", "dim2", "m1", "m2", "unique_dim1") .resultFormat(ScanQuery.RESULT_FORMAT_COMPACTED_LIST) .context(QUERY_CONTEXT_DEFAULT) .build() ), ImmutableList.of( new Object[]{T("2000-01-01"), 1L, "forbidden", "abcd", 9999.0f, 0.0, HLLCV1.class.getName()} ) ); }
Source:
public OuiaComponentIdAttribute ouiaComponentId() { return new OuiaComponentIdAttribute(OUIA_COMPONENT_TYPE + "-" + dock.getDockPosition().getShortName() + "-" + dock.getIdentifier()); }

Target:
public OuiaComponentIdAttribute ouiaComponentId() { return new OuiaComponentIdAttribute(OUIA_COMPONENT_TYPE + "-" + dock.getIdentifier()); }
Source:
List<MetricFamilySamples> fromTimer(String name, Timer timer) { return fromSnapshotAndCount(name, timer.getSnapshot(), timer.getCount(), 1.0D / TIME_UNIT.toNanos(1L), getHelpMessage(name, timer)); }

Target:
List<MetricFamilySamples> fromTimer(String name, Timer timer) { return fromSnapshotAndCount(name, timer.getSnapshot(), timer.getCount(), 1.0D / TimeUnit.SECONDS.toNanos(1L), getHelpMessage(name, timer)); }
Source:
private boolean manageScenarioBodyRightClick(final ScenarioGrid scenarioGrid, final int left, final int top, final int uiRowIndex, final int uiColumnIndex) { ScenarioGridColumn scenarioGridColumn = (ScenarioGridColumn) scenarioGrid.getModel().getColumns().get(uiColumnIndex); if (scenarioGridColumn == null) { return false; } String group = scenarioGridColumn.getInformationHeaderMetaData().getColumnGroup(); switch (group) { case GIVEN: case EXPECT: gridContextMenu.show(left, top, uiRowIndex); break; default: unmodifiableColumnGridContextMenu.show(left, top, uiRowIndex); } scenarioGrid.setSelectedCell(uiRowIndex, uiColumnIndex); return true; }

Target:
private boolean manageScenarioBodyRightClick(final ScenarioGrid scenarioGrid, final int left, final int top, final int uiRowIndex, final int uiColumnIndex) { ScenarioGridColumn scenarioGridColumn = (ScenarioGridColumn) scenarioGrid.getModel().getColumns().get(uiColumnIndex); if (scenarioGridColumn == null) { return false; } String group = scenarioGridColumn.getInformationHeaderMetaData().getColumnGroup(); switch (group) { case "GIVEN": case "EXPECT": gridContextMenu.show(left, top, uiRowIndex); break; default: unmodifiableColumnGridContextMenu.show(left, top, uiRowIndex); } scenarioGrid.setSelectedCell(uiRowIndex, uiColumnIndex); return true; }
Source:
public void init(int position, boolean isDropDownView, String savedLanguageValue) { String languageCode = LangCodeUtils.fixLanguageCode(languageCodesList.get(position)); final String languageName = StringUtils.capitalize(languageNamesList.get(position)); if(savedLanguageValue!=null && savedLanguageValue.equals("")){ savedLanguageValue = Locale.getDefault().getLanguage(); } if (!isDropDownView) { if( !dropDownClicked && savedLanguageValue !=null){ languageCode = LangCodeUtils.fixLanguageCode(savedLanguageValue); } view.setVisibility(View.GONE); if (languageCode.length() > 2) tvLanguage.setText(languageCode.substring(0, 2)); else tvLanguage.setText(languageCode); } else { view.setVisibility(View.VISIBLE); if (languageCodesList.get(position).isEmpty()) { tvLanguage.setText(languageName); tvLanguage.setTextAlignment(View.TEXT_ALIGNMENT_CENTER); } else { tvLanguage.setText( String.format("%s [%s]", languageName, languageCode)); if (selectedLanguages.containsKey(languageCodesList.get(position)) && !languageCodesList.get(position).equals(selectedLangCode)) { tvLanguage.setTextColor(Color.GRAY); } } } }

Target:
public void init(int position, boolean isDropDownView, String savedLanguageValue) { String languageCode = LangCodeUtils.fixLanguageCode(languageCodesList.get(position)); final String languageName = StringUtils.capitalize(languageNamesList.get(position)); if(TextUtils.isEmpty(savedLanguageValue)){ savedLanguageValue = Locale.getDefault().getLanguage(); } if (!isDropDownView) { if( !dropDownClicked && savedLanguageValue !=null){ languageCode = LangCodeUtils.fixLanguageCode(savedLanguageValue); } if (view != null) { view.setVisibility(View.GONE); } if (languageCode.length() > 2) tvLanguage.setText(languageCode.substring(0, 2)); else tvLanguage.setText(languageCode); } else { view.setVisibility(View.VISIBLE); if (languageCodesList.get(position).isEmpty()) { tvLanguage.setText(languageName); tvLanguage.setTextAlignment(View.TEXT_ALIGNMENT_CENTER); } else { tvLanguage.setText( String.format("%s [%s]", languageName, languageCode)); if (selectedLanguages.containsKey(languageCodesList.get(position)) && !languageCodesList.get(position).equals(selectedLangCode)) { tvLanguage.setTextColor(Color.GRAY); } } } }
Source:
protected final boolean trySuccessInternal(V result) { boolean done = super.trySuccess(result); return clearTaskAfterCompletion(done, COMPLETED); }

Target:
protected final boolean trySuccessInternal(V result) { return clearTaskAfterCompletion(super.trySuccess(result), COMPLETED); }
Source:
private void check(String databaseName, int expectedFileCount, int expectedStatsCount) { String filesStudyIdField = String.format("%s.%s", FILES_FIELD, STUDYID_FIELD); String statsStudyIdField = String.format("%s.%s", STATS_FIELD, STUDYID_FIELD); DBCollection variantsCollection = mongoRule.getCollection(databaseName, COLLECTION_VARIANTS_NAME); BasicDBObject variantFiles = new BasicDBObject(filesStudyIdField, STUDY_ID_TO_DROP); BasicDBObject variantStats = new BasicDBObject(statsStudyIdField, STUDY_ID_TO_DROP); System.out.println(variantsCollection.count(variantFiles)); System.out.println(variantsCollection.count(variantStats)); assertEquals(expectedFileCount, variantsCollection.count(variantFiles)); assertEquals(expectedStatsCount, variantsCollection.count(variantStats)); }

Target:
private void check(String databaseName, int expectedFileCount, int expectedStatsCount) { String filesStudyIdField = String.format("%s.%s", FILES_FIELD, STUDYID_FIELD); String statsStudyIdField = String.format("%s.%s", STATS_FIELD, STUDYID_FIELD); DBCollection variantsCollection = mongoRule.getCollection(databaseName, COLLECTION_VARIANTS_NAME); BasicDBObject variantFiles = new BasicDBObject(filesStudyIdField, STUDY_ID_TO_DROP); BasicDBObject variantStats = new BasicDBObject(statsStudyIdField, STUDY_ID_TO_DROP); assertEquals(expectedFileCount, variantsCollection.count(variantFiles)); assertEquals(expectedStatsCount, variantsCollection.count(variantStats)); }
Source:
public void addReference(NativeObject referent) { new NativeObjectReference(this, referent, referenceQueue); }

Target:
void addReference(NativeObject referent) { new NativeObjectReference(this, referent, referenceQueue); }
Source:
public String send(HttpSession session, @RequestParam(value = "recipient") String recipientUsername, @RequestParam(value = "subject") String subject, @RequestParam(value = "body") String body, @RequestParam(value = "draft_id") Integer draftId) { if (session.getAttribute("member") == null) return "redirect:denied"; MemberDao memberDao = new MemberDao(); MessageDao messageDao = new MessageDao(); Member sender = (Member) session.getAttribute("member"); Member recipient = memberDao.getMemberByUsername(recipientUsername); if (draftId != null) { Message draft = messageDao.getMessageById(draftId); draft.setRecipient(recipient).setSubject(subject).setBody(body).setDraft(false).setSent(true); messageDao.save(draft); } else { Message newMessage = new Message(subject, body, sender, recipient); newMessage.setSent(true); newMessage.setDraft(false); messageDao.save(newMessage); } session.setAttribute("message", "Message sent!"); session.setAttribute("member", memberDao.getMemberById(sender.getId())); return "mail"; }

Target:
public String send( HttpSession session, @RequestParam(value = "recipient") String recipientUsername, @RequestParam(value = "subject") String subject, @RequestParam(value = "body") String body, @RequestParam(value = "draft_id") Integer draftId) { if (session.getAttribute("member") == null) return "redirect:/denied"; MemberDao memberDao = new MemberDao(); MessageDao messageDao = new MessageDao(); Member sender = (Member) session.getAttribute("member"); Member recipient = memberDao.getMemberByUsername(recipientUsername); if (draftId != null) { Message draft = messageDao.getById(draftId); draft.setRecipient(recipient).setSubject(subject).setBody(body).setDraft(false).setSent(true); messageDao.merge(draft); } else { Message newMessage = new Message(subject, body, sender, recipient); newMessage.setSent(true); newMessage.setDraft(false); messageDao.merge(newMessage); } session.setAttribute("message", "Message sent!"); session.setAttribute("member", memberDao.getMemberById(sender.getId())); return "mail"; }
Source:
public Future<UpdateCenterJob> deploy(boolean dynamicLoad, @CheckForNull UUID correlationId, @CheckForNull List<PluginWrapper> batch) { Jenkins.get().checkPermission(Jenkins.ADMINISTER); UpdateCenter uc = Jenkins.get().getUpdateCenter(); for (Plugin dep : getNeededDependencies()) { UpdateCenter.InstallationJob job = uc.getJob(dep); if (job == null || job.status instanceof UpdateCenter.DownloadJob.Failure) { LOGGER.log(Level.FINEST, "Adding dependent install of " + dep.name + " for plugin " + name); dep.deploy(dynamicLoad, null, batch); } else { LOGGER.log(Level.FINE, "Dependent install of {0} for plugin {1} already added, skipping", new Object[] {dep.name, name}); } } PluginWrapper pw = getInstalled(); if(pw != null) { Future<UpdateCenterJob> enableJob = null; if(!pw.isEnabled()) { UpdateCenter.EnableJob job = uc.new EnableJob(UpdateSite.this, null, this, dynamicLoad); job.setCorrelationId(correlationId); enableJob = uc.addJob(job); } if(pw.getVersionNumber().equals(new VersionNumber(version))) { return enableJob != null ? enableJob : uc.addJob(uc.new NoOpJob(UpdateSite.this, null, this)); } } UpdateCenter.InstallationJob job = createInstallationJob(this, uc, dynamicLoad); job.setCorrelationId(correlationId); job.setBatch(batch); return uc.addJob(job); }

Target:
public Future<UpdateCenterJob> deploy(boolean dynamicLoad, @CheckForNull UUID correlationId, @CheckForNull List<PluginWrapper> batch) { Jenkins.get().checkPermission(Jenkins.ADMINISTER); UpdateCenter uc = Jenkins.get().getUpdateCenter(); for (Plugin dep : getNeededDependencies()) { UpdateCenter.InstallationJob job = uc.getJob(dep); if (job == null || job.status instanceof UpdateCenter.DownloadJob.Failure) { LOGGER.log(Level.INFO, "Adding dependent install of " + dep.name + " for plugin " + name); dep.deploy(dynamicLoad, null, batch); } else { LOGGER.log(Level.FINE, "Dependent install of {0} for plugin {1} already added, skipping", new Object[] {dep.name, name}); } } PluginWrapper pw = getInstalled(); if(pw != null) { Future<UpdateCenterJob> enableJob = null; if(!pw.isEnabled()) { UpdateCenter.EnableJob job = uc.new EnableJob(UpdateSite.this, null, this, dynamicLoad); job.setCorrelationId(correlationId); enableJob = uc.addJob(job); } if(pw.getVersionNumber().equals(new VersionNumber(version))) { return enableJob != null ? enableJob : uc.addJob(uc.new NoOpJob(UpdateSite.this, null, this)); } } UpdateCenter.InstallationJob job = createInstallationJob(this, uc, dynamicLoad); job.setCorrelationId(correlationId); job.setBatch(batch); return uc.addJob(job); }
Source:
public SmsDetails sendWakeUpSms(final DlmsDeviceMessageMetadata messageMetadata) throws OsgpException, ProtocolAdapterException { final DlmsDevice device = this.domainHelperService.findDlmsDevice(messageMetadata); if (!COMMUNICATION_METHOD_GPRS.equals(device.getCommunicationMethod())) { throw new OsgpException(ComponentType.PROTOCOL_DLMS, "Device communication method is not GPRS"); } final SendSMSResponse response = this.smsClient.sendWakeUpSMS(device.getIccId()); return new SmsDetails(device.getDeviceIdentification(), response.getSmsMsgId(), null, null, null); }

Target:
public SmsDetails sendWakeUpSms(final DlmsDeviceMessageMetadata messageMetadata) throws OsgpException { final DlmsDevice device = this.domainHelperService.findDlmsDevice(messageMetadata); if (!COMMUNICATION_METHOD_GPRS.equals(device.getCommunicationMethod())) { throw new OsgpException(ComponentType.PROTOCOL_DLMS, "Device communication method is not GPRS"); } final SendSMSResponse response = this.smsClient.sendWakeUpSMS(device.getIccId()); return new SmsDetails(device.getDeviceIdentification(), response.getSmsMsgId(), null, null, null); }
Source:
protected Multimap<String, FaultDomain> computeHostToFaultDomainMap() { Multimap<String, FaultDomain> hostToRackMap = HashMultimap.create(); try { List<NodeReport> nodeReport = yarnClient.getNodeReports(NodeState.RUNNING); nodeReport.forEach(report -> { FaultDomain rack = new FaultDomain(FaultDomainType.RACK, report.getRackName()); hostToRackMap.put(report.getNodeId().getHost(), rack); }); } catch (YarnException | IOException e) { e.printStackTrace(); } return hostToRackMap; }

Target:
Multimap<String, FaultDomain> computeHostToFaultDomainMap() { Multimap<String, FaultDomain> hostToRackMap = HashMultimap.create(); try { List<NodeReport> nodeReport = yarnClient.getNodeReports(NodeState.RUNNING); nodeReport.forEach(report -> { FaultDomain rack = new FaultDomain(FaultDomainType.RACK, report.getRackName()); hostToRackMap.put(report.getNodeId().getHost(), rack); }); log.info("Computed the host to rack map successfully from Yarn."); } catch (YarnException | IOException e) { throw new SamzaException("Yarn threw an exception while getting NodeReports.", e); } return hostToRackMap; }
Source:
public void newChangeIsMergedWithFix() throws Exception { Change c = newChange(project, userId); db.changes().insert(singleton(c)); RevCommit commit = repo.branch(c.currentPatchSetId().toRefName()).commit() .parent(tip).create(); PatchSet ps = newPatchSet(c.currentPatchSetId(), commit, userId); db.patchSets().insert(singleton(ps)); repo.branch(c.getDest().get()).update(commit); List<ProblemInfo> problems = checker.check(c, new FixInput()).problems(); assertThat(problems).hasSize(1); ProblemInfo p = problems.get(0); assertThat(p.message).isEqualTo( "Patch set 1 (" + commit.name() + ") is merged into destination ref" + " master (" + commit.name() + "), but change status is NEW"); assertThat(p.status).isEqualTo(ProblemInfo.Status.FIXED); assertThat(p.outcome).isEqualTo("Marked change as merged"); assertProblems(db.changes().get(c.getId())); }

Target:
public void newChangeIsMergedWithFix() throws Exception { Change c = newChange(project, userId); db.changes().insert(singleton(c)); RevCommit commit = repo.branch(c.currentPatchSetId().toRefName()).commit() .parent(tip).create(); PatchSet ps = newPatchSet(c.currentPatchSetId(), commit, userId); db.patchSets().insert(singleton(ps)); repo.branch(c.getDest().get()).update(commit); List<ProblemInfo> problems = checker.check(c, new FixInput()).problems(); assertThat(problems).hasSize(1); ProblemInfo p = problems.get(0); assertThat(p.message).isEqualTo( "Patch set 1 (" + commit.name() + ") is merged into destination ref" + " master (" + commit.name() + "), but change status is NEW"); assertThat(p.status).isEqualTo(ProblemInfo.Status.FIXED); assertThat(p.outcome).isEqualTo("Marked change as merged"); c = db.changes().get(c.getId()); assertThat(c.getStatus()).isEqualTo(Change.Status.MERGED); assertProblems(c); }
Source:
public boolean isSecure() { return config.getBool("server", "https").orElse(false); }

Target:
public boolean isSecure() { return config.get("server", "https-private-key").isPresent() && config.get("server", "https-certificate").isPresent(); }
Source:
private HashMap<String, VariantAnnotation> generateVariantAnnotations(List<? extends Annotation> annotations) { HashMap<String, VariantAnnotation> variantAnnotations = new HashMap<>(); for (Annotation annotation : annotations) { String id = annotation.buildVariantId(); variantAnnotations.putIfAbsent(id, new VariantAnnotation(annotation)); variantAnnotations.computeIfPresent(id, (key, oldVar) -> oldVar.concatenate(annotation)); } return variantAnnotations; }

Target:
private Map<String, VariantAnnotation> generateVariantAnnotations(List<? extends Annotation> annotations) { HashMap<String, VariantAnnotation> variantAnnotations = new HashMap<>(); for (Annotation annotation : annotations) { String id = annotation.buildVariantId(); variantAnnotations.putIfAbsent(id, new VariantAnnotation(annotation)); variantAnnotations.computeIfPresent(id, (key, oldVar) -> oldVar.concatenate(annotation)); } return variantAnnotations; }
Source:
public String getAsLastNamesLatexFree(boolean oxfordComma) { int abbrInt = oxfordComma ? 0 : 1; if (authorsLastOnlyLatexFree[abbrInt] != null) { return authorsLastOnlyLatexFree[abbrInt]; } authorsLastOnlyLatexFree[abbrInt] = LatexToUnicodeAdapter.format(getAsLastNames(oxfordComma)); return authorsLastOnlyLatexFree[abbrInt]; }

Target:
public String getAsLastNamesLatexFree(boolean oxfordComma) { int abbreviationIndex = oxfordComma ? 0 : 1; if (authorsLastOnlyLatexFree[abbreviationIndex] != null) { return authorsLastOnlyLatexFree[abbreviationIndex]; } authorsLastOnlyLatexFree[abbreviationIndex] = LatexToUnicodeAdapter.format(getAsLastNames(oxfordComma)); return authorsLastOnlyLatexFree[abbreviationIndex]; }
Source:
public LabelTypes getLabelTypes() { String destBranch = getChange().getDest().get(); List<LabelType> all = getProjectControl().getLabelTypes().getLabelTypes(); List<LabelType> accessSectionsLabels = getRefControl().getLabelTypes().getLabelTypes(); List<LabelType> r = Lists.newArrayListWithCapacity(all.size()); for (LabelType l : all) { List<String> refs = l.getRefPatterns(); if (refs == null) { r.add(l); } else if (refs.size() == 1 && refs.get(0).equals("sameAsAccess")) { if (accessSectionsLabels.contains(l)) { r.add(l); } } else { for (String refPattern : refs) { if (RefConfigSection.isValid(refPattern) && match(destBranch, refPattern)) { r.add(l); break; } } } } return new LabelTypes(r); }

Target:
public LabelTypes getLabelTypes() { String destBranch = getChange().getDest().get(); List<LabelType> all = getProjectControl().getLabelTypes().getLabelTypes(); List<LabelType> accessSectionsLabels = getRefControl().getLabelTypes().getLabelTypes(); List<LabelType> r = Lists.newArrayListWithCapacity(all.size()); for (LabelType l : all) { List<String> refs = l.getRefPatterns(); boolean branchSameAsAccess = l.branchSameAsAccess(); if (refs == null && !branchSameAsAccess) { r.add(l); } else { if (branchSameAsAccess) { if (accessSectionsLabels.contains(l)) { r.add(l); continue; } } if (refs != null) { for (String refPattern : refs) { if (RefConfigSection.isValid(refPattern) && match(destBranch, refPattern)) { r.add(l); break; } } } } } return new LabelTypes(r); }
Source:
public static Collection<String> descriptions(Collection<ConfigInfo> infos) { if (infos == null) { return Collections.emptyList(); } return Lists.newArrayList(Iterables.transform(infos, new Function<ConfigInfo, String>() { @Override public String apply(ConfigInfo info) { return info.description(); } })); }

Target:
public static List<String> descriptions(Collection<ConfigInfo> infos) { if (infos == null) { return Collections.emptyList(); } return infos.stream() .map(ConfigInfo::description) .collect(Collectors.toList()); }
Source:
public Statement apply(final Statement base, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { final Future<Object> future = executor.submit(new Callable<Object>() { @Override public Object call() throws Exception { before(); try { try { base.evaluate(); } catch (Throwable throwable) { Throwables.propagateIfPossible(throwable, Exception.class); throw Throwables.propagate(throwable); } } finally { after(); } return null; } }); while (!future.isDone()) { Thread.sleep(JOB_HEALTH_CHECK_INTERVAL_MILLIS); verifyJobsHealthy(); } try { future.get(); } catch (ExecutionException e) { final Throwable cause = (e.getCause() == null) ? e : e.getCause(); throw Throwables.propagate(cause); } } }; }

Target:
public Statement apply(final Statement base, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { before(); try { perform(base); } finally { after(); } } }; }
Source:
private void addGlusterBricksFeature(Features features) { Feature feature = new Feature(); feature.setName("Gluster Bricks management"); feature.setDescription("Ability to manage gluster bricks"); features.getFeature().add(feature); }

Target:
private void addGlusterBricksFeature(Features features) { Feature feature = new Feature(); feature.setName("Gluster Bricks management"); feature.setDescription("Ability to delete gluster bricks with data migration"); features.getFeature().add(feature); }
Source:
protected UsernamePasswordCredentials retrieveCredentials(final WebContext context) throws RequiresHttpAction { final String username = context.getRequestParameter(this.usernameParameter); UsernamePasswordCredentials credentials; try { credentials = getCredentialsExtractor().extract(context); logger.debug("usernamePasswordCredentials: {}", credentials); if (credentials == null) { if (getAjaxRequestResolver().isAjax(context)) { logger.info("AJAX request detected -> returning 401"); throw RequiresHttpAction.unauthorized("AJAX request -> 401", context, null); } else { String redirectionUrl = CommonHelper.addParameter(this.loginUrl, this.usernameParameter, username); redirectionUrl = CommonHelper.addParameter(redirectionUrl, ERROR_PARAMETER, MISSING_FIELD_ERROR); logger.debug("redirectionUrl: {}", redirectionUrl); final String message = "Username and password cannot be blank -> return to the form with error"; logger.debug(message); throw RequiresHttpAction.redirect(message, context, redirectionUrl); } } getAuthenticator().validate(credentials); } catch (final CredentialsException e) { if (getAjaxRequestResolver().isAjax(context)) { logger.info("AJAX request detected -> returning 403"); throw RequiresHttpAction.forbidden("AJAX request -> 403", context); } else { String redirectionUrl = CommonHelper.addParameter(this.loginUrl, this.usernameParameter, username); String errorMessage = computeErrorMessage(e); redirectionUrl = CommonHelper.addParameter(redirectionUrl, ERROR_PARAMETER, errorMessage); logger.debug("redirectionUrl: {}", redirectionUrl); final String message = "Credentials validation fails -> return to the form with error"; logger.debug(message); throw RequiresHttpAction.redirect(message, context, redirectionUrl); } } return credentials; }

Target:
protected UsernamePasswordCredentials retrieveCredentials(final WebContext context) throws RequiresHttpAction { final String username = context.getRequestParameter(this.usernameParameter); UsernamePasswordCredentials credentials; try { credentials = getCredentialsExtractor().extract(context); logger.debug("usernamePasswordCredentials: {}", credentials); if (credentials == null) { throw handleInvalidCredentials(context, username, "Username and password cannot be blank -> return to the form with error", MISSING_FIELD_ERROR, 401); } getAuthenticator().validate(credentials); } catch (final CredentialsException e) { throw handleInvalidCredentials(context, username, "Credentials validation fails -> return to the form with error", computeErrorMessage(e), 403); } return credentials; }
Source:
public void setComment(String comment) throws CentralRepoException { String updateClause = "UPDATE personas SET comment = \"" + comment + "\" WHERE id = " + id; CentralRepository.getInstance().executeUpdateSQL(updateClause); }

Target:
public void setComment(String comment) throws CentralRepoException { String updateClause = "UPDATE personas SET comment = \"" + comment + "\" WHERE id = " + id; CentralRepository cr = CentralRepository.getInstance(); if (cr != null) { cr.executeUpdateSQL(updateClause); } }
Source:
notifyAboutOrder(OrderReadyToBeServed orderReady) { throw new RuntimeException(); }

Target:
notifyAboutOrder(OrderReadyToBeServed orderReady) { throw new RuntimeException("Could not send notifications."); }
Source:
private static ListenableFuture<?> getBlockedFuture(Operator operator) { ListenableFuture<?> blocked = operator.isBlocked(); if (blocked.isDone()) { blocked = operator.getOperatorContext().isWaitingForMemory(); } return blocked; }

Target:
private static Optional<ListenableFuture<?>> getBlockedFuture(Operator operator) { ListenableFuture<?> blocked = operator.isBlocked(); if (!blocked.isDone()) { return Optional.of(blocked); } blocked = operator.getOperatorContext().isWaitingForMemory(); if (!blocked.isDone()) { return Optional.of(blocked); } return Optional.empty(); }
Source:
public void initialize(final String endpointId) { if (initialized.get()) { return; } this.evalPrefix = endpointId.split("-")[0]; LOG.log(Level.INFO, "Initialize router with localEndPointId: {0}", endpointId); if (!addedEval) { if (!initialized.compareAndSet(false, true)) { return; } initRoutingTable(); } else { requestRoutingTable(); } }

Target:
public void initialize(final String endpointId) { this.evalPrefix = endpointId.split("-")[0]; LOG.log(Level.INFO, "Initialize router with localEndPointId: {0}", endpointId); if (!addedEval) { initRoutingTable(); } else { requestRoutingTable(); } }
Source:
private void runInBackground() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); while (!stopped) { String commandDescription = null; try { final Command command = queuedCommands.take(); if (command != null) { commandDescription = command.description; if (K9.DEBUG) Log.i(K9.LOG_TAG, "Running " + (command.isForeground ? "Foreground" : "Background") + " command '" + command.description + "', seq = " + command.sequence); try { command.runnable.run(); } catch (UnavailableAccountException e) { new Thread() { @Override public void run() { try { sleep(30 * 1000); queuedCommands.put(command); } catch (InterruptedException e) { Log.e(K9.LOG_TAG, "interrupted while putting a pending command for" + " an unavailable account back into the queue." + " THIS SHOULD NEVER HAPPEN."); } } } .start(); } if (K9.DEBUG) Log.i(K9.LOG_TAG, (command.isForeground ? "Foreground" : "Background") + " Command '" + command.description + "' completed"); for (MessagingListener l : getListeners(command.listener)) { l.controllerCommandCompleted(!queuedCommands.isEmpty()); } } } catch (Exception e) { Log.e(K9.LOG_TAG, "Error running command '" + commandDescription + "'", e); } } }

Target:
private void runInBackground() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); while (!stopped) { String commandDescription = null; try { final Command command = queuedCommands.take(); if (command != null) { commandDescription = command.description; if (K9.DEBUG) { Log.i(K9.LOG_TAG, "Running command '" + command.description + "', seq = " + command.sequence + "(" + (command.isForegroundPriority ? "foreground" : "background") + "priority)"); } try { command.runnable.run(); } catch (UnavailableAccountException e) { new Thread() { @Override public void run() { try { sleep(30 * 1000); queuedCommands.put(command); } catch (InterruptedException e) { Log.e(K9.LOG_TAG, "interrupted while putting a pending command for" + " an unavailable account back into the queue." + " THIS SHOULD NEVER HAPPEN."); } } } .start(); } if (K9.DEBUG) { Log.i(K9.LOG_TAG, " Command '" + command.description + "' completed"); } for (MessagingListener l : getListeners(command.listener)) { l.controllerCommandCompleted(!queuedCommands.isEmpty()); } } } catch (Exception e) { Log.e(K9.LOG_TAG, "Error running command '" + commandDescription + "'", e); } } }
Source:
public void testRecoveryMonitorWithFailure() throws Exception { XATestResourceXARecovery.setUseFaultyResources(true); UserTransaction ut = com.arjuna.ats.jta.UserTransaction.userTransaction(); ut.begin(); TransactionImple tx = TransactionImple.getTransaction(); assertTrue(tx.enlistResource(new XATestResource(XATestResource.OK_JNDI_NAME, false))); assertTrue(tx.enlistResource(new XATestResource(XATestResource.FAULTY_JNDI_NAME, true))); ut.commit(); manager.scan(); assertTrue(!xaRecoveryModule.isPeriodicWorkSuccessful()); }

Target:
public void testRecoveryMonitorWithFailure() throws Exception { XATestResourceXARecovery.setUseFaultyResources(true); UserTransaction ut = com.arjuna.ats.jta.UserTransaction.userTransaction(); ut.begin(); TransactionImple tx = TransactionImple.getTransaction(); assertTrue(tx.enlistResource(new XATestResource(XATestResource.OK_JNDI_NAME, false))); assertTrue(tx.enlistResource(new XATestResource(XATestResource.FAULTY_JNDI_NAME, true))); ut.commit(); manager.scan(); assertFalse(xaRecoveryModule.isPeriodicWorkSuccessful()); }
Source:
public void testEntryInvalidated(boolean isOwner, WriteMethod method) { Cache<Object, String> primary = cache(isOwner ? 0 : 2, DIST); Cache<Object, String> backup = cache(1, DIST); Cache<Object, String> reader = cache(3, DIST); Cache<Object, String> nonOwner = cache(isOwner ? 2 : 0, DIST); Object KEY = getKeyForCache(primary, backup); primary.put(KEY, "value"); assertEquals(null, reader.getAdvancedCache().getDataContainer().get(KEY)); assertEquals("value", reader.get(KEY)); assertEntry(primary.getAdvancedCache().getDataContainer().get(KEY), "value", false); assertEntry(backup.getAdvancedCache().getDataContainer().get(KEY), "value", false); assertEntry(reader.getAdvancedCache().getDataContainer().get(KEY), "value", true); assertEquals(null, nonOwner.getAdvancedCache().getDataContainer().get(KEY)); FunctionalMapImpl<Object, String> functionalMap = FunctionalMapImpl.create(this.<Object, String>cache(0, DIST).getAdvancedCache()); FunctionalMap.WriteOnlyMap<Object, String> wo = WriteOnlyMapImpl.create(functionalMap); FunctionalMap.ReadWriteMap<Object, String> rw = ReadWriteMapImpl.create(functionalMap); Function<ReadEntryView<Object, String>, String> readFunc = MarshallableFunctions.returnReadOnlyFindOrNull(); BiConsumer<WriteEntryView<String>, String> writeFunc = (Serializable & BiConsumer<WriteEntryView<String>, String>) (view, nil) -> view.set("value2"); method.action.eval(KEY, wo, rw, readFunc, writeFunc, FunctionalL1Test.class); assertEntry(primary.getAdvancedCache().getDataContainer().get(KEY), "value2", false); assertEntry(backup.getAdvancedCache().getDataContainer().get(KEY), "value2", false); assertEquals(null, reader.getAdvancedCache().getDataContainer().get(KEY)); assertEquals(null, nonOwner.getAdvancedCache().getDataContainer().get(KEY)); }

Target:
public void testEntryInvalidated(boolean isOwner, WriteMethod method) { Cache<Object, String> primary = cache(isOwner ? 0 : 2, DIST); Cache<Object, String> backup = cache(1, DIST); Cache<Object, String> reader = cache(3, DIST); Cache<Object, String> nonOwner = cache(isOwner ? 2 : 0, DIST); Object KEY = getKeyForCache(primary, backup); primary.put(KEY, "value"); assertNoEntry(reader, KEY); assertEquals("value", reader.get(KEY)); assertEntry(primary, KEY, "value", false); assertEntry(backup, KEY, "value", false); assertEntry(reader, KEY, "value", true); assertNoEntry(nonOwner, KEY); FunctionalMapImpl<Object, String> functionalMap = FunctionalMapImpl.create(this.<Object, String>cache(0, DIST).getAdvancedCache()); FunctionalMap.WriteOnlyMap<Object, String> wo = WriteOnlyMapImpl.create(functionalMap); FunctionalMap.ReadWriteMap<Object, String> rw = ReadWriteMapImpl.create(functionalMap); Function<ReadEntryView<Object, String>, String> readFunc = MarshallableFunctions.returnReadOnlyFindOrNull(); method.eval(KEY, wo, rw, readFunc, (view, nil) -> view.set("value2"), FunctionalL1Test.class); assertEntry(primary, KEY, "value2", false); assertEntry(backup, KEY, "value2", false); assertNoEntry(reader, KEY); assertNoEntry(nonOwner, KEY); }
Source:
public Repo create( final RepoCreate settings ) throws IOException { String user = this.self; final String org = settings.organization(); if (org != null && !org.isEmpty()) { user = "/orgs/".concat(org).concat("/repos"); } final Coordinates coords = new Coordinates.Simple( user, settings.name() ); this.storage.apply( new Directives().xpath(this.xpath()).add("repo") .attr("coords", coords.toString()) .add("name").set(settings.name()).up() .add("description").set("test repository").up() .add("private").set(settings.isPrivate()).up() ); final Repo repo = this.get(coords); repo.patch(settings.json()); Logger.info( this, "repository %s created by %s", coords, user ); return repo; }

Target:
public Repo create( final RepoCreate settings ) throws IOException { String owner = this.self; final String org = settings.organization(); if (org != null && !org.isEmpty()) { owner = "/orgs/".concat(org).concat("/repos"); } final Coordinates coords = new Coordinates.Simple( owner, settings.name() ); this.storage.apply( new Directives().xpath(this.xpath()).add("repo") .attr("coords", coords.toString()) .add("name").set(settings.name()).up() .add("description").set("test repository").up() .add("private").set(settings.isPrivate()).up() ); final Repo repo = this.get(coords); repo.patch(settings.json()); Logger.info( this, "repository %s created by %s", coords, owner ); return repo; }
Source:
public void prepare(CastContext context, ConfigurationSection parameters) { super.prepare(context, parameters); ConfigurationSection section = parameters.getConfigurationSection("attributes"); if (section == null) return; this.attributes = new HashMap<>(); for (String key : section.getKeys(false)) { attributes.put(key, section.getDouble(key, 0)); } for (String key : parameters.getKeys(false)) { if (key.startsWith("attribute_")) { String str = key.replace("attribute_", ""); attributes.put(str, parameters.getDouble(key)); } } }

Target:
public void prepare(CastContext context, ConfigurationSection parameters) { super.prepare(context, parameters); ConfigurationSection section = parameters.getConfigurationSection("attributes"); if (section == null) return; this.attributes = new HashMap<>(); for (String key : section.getKeys(false)) { attributes.put(key, section.getDouble(key, 0)); } for (String key : parameters.getKeys(false)) { if (key.startsWith("attribute_")) { String str = key.replace("attribute_", ""); if (attributes.containsKey(str)) { continue; } attributes.put(str, parameters.getDouble(key)); } } }
Source:
public String makeBoxes() { String projectStateBackgroundColour = "projectStateInactive"; if( project.isSetState() && project.state == ProjectState.ACTIVE ) { projectStateBackgroundColour = "projectStateActive"; } String clearingStateBackgroundColour = "clearingStateUnknown"; if(project.isSetClearingState()) { switch(project.clearingState) { case CLOSED: clearingStateBackgroundColour = "clearingStateClosed"; break; case IN_PROGRESS: clearingStateBackgroundColour = "clearingStateInProgress"; break; case OPEN: clearingStateBackgroundColour = "clearingStateOpen"; break; } } String box_PS = "<div class=\"stateBox " + projectStateBackgroundColour + " capsuleLeft \" title=\"Project state: " + ThriftEnumUtils.enumToString(project.state) + "\"> PS </div>"; String box_CS = "<div class=\"stateBox capsuleRight " + clearingStateBackgroundColour + "\" title=\"Project clearing state: " + ThriftEnumUtils.enumToString(project.clearingState) + "\"> CS </div>"; return box_PS+box_CS; }

Target:
public String makeBoxes() { String projectStateBackgroundColour = PortalConstants.PROJECT_STATE_INACTIVE__CSS; if( project.isSetState() && project.state == ProjectState.ACTIVE ) { projectStateBackgroundColour = PortalConstants.PROJECT_STATE_ACTIVE__CSS; } String clearingStateBackgroundColour = PortalConstants.CLEARING_STATE_UNKNOWN__CSS; if(project.isSetClearingState()) { switch(project.clearingState) { case CLOSED: clearingStateBackgroundColour = PortalConstants.CLEARING_STATE_CLOSED__CSS; break; case IN_PROGRESS: clearingStateBackgroundColour = PortalConstants.CLEARING_STATE_INPROGRESS__CSS; break; case OPEN: clearingStateBackgroundColour = PortalConstants.CLEARING_STATE_OPEN__CSS; break; } } String box_PS = "<div class=\"stateBox " + projectStateBackgroundColour + " capsuleLeft \" title=\"Project state: " + ThriftEnumUtils.enumToString(project.state) + "\"> PS </div>"; String box_CS = "<div class=\"stateBox capsuleRight " + clearingStateBackgroundColour + "\" title=\"Project clearing state: " + ThriftEnumUtils.enumToString(project.clearingState) + "\"> CS </div>"; return box_PS+box_CS; }
Source:
public void pullRequestReviewComments() throws Exception { String name = "pullRequestReviewComments"; GHPullRequest p = getRepository().createPullRequest(name, "test/stable", "master", "## test"); assertTrue(p.listReviewComments().toList().isEmpty()); p.createReviewComment("Sample review comment", p.getHead().getSha(), "README.md", 1); List<GHPullRequestReviewComment> comments = p.listReviewComments().toList(); assertEquals(1, comments.size()); GHPullRequestReviewComment comment = comments.get(0); assertEquals("Sample review comment", comment.getBody()); assertNotNull(comment.getHtmlUrl()); comment.update("Updated review comment"); comments = p.listReviewComments().toList(); assertEquals(1, comments.size()); comment = comments.get(0); assertEquals("Updated review comment", comment.getBody()); comment.delete(); comments = p.listReviewComments().toList(); assertTrue(comments.isEmpty()); }

Target:
public void pullRequestReviewComments() throws Exception { String name = "pullRequestReviewComments"; GHPullRequest p = getRepository().createPullRequest(name, "test/stable", "master", "## test"); assertTrue(p.listReviewComments().toList().isEmpty()); p.createReviewComment("Sample review comment", p.getHead().getSha(), "README.md", 1); List<GHPullRequestReviewComment> comments = p.listReviewComments().toList(); assertEquals(1, comments.size()); GHPullRequestReviewComment comment = comments.get(0); assertEquals("Sample review comment", comment.getBody()); assertNotNull(comment.getHtmlUrl()); assertEquals(new URL("<LINK_0>"), comment.getHtmlUrl()); comment.update("Updated review comment"); comments = p.listReviewComments().toList(); assertEquals(1, comments.size()); comment = comments.get(0); assertEquals("Updated review comment", comment.getBody()); comment.delete(); comments = p.listReviewComments().toList(); assertTrue(comments.isEmpty()); }
Source:
public static void addRecipe(ILiquidStack fluidOutput, ILiquidStack fluidInput, int timePerUnit) { fluidOutput.amount(fluidOutput.getAmount() / 100); fluidInput.amount(fluidInput.getAmount() / 100); ModTweaker.LATE_ADDITIONS.add(new Add(new StillRecipe(timePerUnit, toFluid(fluidInput), toFluid(fluidOutput)))); }

Target:
public static void addRecipe(ILiquidStack fluidOutput, ILiquidStack fluidInput, int timePerUnit) { ModTweaker.LATE_ADDITIONS.add(new Add(new StillRecipe(timePerUnit, toFluid(fluidInput), toFluid(fluidOutput)))); }
Source:
public ContentWriteController( ApplicationConfigurationFetcher appConfigFetcher, ContentWriteExecutor contentWriteExecutor, LookupBackedContentIdGenerator lookupBackedContentIdGenerator, MessageSender<ContentWriteMessage> messageSender, AtlasModelWriter<QueryResult<Identified, ? extends Identified>> outputWriter, LookupEntryStore lookupEntryStore, ContentResolver contentResolver, ContentWriter contentWriter ) { this.appConfigFetcher = checkNotNull(appConfigFetcher); this.writeExecutor = checkNotNull(contentWriteExecutor); this.lookupBackedContentIdGenerator = checkNotNull(lookupBackedContentIdGenerator); this.messageSender = checkNotNull(messageSender); this.outputWriter = outputWriter; this.lookupEntryStore = checkNotNull(lookupEntryStore); this.contentResolver = checkNotNull(contentResolver); this.contentWriter = checkNotNull(contentWriter); }

Target:
private ContentWriteController( ApplicationConfigurationFetcher appConfigFetcher, ContentWriteExecutor contentWriteExecutor, LookupBackedContentIdGenerator lookupBackedContentIdGenerator, MessageSender<ContentWriteMessage> messageSender, AtlasModelWriter<QueryResult<Identified, ? extends Identified>> outputWriter, LookupEntryStore lookupEntryStore, ContentResolver contentResolver, ContentWriter contentWriter ) { this.appConfigFetcher = checkNotNull(appConfigFetcher); this.writeExecutor = checkNotNull(contentWriteExecutor); this.lookupBackedContentIdGenerator = checkNotNull(lookupBackedContentIdGenerator); this.messageSender = checkNotNull(messageSender); this.outputWriter = outputWriter; this.lookupEntryStore = checkNotNull(lookupEntryStore); this.contentResolver = checkNotNull(contentResolver); this.contentWriter = checkNotNull(contentWriter); }
Source:
private static Query createKeywordRangeQuery(String fieldName, RangeQueryContext rangeContext, QueryBuildingContext queryContext, ConversionContext conversionContext, FieldContext fieldContext) { final Analyzer queryAnalyzer = queryContext.getQueryAnalyzer(); final Object fromObject = rangeContext.getFrom(); final Object toObject = rangeContext.getTo(); final DocumentBuilderIndexedEntity documentBuilder = Helper.getDocumentBuilder( queryContext ); final String fromString = fromObject == null ? null : fieldContext.objectToString( documentBuilder, fromObject, conversionContext ); final String lowerTerm = fromString == null ? null : Helper.getAnalyzedTerm( fieldName, fromString, "from", queryAnalyzer, fieldContext ); final String toString = toObject == null ? null : fieldContext.objectToString( documentBuilder, toObject, conversionContext ); final String upperTerm = toString == null ? null : Helper.getAnalyzedTerm( fieldName, toString, "to", queryAnalyzer, fieldContext ); return TermRangeQuery.newStringRange( fieldName, lowerTerm, upperTerm, !rangeContext.isExcludeFrom(), !rangeContext.isExcludeTo() ); }

Target:
private static Query createKeywordRangeQuery(String fieldName, RangeQueryContext rangeContext, QueryBuildingContext queryContext, ConversionContext conversionContext, FieldContext fieldContext) { final Analyzer queryAnalyzer = queryContext.getQueryAnalyzer(); final DocumentBuilderIndexedEntity documentBuilder = Helper.getDocumentBuilder( queryContext ); final String fromString = rangeContext.hasFrom() ? fieldContext.objectToString( documentBuilder, rangeContext.getFrom(), conversionContext ) : null; final String lowerTerm = fromString == null ? null : Helper.getAnalyzedTerm( fieldName, fromString, "from", queryAnalyzer, fieldContext ); final String toString = rangeContext.hasTo() ? fieldContext.objectToString( documentBuilder, rangeContext.getTo(), conversionContext ) : null; final String upperTerm = toString == null ? null : Helper.getAnalyzedTerm( fieldName, toString, "to", queryAnalyzer, fieldContext ); return TermRangeQuery.newStringRange( fieldName, lowerTerm, upperTerm, !rangeContext.isExcludeFrom(), !rangeContext.isExcludeTo() ); }
Source:
protected void onDestroy() { super.onDestroy(); conversionManager.shutdown(); conversionManager.removeGlobalDownloadCallback(getSlidingUpFragment()); conversionManager.removeBaseInfoViewListener(getSlidingUpFragment()); conversionManager.removeGlobalJobViewListener(getSlidingUpFragment()); client = null; }

Target:
protected void onDestroy() { super.onDestroy(); conversionManager.shutdown(); conversionManager.removeGlobalDownloadCallback(getSlidingUpFragment()); conversionManager.removeBaseInfoViewListener(getSlidingUpFragment()); conversionManager.removeGlobalJobViewListener(getSlidingUpFragment()); }
Source:
public <T> Optional<T> getSagaIdentifierFrom(final Event event) { checkNotNull(event); Object identifier =null; try { identifier = identifierMethod.invoke(event); } catch (final IllegalAccessException e) { e.printStackTrace(); } catch (final InvocationTargetException e) { e.printStackTrace(); } return Optional.fromNullable((T)identifier); }

Target:
public <T> Optional<T> getSagaIdentifierFrom(final Event event) { checkNotNull(event); Object identifier = null; try { identifier = identifierMethod.invoke(event); } catch (IllegalAccessException | InvocationTargetException e) { LOGGER.warn("Failed to retrieve saga identifier from the given event, <getter={}> <event={}>", identifierMethod.getName(), event.getClass().getName(), e); } return Optional.fromNullable((T)identifier); }
Source:
public String getFlagMessage() { return "Mother not HIV Tested"; }

Target:
public String getFlagMessage() { return "Not HIV Tested"; }
Source:
public boolean canExecute() { final IEditorPart activeEditor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor(); return activeEditor instanceof AbstractMultiPageSashEditor; }

Target:
public boolean canExecute() { final IEditorPart activeEditor = EditorHelper.getCurrentEditor(); return activeEditor instanceof IMultiPageEditorPart; }
Source:
private static byte[] getBytes(String path, InputStream in, long maxLength) throws IOException { if (maxLength > Integer.MAX_VALUE) { throw new IOException( MessageFormat.format(JGitText.get().fileIsTooLarge, path)); } int max = (int) maxLength; byte[] buffer = new byte[max]; int read = IO.readFully(in, buffer, 0); if (read == max) { return buffer; } else { byte[] copy = new byte[read]; System.arraycopy(buffer, 0, copy, 0, read); return copy; } }

Target:
private static byte[] getBytes(String path, InputStream in, long maxLength) throws IOException { if (maxLength > Integer.MAX_VALUE) { throw new IOException( MessageFormat.format(JGitText.get().fileIsTooLarge, path)); } int max = (int) maxLength; byte[] buffer = new byte[max]; int read = IO.readFully(in, buffer, 0); if (read == max) { return buffer; } byte[] copy = new byte[read]; System.arraycopy(buffer, 0, copy, 0, read); return copy; }